diff --git "a/1275.jsonl" "b/1275.jsonl" new file mode 100644--- /dev/null +++ "b/1275.jsonl" @@ -0,0 +1,656 @@ +{"seq_id":"367737784","text":"from behave.runner import Context\n\nfrom pages.main_header import MainHeader\nfrom utils.base_page import BasePage\nfrom utils.browsers.browser_selector import browser\nfrom utils.fake_persons.fake_client import FakeClient\n\n\ndef start_driver():\n driver = browser().driver\n return driver\n\n\ndef before_all(context):\n context.stuff = Stuff(context)\n context.client = context.stuff.client()\n\n\ndef before_scenario(context, scenario):\n context.driver = start_driver()\n context.environment = Environment(context, context.driver)\n pages = context.environment._origin\n behave = (\"feature\", \"text\", \"table\", \"stdout_capture\", \"stderr_capture\", \"log_capture\", \"fail_on_cleanup_errors\")\n for behave_item in behave:\n pages.pop(behave_item, None)\n for page in pages:\n setattr(context, page, getattr(context.environment, page))\n\n\ndef after_scenario(context, scenario):\n context.driver.close()\n\n\ndef after_step(context, step):\n if step.status == 'failed':\n step_str = step.name\n context.driver.save_screenshot(f\"{step_str}.png\")\n\n\nclass Environment(Context):\n\n def __init__(self, runner, driver):\n super().__init__(runner)\n self.base = BasePage(driver)\n self.main_header = MainHeader(driver)\n\n\nclass Stuff(Context):\n\n def __init__(self, runner):\n super().__init__(runner)\n self.client = FakeClient\n","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"47391192","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os\nos.environ.update({\"DJANGO_SETTINGS_MODULE\": \"SqlAudit.settings\"})\nfrom django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives\n\ndef sendMail(subject, html_content,to_email):\n try:\n ToEmail = []\n if type(to_email) != list:\n ToEmail.append(to_email)\n else:\n ToEmail = to_email\n from_email = settings.DEFAULT_FROM_EMAIL\n # subject = '来自SQL审核系统的通知'\n # text_content = '这是一封重要的邮件.'\n # html_content = '

这是一封重要的邮件.

'\n msg = EmailMultiAlternatives(subject, html_content, from_email, ToEmail)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n print(\"Send Email Successful.\")\n return \"Send Email Successful.\"\n except Exception as e:\n print(e)\n return e\n\nif __name__ == '__main__':\n html_content = \"这是一封特别重要的邮件.\"\n print (sendMail(html_content,'baochengcai@lanjingren.com'))","sub_path":"drf_api/app/celery_tasks/asynchronous/sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"236392588","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n\n p = head\n all_val = []\n while p:\n q = ListNode(0)\n q.val = p.val\n all_val.append(q)\n p = p.next\n\n all_val.remove(all_val[len(all_val) - n])\n if len(all_val) == 0:\n return None\n for i in range(len(all_val) - 1):\n all_val[i].next = all_val[i + 1]\n\n return all_val[0]\n\n\na = Solution()\nt1 = ListNode(1)\nt2 = ListNode(2)\n# t3 = ListNode(3)\n# t4 = ListNode(4)\n# t5 = ListNode(5)\nt1.next = t2\n# t2.next = t3\n# t3.next = t4\n# t4.next = t5\n\na.removeNthFromEnd(t1, 1)\n","sub_path":"PythonLearning/OJ/test_all/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"498101313","text":"f = open(\"p079_keylog.txt\", \"r\")\nlogs = []\nfor row in f:\n logs.append(row[:-1])\n \ndigits = []\nfor row in logs:\n for i in row:\n if i not in digits:\n digits.append(i)\n","sub_path":"Python/079.py","file_name":"079.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"429916942","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseNotFound\n\nfrom django.contrib.auth.models import User\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import GeneralTopic, UserTopic, BookReference, CourseReference, WebsiteReference\n\nfrom navigatte import wikipedia_api, settings\n\n#Method to get the url from its label\nfrom django.core.urlresolvers import reverse\n\n\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\n\n# Create your views here.\n\n@login_required\ndef addNewUserTopic(request, userpage):\n\n #ON POST\n\n #If it was a new topic to be added\n if request.method == \"POST\" and 'topic_url_title' in request.POST and request.POST['topic_url_title']:\n \n queryResult = wikipedia_api.query(request.POST['topic_url_title'])\n if queryResult == None:\n return HttpResponse(\"Invalid request\")\n \n #Try to get topic, if not found, create a new\n try: \n topicReference = GeneralTopic.objects.get(pageid=queryResult['pageid'])\n except GeneralTopic.DoesNotExist:\n topicReference = GeneralTopic(title=queryResult['title'], \n pageid=queryResult['pageid'], urlTitle=queryResult['urlTitle'])\n topicReference.save()\n\n #Try to get this reference on the current user topics, if it does not exists, create a new\n try:\n request.user.usertopic_set.get(generalTopic=topicReference, deleted=False)\n return HttpResponse(\"User topic already exists.\")\n except UserTopic.DoesNotExist:\n #If it does not exists, create it\n newUserTopic = UserTopic(generalTopic=topicReference, owner=request.user)\n newUserTopic.save()\n\n return redirect('display_user_topics', userpage)\n\n #ON GET \n\n if not 'search' in request.GET or not request.GET['search']:\n return render(request, \"add-new-user-topic.html\", {\n 'noQuery': True,\n 'userpage': userpage\n })\n\n resultObject = wikipedia_api.search(request.GET['search'])\n\n if resultObject == None:\n return HttpResponse(\"Error while completing the request.\")\n\n return render(request, \"add-new-user-topic.html\",{\n 'resultTopics': resultObject,\n 'userpage': userpage\n })\n\n\ndef displayUserTopics(request, userpage):\n #Check whether the user exists and get it\n try:\n userpageRef = User.objects.get_by_natural_key(username=userpage)\n except User.DoesNotExist:\n return HttpResponseNotFound(\"User not found.\")\n\n #return the request userpage, signaling whether this user is the owner or not\n\n #userpage is the current userpage displayed\n #Get all the subjects that are not deleted\n return render(request, 'user-topics-display.html', {\n 'topic_list': userpageRef.usertopic_set.filter(deleted=False),\n 'userpage': userpage,\n 'isOwner': userpageRef == request.user,\n })\n\ndef userTopicDetails(request, userpage):\n \n #Check whether the user exists and get it\n try:\n userpageRef = User.objects.get_by_natural_key(username=userpage)\n except:\n return HttpResponseNotFound(\"User not found.\") \n\n if 'id' in request.GET and request.GET['id']:\n\n try:\n topic_details = UserTopic.objects.get(id=request.GET['id'])\n\n #Get all the references that have not the delete flag set\n return render(request, 'user-topic-details.html', { \n 'name': topic_details, \n 'books': topic_details.books.all(),\n 'courses': topic_details.courses.all(), \n 'websites': topic_details.websites.all(),\n 'subject_id': request.GET['id'], \n 'userpage': userpage,\n 'isOwner': userpageRef == request.user, \n })\n\n except UserTopic.DoesNotExist:\n return HttpResponseNotFound(\"User topic not found\")\n\n else: #If no id, return the topics list\n return redirect('display_user_topics')\n\n#View to handle subject delete\n@login_required\ndef deleteUserTopic(request, userpage):\n if request.method != 'POST':\n return HttpResponse(\"Invalid Request\")\n\n #If a subject_id field is present and is valid (not empty)\n if 'subject_id' in request.POST and request.POST['subject_id']:\n\n try:\n targetSubject = UserTopic.objects.get(id=request.POST['subject_id'], owner=request.user)\n\n #Verifies if this subject does belongs to this user\n #if request.user != targetSubject.owner:\n #return invalidRequest(\"Invalid Delete. This subject does not belong to the signed in user.\")\n\n #If it is the owner, set delete flag in the object and return subjects page\n targetSubject.deleted = True\n targetSubject.save()\n\n return redirect('display_user_topics', userpage=userpage)\n\n except Exception as e:\n return invalidRequest(\"Error while deleting: \" + str(e))\n\n return invalidRequest(\"No subject id or invalid subject id send.\")\n\n\n@login_required\ndef addUserTopicReference(request, userpage):\n if not \"subject_id\" in request.POST:\n return invalidRequest(\"Invalid reference add request. No subjectID in POST method.\")\n\n \n subjectId = request.POST[\"subject_id\"]\n\n #Check if the subject_id is valid and belongs to this user\n try:\n targetSubject = UserTopic.objects.get(id=subjectId, owner=request.user)\n\n #If the target object owner is not the current user, finish with error\n #if request.user != targetSubject.owner:\n #return invalidRequest(\"Invalid reference add request. The target user owner of the subject is not the authenticated user.\")\n\n #check which reference is being add\n if \"course_name\" in request.POST and request.POST[\"course_name\"]:\n newCourse = CourseReference(name=request.POST[\"course_name\"])\n newCourse.save()\n #Add the new course to the target subject\n targetSubject.courses.add(newCourse)\n\n elif \"book_title\" in request.POST and request.POST[\"book_title\"]:\n #Create new book (should be checked whether the desired exists before add a new)\n newBook = BookReference(name=request.POST[\"book_title\"])\n newBook.save()\n targetSubject.books.add(newBook)\n\n elif \"website_address\" in request.POST and request.POST[\"website_address\"]:\n \n #Try to get a reference to the address\n try:\n websiteRef = WebsiteReference.objects.get(address=request.POST[\"website_address\"])\n targetSubject.websites.add(websiteRef)\n \n except WebsiteReference.DoesNotExist:\n\n #If it does not exists, create a new\n try:\n #Get site data\n websiteData = urllib.request.urlopen(request.POST[\"website_address\"]).read()\n\n #Parse site data to objects\n websiteObj = BeautifulSoup(websiteData)\n\n #Get a title if there is one on the page\n if not websiteObj.title or websiteObj.title.string == None:\n websiteName = request.POST[\"website_address\"]\n else:\n websiteName = websiteObj.title.string\n\n #If the url is invalid\n except ValueError:\n return HttpResponse(\"Invalid URL.\")\n\n except Exception:\n #If we can not retrieve site url, set the site title as the url\n websiteName = request.POST[\"website_address\"]\n\n newWebsite = WebsiteReference(name=websiteName, address=request.POST[\"website_address\"])\n newWebsite.save()\n targetSubject.websites.add(newWebsite)\n\n else:\n #If no valid reference, return error\n return HttpResponse(\"Invalid reference add request (invalid reference).\")\n\n return redirect(reverse('user_topic_details', kwargs={'userpage': userpage}) + \"?id=\" + subjectId)\n\n except Exception as e:\n #return invalidRequest(\"Invalid reference add request. Exception: \" + str(e))\n raise e\n\n\n#View to handle subject reference delete\n#For now remove the reference from the subject, later set a remove flag and keeps record\ndef deleteUserTopicReference(request, userpage):\n if request.method != 'POST':\n return invalidRequest(\"Invalid request. POST method expected.\")\n\n if not validateEntries(request.POST, [\"subject_id\", \"reference_type\", \"reference_id\"]):\n return invalidRequest(\"Invalid request. subject_id, reference_type or reference_id missing or not valid.\")\n\n subjectId = request.POST['subject_id']\n referenceType = request.POST['reference_type']\n referenceId = request.POST['reference_id']\n\n try:\n #Get the target subject\n targetSubject = UserTopic.objects.get(id=subjectId, owner=request.user)\n\n #Verifies if this subject does belongs to this user\n #if request.user != targetSubject.owner:\n #return invalidRequest(\"Invalid Delete. This subject does not belong to the signed in user.\")\n \n #Get the target reference\n if referenceType == \"website\":\n targetReference = WebsiteReference.objects.get(id=referenceId)\n #remove the reference from the subject\n targetSubject.websites.remove(targetReference)\n\n elif referenceType == \"book\":\n targetReference = BookReference.objects.get(id=referenceId)\n #remove the reference from the subject\n targetSubject.books.remove(targetReference)\n \n elif referenceType == \"course\":\n targetReference = CourseReference.objects.get(id=referenceId)\n #remove the reference from the subject\n targetSubject.courses.remove(targetReference)\n else:\n return invalidRequest(\"Invalid Delete. Invalid type: \" + referenceType)\n\n #save target subject\n targetSubject.save()\n\n return redirect(reverse('user_topic_details', kwargs={'userpage': userpage}) + \"?id=\" + subjectId)\n\n except Exception as e:\n return invalidRequest(\"Error while deleting: \" + str(e))\n\n\ndef invalidRequest(debugMsg, nonDebugMsg = \"Invalid Request\"):\n if settings.DEBUG:\n return HttpResponse(debugMsg) \n\n return HttpResponse(nonDebugMsg) \n\ndef validateEntries(collection, entries, blankAllowed = False):\n #iterate thru the entries\n for entry in entries:\n #if the entry does not exist, or is invalid (in case blankAllowed is false), return false\n if not entry in collection or not (collection[entry] or blankAllowed):\n return False\n \n return True","sub_path":"topics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"423806636","text":"import unittest\nfrom Controller import Checker\nfrom Models.Student import Student\nfrom Models.BRSPoints import BRSPoints\nfrom Models.EducationYear import EducationYear\nfrom Models.CrossSection import CrossSection\nfrom Models.Group import Group\nfrom Models.Subject import Subject\n\n\nclass CheckPointsTestCase(unittest.TestCase):\n def test_check_points(self):\n group1 = Group(\"М-ФИИТ-20\", 2020)\n group2 = Group(\"М-ФИИТ-19\", 2019)\n\n year1 = EducationYear(2020, 2021)\n\n subject1 = Subject(\"321\", \"Психология\")\n subject3 = Subject(\"323\", \"Английский\")\n\n cross_section1 = CrossSection.FirstSection\n cross_section2 = CrossSection.SecondSection\n cross_section3 = CrossSection.FinalSection\n\n student1 = Student(code=123, fio=\"Егоров Алексей Васильевич\", birthdate=\"01. 04. 1996\",\n email=\"eavamga@gmail.com\", phone=\"+79244669579\", group=group1)\n student2 = Student(code=124, fio=\"Иванов Иван Иванович\", birthdate=\"30. 12. 2000\", email=\"example@gmail.com\",\n phone=\"+79991112233\", group=group2)\n\n EgorovAV_cs1 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section1, points=33,\n student=student1)\n EgorovAV_cs2 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section2, points=66,\n student=student1)\n EgorovAV_cs3 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section3, points=99,\n student=student1)\n\n IvamovII_cs1 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section1, points=20,\n student=student2)\n IvamovII_cs2 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section2, points=20,\n student=student2)\n IvamovII_cs3 = BRSPoints(subject=subject1, year=year1, cross_section=cross_section3, points=20,\n student=student2)\n\n EgorovAV_cs1_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section1, points=101,\n student=student1)\n EgorovAV_cs2_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section2, points=0,\n student=student1)\n EgorovAV_cs3_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section3, points=0,\n student=student1)\n\n IvamovII_cs1_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section1, points=65,\n student=student2)\n IvamovII_cs2_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section2, points=60,\n student=student2)\n IvamovII_cs3_wrong = BRSPoints(subject=subject3, year=year1, cross_section=cross_section3, points=30,\n student=student2)\n\n Egorov_subject1_2020_2021 = [EgorovAV_cs1, EgorovAV_cs2, EgorovAV_cs3]\n Egorov_subject3_2020_2021_wrong = [EgorovAV_cs1_wrong, EgorovAV_cs2_wrong, EgorovAV_cs3_wrong]\n\n Ivanov_subject1_2020_2021 = [IvamovII_cs1, IvamovII_cs2, IvamovII_cs3]\n Ivanov_subject1_2020_2021_wrong = [IvamovII_cs1_wrong, IvamovII_cs2_wrong, IvamovII_cs3_wrong]\n\n self.assertEqual(Checker.check_points(Egorov_subject1_2020_2021, cross_section3, EgorovAV_cs3.points), True)\n self.assertEqual(Checker.check_points(Ivanov_subject1_2020_2021, cross_section3, IvamovII_cs3.points), True)\n\n self.assertEqual(\n Checker.check_points(Egorov_subject3_2020_2021_wrong, cross_section1, EgorovAV_cs1_wrong.points), False)\n self.assertEqual(\n Checker.check_points(Ivanov_subject1_2020_2021_wrong, cross_section3, IvamovII_cs3_wrong.points), False)\n","sub_path":"Tests/Controller/Checker/test_check_points.py","file_name":"test_check_points.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"511271691","text":"#! /usr/bin/python3\n\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.scatter import Scatter\nfrom kivy.uix.label import Label\nfrom kivy.uix.floatlayout import FloatLayout\n\nclass TutorialApp(App):\n def build(self):\n f = FloatLayout()\n s = Scatter()\n l = Label(text='Hello!',\n font_size=150)\n f.add_widget(s)\n s.add_widget(l)\n return f\n # This was a button.\n #return Button(text='Hello!',\n # background_color=(0, 0, 1, 1), # List of\n # # rgba components\n # font_size=150)\ndef main():\n print(\"main() function.\")\n TutorialApp().run()\n\nif __name__ == \"main\":\n print(\"main.\")\n main()\nelse:\n print(\"Not main.\")\n #TutorialApp().run()\n\n\n#if __name__ == \"__main__\":\n# TutorialApp().run()","sub_path":"video1.py","file_name":"video1.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"117525545","text":"file_name = 'dataset_3363_3.txt'\nwith open(file_name) as file:\n dataset = [] \n for i in file:\n dataset.append(i.strip())\ndef enc_list(lst):\n '''func decompose list in string'''\n result = []\n for i in lst:\n result += i.lower().split()\n return result\ndata = enc_list(dataset)\ndef counter(iterat_obj):\n d = {}\n for i in iterat_obj:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n return d\ndef who_much(dictionary):\n wold = ''\n count = 0\n for i in list(dictionary.items()):\n if i[1] > count:\n count = i[1]\n wold = i[0]\n elif i[1] == count:\n if i[0] < wold:\n wold = i[0]\n print(wold, end=' ')\n print(count)\nwho_much(counter(data)) \n#with open(file_name + '_answer.txt', 'w') as file:\n #file.write(winer) \n# очень понравилось решение\nwith open('dataset_3363_3.txt') as inf, open('MostPopularWord.txt','w') as ouf:\n maxc = 0\n s = inf.read().lower().strip().split()\n s.sort()\n for word in s:\n counter = s.count(word)\n if counter > maxc:\n maxc = counter\n result_word = word\n ouf.write(result_word +' ' + str(maxc))\n","sub_path":"py4_6.py","file_name":"py4_6.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"33840886","text":"import os\nimport json\nimport logging\nfrom glob import glob\n\nfrom lxml import etree\n\nimport settings as s\nfrom .utils import translate_dir\nfrom .log import set_up_logging\n\nlog = set_up_logging('transform', loglevel=logging.DEBUG)\n\n\ndef transform_sopr(options):\n def _is_array(element):\n return element.getchildren() != []\n\n def _add_element_single(element, json_dict):\n json_dict[element.tag] = dict(element.attrib)\n\n def _add_element_array(root_node, json_dict):\n json_dict[root_node.tag] = []\n for e in root_node.getchildren():\n json_dict[root_node.tag].append(dict(e.attrib))\n\n def _add_element(element, json_dict):\n if _is_array(element):\n _add_element_array(element, json_dict)\n else:\n _add_element_single(element, json_dict)\n\n def _write_to_file(xml_filepath, filing):\n path, destination_dir = translate_dir(xml_filepath,\n from_dir=s.ORIG_DIR,\n to_dir=s.TRANS_DIR)\n filing_id = json_filing['ID']\n output_path = os.path.join(destination_dir,\n '{fid}.json'.format(fid=filing_id))\n if os.path.exists(output_path) and not options['force']:\n raise OSError(os.errno.EEXIST,\n ' '.join([os.strerror(os.errno.EEXIST)+':',\n output_path]))\n\n with open(output_path, 'w') as output_file:\n json.dump(json_filing, output_file)\n\n all_fields = ['AffiliatedOrgs',\n 'Client',\n 'ForeignEntities',\n 'GovernmentEntities',\n 'Issues',\n 'Lobbyists',\n 'Registrant']\n\n xml_files = glob(os.path.join(s.ORIG_DIR, 'sopr/*/*/*.xml'))\n\n for xml_filepath in xml_files:\n for filing in etree.parse(open(xml_filepath)).getroot().iterchildren():\n json_filing = dict.fromkeys(all_fields)\n json_filing.update(dict(filing.attrib))\n\n for element in filing.getchildren():\n _add_element(element, json_filing)\n\n _write_to_file(xml_filepath, json_filing)\n","sub_path":"tasks/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"228479760","text":"from functools import reduce\nfrom pyquery import PyQuery as pq\nfrom random import random\nimport time\nimport json\nfrom pprint import pprint\n\n\ndef fetchPQO(url):\n \"\"\" URLにアクセスし,HTMLを pyQuery Object にして返す\n 1~4秒スリープ後に処理をする.\n \"\"\"\n time.sleep(round(random() * 3.0 + 1.0, 3))\n return pq(url)\n\n\ndef fetchPQOs(url, max=100):\n \"\"\" リンクをたどり,page毎に pyQuery Object を取得し,格納したリストを返す\n \"\"\"\n def isLastPage(p):\n return not(p('.pager'))\n\n pqos = []\n for i in range(1, max+1):\n print('page '+str(i)+' fetching...')\n p = fetchPQO(url + '?page=' + str(i))\n pqos.append(p)\n if(isLastPage(p)):\n break\n print('num of page = '+str(len(pqos)))\n return pqos\n\n\ndef getContent(bokeContainer):\n def extractEl(l=['', '']):\n if(l[0] == 'boke-text'):\n return [l[0], pq(l[1])('.boke-text').text()]\n elif(l[0] == 'boke-meta'):\n # 配下に'.boke-stars'があるので取得'\n return ['boke-stars', int(pq(l[1])('.boke-stars').text())]\n else:\n return []\n\n # boke の直接の子要素のうち classを持つもののリスト\n childl = pq(bokeContainer).children('[class]')\n\n # [[class名,html],[]....] となるリストを作成\n datal = [[pq(c).attr('class'), c] for c in childl]\n\n # htmlから必要なデータを抽出し,辞書を作成.(空リストは削除)\n return dict(filter(lambda el: el != [], [extractEl(i) for i in datal]))\n\n\ndef getContents(pqo):\n # pqoから 1つ目の要素(お題), 広告 を除外\n bokediv = pqo('.boke:gt(0)').filter(lambda i, e:\n pq(e).children().length >= 4)\n return [getContent(el) for el in bokediv]\n\n\ndef getAllContents(pqos):\n if(not(len(pqos))):\n return []\n\n ll = [getContents(pqo) for pqo in pqos]\n return list(reduce(lambda tlist, t: tlist+t, ll))\n\n\ndef fetchData(url='', max=100):\n \"\"\" url にアクセスし,1つのお題に対する全てのデータを取得\n url : アクセスするページ(お題のトップページ. ex:http://bokete.jp/odai/2227309)\n max : 取得するbokeのページ数上限\n \"\"\"\n # TODO:中 URLにurl末尾のみ入れても動くようにする\n # TODO:高 fetchしたあと抽出に入る前にお題の画像をとってくる処理、fetchResourceをはさむ\n # TODO:高 返り値に odaiId(ex. odaiId:2227309 ),\n # imgPath(ex. imgPath:'./img/2227309.png')を追加する\n # TODO:高 返り値を辞書に. {odaiId:0, imgPath:'' ,boke:[{},{},{},...]}\n return getAllContents(fetchPQOs(url, max))\n\n\ndef outputJson(obj=[], filename='def.json'):\n \"\"\" obj を jsonファイル(filename)に出力\n \"\"\"\n with open(filename, 'w') as f:\n f.writelines(json.dumps(obj))\n\n\ndef decodeJson(filename='def.json'):\n \"\"\"jsonファイル(filename)をロードし,返す\n \"\"\"\n with open(filename, 'r', encoding='UTF-8') as f:\n return json.loads(f.read(), 'UTF-8')\n\n\ndef printJson(filename='def.json'):\n \"\"\" jsonファイル(filename)をロードし,表示\n \"\"\"\n pprint(decodeJson(filename), indent=4)\n\n\n#\n# main\n#\nif __name__ == '__main__':\n baseUrl = 'http://bokete.jp/odai'\n odaiId = '2227309'\n url = baseUrl+'/'+odaiId\n print('url = \"'+url+'\"')\n\n # 全ての boke を取得\n boke = fetchData(url, max=100)\n\n # 取得データをファイルに保存\n outputJson(boke, filename='boke.json')\n\n # jsonの中身確認\n printJson('boke.json')\n","sub_path":"bokete_scraping/bokescr.py","file_name":"bokescr.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"158535865","text":"\n\nfrom xai.brain.wordbase.nouns._gadabout import _GADABOUT\n\n#calss header\nclass _GADABOUTS(_GADABOUT, ):\n\tdef __init__(self,): \n\t\t_GADABOUT.__init__(self)\n\t\tself.name = \"GADABOUTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"gadabout\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_gadabouts.py","file_name":"_gadabouts.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"453523928","text":"\"\"\"A configuration file for the school script.\"\"\"\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass CourseType:\n \"\"\"A class for various types of courses (lectures/labs/whatever).\"\"\"\n\n color: int\n has_homework: bool\n\n\n# the relative path to the folder where the courses are stored\ncourses_folder = \"courses/\"\n\n\n# settings regarding course types -- labs/lectures/...\n# the numbers are ANSI colors that the course type will be painted with\n# see https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html\ncourse_types = {\n \"cvičení\": CourseType(118, True),\n \"přednáška\": CourseType(39, False),\n}\n\n\n# default handlers for opening course folders/websites/notes...\nfile_browser = [\"ranger\"]\nweb_browser = [\"qutebrowser\", \"--target\", \"window\"]\ntext_editor = [\"vim\"]\nnote_handlers = {\".xopp\": \"xournalpp\", \".md\": \"vim\"}\n\n\n# default handler for Cron class notifications\n# the first argument after this command is the body of the notification\nnotify_command = \"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus dunstify 'School Schedule'\"\n\nnotify_started_message = \"právě začal předmět\" # course started message\nnotify_no_more_courses = \"dnes již žádný další předmět není\" # no more courses today\nnotify_next_course_message = (\n \"další předmět je {0} ({1}), \" # {0} is course name, {1} is course type\n \"který začíná {2} minut po tomto \" # {2} is minutes till next course\n \"v učebně {3}\" # {3} is the location\n)\n","sub_path":"school/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"544636999","text":"import json\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom matplotlib.widgets import Slider\nfrom skimage import io\nfrom skimage.segmentation import find_boundaries\n\n\ndef segid_to_rgb(seg_id):\n r, seg_id = seg_id % 256, seg_id / 256\n g, seg_id = seg_id % 256, seg_id / 256\n b = seg_id % 256\n return np.array([r, g, b])\n\n\ndef rgb_to_segid(rgb):\n r, g, b = rgb\n return r + 256*g + 256*256*b\n\n\ndef get_boundaries(msk):\n msk_id = msk.astype(np.uint32)\n msk_id = msk[:, :, 0] + 255*msk[:, :, 1] + 255*255*msk_id[:, :, 2]\n boundaries = find_boundaries(msk_id, mode='thick')\n # img[boundaries] = 0\n return boundaries \n\n\ndef plot_categories_in_legend(ann, categories):\n patches = []\n for seg in ann['segments_info']:\n color = segid_to_rgb(seg['id']) / 255.\n label = categories[seg['category_id']]['name']\n\n patches.append(mpatches.Patch(color=color, label=label))\n\n plt.subplots_adjust(right=0.7)\n plt.legend(handles=list(set(patches)),\n bbox_to_anchor=(1.04,1), loc=\"upper left\", borderaxespad=0)\n\n\ndef plot_img(img, msk, ann, categories):\n fig = plt.figure()\n\n opacity = 0.6\n res = img*opacity + msk*(1 - opacity)\n \n boundaries = get_boundaries(msk)\n res[boundaries] = 0\n\n plt_img = plt.imshow(res.astype(np.uint8))\n plt_img.axes.format_coord = lambda x, y: format_coord(x, y,\n msk, ann, categories)\n plot_categories_in_legend(ann, categories)\n slider = add_opacity_slider(img, msk, opacity, boundaries, plt_img, fig)\n\n # quit by q\n plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)\n plt.show()\n\n\ndef main():\n WDIR = './__data/source'\n IDIR = os.path.join(WDIR, 'train2017')\n MDIR = os.path.join(WDIR, 'annotations', 'panoptic_train2017')\n ANN_PATH = os.path.join(WDIR, 'annotations', 'fix_panoptic_train2017.json')\n # CAT_PATH = os.path.join(WDIR, 'annotations', 'panoptic_coco_categories.json')\n\n with open(ANN_PATH, 'r') as f:\n dataset = json.load(f)\n # with open(CAT_PATH, 'r') as f:\n # categories = json.load(f)\n\n images = dataset['images']\n annotations = dataset['annotations']\n categoriest_cnt = max(cat['id'] for cat in dataset['categories']) + 1\n categories = [{'id':-1, 'name': 'unknown'}]*categoriest_cnt\n categories[0] = {'id': 0, 'name': 'void'}\n\n for cat in dataset['categories']:\n categories[cat['id']] = cat\n\n from_idx = np.random.randint(len(images))\n to_idx = len(images)\n lst = zip(images[from_idx:to_idx], annotations[from_idx:to_idx])\n for img, ann in lst:\n # print(img['file_name'], ann['file_name'])\n img_path = os.path.join(IDIR, img['file_name'])\n msk_path = os.path.join(MDIR, ann['file_name'])\n\n img = io.imread(img_path)\n msk = io.imread(msk_path)\n\n plot_img(img, msk, ann, categories)\n\n\ndef add_opacity_slider(img, msk, init_opacity, boundaries, plt_img, fig):\n def update(opacity):\n res = img*opacity + msk*(1 - opacity)\n res[boundaries] = 0\n plt_img.set_array(res.astype(np.uint8))\n fig.canvas.draw_idle()\n\n axcolor = 'lightgoldenrodyellow'\n axopacity = plt.axes([0.15, 0.95, 0.75, 0.03], facecolor=axcolor)\n slider = Slider(axopacity, 'Opacity', 0., 1., valinit=init_opacity)\n slider.on_changed(update)\n\n return slider\n\n\ndef format_coord(x, y, msk, ann, categories):\n seg_id = rgb_to_segid(msk[int(y), int(x)])\n cat_id = 0\n if seg_id != 0:\n cat_id = [seg['category_id'] for seg in ann['segments_info'] if seg['id'] == seg_id][0]\n seg_name = categories[cat_id]['name']\n return 'x={:.4f}, y={:.4f} {}'.format(x, y, seg_name)\n\n\ndef quit_figure(event):\n if event.key == 'q':\n plt.close(event.canvas.figure)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run02_inspect_imgs.py","file_name":"run02_inspect_imgs.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"248873510","text":"import turtle\nimport pandas\n\nscreen = turtle.Screen()\nscreen.title(\"U.S. States Game\")\nimage = \"blank_states_img.gif\"\nscreen.addshape(image)\nturtle.shape(image)\n\ncursor = turtle.Turtle()\ncursor.hideturtle()\ncursor.penup()\n\ndata = pandas.read_csv(\"50_states.csv\")\nnum_states = len(data)\ncorrect_answers = 0\ncorrect_guesses = []\nstates_to_learn = []\n\nwhile correct_answers < num_states:\n answer_state = screen.textinput(title=f\"{correct_answers}/{num_states} States Correct\",\n prompt=\"What's another state's name?\").title()\n if answer_state == \"Exit\":\n for state in data.state:\n if state not in correct_guesses:\n states_to_learn.append(state)\n df = pandas.DataFrame(states_to_learn, columns=['state'])\n df.to_csv(\"states_to_learn.csv\")\n break\n for state in data.state:\n if (answer_state == state) and (answer_state not in correct_guesses):\n x_pos = float(data.x[data.state == answer_state])\n y_pos = float(data.y[data.state == answer_state])\n cursor.setpos(x_pos, y_pos)\n cursor.write(answer_state, align=\"center\")\n correct_guesses.append(answer_state)\n correct_answers += 1\n","sub_path":"us-states-game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"517145162","text":"#Embedded file name: C:/Users/hovel/Dropbox/packages/studiolibrary/1.6.14/build27/studiolibrary/packages/mutils\\pose.py\n\"\"\"\n# Released subject to the BSD License\n# Please visit http://www.voidspace.org.uk/python/license.shtml\n#\n# Copyright (c) 2014, Kurt Rathjen\n# All rights reserved.\n# Comments, suggestions and bug reports are welcome.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n # * Redistributions of source code must retain the above copyright\n # notice, this list of conditions and the following disclaimer.\n # * Redistributions in binary form must reproduce the above copyright\n # notice, this list of conditions and the following disclaimer in the\n # documentation and/or other materials provided with the distribution.\n # * Neither the name of Kurt Rathjen nor the\n # objects of its contributors may be used to endorse or promote products\n # derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY KURT RATHJEN ''AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL KURT RATHJEN BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# pose.py\nimport pose\n\n# Example 1:\n# Create pose from objects\np = mutils.Pose.createFromObjects(objects)\n\n# Example 2:\n# Create from selected objects\nobjects = maya.cmds.ls(selection=True)\np = mutils.Pose.createFromObjects(objects)\n\n# Example 3:\n# Save to file\npath = \"/tmp/pose.json\"\np.save(path)\n\n# Example 4:\n# Load from file\npath = \"/tmp/pose.json\"\np = mutils.Pose.createFromPath(path)\n\n# load to objects from file\np.load()\n\n# load to selected objects\nobjects = maya.cmds.ls(selection=True)\np.load(objects=objects)\n\n# load to namespaces\np.load(namespaces=[\"character1\", \"character2\"])\n\n# load to specified objects\np.load(objects=[\"Character1:Hand_L\", \"Character1:Finger_L\"])\n\n\"\"\"\nimport mutils\nlog = mutils.logger\ntry:\n import maya.cmds\nexcept ImportError:\n import traceback\n traceback.print_exc()\n\n__all__ = ['Pose']\n\nclass Pose(mutils.SelectionSet):\n\n def __init__(self):\n \"\"\"\n \"\"\"\n mutils.SelectionSet.__init__(self)\n self._cache = None\n self._cacheKey = None\n self._mirrorTable = None\n\n def cache(self):\n \"\"\"\n @rtype: list[(Attribute, Attribute)]\n \"\"\"\n return self._cache\n\n def createObjectData(self, name):\n \"\"\"\n @type name: name\n @rtype: list[Attribute]\n \"\"\"\n attrs = maya.cmds.listAttr(name, unlocked=True, keyable=True) or []\n attrs = list(set(attrs))\n attrs = [ mutils.Attribute(name, attr) for attr in attrs ]\n result = {'attrs': self.attrs(name)}\n for attr in attrs:\n if attr.isValid():\n if attr.value() is None:\n log.warning('Cannot save the attribute %s with value None.' % attr.fullname())\n else:\n result['attrs'][attr.attr()] = {'type': attr.type(),\n 'value': attr.value()}\n\n return result\n\n def attrs(self, name):\n \"\"\"\n @type name: str\n @rtype: dict[]\n \"\"\"\n return self.object(name).get('attrs', {})\n\n def attr(self, name, attr):\n \"\"\"\n @type name: str\n @rtype: dict[]\n \"\"\"\n return self.attrs(name).get(attr, {})\n\n def attrType(self, name, attr):\n \"\"\"\n @type name: str\n @type attr: str\n @rtype: str\n \"\"\"\n return self.attr(name, attr).get('type', None)\n\n def attrValue(self, name, attr):\n \"\"\"\n @type name: str\n @type attr: str\n @rtype: str | int | float\n \"\"\"\n return self.attr(name, attr).get('value', None)\n\n @mutils.timing\n def load(self, objects = None, namespaces = None, attrs = None, blend = 100, key = False, refresh = False, ignoreConnected = False, onlyConnected = False, cache = True, mirrorTable = None, mirror = False):\n \"\"\"\n @type objects: list[str]\n @type namespaces: list[str]\n @type attrs: list[str]\n @type blend: float\n @type key: bool\n @type refresh: bool\n @type mirrorTable: mutils.MirrorTable\n \"\"\"\n if mirror and not mirrorTable:\n log.warning('Cannot mirror pose without a mirror table!')\n mirror = False\n self.updateCache(objects=objects, namespaces=namespaces, dstAttrs=attrs, ignoreConnected=ignoreConnected, onlyConnected=onlyConnected, cache=cache, mirrorTable=mirrorTable)\n self.loadCache(blend=blend, key=key, mirror=mirror)\n if refresh:\n maya.cmds.refresh(cv=True)\n\n def updateCache(self, objects = None, namespaces = None, dstAttrs = None, ignoreConnected = False, onlyConnected = False, cache = True, mirrorTable = None):\n \"\"\"\n @type objects: list[str]\n @type namespaces: list[str]\n @type dstAttrs: list[str]\n \"\"\"\n cacheKey = str(objects) + str(namespaces) + str(dstAttrs) + str(ignoreConnected) + str(maya.cmds.currentTime(query=True))\n if self._cacheKey != cacheKey or not cache:\n self._cache = []\n self._cacheKey = cacheKey\n dstObjects = objects\n srcObjects = self.objects()\n usingNamespaces = not objects and namespaces\n if mirrorTable:\n self.setMirrorTable(mirrorTable)\n mutils.matchObjects(srcObjects, dstObjects=dstObjects, dstNamespaces=namespaces, callback=self.cacheNode, dstAttrs=dstAttrs, ignoreConnected=ignoreConnected, onlyConnected=onlyConnected, usingNamespaces=usingNamespaces)\n if not self.cache():\n raise mutils.NoMatchFoundError('No objects match when loading data')\n\n def setMirrorAxis(self, name, mirrorAxis):\n \"\"\"\n @type name: str\n @type mirrorAxis: list[int]\n \"\"\"\n if name in self.objects():\n self.object(name).setdefault('mirrorAxis', mirrorAxis)\n else:\n log.debug('Object does not exist in pose. Cannot set mirror axis for %s' % name)\n\n def mirrorAxis(self, name):\n \"\"\"\n @rtype: list[int] | None\n \"\"\"\n result = None\n if name in self.objects():\n result = self.object(name).get('mirrorAxis', None)\n if result is None:\n log.debug('Cannot find mirror axis in pose for %s' % name)\n return result\n\n def mirrorTable(self):\n \"\"\"\n @rtype: mutils.MirrorTable\n \"\"\"\n return self._mirrorTable\n\n def setMirrorTable(self, mirrorTable):\n \"\"\"\n @type mirrorTable: mutils.MirrorTable\n \"\"\"\n self._mirrorTable = mirrorTable\n mirrorTable.matchObjects(objects=self.objects().keys(), callback=self.updateMirrorAxis)\n\n def updateMirrorAxis(self, srcNode, dstNode, mirrorAxis):\n \"\"\"\n @type srcNode: mutils.Node\n @type mirrorAxis: list[int]\n \"\"\"\n self.setMirrorAxis(dstNode, mirrorAxis)\n\n def cacheNode(self, srcNode, dstNode, dstAttrs = None, ignoreConnected = None, onlyConnected = None, usingNamespaces = None):\n \"\"\"\n @type srcNode: mutils.Node\n @type dstNode: mutils.Node\n \"\"\"\n mirrorAxis = None\n mirrorObject = None\n dstNode.stripFirstPipe()\n if self.mirrorTable():\n mirrorObject = self.mirrorTable().mirrorObject(srcNode.name())\n if not mirrorObject:\n mirrorObject = srcNode.name()\n log.debug('Cannot find mirror object in pose for %s' % srcNode.name())\n mirrorAxis = self.mirrorAxis(mirrorObject) or self.mirrorAxis(srcNode.name())\n if mirrorObject and not maya.cmds.objExists(mirrorObject):\n log.debug('Mirror object does not exist in the scene %s' % mirrorObject)\n if usingNamespaces:\n try:\n dstNode = dstNode.toShortName()\n except mutils.NoObjectFoundError as msg:\n log.debug(msg)\n return\n except mutils.MoreThanOneObjectFoundError as msg:\n log.debug(msg)\n return\n\n for attr in self.attrs(srcNode.name()):\n if dstAttrs and attr not in dstAttrs:\n continue\n dstAttribute = mutils.Attribute(dstNode.name(), attr)\n isConnected = dstAttribute.isConnected()\n if ignoreConnected and isConnected or onlyConnected and not isConnected:\n continue\n type_ = self.attrType(srcNode.name(), attr)\n value = self.attrValue(srcNode.name(), attr)\n srcMirrorValue = self.attrMirrorValue(mirrorObject, attr, mirrorAxis=mirrorAxis)\n srcAttribute = mutils.Attribute(dstNode.name(), attr, value=value, type=type_)\n dstAttribute.update()\n self._cache.append((srcAttribute, dstAttribute, srcMirrorValue))\n\n def attrMirrorValue(self, name, attr, mirrorAxis):\n \"\"\"\n @type name: str\n @type attr: str\n @type mirrorAxis: list[]\n @rtype: None | int | float\n \"\"\"\n value = None\n if self.mirrorTable() and name:\n value = self.attrValue(name, attr)\n if value is not None:\n value = self.mirrorTable().formatValue(attr, value, mirrorAxis)\n else:\n log.debug('cannot find mirror value for %s.%s' % (name, attr))\n return value\n\n def loadCache(self, blend = 100, key = False, mirror = False):\n \"\"\"\n @type blend: float\n @type key: bool\n \"\"\"\n cache = self.cache()\n for i in range(0, len(cache)):\n srcAttribute, dstAttribute, srcMirrorValue = cache[i]\n if srcAttribute and dstAttribute:\n if mirror and srcMirrorValue is not None:\n value = srcMirrorValue\n else:\n value = srcAttribute.value()\n try:\n dstAttribute.set(value, blend=blend, key=key)\n except (ValueError, RuntimeError):\n cache[i] = (None, None)\n log.debug('Ignoring %s.' % dstAttribute.fullname())\n","sub_path":"packages/mutils/pose.py","file_name":"pose.py","file_ext":"py","file_size_in_byte":10774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"593709502","text":"#!/usr/bin/env python\nimport MySQLdb\nimport yaml\nimport re\nimport os\n\n# import json\n# db = MySQLdb.connect(\"bol-db-products-prod-01.ecmwf.int\", \"ecmwf_ro\", \"ecmwf_ro\", \"param\")\ndb = MySQLdb.connect(\"k8s-bol-webapps-test-worker-016.ecmwf.int\", \"products\", \"products\", \"param\", port=30544)\n# db = MySQLdb.connect(\"k8s-bol-webapps-prod-worker-012.ecmwf.int\", \"products\", \"products\", \"param\", port=30545)\n \nPRODGEN = {}\nif os.path.exists(\"prodgen-paramids.yaml\"):\n with open(\"prodgen-paramids.yaml\") as f:\n PRODGEN = yaml.load(f.read(), Loader=yaml.FullLoader)\n\n# print(json.dumps(PRODGEN))\n\nPARAMSIDS = {}\nif os.path.exists(\"paramids.yaml\"):\n with open(\"paramids.yaml\") as f:\n PARAMSIDS = yaml.load(f.read(), Loader=yaml.FullLoader)\n\ncursor = db.cursor()\n\ncursor.execute(\"select * from param\")\n\nfor data in cursor.fetchall():\n paramid, abbr, longname = int(data[0]), data[1].lower(), data[2].lower()\n\n abbr = re.sub(r\"\\W\", \"_\", abbr)\n abbr = re.sub(r\"_+\", \"_\", abbr)\n abbr = re.sub(r\"^_\", \"\", abbr)\n abbr = re.sub(r\"_$\", \"\", abbr)\n\n if not abbr:\n abbr = \"_param_%06d\" % (paramid,)\n\n entry = [abbr.strip(), longname.strip()]\n\n if paramid in PRODGEN:\n pgen = [str(x).lower() for x in PRODGEN[paramid]]\n p = []\n for n in pgen:\n if (\n n not in entry\n ): # and (' ' not in n) and ('.' not in n): # and ('-' not in n):\n entry.append(n)\n p.append(n)\n\n entry = tuple(entry)\n\n if paramid in PARAMSIDS:\n before = tuple(PARAMSIDS[paramid])\n if before != entry:\n print(\n \"WARNING! updated paramid: {}, {} => {}\".format(paramid, before, entry)\n )\n PARAMSIDS[paramid] = list(entry)\n else:\n print(\"new paramid: {} {}\".format(paramid, entry))\n PARAMSIDS[paramid] = list(entry)\n\ncursor.close()\ndb.close()\n\n\nfor paramid, entry in PRODGEN.items():\n if paramid not in PARAMSIDS:\n print(\"WARNING! adding pseudo-paramid: {}, {}\".format(paramid, tuple(entry)))\n PARAMSIDS[paramid] = entry\n\nwith open(\"paramids.yaml\", \"w\") as f:\n f.write(\n \"# File automatically generated by %s\\n# Do not edit\\n\\n\"\n % (os.path.basename(__file__))\n )\n f.write(yaml.safe_dump(PARAMSIDS, default_flow_style=False))\n","sub_path":"share/metkit/make-paramids-yaml-esuite.py","file_name":"make-paramids-yaml-esuite.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"132709075","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/16 22:50\n# @Author : Evescn\n# @Site : \n# @File : 多进程queue.py\n# @Software: PyCharm\n\nfrom multiprocessing import Process, Queue\n\n\ndef f(q):\n q.put([42, None, 'hello'])\n\ndef f2(q):\n # print('from f2:',q.get()) # prints \"[42, None, 'hello']\"\n q.put([42, None, 'hello'])\n print('from f21:', q.get()) # prints \"[42, None, 'hello']\"\n\nif __name__ == '__main__':\n q = Queue()\n p = Process(target=f, args=(q,))\n p.start()\n print('from parent1:', q.get()) # prints \"[42, None, 'hello']\"\n p.join()\n\n p2 = Process(target=f2, args=(q,))\n p2.start()\n print('from parent2:',q.get()) # prints \"[42, None, 'hello']\"\n p2.join()","sub_path":"day8/多进程queue.py","file_name":"多进程queue.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"87720264","text":"import os\n\nimport torch\nfrom torch import optim\nfrom torch.utils.data import sampler\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom common import use_cuda\nfrom widgets import init_pars\nimport os.path as osp\nimport pickle as pkl\nfrom torch.utils.data import Dataset, DataLoader\nimport random\nfrom copy import deepcopy\n\n\nclass LocalDataset(Dataset):\n\n def __init__(self, root_dir):\n \"\"\"\n :param root_dir: the root directory files saved in\n \"\"\"\n super()\n self.root_dir = root_dir\n\n for i, (root, dirs, files) in enumerate(os.walk(self.root_dir)):\n if i == 0:\n self.index_entries = [osp.join(root, filen) for filen in files] \n else:\n print('Directory structure not expected!')\n raise AssertionError()\n random.shuffle(self.index_entries)\n\n def __len__(self):\n return len(self.index_entries)\n\n def __getitem__(self, idx):\n \"\"\"\n\n :param idx:\n :return: (resized img, class)\n \"\"\"\n with open(self.index_entries[idx], 'rb') as f:\n data = pkl.load(f)\n\n return data\n\n\nclass Worker:\n def __init__(self, identifier, dir=osp.join('data', 'debug')):\n self.data_dir = osp.join(dir, str(identifier))\n if not osp.exists(self.data_dir):\n print(f\"Given worker {self.data_dir} doesn't have its data partitioned\")\n raise AssertionError()\n self.dataset = LocalDataset(self.data_dir)\n\n @property\n def num_samples(self):\n return len(self.dataset)\n\n def train(self, model, criterion, current_lr, num_epoches, batch_size=5, verbose=False):\n \"\"\"\n new grads are logged in model itself\n :param num_its: the number of iterations to train locally\n :param current_lr: current learning rate\n :param model: model to be trained in place\n :param criterion:\n :return: model update\n \"\"\"\n running_model = deepcopy(model)\n\n loader = DataLoader(self.dataset, batch_size=batch_size, shuffle=True)\n\n if use_cuda:\n device = torch.device('cuda')\n else:\n device = torch.device('cpu')\n\n running_model = running_model.to(device)\n optimizer = optim.SGD(running_model.parameters(), lr=current_lr)\n\n for epoch in range(num_epoches):\n for it, data in enumerate(loader): # _ start from 0\n inputs, labels = data\n if use_cuda:\n inputs = inputs.to(device=torch.device('cuda'))\n labels = labels.to(device=torch.device('cuda'))\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = running_model(inputs)\n loss = criterion(outputs, labels)\n\n if verbose:\n print(f'Epoch: {epoch}, it: {it}, loss: {loss.item()}')\n\n loss.backward()\n optimizer.step()\n \n return [new_par.data - old_par.data for new_par, old_par in zip(running_model.parameters(), model.parameters())]\n\n\ndef _test():\n worker = Worker(0)\n from model import CNNCifar\n from torch import nn\n\n net = CNNCifar()\n worker.train_(net, nn.CrossEntropyLoss(), 0.01, 10, 5, True)\n\n\nif __name__ == '__main__':\n _test()\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"91220882","text":"#! python3\n\"\"\"\nAqui serão definidas funções singulares que serão utilizadas como auxílio para outras funções ou classes\ndefinidas\n\"\"\"\nfrom math import pi,radians,sin,cos,atan2, sqrt, modf\nimport re, constantes\n\n\n\"\"\"\nCalcula a distância de linha reta entre 2 pontos.\nParâmetros: coordenadas1 - Tupla com as coordenadas, em graus, de um ponto\n coordenadas2 - Tupla com as coordenadas, em graus, de outro ponto\n\nretorno: Valor, em quilômetros, da distância entre os pontos\n\nAutor: https://stackoverflow.com/a/365853\n\"\"\"\ndef calcula_distancia(coordenadas1:tuple,coordenadas2:tuple):\n #Calcula a diferença de latitude e longetude em radianos\n diferenca_latitude = radians(coordenadas2[0] - coordenadas1[0])\n diferenca_longetude = radians(coordenadas2[1] - coordenadas1[1])\n \n # Calcula o radiano para os graus de latitude dos dois pontos\n latitude1 = radians(coordenadas1[0])\n latitude2 = radians(coordenadas2[0])\n\n # Calculo da distância, Eu particularmente não entendo\n angulo = sin(diferenca_latitude / 2) * sin(diferenca_latitude / 2) + \\\n sin(diferenca_longetude / 2) * sin(diferenca_longetude / 2 ) * \\\n cos(latitude1) * cos(latitude2)\n calculo = 2 * atan2(sqrt(angulo),sqrt(1-angulo))\n\n # Retorna o calculo considerando o raio da terra na equação devido a circunferÊncia.\n return calculo * constantes.RAIO_DA_TERRA\n\n\"\"\"\nFunção para converter os valores GMS para graus\nParâmetros: coordenada - Uma tupla com a latitude e a longetude em GMS (e.g. 0°0'0\"N)\n\nretorno: Uma tupla com os valores em graus\n\"\"\"\ndef converte_GMS_Graus(coordenada:tuple):\n # salva os valores de latitude e longetude em variáveis para melhor manipulação\n latitude = coordenada[0]\n longetude = coordenada[1]\n \n # Separa a latitude GMS em tokens com os valores de cada elemento (grau, minuto, segundo e direção)\n tokens = re.split(\"[° \\' \\\"]\",latitude)\n \n # Calcula os graus da latitude\n grausL = int(tokens[0]) + int(tokens[1]) / 60 + int(tokens[2]) / 3600\n # Define o sinal de acordo com a direção\n grausL = grausL if tokens[3] == \"N\" else grausL * -1 \n\n # Separa a longetude GMS em tokens com os valores de cada elemento (grau, minuto, segundo e direção)\n tokens = tokens = re.split(\"[° \\' \\\"]\",longetude)\n \n # Calcula os graus da longetude\n grausLo = int(tokens[0]) + int(tokens[1]) / 60 + int(tokens[2]) / 3600\n # Define o sinal de acordo com a direção\n grausLo = grausLo if tokens[3] == \"E\" else grausLo * -1 \n\n # Retorna Tupla com os valores em graus\n return (grausL,grausLo)\n \n\"\"\"\nFunção para converter de Graus para o formato GMS (e.g 0°0'0\"N)\nParâmetros: coordenada - Uma tupla com a coordenada em graus\n\nretorno: uma tupla com a coordenada no formato GMS\n\"\"\"\ndef converte_Graus_GMS(coordenada:tuple):\n # Separa latitude e longetude para maior clareza\n latitude = coordenada[0]\n longetude = coordenada[1]\n \n # Obtem a direção a partir do sinal e remove-o do valor\n direcaoL, latitude = (\"N\", latitude) if latitude > 0 else (\"S\", latitude * (-1))\n\n # Separa parte inteira e decimal do valor original.\n # O Formato GMS só salva os valores inteiros para os graus e os minutos.\n # Os segundos mantém a parte decimal\n separacao = modf(latitude)\n # Salva a parte inteira dos graus\n grausL = separacao[1]\n\n # Os minutos são obtidos multiplicando a parte decimal por 60\n # Como foi previamente descrito, apenas a parte inteira importa para os minutos\n separacao = modf(separacao[0]*60)\n # Salva a parte inteira como minutos\n minutosL = separacao[1]\n\n # Os segundos utilizam a parte decimal dos minutos multiplicada por 60\n # Os segundos mantem todo o valor obtido.\n segundosL = separacao[0]*60\n \n # Obtem a direção a partir do sinal e remove-o do valor\n direcaoLo, longetude = (\"E\", longetude) if longetude > 0 else (\"W\", longetude * (-1))\n\n # Separa parte inteira e decimal do valor original.\n # O Formato GMS só salva os valores inteiros para os graus e os minutos.\n # Os segundos mantém a parte decimal\n separacao = modf(longetude)\n # Salva a parte inteira dos graus\n grausLo = separacao[1]\n\n # Os minutos são obtidos multiplicando a parte decimal por 60\n # Como foi previamente descrito, apenas a parte inteira importa para os minutos\n separacao = modf(separacao[0]*60)\n # Salva a parte inteira como minutos\n minutosLo = separacao[1]\n\n # Os segundos utilizam a parte decimal dos minutos multiplicada por 60\n # Os segundos mantem todo o valor obtido.\n segundosLo = separacao[0]*60\n\n # Retorna uma tupla no formato GMS\n return (str(grausL) + \"°\" + str(minutosL) + \"'\" + \"{0:.1f}\".format(segundosL) + \"\\\"\" + direcaoL, str(grausLo) + \"°\" + str(minutosLo) + \"'\" + \"{0:.1f}\".format(segundosLo) + \"\\\"\" + direcaoLo)","sub_path":"funcoes_genericas.py","file_name":"funcoes_genericas.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"228222465","text":"from art.unittest_lib import testflow\n\nfrom reports.reports_base import ReportsTest\nimport config\n\n\nclass LoggingTest(ReportsTest):\n \"\"\"Base class for logging test\"\"\"\n @staticmethod\n def assert_grep_diff_logs(\n search,\n log_file=config.DWH_LOG,\n backup_log_file=config.DWH_LOG_BACKUP,\n lines=0\n ):\n \"\"\"\n Grep diff of two log files\n\n Args:\n search (str): grepped string\n log_file (str): log file\n backup_log_file (str): backup of the same log file from past\n lines (int): append number of lines to grep\n Returns\n str: return grepped string from diff of two files\n \"\"\"\n testflow.step(\"Grepping dwh log\")\n cmd = [\n 'diff', '-e', backup_log_file, log_file, '|',\n 'grep', '-F', search, '-A' + str(lines), '|',\n 'grep', '-Fv', 'tWarn'\n ]\n result = config.ENGINE_HOST.run_command(command=cmd)\n assert not result[0]\n\n return result[1]\n\n @staticmethod\n def assert_backup_file(file_name, backup_file):\n \"\"\"\n Create a backup for file\n\n Args:\n file (str): file to be backed up\n backup_file (str): service that should run\n \"\"\"\n testflow.step(\"Backing up %s log to %s\", file_name, backup_file)\n cmd = ['cp', file_name, backup_file]\n assert config.ENGINE_HOST.run_command(command=cmd), (\n \"Error: Unable to backup {0}\".format(file_name)\n )\n\n @staticmethod\n def assert_remove_backup(file_name):\n \"\"\"\n Remove backup file\n\n Args:\n file (str): backed up file to be removed\n \"\"\"\n testflow.step(\"Removing backup {0}\".format(file_name))\n assert config.ENGINE_HOST.run_command(['rm', file_name])\n\n @staticmethod\n def assert_setting_variable(settings, var, val):\n \"\"\"\n Check value of application server variable\n\n Args:\n settings (dict): dictionary with settings 'key':value\n var (str): variable to find\n val (str): value to check\n \"\"\"\n assert var in settings.keys(), \"Variable {0} not found.\".format(var)\n assert val in settings[var], (\n \"Option {0} with value {1} not in: {2}\".format(var, val, settings)\n )\n","sub_path":"art/tests/rhevmtests/integration/reports/logging/logging_base.py","file_name":"logging_base.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"449696871","text":"\n\n#calss header\nclass _REGISTRAR():\n\tdef __init__(self,): \n\t\tself.name = \"REGISTRAR\"\n\t\tself.definitions = [u'an official whose job is to keep official records, especially of births, deaths, and marriages', u'at some colleges, an official in charge of exams, keeping records, and new students', u'a type of hospital doctor: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_registrar.py","file_name":"_registrar.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"153004146","text":"from requests import get\nimport requests.exceptions\nimport logging\nfrom time import sleep\nimport re\n\n\nAPI_URL = \"https://api.freelancehunt.com/v2\"\nEVENT_TEMPLATE = '{type} {login} {message}'\nOK, NETWORK_ERROR, TOKEN_ERROR, TOO_MANY_REQUESTS = range(4)\nlogger = logging.getLogger(__name__)\n\n\ndef _api_get(token, rel_url=\"/\"):\n return get(API_URL + rel_url, headers={'Authorization': f'Bearer {token}'})\n\n\ndef validate(token):\n try:\n response = _api_get(token)\n except requests.exceptions.RequestException as error:\n return NETWORK_ERROR\n res = response.json()\n if 'error' in res and response.status_code != 404:\n if response.status_code == 429:\n logger.warning(\"Server returned 'Too Many Requests' for validation query for user with token %s...\",\n token[:len(token) // 2])\n return TOO_MANY_REQUESTS\n logger.warning(\"Received error '%s' for token %s...\", res['error'], token[:len(token) // 2])\n return TOKEN_ERROR\n else:\n return OK\n\n\ndef _get_feed(token):\n try:\n response = _api_get(token, \"/my/feed\")\n except requests.exceptions.RequestException as error:\n logger.critical(\"Request raised error '%s'. Returned 'NETWORK_ERROR'\", error)\n return NETWORK_ERROR\n feed = response.json()\n if 'error' in feed and response.status_code != 404:\n if response.status_code == 429:\n logger.warning(\"Server returned 'Too Many Requests' for validation query for user with token %s...\",\n token[:len(token) // 2])\n return TOO_MANY_REQUESTS\n logger.warning(\"Received error '%s' for token %s...\", feed['error'], token[:len(token) // 2])\n return TOKEN_ERROR\n return _prepare_feed(feed)\n\n\ndef _prepare_event_msg(text):\n msg = re.sub(r\"\", \"\", text)\n msg = re.sub(r'', lambda m: f'', msg)\n return msg\n\n\ndef _prepare_feed(feed):\n events = []\n for i in feed['data']:\n attrs = i['attributes']\n if not attrs['is_new']:\n break\n from_type = \"закачкик\" if attrs['from']['type'] == \"employer\" else \"исполнитель\"\n login = attrs['from']['login']\n msg = _prepare_event_msg(attrs['message'])\n event = EVENT_TEMPLATE.format(type=from_type, login=login, message=msg)\n events.append(event)\n return events[::-1]\n\n\ndef _get_threads(token):\n try:\n response = _api_get(token, \"/threads\")\n except requests.exceptions.RequestException as error:\n logger.critical(\"Request raised error '%s'. Returned 'NETWORK_ERROR'\", error)\n return NETWORK_ERROR\n threads = response.json()\n if 'error' in threads and response.status_code != 404:\n if response.status_code == 429:\n logger.warning(\"Server returned 'Too Many Requests' for validation query for user with token %s...\",\n token[:len(token) // 2])\n return TOO_MANY_REQUESTS\n logger.warning(\"Received error '%s' for token %s...\", msgs['error'], token[:len(token) // 2])\n return TOKEN_ERROR\n return threads['data']\n\n\ndef _get_message(token):\n return \"some text\"\n\n\ndef _get_messages(token):\n threads = _get_threads(token)\n msgs = []\n for thread in threads:\n attrs = thread['attributes']\n if not attrs['is_unread']:\n continue\n\n\n\ndef get_updates(settings):\n token = settings['token']\n logger.debug(\"Starting 'get_updates' for token %s...\", token[:len(token) // 2])\n validation = validate(token)\n if validation == TOO_MANY_REQUESTS:\n sleep(20)\n return get_updates(settings)\n elif validation != OK:\n return validation\n\n feed = _get_feed(token)\n if not isinstance(feed, list):\n return feed\n return feed\n\n\nif __name__ == \"__main__\":\n TEST_TOKEN = \"a10207aff6d23d9d735bcd6e36eefa9f2ba2a0d0\"\n TEST_SETTINGS = {\n 'token': TEST_TOKEN\n }\n TEST_MSG = 'От закачкика freelancehunt:\\nИтоги 2019 года Freelancehunt: рекорды в цифрах! '\n #print(get_updates(TEST_SETTINGS))\n #print(_get_feed(TEST_TOKEN))\n print(_get_threads(TEST_TOKEN))\n #print(_prepare_msg(TEST_MSG))\n","sub_path":"app/fhapi.py","file_name":"fhapi.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"586549671","text":"'''\nSingle-pole balancing experiment using a continuous-time recurrent neural network (CTRNN).\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport pickle\n\nimport cart_pole\n\nfrom neatsociety import ctrnn, parallel, population, visualize\nfrom neatsociety.config import Config\nfrom neatsociety.math_util import mean\n\nruns_per_net = 5\nnum_steps = 60000 # equivalent to 1 minute of simulation time\n\n\n# Use the CTRNN network phenotype and the discrete actuator force function.\ndef evaluate_genome(g):\n net = ctrnn.create_phenotype(g)\n\n fitnesses = []\n\n for runs in range(runs_per_net):\n sim = cart_pole.CartPole()\n\n # Run the given simulation for up to num_steps time steps.\n fitness = 0.0\n for s in range(num_steps):\n inputs = sim.get_scaled_state()\n action = net.parallel_activate(inputs)\n\n # Apply action to the simulated cart-pole\n force = cart_pole.discrete_actuator_force(action)\n sim.step(force)\n\n # Stop if the network fails to keep the cart within the position or angle limits.\n # The per-run fitness is the number of time steps the network can balance the pole\n # without exceeding these limits.\n if abs(sim.x) >= sim.position_limit or abs(sim.theta) >= sim.angle_limit_radians:\n break\n\n fitness += 1.0\n\n fitnesses.append(fitness)\n\n # The genome's fitness is its worst performance across all runs.\n return min(fitnesses)\n\n\n# Load the config file, which is assumed to live in\n# the same directory as this script.\nlocal_dir = os.path.dirname(__file__)\nconfig = Config(os.path.join(local_dir, 'ctrnn_config'))\nconfig.node_gene_type = ctrnn.CTNodeGene\n\npop = population.Population(config)\npe = parallel.ParallelEvaluator(evaluate_genome)\npop.run(pe.evaluate, 2000)\n\n# Save the winner.\nprint('Number of evaluations: {0:d}'.format(pop.total_evaluations))\nwinner = pop.statistics.best_genome()\nwith open('ctrnn_winner_genome', 'wb') as f:\n pickle.dump(winner, f)\n\nprint(winner)\n\n# Plot the evolution of the best/average fitness.\nvisualize.plot_stats(pop.statistics, ylog=True, filename=\"ctrnn_fitness.svg\")\n# Visualizes speciation\nvisualize.plot_species(pop.statistics, filename=\"ctrnn_speciation.svg\")\n# Visualize the best network.\nvisualize.draw_net(winner, view=True, filename=\"ctrnn_winner.gv\")\n","sub_path":"examples/pole_balancing/single_pole/ctrnn_evolve.py","file_name":"ctrnn_evolve.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"223281726","text":"#!/usr/bin/python3\n\"\"\"\nThis module contains Fabric script that creates and distributes an archive\nto the web servers, using the function deploy\n\"\"\"\nfrom fabric.api import *\nenv.user = 'ubuntu'\nenv.hosts = ['52.71.155.152', '184.72.141.74']\n\n\ndef do_clean(number=0):\n \"\"\"\n clean local archive and server\n \"\"\"\n num = int(number)\n if num == 0:\n num += 1\n files = local(\"ls -tr versions\", capture=True).split(\"\\n\")\n if len(files) > num:\n for file in files[:num]:\n local(\"rm -f versions/{}\".format(file))\n with cd(\"/data/web_static/releases\"):\n files = sudo(\"ls -tr\").split(\" \")\n files = [file for file in files if file != '']\n print(files)\n print(len(files))\n if len(files) > num:\n for file in files[:num]:\n print(file)\n run(\"sudo rm -rf {}\".format(file))\n","sub_path":"100-clean_web_static.py","file_name":"100-clean_web_static.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"311421251","text":"#pylint:disable=W0312\nx=(int(input('Enter number of team:')))\ny=list(range(1,x+1))\nbyes=0\nbyes_from=[2,4,8,16,32]\nbyes_form_index=[1,-1,2,-2,3,-3,4,-4,5,-5]\nprint(\"Team in Fixture\",y)\nupper_half=y[0:int(((len(y)+1)/2))]\nprint(\"Upper Half:\",upper_half)\nupper_half.insert(0,0)\nlower_half=y[int(((len(y)+1)/2)):]\nprint(\"Lower Half:\",lower_half)\nlower_half.insert(0,0)\nfor i in byes_from:\n\tif x>i and x< byes_from[byes_from.index(i)+1]:\n\t \t\tbyes=byes_from[byes_from.index(i)+1]-x\nprint(\"Byes=\",byes)\ndef give_byes(byes):\n\tfor i in byes_form_index:\n\t\t if byes !=0:\n\t\t \tn=-i\n\t\t \t#lower_half.remove(lower_half[n])\n\t\t \t#lower_half.insert(n,\"Byes\")\n\t\t \tlower_half[n]=\"byes\"\n\t\t \tbyes-=1\n\t\t else:\n\t\t \t return \n\t\t if byes !=0:\n\t\t \tj=-(-i)\n\t\t \t#upper_half.remove(upper_half[j])\n\t\t \t#upper_half.insert(j,\"byes\")\n\t\t \tupper_half[j]=\"byes\"\n\t\t \tbyes-=1\n\t\t else:\n\t\t \treturn\ngive_byes(byes)\nupper_half.remove(0)\nlower_half.remove(0)\nprint(\"-\"*15)\nprint(\"Teams\")\nprint(\"-\"*15)\nfor k in upper_half:\n\tprint(k)\nprint(\"-\"*15)\nfor s in lower_half:\n\tprint(s)","sub_path":"corr.py","file_name":"corr.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"638723367","text":"\"\"\"\nCreated by Alex Hopkins\non 10/19/18\n\nElectricity and magnetism model test functions\n\"\"\"\nimport models.em.em_model as emm\nimport unittest\n\n\nclass TestEM(unittest.TestCase):\n\n def test_coulomb_force(self):\n \"\"\"\n Tests the coulomb force between two charges. The asserted values are calculated by hand using the equation\n F = k * q_1 * q_2 / r ** 2\n \"\"\"\n print(emm.coulomb_force(1.6e-19, -1.6e-19, 1))\n self.assertAlmostEqual(emm.coulomb_force(1.6e-19, -1.6e-19, 1), -2.3e-28, places=3)\n\n def test_n_electric_field(self):\n nq = 2\n emm.n_electric_field(nq)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"models/em/tests/electricity_magnetism_model_test.py","file_name":"electricity_magnetism_model_test.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"619601740","text":"from app.models.endpoint import Endpoint\nfrom bs4 import BeautifulSoup, NavigableString\nimport html\nimport os\nimport urllib.parse as urlparse\nfrom urllib.parse import parse_qs\nimport re\n\nSKIP_ARGS = ['ref_src', 'utm']\nSKIP_PREFIX = ['//www.', '//mobile.', '//m.']\nGOOG_STATIC = 'www.gstatic.com'\nGOOG_IMG = '/images/branding/searchlogo/1x/googlelogo'\nLOGO_URL = GOOG_IMG + '_desk'\nBLANK_B64 = ('data:image/png;base64,'\n 'iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAQAAAAnOwc2AAAAD0lEQVR42mNkw'\n 'AIYh7IgAAVVAAuInjI5AAAAAElFTkSuQmCC')\n\n# Ad keywords\nBLACKLIST = [\n 'ad', 'anuncio', 'annuncio', 'annonce', 'Anzeige', '广告', '廣告', 'Reklama',\n 'Реклама', 'Anunț', '광고', 'annons', 'Annonse', 'Iklan', '広告', 'Augl.',\n 'Mainos', 'Advertentie', 'إعلان', 'Գովազդ', 'विज्ञापन', 'Reklam', 'آگهی',\n 'Reklāma', 'Reklaam', 'Διαφήμιση', 'מודעה', 'Hirdetés', 'Anúncio'\n]\n\nSITE_ALTS = {\n 'twitter.com': os.getenv('WHOOGLE_ALT_TW', 'nitter.net'),\n 'youtube.com': os.getenv('WHOOGLE_ALT_YT', 'invidious.snopyta.org'),\n 'instagram.com': os.getenv('WHOOGLE_ALT_IG', 'bibliogram.art/u'),\n 'reddit.com': os.getenv('WHOOGLE_ALT_RD', 'libredd.it'),\n **dict.fromkeys([\n 'medium.com',\n 'levelup.gitconnected.com'\n ], os.getenv('WHOOGLE_ALT_MD', 'scribe.rip'))\n}\n\n\ndef bold_search_terms(response: str, query: str) -> BeautifulSoup:\n \"\"\"Wraps all search terms in bold tags (). If any terms are wrapped\n in quotes, only that exact phrase will be made bold.\n\n Args:\n response: The initial response body for the query\n query: The original search query\n\n Returns:\n BeautifulSoup: modified soup object with bold items\n \"\"\"\n response = BeautifulSoup(response, 'html.parser')\n\n def replace_any_case(element: NavigableString, target_word: str) -> None:\n # Replace all instances of the word, but maintaining the same case in\n # the replacement\n if len(element) == len(target_word):\n return\n\n if not re.match('.*[a-zA-Z0-9].*', target_word) or (\n element.parent and element.parent.name == 'style'):\n return\n\n element.replace_with(BeautifulSoup(\n re.sub(fr'\\b((?![{{}}<>-]){target_word}(?![{{}}<>-]))\\b',\n r'\\1',\n html.escape(element),\n flags=re.I), 'html.parser')\n )\n\n # Split all words out of query, grouping the ones wrapped in quotes\n for word in re.split(r'\\s+(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)', query):\n word = re.sub(r'[^A-Za-z0-9 ]+', '', word)\n target = response.find_all(\n text=re.compile(r'' + re.escape(word), re.I))\n for nav_str in target:\n replace_any_case(nav_str, word)\n\n return response\n\n\ndef has_ad_content(element: str) -> bool:\n \"\"\"Inspects an HTML element for ad related content\n\n Args:\n element: The HTML element to inspect\n\n Returns:\n bool: True/False for the element containing an ad\n\n \"\"\"\n return (element.upper() in (value.upper() for value in BLACKLIST)\n or 'ⓘ' in element)\n\n\ndef get_first_link(soup: BeautifulSoup) -> str:\n \"\"\"Retrieves the first result link from the query response\n\n Args:\n soup: The BeautifulSoup response body\n\n Returns:\n str: A str link to the first result\n\n \"\"\"\n # Replace hrefs with only the intended destination (no \"utm\" type tags)\n for a in soup.find_all('a', href=True):\n # Return the first search result URL\n if 'url?q=' in a['href']:\n return filter_link_args(a['href'])\n return ''\n\n\ndef get_site_alt(link: str) -> str:\n \"\"\"Returns an alternative to a particular site, if one is configured\n\n Args:\n link: A string result URL to check against the SITE_ALTS map\n\n Returns:\n str: An updated (or ignored) result link\n\n \"\"\"\n # Need to replace full hostname with alternative to encapsulate\n # subdomains as well\n hostname = urlparse.urlparse(link).hostname\n\n for site_key in SITE_ALTS.keys():\n if not hostname or site_key not in hostname:\n continue\n\n link = link.replace(hostname, SITE_ALTS[site_key])\n for prefix in SKIP_PREFIX:\n link = link.replace(prefix, '//')\n break\n\n return link\n\n\ndef filter_link_args(link: str) -> str:\n \"\"\"Filters out unnecessary URL args from a result link\n\n Args:\n link: The string result link to check for extraneous URL params\n\n Returns:\n str: An updated (or ignored) result link\n\n \"\"\"\n parsed_link = urlparse.urlparse(link)\n link_args = parse_qs(parsed_link.query)\n safe_args = {}\n\n if len(link_args) == 0 and len(parsed_link) > 0:\n return link\n\n for arg in link_args.keys():\n if arg in SKIP_ARGS:\n continue\n\n safe_args[arg] = link_args[arg]\n\n # Remove original link query and replace with filtered args\n link = link.replace(parsed_link.query, '')\n if len(safe_args) > 0:\n link = link + urlparse.urlencode(safe_args, doseq=True)\n else:\n link = link.replace('?', '')\n\n return link\n\n\ndef append_nojs(result: BeautifulSoup) -> None:\n \"\"\"Appends a no-Javascript alternative for a search result\n\n Args:\n result: The search result to append a no-JS link to\n\n Returns:\n None\n\n \"\"\"\n nojs_link = BeautifulSoup(features='html.parser').new_tag('a')\n nojs_link['href'] = f'/{Endpoint.window}?location=' + result['href']\n nojs_link.string = ' NoJS Link'\n result.append(nojs_link)\n\n\ndef add_ip_card(html_soup: BeautifulSoup, ip: str) -> BeautifulSoup:\n \"\"\"Adds the client's IP address to the search results\n if query contains keywords\n\n Args:\n html_soup: The parsed search result containing the keywords\n ip: ip address of the client\n\n Returns:\n BeautifulSoup\n\n \"\"\"\n if (not html_soup.select_one(\".EY24We\")\n and html_soup.select_one(\".OXXup\").get_text().lower() == \"all\"):\n # HTML IP card tag\n ip_tag = html_soup.new_tag(\"div\")\n ip_tag[\"class\"] = \"ZINbbc xpd O9g5cc uUPGi\"\n\n # For IP Address html tag\n ip_address = html_soup.new_tag(\"div\")\n ip_address[\"class\"] = \"kCrYT ip-address-div\"\n ip_address.string = ip\n\n # Text below the IP address\n ip_text = html_soup.new_tag(\"div\")\n ip_text.string = \"Your public IP address\"\n ip_text[\"class\"] = \"kCrYT ip-text-div\"\n\n # Adding all the above html tags to the IP card\n ip_tag.append(ip_address)\n ip_tag.append(ip_text)\n\n # Finding the element before which the IP card would be placed\n f_link = html_soup.select_one(\".BNeawe.vvjwJb.AP7Wnd\")\n ref_element = f_link.find_parent(class_=\"ZINbbc xpd O9g5cc\" +\n \" uUPGi\")\n\n # Inserting the element\n ref_element.insert_before(ip_tag)\n return html_soup\n","sub_path":"app/utils/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"555222650","text":"# Sean McIlvenny\n# CTEC 121 / Winter 2019\n# Module 4 / Problem Set 5\n# Problem 3 (25 points)\n\n\"\"\"\nDevelop a program that draws some sort of substantial face that includes two eyes, a nose, a mouth with some teeth, two ears and some hair.\n\nYou will find faces that were drawn by students in prior classes in a file named faces.png.\n\"\"\"\n\nfrom graphics import *\n\ndef main():\n win = GraphWin('Faces',800,800)\n\n face = Circle (Point(400,400),200)\n face.setFill('yellow')\n face.draw(win)\n\n \n\n hair = Polygon (Point(585,320),Point(585,140),Point(205,150),Point(215,325),Point(260,260),Point(290,270),Point(375,235),Point(385,260),Point(470,235),Point(580,310))\n hair.setFill('purple')\n hair.setOutline('green')\n hair.draw(win)\n\n eye1 = Circle(Point(300,325),40)\n eye1.setFill('white')\n eye1.draw(win)\n\n eye2 = eye1.clone()\n eye2.move(170,0)\n eye2.draw(win)\n pupil1 = Circle(Point(300,325),15)\n pupil1.setFill('blue')\n pupil1.draw(win)\n pupil2 = pupil1.clone()\n pupil2.setFill('brown')\n pupil2.move(170,0)\n pupil2.draw(win)\n\n nose = Polygon(Point(380,325),Point(340,410),Point(425,410))\n nose.setFill('yellow')\n nose.draw(win)\n\n mouth = Rectangle(Point(310,455),Point(490,540))\n mouth.setFill('black')\n mouth.draw(win)\n\n teethtoprow = Rectangle(Point(310,455),Point(490,475))\n teethtoprow.setFill('white')\n teethtoprow.draw(win)\n teethbottomrow = teethtoprow.clone()\n teethbottomrow.move(0,70)\n teethbottomrow.draw(win)\n\n ear1 = Polygon(Point(585,395),Point(605,310),Point(625,445))\n ear1.setFill('yellow')\n ear1.draw(win)\n ear2 = Polygon(Point(215,390),Point(190,305),Point(175,440))\n ear2.setFill('yellow')\n ear2.draw(win)\n\n\n\n # for i in range(10):\n # point = win.getMouse()\n # x = point.getX()\n # y = point.getY()\n # print(x,y)\n\n\n\n\n\n input('close program')\n win.close()\n\n\nmain()","sub_path":"problem-set-5-problem-3.py","file_name":"problem-set-5-problem-3.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"57203765","text":"\"\"\"\nUsage of the Solar PV dataset\n\n1. Download the github repository: https://github.com/zae-bayern/elpv-dataset\n2. Extract the zip file elpv-dataset-master.zip\n3. Make sure the utils folder and this script are outside the extracted folder.\n4. Run this file.\n\n\"\"\"\n\n\nfrom utils.elpv_reader import load_dataset\nimport cv2\nimport numpy as np\nimport shutil\nimport os\nfrom sklearn.model_selection import train_test_split\n\n\ndestination_folder = 'solar_panels_products_V2'\n\nif not os.path.exists(destination_folder):\n\tos.mkdir(destination_folder)\n\n\n# datafolder is the relative path for the contents in the elpv dataset\n\nimages, probs, types = load_dataset(datafolder = 'elpv_dataset')\n\ntrain_images, test_images, train_probs, test_probs, train_types, test_types = train_test_split(images, probs, types, test_size= 0.1)\n\ndef create_dataset(images, probs, types, split):\n\n\tthreshold = 0.6\n\n\tdata_folder = os.path.join(destination_folder, split)\n\n\tif not os.path.exists(data_folder):\n\t\tos.mkdir(data_folder)\n\n\tidx = 0\n\n\tfor image , prob, type_ in zip(images, probs, types):\n\n\n\t\tif prob > threshold:\n\n\n\t\t\timage = cv2.resize(image, (300, 300)).reshape(300,300,1)\n\n\t\t\tcategory_folder = os.path.join(data_folder, type_ + '_defective')\n\n\t\t\tif not os.path.exists(category_folder):\n\t\t\t\tos.mkdir(category_folder)\n\n\t\t\timage_name = os.path.join( category_folder, 'elpv_' + str(idx) + '.jpg')\n\n\n\t\t\tif not os.path.exists(image_name):\n\n\t\t\t\tcv2.imwrite(image_name, image )\n\n\n\t\tif prob < threshold:\n\n\n\t\t\timage = cv2.resize(image, (300, 300)).reshape(300,300,1)\n\n\t\t\tcategory_folder = os.path.join(data_folder, type_ + '_non_defective')\n\n\t\t\tif not os.path.exists(category_folder):\n\t\t\t\tos.mkdir(category_folder)\n\n\t\t\timage_name = os.path.join( category_folder, 'elpv_' + str(idx) + '.jpg')\n\n\n\t\t\tif not os.path.exists(image_name):\n\n\t\t\t\tcv2.imwrite(image_name, image )\n\n\t\t\n\t\tidx += 1\n\t\t\t\n\ncreate_dataset(train_images, train_probs, train_types, \"train\")\ncreate_dataset(test_images, test_probs, test_types, \"test\")\n\n","sub_path":"1.preprocess_dataset/solar_panels_products_v2.py","file_name":"solar_panels_products_v2.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"630673257","text":"import socket\nimport sys\nimport time\n\n# 创建一个套接字\ns = socket.socket()\n\n# 尝试连接 127.0.0.1 的 6666 端口\ns.connect(('127.0.0.1', 6666))\n\nprint('已连接 127.0.0.1')\n\nmessage = '消息: ' + sys.argv[1]\n\nsleep_seconds = int(sys.argv[2])\ntime.sleep(sleep_seconds)\n\n# 发送消息\ns.send(message.encode('utf8'))\n\n# 接受返回消息\nreply_message = s.recv(1024)\n\nprint(reply_message.decode('utf8'))\n\n# 关闭连接\ns.close()\n","sub_path":"03-GUI/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"446774125","text":"def inversion_count(T):\n def merge(T, temp_T, left, mid, right):\n i = left\n j = mid + 1\n k = left\n inv_count = 0\n\n while i <= mid and j <= right:\n if T[i] <= T[j]:\n temp_T[k] = T[i]\n k += 1\n i += 1\n else:\n temp_T[k] = T[j]\n inv_count += (mid - i + 1)\n k += 1\n j += 1\n\n while i <= mid:\n temp_T[k] = T[i]\n k += 1\n i += 1\n while j <= right:\n temp_T[k] = T[j]\n k += 1\n j += 1\n\n for m in range(left, right + 1):\n T[m] = temp_T[m]\n\n return inv_count\n\n def mergesort(T, temp_T, left, right):\n inv_count = 0\n \n if left < right:\n mid = (left + right)//2\n\n inv_count += mergesort(T, temp_T, left, mid)\n inv_count += mergesort(T, temp_T, mid + 1, right)\n inv_count += merge(T, temp_T, left, mid, right)\n\n return inv_count\n\n n = len(T)\n temp_arr = [0]*n\n\n return mergesort(T, temp_arr, 0, n-1)\n","sub_path":"zestaw_2/zad2.py","file_name":"zad2.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"404130858","text":"class Solution:\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n \n if len(strs) == 0:\n return \"\"\n \n prefix = strs[0]\n \n for i in range(1,len(strs)):\n newprefix = ''\n #print(len(prefix))\n for j in range(min(len(prefix),len(strs[i]))):\n #print(j)\n newstr = prefix[j] if strs[i][j] == prefix[j] else ''\n if newstr == '':\n break\n newprefix = newprefix + newstr\n \n prefix = newprefix\n \n return prefix","sub_path":"leetcode/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"543708111","text":"numlist = list()\r\n\r\nwhile True:\r\n temp = input('Enter a number: ')\r\n if temp == 'done' : break\r\n try:\r\n numlist.append(float(temp))\r\n except:\r\n continue\r\nif len(numlist) > 0:\r\n print('Maximum:', max(numlist))\r\n print('Minimum:', min(numlist))\r\n print('Count: ', len(numlist))\r\nelse : print('You entered no numbers!')\r\n","sub_path":"ex_08_06.py","file_name":"ex_08_06.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"349807446","text":"#####################################\nimport GAME.core\nimport TILEED.core\nimport config\nimport getopt, sys, os\n#####################################\n\ndef main():\n\ttry:\n\t\topts, args = getopt.getopt(sys.argv[1:], \"hev\", [\"help\"])\n\texcept getopt.GetoptError as err:\n\t\tprint(err)\n\t\tsys.exit(2)\n\tverbose = False\n\tstarteditor = False\n\tfor o, a in opts:\n\t\tif o == \"-v\":\n\t\t\tverbose = True\n\t\telif o in (\"-h\", \"--help\"):\n\t\t\tsys.exit()\n\t\telif o in (\"-e\"):\n\t\t\tstarteditor = True\n\t\telse:\n\t\t\tassert False, \"unhandled option\"\n\tif not starteditor:\n\t\tgame = GAME.core.Game(config.Config())\n\t\tgame.start()\n\telse: \n\t\teditor = TILEED.core.TileEditor(config.Config())\n\t\teditor.start()\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"61"} +{"seq_id":"487275919","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\t\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\"\"\"wizard that replace completely the wizard on stock with same name,\nbeacause adds the functionally that set zero prodlotas not products\"\"\"\n\nimport wizard\nimport pooler\nfrom tools.translate import _\n\n\nFORM = \"\"\"\n
\n \n \n \n