diff --git "a/2421.jsonl" "b/2421.jsonl" new file mode 100644--- /dev/null +++ "b/2421.jsonl" @@ -0,0 +1,694 @@ +{"seq_id":"652530831","text":"from . import FixtureTest\n\n\nclass CampGroundsZoom(FixtureTest):\n def test_large(self):\n # update landuse to include campground features and fix label zoom\n # large campground in landuse zoom 16\n self.load_fixtures(['http://www.openstreetmap.org/way/237314510'])\n\n self.assert_has_feature(\n 16, 10599, 25679, 'landuse',\n {'kind': 'camp_site', 'sort_rank': 92})\n\n self.assert_has_feature(\n 16, 10599, 25679, 'pois',\n {'kind': 'camp_site'})\n\n # large campground in landuse zoom 13\n self.assert_has_feature(\n 13, 1324, 3209, 'landuse',\n {'kind': 'camp_site', 'sort_rank': 92})\n\n # large campground in point zoom 13\n self.assert_has_feature(\n 13, 1324, 3209, 'pois',\n {'kind': 'camp_site'})\n\n def test_small(self):\n # small campground in landuse zoom 16\n self.load_fixtures(['http://www.openstreetmap.org/way/417405356'])\n\n self.assert_has_feature(\n 16, 10471, 25326, 'landuse',\n {'kind': 'camp_site', 'sort_rank': 92})\n\n # small campground in point zoom 16\n self.assert_has_feature(\n 16, 10471, 25326, 'pois',\n {'kind': 'camp_site'})\n\n # small campground in landuse zoom 13\n self.assert_has_feature(\n 13, 1308, 3165, 'landuse',\n {'kind': 'camp_site', 'sort_rank': 92})\n\n # small campground in point zoom 13\n self.assert_no_matching_feature(\n 13, 1308, 3165, 'pois',\n {'kind': 'camp_site'})\n","sub_path":"integration-test/875-camp-grounds-zoom.py","file_name":"875-camp-grounds-zoom.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"447712472","text":"#!/usr/bin/python\n\nimport matplotlib.pyplot as plt\nfrom prep_terrain_data import makeTerrainData\nfrom class_vis import prettyPicture\n\nfeatures_train, labels_train, features_test, labels_test = makeTerrainData()\n\n\n### the training data (features_train, labels_train) have both \"fast\" and \"slow\"\n### points mixed together--separate them so we can give them different colors\n### in the scatterplot and identify them visually\ngrade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0]\nbumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0]\ngrade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1]\nbumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1]\n\n\n#### initial visualization\nplt.xlim(0.0, 1.0)\nplt.ylim(0.0, 1.0)\nplt.scatter(bumpy_fast, grade_fast, color = \"b\", label=\"fast\")\n#plt.scatter(grade_slow, bumpy_slow, color = \"b\", label=\"slow\")\nplt.scatter(bumpy_slow, grade_slow, color = \"r\", label=\"slow\")\nplt.legend()\nplt.xlabel(\"bumpiness\")\nplt.ylabel(\"grade\")\nplt.show()\n################################################################################\n\n\n### your code here! name your classifier object clf if you want the \n### visualization code (prettyPicture) to show you the decision boundary\n\nfrom time import time\n\nmethod = 'knn'\n#method = 'random_forest'\n#method = 'adaboost'\n\nif method=='knn':\n # K-Nearest Neighbors Classifier\n from sklearn.neighbors import KNeighborsClassifier\n clf = KNeighborsClassifier(n_neighbors=22, weights='uniform')\nelif method=='random_forest':\n # Random forest\n from sklearn.ensemble import RandomForestClassifier\n clf = RandomForestClassifier(n_estimators=50, min_samples_split=5)\nelif method=='adaboost':\n # Adaboost\n from sklearn.tree import DecisionTreeClassifier\n from sklearn.ensemble import AdaBoostClassifier\n clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(min_samples_split=20) , n_estimators=100)\nelse:\n pass\n\ntry:\n t0 = time()\n clf.fit(features_train, labels_train)\n print('Training time = ', round(time()-t0, 3), 's')\n t0 = time()\n pred_test = clf.predict(features_test)\n print('Testing time = ', round(time()-t0, 3), 's')\n from sklearn.metrics import accuracy_score\n accuracy = accuracy_score(labels_test, pred_test)\n print('Accuracy = ', accuracy)\n\n prettyPicture(clf, features_test, labels_test)\nexcept:\n pass\n\n\n","sub_path":"Mini-Projects/choose_your_own/your_algorithm.py","file_name":"your_algorithm.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"426340314","text":"'''\n2021 02 05 14:33 ~ 42 50점/효율성 0점\n\n해시문제. 리스트 반복문으로 풀면 안됨. 딕셔너리 이용해서 품\n'''\n\ndef solution(participant, completion):\n answer = ''\n participants = dict()\n for name in participant:\n if name in participants:\n participants[name] += 1\n else:\n participants[name] = 1\n \n for name in completion:\n if name in participants:\n participants[name] -= 1\n \n # print(participants)\n \n # value값이 1이상인 값의 key 출력\n for key, value in participants.items():\n if value == 1:\n print(key)\n answer = key\n \n return answer","sub_path":"Level1/03.완주하지못한선수.py","file_name":"03.완주하지못한선수.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"233628214","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\n\nfig, ax = plt.subplots()\n\nx = np.linspace(0, 2 * np.pi, 100)\nline, = ax.plot(x, np.sin(x))\n\n\ndef animate(i):\n line.set_ydata(np.sin(x + i/ 50))\n return line,\n\nani = animation.FuncAnimation(\n fig, animate, interval=16, blit=True, save_count=50)\n\n# to save animation, use e.g.\n# ani.save(\"movie.mp4\")\n#\n# or\n#\n# writer = animation.FFMpegWriter(\n# fps=15, metadata=dict(artist='Me'), bitrate=1800)\n# ani.save(\"movie.mp4\", writer=writer)\n\nplt.show()\n","sub_path":"math/animation/sin.py","file_name":"sin.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"382659819","text":"from django.db.models import Q\n\nfrom rest_framework import filters\n\n\nclass AnonDjangoObjectPermissionFilter(filters.DjangoObjectPermissionsFilter):\n def filter_queryset(self, request, queryset, view):\n \"\"\"\n Anonymous user has no object permissions, return queryset as it is.\n \"\"\"\n user = request.user\n if user.is_anonymous():\n return queryset\n\n return super(AnonDjangoObjectPermissionFilter, self)\\\n .filter_queryset(request, queryset, view)\n\n\nclass XFormOwnerFilter(filters.BaseFilterBackend):\n\n owner_prefix = 'user'\n\n def filter_queryset(self, request, queryset, view):\n owner = request.QUERY_PARAMS.get('owner')\n\n if owner:\n kwargs = {\n self.owner_prefix + '__username': owner\n }\n\n return queryset.filter(**kwargs)\n\n return queryset\n\n\nclass ProjectOwnerFilter(XFormOwnerFilter):\n owner_prefix = 'organization'\n\n\nclass AnonUserProjectFilter(filters.DjangoObjectPermissionsFilter):\n def filter_queryset(self, request, queryset, view):\n \"\"\"\n Anonymous user has no object permissions, return queryset as it is.\n \"\"\"\n user = request.user\n if user.is_anonymous():\n return queryset.filter(Q(shared=True))\n\n return super(AnonUserProjectFilter, self)\\\n .filter_queryset(request, queryset, view)\n","sub_path":"onadata/libs/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"7723610","text":"\"\"\" Auto-delete sticker when someone reply \"\"\"\n\nfrom pagermaid import user_id\nfrom pagermaid.listener import listener\n\n\n@listener(incoming=True, ignore_edited=True)\nasync def auto_remove_sticker(context):\n \"\"\" Event handler to remove stickers. \"\"\"\n reply = await context.get_reply_message()\n if reply:\n if reply.sender:\n reply_user_id = reply.sender.id\n else:\n return\n if context.sticker:\n return\n if not reply.sticker:\n return\n if context.chat_id > 0:\n return\n if context.sender:\n if context.sender.bot:\n return\n else:\n return\n\n if reply_user_id == user_id:\n try:\n await reply.delete()\n except:\n pass\n","sub_path":"antisticker.py","file_name":"antisticker.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"248338457","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 3 11:26:14 2020\n\n@author: crow104\n\"\"\"\n\nimport pickle\n\nif __name__ == '__main__':\n def __init__(self):\n self.name = self\n\n path0 = \"C:\\\\Data\\\\2020\\\\ep_metrology\\\\data\\\\data_200303\"\n fname = path0 + \"\\\\20200304_080823.pickle\"\n \n# with open(fname, \"wb\") as open_file:\n# pickle.dump((ramsey, t1decay), open_file)\n\n with open(fname, \"rb\") as open_file: \n x = pickle.load(open_file)\n print(x)","sub_path":"instruments/old_python/old/try_pickle.py","file_name":"try_pickle.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649473621","text":"#!/usr/bin/env python\n#START STUDENT CODE43\nfrom mrjob.job import MRJob\nfrom mrjob.step import MRStep\nfrom mrjob.protocol import RawValueProtocol\nimport re \n \nclass MostFrequentVisits(MRJob):\n \n OUTPUT_PROTOCOL = RawValueProtocol\n \n pages = [\"NA\",\"NA\",\"NA\",\"NA\",\"NA\"]\n counts = [0,0,0,0,0]\n\n def steps(self):\n return [MRStep(\n mapper = self.mapper,\n combiner = self.combiner,\n reducer = self.reducer,\n reducer_final = self.reducer_final\n )]\n \n def mapper(self, _, line):\n data = re.split(\",\",line)\n pageID = data[1]\n yield pageID,1\n \n def combiner(self,pageID,counts):\n count = sum(counts)\n yield pageID,count\n\n def reducer(self,pageID,counts):\n count = sum(counts)\n ix = -1\n for i in range(5):\n if count > self.counts[i]:\n ix = i\n else:\n break\n\n if ix >= 0:\n self.counts.insert(ix+1,count)\n self.pages.insert(ix+1,pageID)\n self.counts = self.counts[1:6]\n self.pages = self.pages[1:6]\n\n def reducer_final(self):\n self.counts.reverse()\n self.pages.reverse()\n \n for i in range(5):\n yield None,self.pages[i] + \",\" + str(self.counts[i])\n\nif __name__ == '__main__':\n MostFrequentVisits.run()\n\n\n#END STUDENT CODE43","sub_path":"HW4/MostFrequentVisits.py","file_name":"MostFrequentVisits.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"445006574","text":"import os\nimport requests\n\nfrom django.core.management import BaseCommand\nfrom news.models import Article, Topic, Trend\n\n\nclass Command(BaseCommand):\n help = 'Retrieves the most viewed New York Times articles in the past day'\n\n def handle(self, *args, **options):\n response = requests.get(\n 'https://api.nytimes.com/svc/mostpopular/v2/shared/1.json',\n params={'api-key': os.getenv('NYT_API_KEY')}\n )\n\n data = response.json()\n\n trend = Trend.objects.create()\n\n for article_data in data['results']:\n article, _ = Article.objects.get_or_create(\n nyt_id=article_data['id'],\n url=article_data['url'],\n title=article_data['title'],\n abstract=article_data['abstract'],\n )\n\n for facet in article_data['des_facet']:\n topic, _ = Topic.objects.get_or_create(\n name=facet,\n type='topic',\n )\n article.topics.add(topic)\n\n for facet in article_data['org_facet']:\n topic, _ = Topic.objects.get_or_create(\n name=facet,\n type='organization',\n )\n article.topics.add(topic)\n\n for facet in article_data['per_facet']:\n topic, _ = Topic.objects.get_or_create(\n name=facet,\n type='person',\n )\n article.topics.add(topic)\n\n trend.articles.add(article)\n","sub_path":"server/news/management/commands/get_nyt_most_popular.py","file_name":"get_nyt_most_popular.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84671135","text":"import asyncio\nfrom pathlib import Path as FilePath\n\nfrom indexpy import FileResponse, HTTPException, Index, Path, required_method\nfrom indexpy.routing import HttpRoute\n\n\nasync def homepage():\n \"\"\"\n Homepage\n \"\"\"\n return \"hello, index.py\"\n\n\nasync def exc():\n raise Exception(\"For get debug page.\")\n\n\nasync def message():\n \"\"\"\n Message\n\n For testing server send event response\n \"\"\"\n\n async def message_gen():\n for i in range(5):\n await asyncio.sleep(app.state.wait_time)\n yield {\"id\": i, \"data\": \"hello\"}\n\n return message_gen()\n\n\n@required_method(\"GET\")\nasync def sources(filepath: str = Path()):\n \"\"\"\n Return source files\n \"\"\"\n realpath = FilePath(\".\") / filepath.lstrip(\"./\")\n if realpath.exists() and realpath.is_file():\n return realpath\n else:\n raise HTTPException(404)\n\n\napp = Index(\n debug=True,\n routes=[\n HttpRoute(\"/\", homepage),\n HttpRoute(\"/exc\", exc),\n HttpRoute(\"/message\", message),\n HttpRoute(\"/sources/{filepath:path}\", sources),\n ],\n)\napp.state.wait_time = 1\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375944147","text":"#!/usr/bin/env python\n\nimport rospy\nimport tf\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import Int32\nfrom math import *\nfrom geometry_msgs.msg import Point, Quaternion\n\nTicksPerR = 300\nwheelWidth = 0.038\nwheelDiameter = 0.085\ncarWidth = 0.157\nLengthBW = wheelWidth + carWidth\nmPerTick = (pi*wheelDiameter)/TicksPerR\n\n\nx = 0\ny = 0\ntheta = 0 \n\nCurrentRTick = 0\nCurrentLTick = 0\nRFirst = 1\nLFirst = 1\nLastRTick = CurrentRTick\nLastLTick = CurrentLTick\n\ndef RTickCB(msg):\n global CurrentRTick,LastRTick,RFirst\n CurrentRTick = msg.data\n if RFirst:\n LastRTick = CurrentRTick\n RFirst = 0\ndef LTickCB(msg):\n global CurrentLTick,LastLTick,LFirst\n CurrentLTick = msg.data\n if LFirst:\n LastLTick = CurrentLTick\n LFirst = 0\n\nrospy.init_node('Odometry')\n\nRTickSub = rospy.Subscriber('RTick',Int32,RTickCB)\t\nLTickSub = rospy.Subscriber('LTick',Int32,LTickCB)\nOdomPub = rospy.Publisher('Odom',Odometry,queue_size=50)\n\nOdomframe_id = 'Odom'\nOdomMsg = Odometry()\n\nrate = rospy.Rate(20)\n\nwhile not rospy.is_shutdown():\n Dl = mPerTick*(CurrentLTick - LastLTick)\n Dr = mPerTick*(CurrentRTick - LastRTick)\n Dc = (Dl+Dr)/2\n if abs(Dr - Dl) < 10**(-6):\n x += Dc*cos(theta)\n y += Dc*sin(theta)\n else:\n dtheta = (Dr-Dl)/LengthBW\n R = Dc/dtheta\n x += R*sin(dtheta+theta) - R*sin(theta)\n y += -R*cos(dtheta+theta) + R*cos(theta)\n theta = (theta + dtheta)%(2*pi)\n OdomMsg.header.stamp = rospy.Time.now()\n OdomMsg.header.frame_id = Odomframe_id\n OdomMsg.child_frame_id = 'None'\n OdomMsg.pose.pose.position = Point(x,y,0)\n OdomMsg.pose.pose.orientation = Quaternion(*tf.transformations.quaternion_from_euler(0,0,theta))\n OdomPub.publish(OdomMsg)\n LastLTick = CurrentLTick\n LastRTick = CurrentRTick\n rate.sleep()\n","sub_path":"src/BursaBot/src/Odometry.py","file_name":"Odometry.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119533380","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a Werkenbijkruidvat spider created on top of the ATSSpider\nscrapy crawl werkenbijkruidvat -a url=\"http://www.werkenbijkruidvat.nl/index.php/page/advsearchvacs/bb/1/command/editrequest\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n http://www.werkenbijkruidvat.nl/index.php/page/advsearchvacs/bb/1/command/editrequest\n\"\"\"\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request, FormRequest\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix\n\n\nclass Werkenbijkruidvat(ATSSpider):\n\n name = \"werkenbijkruidvat\"\n ref_re = compile(\"-(\\d+)-\\d+\\.\")\n job_function_req = []\n\n def parse(self, response):\n sel = Selector(response)\n function_req = lambda x: FormRequest.from_response(\n response,\n dont_filter=True,\n formname='advsearchform',\n formdata={'matchcriteria_functiegr[]': x},\n callback=self.parse_list\n )\n # get all job function ids and store req object\n self.job_function_req = map(\n function_req,\n sel.xpath(\n \"//select[@id='multisel_mc_functiegr']/option/@value\"\n ).extract()\n )\n # request one job_function_req to start\n if self.job_function_req:\n yield self.job_function_req.pop()\n\n def parse_list(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\"//div[contains(@class,'itemContainer')]\")\n for job in jobs:\n job_link = job.xpath(\"./h3/a/@href\").extract()\n if job_link:\n meta = {\n 'title': job.xpath(\"./h3/a/text()\").extract(),\n 'location': job.xpath(\n \"./div[contains(@class,'itemWord')]/text()\"\n ).extract(),\n }\n yield Request(\n job_link[0], meta=meta, callback=self.parse_job_callback()\n )\n next_page = sel.xpath(\n \"//a[contains(@class,'pnNext')]/@href\"\n ).extract()\n if next_page:\n # if next page present request next page\n yield Request(\n next_page[0], dont_filter=True, callback=self.parse_list\n )\n elif self.job_function_req:\n # At end of pagination,\n # pop next job function req and proceed\n yield self.job_function_req.pop()\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value('location', response.meta['location'])\n loader.add_xpath(\n \"description\",\n \"//h2[contains(@class,'subHeader')]|//h2[contains(@class,'subHeader')]/following-sibling::div[1]\"\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/werkenbijkruidvat.py","file_name":"werkenbijkruidvat.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"230395164","text":"# substitution ciphers\n# or, how to transform data from one thing to another\nencode_table = {\n 'A': 'H',\n 'B': 'Z',\n 'C': 'Y',\n 'D': 'W',\n 'E': 'O',\n 'F': 'R',\n 'G': 'J',\n 'H': 'D',\n 'I': 'P',\n 'J': 'T',\n 'K': 'I',\n 'L': 'G',\n 'M': 'L',\n 'N': 'C',\n 'O': 'E',\n 'P': 'X',\n 'Q': 'K',\n 'R': 'U',\n 'S': 'N',\n 'T': 'F',\n 'U': 'A',\n 'V': 'M',\n 'W': 'B',\n 'X': 'Q',\n 'Y': 'V',\n 'Z': 'S'\n}\n\n# decode_table = {}\n\n# for key, value in encode_table.items():\n# decode_table[value] = key\n\ndecode_table = {value: key for key, value in encode_table.items()}\n\n\ndef encode(plain_text):\n cipher = \"\"\n\n for char in plain_text:\n if char.isspace():\n cipher += ' '\n else:\n cipher += encode_table[char.upper()]\n return cipher\n\n\ndef decode(cipher_text):\n plain_text = \"\"\n\n for char in cipher_text:\n if char.isspace():\n plain_text += ' '\n else:\n plain_text += decode_table[char.upper()]\n return plain_text\n\n\ncipher = encode(\"Super secret message just for you\")\nprint(cipher)\n\nreversed_plain_text = decode(cipher)\nprint(reversed_plain_text)\n","sub_path":"src/ht3/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"163339143","text":"import cv2\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\n#http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html\n\n# w is a list\t\nw =[[0,0,0,0]]\n\t\t\ndef mkRect(z,i,j,num,origin,start,end):\n\t\n\tnum1=0\n\theight,width = z.shape\n\tnx,ny =height,width\n\tk=j\n\tfor k in range(j,ny):\n\t\tif z[i][k]!=0:\n\t\t\tnum1=num1+1\n\t\t\tk=k+1\n\t\telse:\n\t\t\tbreak\n\n\tif origin :\n\t\tnum=num1\n\n\tif num1 List[float]:\n\n log_probs = []\n for i in range(0, len(inputs), settings.t5_batch_size):\n batch_inputs = inputs[i:i + settings.t5_batch_size]\n\n batch_scores = self.session.run(\n fetches=self.signature_def.outputs[\"scores\"].name,\n feed_dict={\n self.signature_def.inputs[\"input\"].name: batch_inputs})\n\n # 6136 and 1176 are the indexes of the tokens false and true in T5.\n batch_scores = batch_scores[:, [6136, 1176]]\n batch_log_probs = torch.nn.functional.log_softmax(\n torch.from_numpy(batch_scores), dim=1)\n batch_log_probs = batch_log_probs[:len(batch_inputs), 1].tolist()\n log_probs.extend(batch_log_probs)\n\n return log_probs\n\n\nranker = Ranker()\n","sub_path":"api/app/services/ranker.py","file_name":"ranker.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"140081527","text":"from datetime import date\nimport random\nfrom copy import copy, deepcopy\nimport binaryTreeInsert\n\n\n\nclass WareHouse:\n def __init__(self, height, width):\n self.width = width\n self.height = height\n self.items = []\n self.p = binaryTreeInsert.warehouseTree(width, height)\n \n def totalSpace(self):\n return self.width*self.height\n\n def usedSpace(self):\n space = 0\n for item in self.items:\n space += item.width * item.height\n return space\n\n def remainingSpace(self):\n return self.totalSpace() - self.usedSpace()\n \n\n\n def addItem(self, barcode, name, width,\n height, amount, price, owner_name ):\n print(\"trying to add item width: \", width, \", height: \", height, \", Barcode: \", barcode)\n fits = self.p.addItem(width, height, barcode)\n if not fits:\n return False\n else:\n locations = self.itemLocation(barcode)\n self.items.append(Item(barcode, name, width,\n height, amount, price, owner_name, locations))\n return True\n\n def itemLocation(self, barcode):\n return self.p.itemLoc(barcode)\n\n\n def displayMatrix(self):\n self.p.printWarehouseMatrix()\n # all_rects = self.p.rect_list()\n # tests = [ [ 0 for i in range(self.width) ] for j in range(self.height) ]\n # for i in all_rects:\n # for j in range(i[3]):# width\n # for k in range(i[4]):# height\n # disRow = i[2]\n # disCol = i[1]\n # tests[disRow+k][disCol+j] = i[5]\n # # tests[disCol+j][disRow+k] = 1\n # for i in range(self.height):\n # for j in range(self.width):\n # if not tests[i][j] == 0:\n # print(tests[i][j], end=\", \")\n # else:\n # print(\" \", end=\", \")\n # print(\"\")\n\n def checkoutItem(self, barcode):\n for item in self.items:\n if barcode == item.barcode:\n item.checkout()\n\n def checkinItem(self, barcode):\n for item in self.items:\n if barcode == item.barcode:\n item.checkin()\n\nclass Item:\n def __init__(self, barcode, name, width,\n height, amount, price, owner_name, locations):\n self.barcode = barcode\n self.name = name\n self.width = width\n self.height = height\n self.amount = amount\n self.date_in = date.today()\n self.date_out = -1\n self.price = price\n self.owner_name = owner_name\n self.item_locations = locations\n\n def checkout(self):\n self.date_out = date.today()\n def checkin(self):\n self.date_in = date.today()\n\n# make a warehouse, warehousePacker(width, height)\nx = WareHouse(50, 30) \n\n# addItem(width, height, barcode)\n# fits #(barcode, item_name, width, height, amount,price , owner_name)\nprint(\"Was the item placed?: \", x.addItem('d' , \"Disc\" , 3 , 5 , 1 , 20.11, \"Jonathan\" ))\nprint(\"Was the item placed?: \", x.addItem( 2, \"Another Disc\", 3, 30, 1, 49.99, \"JonathanB\" ))\nprint(\"Was the item placed?: \", x.addItem(3 , \"Mouse\", 3, 5, 1, 29.99, \"Jonathan\"))\nprint(\"Was the item placed?: \", x.addItem(4 , \"Keyboard\", 3, 5, 1, 39.99, \"Jonathan\"))\n\n# Item does not fit \nprint(\"Was the item placed?: \", x.addItem(9, \"\", 30, 50,1, 99999, \"people\"))\n\n# checking out item with barcode 'd'\nx.checkoutItem('d')\nprint(x.items[0].date_out)\n\n# checking in item with barcode 'd'\nx.checkinItem('d')\nprint(x.items[0].date_in)\n\n# get the totalspace, usedspace, and remaining space of warehouse\nprint(x.totalSpace(), x.usedSpace(), x.remainingSpace())\n\n# get location of an item in warehouse, using barcode\nprint(\"Location of item with barcode 'd': \",x.itemLocation('d'))\nprint(\"Location of item with barcode 2: \",x.itemLocation(2))\nprint(\"Location of item with barcode 4: \",x.itemLocation(4))\nprint(\"Location of item with barcode 9: \",x.itemLocation(9))\n\n# gives the list of all item rectangles\n# print(x.p.rect_list())\n\n# display warehouse\nx.displayMatrix()\n\n\n# x = binaryTreeInsert.warehouseTree(25, 50)\n# x.addItem(10, 20, 1)\n# x.printNodes()\n# x.addItem(5, 5, 2)\n# # x.addItem(5, 5, 3)\n# x.addItem(5, 5, 4)\n# x.addItem(20, 200, 9)\n# # x.addItem(20, 30, 5)\n# x.addItem(30, 5, 6)\n# x.printWarehouseMatrix()","sub_path":"Old/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228182435","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: /home/ax/Workspace/norm/norm/executable/expression/evaluation.py\n# Compiled at: 2019-05-29 02:40:51\n# Size of source mod 2**32: 22196 bytes\nimport uuid\nfrom norm.utils import hash_df\nfrom pandas import DataFrame, Series, Index\nfrom norm.grammar.literals import COP\nfrom norm.executable import NormError, Projection\nfrom norm.executable.expression.argument import ArgumentExpr\nfrom norm.executable.schema.variable import VariableName, ColumnVariable, JoinVariable\nfrom norm.executable.expression import NormExpression\nfrom collections import OrderedDict\nfrom typing import List, Dict\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass EvaluationExpr(NormExpression):\n\n def __init__(self, args, variable=None, projection=None):\n \"\"\"\n The evaluation of an expression either led by a variable name\n :param args: the arguments provided\n :type args: List[ArgumentExpr]\n :param variable: the variable name to evaluate\n :type variable: VariableName\n :type projection: Projection\n \"\"\"\n super().__init__()\n self.variable = variable\n self.args = args\n self.inputs = None\n self.outputs = None\n self.join_variables = []\n self.projection = projection\n self.equalities = None\n from norm.models.norm import Lambda\n self.equality_scope = None\n\n @property\n def is_constant_arguments(self):\n return all((arg.is_constant for arg in self.args))\n\n def check_assignment_arguments(self):\n \"\"\"\n Check whether the arguments are in the style of assignments. Ex. 234, 'asfs', b=3, c=5\n :return: True or False\n :rtype: bool\n \"\"\"\n keyword_arg = False\n for arg in self.args:\n if arg.op is None:\n if arg.variable is None:\n if keyword_arg:\n msg = 'Keyword based arguments should come after positional arguments'\n logger.error(msg)\n logger.error([str(arg) for arg in self.args])\n raise NormError(msg)\n else:\n keyword_arg = True\n else:\n return False\n\n return True\n\n def build_assignment_inputs(self, lam):\n \"\"\"\n If the arguments are in assignment style, build the inputs as assignments\n :param lam: given the Lambda to be evaluated\n :return: a dictionary mapping from a variable to an expression for the inputs\n :rtype: Dict\n \"\"\"\n if lam.nargs == 0:\n from norm.models.norm import Lambda\n return OrderedDict(((arg.variable.name if arg.variable else '{}{}'.format(Lambda.VAR_ANONYMOUS_STUB, i), arg.expr) for i, arg in enumerate(self.args)))\n keyword_arg = False\n inputs = OrderedDict()\n from norm.models.norm import Variable\n for ov, arg in zip(lam.variables, self.args):\n if arg.expr is None:\n continue\n if arg.op is None:\n if arg.variable is not None:\n keyword_arg = True\n if not keyword_arg:\n inputs[ov.name] = arg.expr\n else:\n inputs[arg.variable.name] = arg.expr\n\n return inputs\n\n def build_conditional_inputs(self):\n \"\"\"\n If the arguments are in conditional style, build the inputs as conditionals\n :return: a query string\n :rtype: Dict\n \"\"\"\n self.equalities = OrderedDict()\n self.equality_scope = None\n inputs = []\n for arg in self.args:\n if arg.is_assign_operator or arg.op is COP.EQ:\n if isinstance(arg.expr, ColumnVariable):\n if isinstance(arg.variable, ColumnVariable):\n self.equalities[arg.expr.name] = arg.variable.name\n if self.equality_scope is None:\n self.equality_scope = arg.expr.lam\n elif not self.equality_scope is arg.expr.lam:\n raise AssertionError\n continue\n else:\n if arg.op is None or arg.expr is None:\n continue\n vn = arg.variable.name\n if isinstance(arg.variable, JoinVariable):\n self.join_variables.append(arg.variable)\n vn = str(arg.variable)\n if arg.op == COP.LK:\n condition = '{}.str.contains({})'.format(vn, arg.expr)\n else:\n condition = '{} {} ({})'.format(vn, arg.op, arg.expr)\n inputs.append(condition)\n\n return ' and '.join(inputs)\n\n def build_outputs(self, lam):\n \"\"\"\n Build the outputs according to the projection\n :return: a dictionary mapping from the original variable to the new variable\n :rtype: Dict\n \"\"\"\n from norm.models.norm import Lambda\n if not isinstance(lam, Lambda):\n raise AssertionError\n else:\n outputs = OrderedDict()\n from norm.models.norm import Variable\n for ov, arg in zip(lam.variables, self.args):\n if arg.projection is not None:\n assert len(arg.projection.variables) <= 1\n assert not arg.projection.to_evaluate\n if arg.variable is None:\n outputs[ov.name] = arg.projection.variables[0].name\n elif len(arg.projection.variables) == 0:\n outputs[arg.variable.name] = arg.variable.name\n else:\n outputs[arg.variable.name] = arg.projection.variables[0].name\n\n if self.projection is not None:\n if not len(self.projection.variables) <= 1:\n raise AssertionError\n else:\n assert not self.projection.to_evaluate\n if self.projection.num == 1:\n new_lambda_name = self.projection.variables[0].name\n else:\n new_lambda_name = lam.name\n outputs = OrderedDict(((key, self.VARIABLE_SEPARATOR.join([new_lambda_name, value])) for key, value in outputs.items()))\n if lam.is_functional:\n outputs[lam.VAR_OUTPUT] = new_lambda_name\n else:\n outputs[lam.VAR_OID] = new_lambda_name\n return outputs\n\n def compile(self, context):\n if self.variable is None:\n from norm.models.norm import Lambda\n assert context.scope is not None\n assert isinstance(context.scope, Lambda)\n lam = context.scope\n assert self.check_assignment_arguments()\n self.inputs = self.build_assignment_inputs(lam)\n self.outputs = None\n is_to_add_data = True\n else:\n lam = self.variable.lam\n if lam is None:\n return self\n if self.check_assignment_arguments():\n self.inputs = self.build_assignment_inputs(lam)\n is_to_add_data = not lam.atomic\n else:\n self.inputs = self.build_conditional_inputs()\n is_to_add_data = False\n self.outputs = self.build_outputs(lam)\n is_to_add_data &= len(self.outputs) == 0\n elif self.equality_scope is not None:\n if len(self.equalities) > 0:\n return JoinEqualityEvaluationExpr(lam, self.equality_scope, self.equalities, self.inputs, self.outputs).compile(context)\n elif is_to_add_data:\n return AddDataEvaluationExpr(lam, self.inputs, self.variable is not None).compile(context)\n if isinstance(self.inputs, dict):\n if self.projection is not None and self.projection.num == 1:\n output_projection = self.projection.variables[0].name\n else:\n output_projection = None\n if lam.atomic:\n return AtomicEvaluationExpr(lam, self.inputs, output_projection).compile(context)\n if len(self.inputs) == 0:\n if isinstance(self.variable, ColumnVariable):\n return ArgumentExpr(self.variable, None, None, self.projection).compile(context)\n if self.projection is not None:\n if len(self.outputs) == 1:\n return RetrieveAllDataExpr(lam, output_projection).compile(context)\n return RetrievePartialDataExpr(lam, self.outputs).compile(context)\n self.eval_lam = lam\n from norm.models import Lambda, Variable\n if len(self.outputs) > 0:\n variables = [Variable(self.outputs[v.name], v.type_) for v in self.eval_lam.variables if v.name in self.outputs.keys()]\n else:\n variables = self.eval_lam.variables\n self.lam = Lambda((context.context_namespace), (context.TMP_VARIABLE_STUB + str(uuid.uuid4())), variables=variables)\n self.lam.cloned_from = self.eval_lam\n return self\n\n def execute(self, context):\n for jv in self.join_variables:\n jv.execute(context)\n\n df = self.eval_lam.data.query((self.inputs), engine='python')\n if isinstance(df, DataFrame):\n if len(self.outputs) > 0:\n df = df[self.outputs.keys()].rename(columns=(self.outputs))\n self.lam.data = df\n return df\n\n\nclass JoinEqualityEvaluationExpr(NormExpression):\n\n def __init__(self, lam, scope, equalities, condition, outputs):\n super().__init__()\n self.eval_lam = lam\n self.scope = scope\n self.equalities = equalities\n self.condition = condition\n self.outputs = outputs\n\n def compile(self, context):\n scope = self.scope\n from norm.models import Lambda, Variable\n if len(self.outputs) > 0:\n variables = [Variable(v.name, v.type_) for v in scope.variables if v.name in self.outputs.keys()]\n leftover = set(self.outputs.values()).difference((v.name for v in variables))\n variables += [Variable(self.outputs[v.name], v.type_) for v in self.eval_lam.variables if self.outputs.get(v.name) in leftover]\n else:\n variables = scope.variables\n scope_variable_names = set((v.name for v in variables))\n variables += [v for v in self.eval_lam.variables if v.name not in scope_variable_names]\n self.lam = Lambda((context.context_namespace), (context.TMP_VARIABLE_STUB + str(uuid.uuid4())), variables=variables)\n self.lam.cloned_from = scope\n return self\n\n def execute(self, context):\n inp = self.lam.cloned_from.data\n equal_cols = list(self.equalities.items())\n to_merge = self.eval_lam.data.query((self.condition), engine='python')\n if len(self.outputs) > 0:\n to_merge = to_merge[set(list(self.outputs.keys()) + list(self.equalities.values()))].rename(columns=(self.outputs))\n else:\n left_col, right_col = equal_cols.pop()\n joined = inp.reset_index().merge(to_merge, left_on=left_col, right_on=right_col)\n joined = joined.set_index(self.lam.VAR_OID)\n condition = ' & '.join(('({} == {})'.format(left_col, right_col) for left_col, right_col in equal_cols))\n if condition != '':\n results = joined.query(condition)\n else:\n results = joined\n self.lam.data = results\n return results\n\n\nclass AtomicEvaluationExpr(NormExpression):\n\n def __init__(self, lam, inputs, output_projection=None):\n \"\"\"\n Evaluate the atomic function\n :param lam: the function to evaluate\n :param inputs: the input values\n :param output_projection: the output projection\n \"\"\"\n super().__init__()\n from norm.models.norm import Lambda\n assert lam is not None\n assert isinstance(lam, Lambda)\n assert isinstance(inputs, dict)\n self.eval_lam = lam\n self.lam = lam.output_type\n self.inputs = inputs\n self.output_projection = output_projection\n\n def __str__(self):\n return '{}({})'.format(self.eval_lam.signature, ', '.join(('{}={}'.format(key, value) for key, value in self.inputs.items())))\n\n def compile(self, context):\n return self\n\n def execute(self, context):\n inputs = dict(((key, value.execute(context)) for key, value in self.inputs.items()))\n result = (self.eval_lam)(**inputs)\n if self.output_projection is not None:\n import numpy\n if isinstance(result, (list, numpy.ndarray)):\n return Series(result, name=(self.output_projection))\n if isinstance(result, (Series, Index)):\n return result.rename(self.output_projection)\n if isinstance(result, DataFrame):\n cols = {col:'{}{}{}'.format(self.output_projection, self.VARIABLE_SEPARATOR, col) for col in result.columns}\n return result.loc[result.index.rename(self.output_projection)].rename(columns=cols)\n return Series([result], name=(self.output_projection))\n return result\n\n\nclass RetrievePartialDataExpr(NormExpression):\n\n def __init__(self, lam, outputs):\n super().__init__()\n from norm.models.norm import Lambda\n assert lam is not None\n assert isinstance(lam, Lambda)\n assert not lam.atomic\n self.eval_lam = lam\n self.lam = None\n self.outputs = outputs\n\n def __str__(self):\n oid = self.eval_lam.VAR_OID\n out = self.eval_lam.VAR_OUTPUT\n return '{}({}){}'.format(self.eval_lam.signature, ', '.join(('{}?'.format(c) for c in self.outputs.keys() if c != oid if c != out)), '?' if (self.outputs.get(oid) or self.outputs.get(out)) else '')\n\n def compile(self, context):\n from norm.models import Lambda, Variable\n if len(self.outputs) > 0:\n variables = [Variable(self.outputs[v.name], v.type_) for v in self.eval_lam.variables if v.name in self.outputs.keys()]\n else:\n variables = self.eval_lam.variables\n self.lam = Lambda((context.context_namespace), (context.TMP_VARIABLE_STUB + str(uuid.uuid4())), variables=variables)\n return self\n\n def execute(self, context):\n oid_output_col = self.outputs.get(self.eval_lam.VAR_OID)\n if oid_output_col is not None:\n del self.outputs[self.eval_lam.VAR_OID]\n result = self.eval_lam.data\n result = result[self.outputs.keys()].rename(columns=(self.outputs))\n self.lam.data = result\n if oid_output_col is not None:\n result.index.rename(oid_output_col, inplace=True)\n return result\n\n\nclass RetrieveAllDataExpr(NormExpression):\n\n def __init__(self, lam, output_projection=None):\n \"\"\"\n Retrieve all data from the given Lambda\n :param lam: the given Lambda\n :param output_projection: the output projection variable name\n \"\"\"\n super().__init__()\n from norm.models.norm import Lambda\n assert lam is not None\n assert isinstance(lam, Lambda)\n assert not lam.atomic\n self.eval_lam = lam\n self.lam = lam\n self.output_projection = output_projection\n\n def __str__(self):\n return '{}?'.format(self.lam.signature)\n\n def compile(self, context):\n return self\n\n def execute(self, context):\n if self.lam.is_functional:\n result = self.lam.data[self.lam.VAR_OUTPUT]\n else:\n result = self.lam.data.index\n if self.output_projection is not None:\n return result.rename(self.output_projection)\n return result\n\n\nclass AddDataEvaluationExpr(NormExpression):\n\n def __init__(self, lam, data, immediately=True):\n \"\"\"\n Add data to a Lambda. If the lambda is not the current scope, revision occurs immediately. Otherwise,\n revision is delayed to TypeImplementation\n :param lam: the Lambda to add data\n :type lam: norm.model.norm.Lambda\n :param data: the data to add\n :type data: Dict\n :param immediately: whether to revise Lambda as a disjunction immediately, default to True\n :type immediately: bool\n \"\"\"\n super().__init__()\n from norm.models.norm import Lambda\n self.lam = lam\n self.data = data\n self.immediately = immediately\n self.description = 'add data'\n self._query_str = None\n\n def __str__(self):\n if self._query_str is None:\n msg = 'Need to execute first!'\n logger.error(msg)\n raise NormError(msg)\n return self._query_str\n\n def compile(self, context):\n if not self.immediately:\n if len(self.data) == 1:\n expr = list(self.data.values())[0]\n from norm.executable.expression.arithmetic import ArithmeticExpr\n if isinstance(expr, ArithmeticExpr):\n if expr.op is not None:\n return expr\n return self\n\n def execute(self, context):\n if len(self.data) == 0:\n return DataFrame(data=[self.lam.default])\n else:\n data = OrderedDict(((key, value.execute(context)) for key, value in self.data.items()))\n data = self.unify(data)\n df = DataFrame(data=data, columns=(data.keys()))\n query_str = hash_df(df)\n self._query_str = query_str\n df = self.lam.fill_primary(df)\n df = self.lam.fill_time(df)\n df = self.lam.fill_oid(df)\n if self.lam.VAR_OID in df.columns:\n df = df.set_index(self.lam.VAR_OID)\n else:\n df.index.rename((self.lam.VAR_OID), inplace=True)\n if self.immediately:\n from norm.models.norm import RevisionType\n df = self.lam.revise(query_str, self.description, df, RevisionType.DISJUNCTION)\n if self.lam.is_functional:\n return df[self.lam.VAR_OUTPUT]\n return df.index\n return df\n\n\nclass ChainedEvaluationExpr(NormExpression):\n\n def __init__(self, lexpr, rexpr):\n super().__init__()\n self.lexpr = lexpr\n self.rexpr = rexpr\n\n def compile(self, context):\n if isinstance(self.rexpr, VariableName):\n if isinstance(self.lexpr, VariableName):\n return VariableName(self.lexpr, self.rexpr.name).compile(context)\n if isinstance(self.lexpr, EvaluationExpr):\n if self.rexpr.name in self.lexpr.lam:\n return ColumnVariable(self.lexpr, self.rexpr.name)\n msg = '{} does not exist in the {}'.format(self.rexpr, self.lexpr)\n logger.error(msg)\n raise NormError(msg)\n else:\n msg = 'Only a variable or an evaluation can have chained operation for now, but got {}'.format(self.lexpr)\n logger.error(msg)\n raise NormError(msg)\n else:\n if isinstance(self.rexpr, EvaluationExpr):\n if self.rexpr.lam is None:\n if isinstance(self.lexpr, ColumnVariable):\n return DataFrameColumnFunctionExpr(self.lexpr, self.rexpr).compile(context)\n self.rexpr.args = [ArgumentExpr(expr=(self.lexpr))] + self.rexpr.args\n return self.rexpr.compile(context)\n else:\n msg = 'Only chaining on a variable or an evaluation, but got {}'.format(self.rexpr)\n logger.error(msg)\n raise NormError(msg)\n\n\nclass DataFrameColumnFunctionExpr(EvaluationExpr):\n\n def __init__(self, column_variable, expr):\n super().__init__([])\n self.column_variable = column_variable\n self.expr = expr\n\n def compile(self, context):\n return self\n\n def execute(self, context):\n col = self.column_variable.execute(context)\n args = []\n kwargs = {}\n for arg in self.expr.args:\n if arg.expr is None:\n continue\n if arg.op is None and arg.variable is not None:\n kwargs[arg.variable.name] = arg.expr.execute(context)\n else:\n args.append(arg.expr.execute(context))\n\n func = self.expr.variable.name\n try:\n df = (getattr(col, func))(*args, **kwargs)\n except:\n print('error on {}'.format(col))\n df = (getattr(col.str, func))(*args, **kwargs)\n print(args, kwargs)\n print(df)\n\n return df","sub_path":"pycfiles/pynorm-0.1.12-py2.py3-none-any/evaluation.cpython-37.py","file_name":"evaluation.cpython-37.py","file_ext":"py","file_size_in_byte":21089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"73473523","text":"import re\nimport os\nimport host\n\ntry:\n from helpers import get_logger\nexcept ImportError:\n from logging import getLogger as get_logger\n\n\nlogger = get_logger()\n\n__version__ = \"1.0.1\"\nlogger.debug(\"%s version: %s\", __name__, __version__)\n\n_email_valid_regexp = re.compile(r\"[^@]+@[^@]+\\.[^@]+\")\n\n\nclass EmailError(Exception):\n pass\n\n\nclass EmailAccountNotFound(EmailError):\n pass\n\n\nclass EmailNotValid(EmailError):\n pass\n\n\ndef _win_encode_path(path):\n if os.name == \"nt\":\n try:\n path = path.decode(\"utf8\")\n except (UnicodeDecodeError, UnicodeEncodeError):\n pass\n return path\n\n\nclass EmailSender(object):\n default_subject = \"{server_name} -> {script_name}\".format(\n server_name=host.settings(\"\").name or \"Client\",\n script_name=host.stats().parent().name,\n )\n\n def __init__(self, account):\n self.__account = self.get_email_account(account)\n self.max_attachments_bytes = 25 * 1024 * 1024\n\n @staticmethod\n def get_email_account(account):\n if not account:\n raise ValueError(\"Empty account\")\n\n for sett in host.settings(\"scripts\").ls():\n if sett.type == \"EmailAccount\" and (sett.name == account or sett.guid == account):\n return sett\n\n raise EmailAccountNotFound(account)\n\n @staticmethod\n def email_is_valid(email):\n return bool(_email_valid_regexp.match(email))\n\n @classmethod\n def parse_mails(cls, emails):\n if not emails:\n raise ValueError(\"Empty emails\")\n else:\n parsed_emails = []\n if isinstance(emails, (str, unicode)):\n emails = emails.split(\",\")\n\n for email in emails:\n if cls.email_is_valid(email):\n parsed_emails.append(email)\n else:\n raise EmailNotValid(email)\n return parsed_emails\n\n def _group_files_by_max_size(self, file_paths):\n \"\"\"Split files to groups. Size of each group is less then max_size\n\n Args:\n file_paths (list): List of files\n \"\"\"\n if not file_paths:\n return []\n\n group = []\n cur_size = 0\n for idx, file_path in enumerate(file_paths):\n encoded_file_path = _win_encode_path(file_path)\n if not os.path.isfile(encoded_file_path):\n logger.warning(\"File not found: %s\", file_path)\n continue\n file_size = os.stat(encoded_file_path).st_size\n logger.debug(\"Add attachment %s: %s\", file_size, file_path)\n if file_size >= self.max_attachments_bytes:\n logger.warning(\n \"%s size %s but max_attachments_bytes=%s\",\n file_path,\n file_size,\n self.max_attachments_bytes,\n )\n if not cur_size or (cur_size + file_size) < self.max_attachments_bytes:\n cur_size += file_size\n group.append(file_path)\n else:\n break\n else:\n return [group]\n\n return [group] + self._group_files_by_max_size(file_paths[idx:])\n\n def send(self, mails, text=\"\", attachments=None, subject=None):\n logger.debug(\n \"Sending email %r, text=%r, attachments=%r, subject=%r\",\n mails,\n text,\n attachments,\n subject,\n )\n if subject is None:\n subject = self.default_subject\n\n if attachments:\n for grouped_attachments in self._group_files_by_max_size(attachments):\n host.send_mail_from_account(\n self.__account.guid,\n self.parse_mails(mails),\n subject,\n text,\n grouped_attachments,\n )\n else:\n host.send_mail_from_account(\n self.__account.guid, self.parse_mails(mails), subject, text, []\n )\n","sub_path":"scripts/screenshots/shot_saver_universal/resources/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55454297","text":"'''\n给定一个长为n英寸的钢条,和价格表,求最佳切割方案\nl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\np = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]\n\n'''\nl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\np = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]\n\n\ndef getMaxValue(price, n): # price是价格列表,n是要切割的钢条的长度\n if n > len(price):\n print(\"Not enough prices for rod of len \" + str(n))\n return None\n global numCalls\n numCalls += 1\n if n == 0:\n return 0\n else:\n maxVal = -1\n for i in range(0, n):\n maxVal = max(maxVal, price[i] + getMaxValue(price[:n - i - 1], n - i - 1))\n print(\"Handling rod of len \" + str(n) + \"; max revenue currently is \" + str(maxVal))\n return maxVal\n\n\nnumCalls = 0\nprint(getMaxValue(p, 10))\nprint(\"调用次数:\", numCalls)\n","sub_path":"算法导论/15DynamicProgramming/钢条切割_递归.py","file_name":"钢条切割_递归.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"581114087","text":"# Author: David van Wyk\n# Description: This is code which follows the example starting at https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0\n# which is written by Arthur Juliani\n\nimport gym\nimport numpy as np\n\n# Loading the environment\n\nenv = gym.make('FrozenLake-v0')\n\n# Implementing the Q-Table Learning Algorithm\n\n# Initialize table with all zeros\n\nQ = np.zeros([env.observation_space.n, env.action_space.n])\n\n# Setting learning parameters\n\nlr = 0.8\ny = 0.95\nnum_episodes = 2000\n\n# Lists which contains total rewards and steps per episode\n\nrList = []\n\nfor i in range(num_episodes):\n #Reset the environment and get first new observation\n s = env.reset()\n rAll = 0\n d = False\n j = 0\n # Q-Table Learning Algorithm\n while j<99:\n j+=1\n\n #Choosing an action using the greedy (with noise) approach from the Q table\n #Here we add a randomized array to our Q-Table array for the specific state.\n #This random action is scaled as a function of the number of the number of episodes\n #So that the chance of doing a random action is decayed as a function of the\n #period spent learning.\n #Thus, toward the end of learning a will approximately be the argument of the\n #Q table for the current state that returns the largest value - while in the beginning\n #we will take primarily random actions.\n a = np.argmax(Q[s, :] + np.random.randn(1, env.action_space.n)*(1./(1+i)))\n\n #Getting the new state and reward from the environment\n # Returns: next state, reward and if the episode is complete\n s1,r,d,_ = env.step(a)\n #Update the Q-Table with new knowledge\n Q[s, a] = Q[s, a] + lr*(r + y*np.max(Q[s1, :]) - Q[s,a])\n rAll += r\n s = s1\n #if episode is complete, move on to next episode, otherwise continue\n if d == True:\n break\n\n rList.append(rAll)\n\nprint(\"Score over time: \" + str(sum(rList)/num_episodes))\nprint(\"Final Q-Table Values\")\nprint(Q)","sub_path":"Q Learning/FrozenLakeQLearning.py","file_name":"FrozenLakeQLearning.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"431751846","text":"import matplotlib.pyplot as plt\na = int(input())\nli = []\nwhile a!=1:\n b = a%2\n if b==0:\n a = a/2\n else:\n a = (a*3)+1\n li.append(a)\nprint(li)\nplt.plot(li)\nplt.show()","sub_path":"py5_matplotlib/plot_list.py","file_name":"plot_list.py","file_ext":"py","file_size_in_byte":174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10723057","text":"#!/usr/bin/env python3.4\n'''\nThe Chat Server\n'''\nimport select\nimport socket\nfrom connectdb import connection\n\n\ndef save_message(message, user, sender):\n try:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO messages (username, message, sender) VALUES (%s, %s, %s)\"\n cursor.execute(sql, (user, message, sender))\n connection.commit()\n except Exception as e:\n print(e)\n print(\"Didn't save. Try Again\")\n\n\nclass ChatServer:\n\n def __init__(self, port):\n self.port = port\n self.sockserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sockserver.bind(('', self.port))\n self.sockserver.listen(100)\n\n self.connectors = {}\n self.connectors[self.sockserver] = 'server'\n print('Chatserver started on port {}'.format(self.port))\n\n def run(self):\n while True:\n read_sockets, write_sockets, error_sockets = select.select(\n self.connectors.keys(), [], [])\n\n for sock in read_sockets:\n\n if sock == self.sockserver:\n self.accept_new_connection()\n else:\n # Data recieved from client, process it\n try:\n data = sock.recv(1024)\n if data:\n _user = self.connectors[sock]\n msg = data.decode('utf-8')\n if msg.find(':') != -1:\n online = False\n _to = msg.split(':')[0]\n for k, v in self.connectors.items():\n if v == msg.split(':')[0]:\n _to = k\n online = True\n break\n self.send_message(\n msg.split(':')[1], _to, _user, online)\n else:\n newstr = '{}'.format(data)\n self.broadcast_string(newstr, sock)\n\n except:\n _user = sock.getpeername()\n status = '{} left \\r\\n'.format(_user)\n self.broadcast_string(status, sock)\n sock.close()\n del self.connectors[sock]\n continue\n\n def accept_new_connection(self):\n newsock, (remhost, remport) = self.sockserver.accept()\n username = newsock.recv(1024).decode('utf-8')\n self.connectors[newsock] = username\n # newsock.send(bytes(\"You're connected to the chatserver\\r\\n\", 'utf-8'))\n status = '{} is online \\r\\n'.format(username)\n self.broadcast_string(status, newsock)\n\n def broadcast_string(self, msg, omit_sock):\n for sock in list(self.connectors):\n if sock != self.sockserver and sock != omit_sock:\n try:\n sock.send(bytes(msg, 'utf-8'))\n except:\n sock.close()\n del self.connectors[sock]\n\n def send_message(self, msg, receiver, sender, online):\n modified_msg = '{} > {}'.format(sender, msg.lstrip())\n reciever_name = receiver\n if online:\n receiver.send(bytes(modified_msg, 'utf-8'))\n reciever_name = self.connectors[receiver]\n save_message(msg.lstrip(), reciever_name, sender)\n\n\nif __name__ == '__main__':\n schat = ChatServer(5700)\n schat.run()\n","sub_path":"cli-chat-masterold/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"432215848","text":"#import numpy as np\nfrom numpy import sum as npSum\nfrom numpy import array as npArray\nfrom numpy import intersect1d as npIntersect1d\nfrom numpy import float32 as npFloat32\nfrom numpy import int32 as npInt32\nfrom numpy import zeros as npZeros\nfrom BFS import connectedComponents\n\ndef collectIntermediateProperty(allClusters, R, S, simParams):\n '''\n Detect clusters and compute their 'intermediate' properties; merge\n clusters where applicable --- i.e. those that straddle periodic boundaries.\n\n allClusters: output of common/extractClusterCoordinates()\n R, S: (filtered and normalized) 2D arrays recording occupancies\n simParams: Python dictionary recording KMC simulation parameters\n\n Returns numpy array of shape (?, 3). Each row corresponds to a cluster\n As for columns -> (area, rOccupancy, sOccupancy)\n Area in units of lattice sites\n '''\n clusters_straddle = list(filter(lambda x: x[2], allClusters))\n intermediate = [] #Will contain the final output\n\n # Extract coordinates of points touching the boundary\n ptsAtBoundary = [_findStraddlingPts(c, simParams) for c in clusters_straddle]\n\n # Based on position of boundary-touching points,\n # determine whether a pair of clusters should belong with each other\n straddlePairing = npZeros(shape=(len(ptsAtBoundary), len(ptsAtBoundary)),\n dtype=npInt32)\n\n for indI in range(len(ptsAtBoundary)):\n for indJ in range(indI+1, len(ptsAtBoundary)):\n if _testPartner( ptsAtBoundary[indI], ptsAtBoundary[indJ], 5 ):\n straddlePairing[indI, indJ] = 1\n straddlePairing[indJ, indI] = 1\n #print(straddlePairing)\n\n mergedClusters = connectedComponents(straddlePairing)\n #print(mergedClusters)\n\n for merged in mergedClusters:\n area, rOccupancy, sOccupancy = 0,0,0\n for cid in merged:\n X, Y = clusters_straddle[cid][0], clusters_straddle[cid][1]\n area += len(X) #len(Y) should be the same\n rOccupancy += npSum(R[Y,X])\n sOccupancy += npSum(S[Y,X])\n\n #print(area, rOccupancy, sOccupancy)\n intermediate.append([area, rOccupancy, sOccupancy])\n\n # Do the same for non-straddling clusters\n clusters_nonstraddle = list(filter(lambda x: not x[2], allClusters))\n result_nonstraddling = [_collectSingleClusterProperty(c,R,S) for c in clusters_nonstraddle]\n intermediate += result_nonstraddling\n intermediate = npArray(intermediate, dtype=npFloat32)\n\n return intermediate\n\ndef _findStraddlingPts(coordinates, paramDict):\n '''\n Given the coordinates of a cluster detected by hierarchical clustering,\n return the coordinates where the cluster touches the boundary\n\n To reduce redundant information, for instance, for the left boundary\n (x == 0) we return only the y coordinates.\n\n coordinates: (X numpy, Y numpy, straddle bool)\n paramDict: dict containing KMC simulation parameters\n '''\n #Integers to faciliate later comparison\n maxX, maxY = paramDict['sizeX']-1, paramDict['sizeY']-1\n X, Y, _ = coordinates\n\n left = Y[X == 0]\n right = Y[X == maxX]\n top = X[Y == maxY] #Top and bottom relative to left,bottom origin\n bottom = X[Y == 0]\n\n return [left, right, top, bottom]\n\ndef _testPartner(boundaryA, boundaryB, partnerThreshold):\n '''\n Decide whether A and B are actually part of a same cluster that\n straddles the periodic boundary\n\n boundaryA and boundaryB: Python lists of format [left, right, top, bottom]\n They record the coordinates of the pts touching the boundaries.\n See _findStraddlingPts() above.\n\n partnerThreshold: an integer; if the clusters A and B touch each other for\n more than this number of pixels, then count them as the same cluster\n '''\n Aleft, Aright, Atop, Abottom = boundaryA\n Bleft, Bright, Btop, Bbottom = boundaryB\n overlap = 0\n\n if (len(Aleft)>0 and len(Bright)>0):\n overlap += len(npIntersect1d(Aleft, Bright))\n\n if (len(Atop)>0 and len(Bbottom)>0):\n overlap += len(npIntersect1d(Atop, Bbottom))\n\n if (len(Bleft)>0 and len(Aright)>0):\n overlap += len(npIntersect1d(Bleft, Aright))\n\n if (len(Btop)>0 and len(Abottom)>0):\n overlap += len(npIntersect1d(Btop, Abottom))\n\n if overlap >= partnerThreshold:\n return True\n else:\n return False\n\ndef _collectSingleClusterProperty(cluster, R, S):\n X,Y,_ = cluster\n assert(len(X)==len(Y)), \"Error:\"\n\n rOccupancy = npSum(R[Y,X])\n sOccupancy = npSum(S[Y,X])\n return [len(X), rOccupancy, sOccupancy]\n\n# Load one data file\n#rawR = np.load(\"1773-configR_2D.dat.npy\")/100\n#rawS = np.load(\"1773-configS_2D.dat.npy\")/100\n#filteredS = sgolay2d(rawS, 17, 5)\n#bwData, clusters_all = extractClusterCoordinates(filteredS, threshold=0.1)\n#intermediateResult = collectIntermediateProperty(clusters_all, rawR, rawS, simParams_dict)\n","sub_path":"src/averageCluster/singleStep.py","file_name":"singleStep.py","file_ext":"py","file_size_in_byte":4981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"92613113","text":"from kivy.app import App\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.properties import (\r\n NumericProperty, ReferenceListProperty, ObjectProperty\r\n)\r\nfrom kivy.vector import Vector\r\nfrom kivy.clock import Clock\r\nimport socket\r\nimport json\r\nimport threading\r\nimport time\r\nimport pickle\r\n\r\nready = False\r\nball_x = 0\r\nball_y = 0\r\nPlayer_O = 0\r\nPlayer_id = 0\r\nScore_1 = 0\r\nScore_2 = 0 \r\nPlayer_My = 0\r\nOn = True\r\n\r\ndef sending(s):\r\n\t#while (not ready):\r\n\t#\tpass\r\n\t#print(\"hello\")\r\n\t#global On\r\n\t#global Player_My\r\n\twhile(On):\r\n\t\ttime.sleep(10/1000)\r\n\t\tdata = {\r\n\t\t\"Player_O\": Player_My\r\n\t\t}\r\n\t\tdata = pickle.dumps(data)\r\n\t\ts.send(data)\r\n\ts.close()\r\n\r\ndef getting(s):\r\n\t#print(\"hello\")\r\n\t#global On\r\n\tglobal ball_x\r\n\tglobal ball_y\r\n\tglobal Player_O\r\n\tglobal Score_1\r\n\tglobal Score_2\r\n\tglobal Player_id\r\n\tglobal ready\r\n\twhile(On):\r\n\t\t#print(\"hello1\")\r\n\t\tdata = s.recv(1024)\r\n\t\t#print(data)\r\n\t\t#print(\"hello2\")\r\n\t\tdata = pickle.loads(data)\r\n\t\t#print(\"ehll\")\r\n\t\t#print(data)\r\n\t\tball_x = data[\"ball_x\"]\r\n\t\tball_y = data[\"ball_y\"]\r\n\t\tPlayer_O = data[\"Player_O\"]\r\n\t\tPlayer_id = data[\"Player_id\"]\r\n\t\tScore_1 = data[\"Score_1\"]\r\n\t\tScore_2 = data[\"Score_2\"]\r\n\t\t#ready = True\r\n\ts.close()\r\nclass Connection:\r\n\t#global Player_id\r\n\thost = '127.0.0.1'\r\n\tport = 8006\r\n\ts = socket.socket()\r\n\tdef __init__(self):\r\n\t\tself.player = Player_id\r\n\r\n\tdef connect_to_server(self):\r\n\t\tself.s.connect((self.host, self.port))\r\n\t\tprint(\"Connected to server\")\r\n\t\r\n\tdef SendGetPos(self):\r\n\t\tsending_ = threading.Thread(target = sending, args = (self.s,))\r\n\t\tgetting_ = threading.Thread(target = getting, args = (self.s,))\r\n\t\tsending_.start()\r\n\t\tgetting_.start()\r\n \r\nclass PongPaddle(Widget):\r\n\tscore = NumericProperty(0)\r\n\r\n\r\n\r\nclass PongBall(Widget):\r\n\tpass\r\n\r\n\r\nclass PongGame(Widget):\r\n\tball = ObjectProperty(None)\r\n\tplayer1 = ObjectProperty(None)\r\n\tplayer2 = ObjectProperty(None)\r\n\r\n\tdef update(self, dt):\r\n\t\tself.ball.x = ball_x\r\n\t\tself.ball.y = ball_y\r\n\t\tself.player1.score = Score_1\r\n\t\tself.player2.score = Score_2\r\n\t\tif Player_id == 1:\r\n\t\t\tself.player2.center_y = Player_O\r\n\t\telse:\r\n\t\t\tself.player1.center_y = Player_O\r\n\r\n\tdef on_touch_move(self, touch):\r\n\t\tglobal Player_My\r\n\t\tif touch.x < self.width / 3 and Player_id == 1:\r\n\t\t\tself.player1.center_y = touch.y\r\n\t\t\tPlayer_My = touch.y\r\n\t\t\t#print(Player_My)\r\n\t\telif touch.x > self.width - self.width / 3 and Player_id == 2:\r\n\t\t\tself.player2.center_y = touch.y\r\n\t\t\tPlayer_My = touch.y\r\n\t\t\t#print(Player_My)\r\n\r\n\r\nclass PongApp(App):\r\n\tdef build(self):\r\n\t\tcon = Connection()\r\n\t\tcon.connect_to_server()\r\n\t\tcon.SendGetPos()\r\n\t\tgame = PongGame()\r\n\t\tClock.schedule_interval(game.update, 1.0 / 60.0)\r\n\t\treturn game\r\n\r\nif __name__ == '__main__':\r\n\t#global On\r\n\tPongApp().run()\r\n\tOn = False","sub_path":"pongGame/client_2/client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174567705","text":"# coding=utf-8\nfrom django.http import HttpResponse, HttpResponseBadRequest\nimport json\nimport logging\nfrom politics.apps.comments.models import Comment\nfrom politics.apps.comments.forms import CommentForm\nfrom politics.utils.decorators import pk_url, require_authenticated\nimport reversion\n\n\n@pk_url(Comment)\n@require_authenticated\ndef comment(request, instance):\n \"\"\"A RESTful view for deleting/editing comments.\n\n :param request: The HTTP request that was made.\n :type request: ``django.http.HttpRequest``\n :param instance: The comment that is to be operated on.\n :type instance: ``politics.apps.comments.models.Comment``\n \"\"\"\n # The client must be the author of the comment.\n if request.user != instance.author:\n return HttpResponse(status=403)\n\n if request.method == \"DELETE\":\n with reversion.create_revision():\n instance.is_deleted = True\n instance.save()\n\n return HttpResponse(json.dumps(instance.to_json()))\n elif request.method == \"PUT\":\n # Deleted comments can't be edited.\n if instance.is_deleted:\n return HttpResponseBadRequest()\n\n form = CommentForm(request.PUT, instance=instance)\n\n if form.is_valid():\n with reversion.create_revision():\n instance = form.save()\n\n return HttpResponse(json.dumps(instance.to_json()))\n else:\n return HttpResponseBadRequest()\n\n # Method Not Allowed\n return HttpResponse(status=405)\n\n\n@require_authenticated\ndef comments(request, instance):\n \"\"\"A generic, RESTful view for creating/reading comments on an object.\n\n .. code-block:: python\n\n from politics.apps.comments.views import comments as base_comments\n\n\n @pk_url(MyModel)\n def comments(request, my_model):\n return base_comments(request, my_model)\n\n :param request: The HTTP request that was made.\n :type request: ``django.http.HttpRequest``\n :param instance: The object to operate on.\n :type instance: ``django.db.models.Model``\n \"\"\"\n if request.method == \"POST\":\n comment = Comment(author=request.user, content_object=instance)\n form = CommentForm(request.POST, instance=comment)\n\n if form.is_valid():\n with reversion.create_revision():\n comment = form.save()\n\n logging.getLogger(\"email\").info(\"New Comment\", extra={\"body\":\n \"%s commented on %s %d.\" % (\n request.user.get_full_name(),\n instance.__class__.__name__,\n instance.pk\n )\n })\n\n return HttpResponse(json.dumps(comment.to_json()), status=201)\n else:\n return HttpResponseBadRequest()\n\n # Method Not Allowed\n return HttpResponse(status=405)\n","sub_path":"politics/apps/comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"509326807","text":"from core.lsm import LSM\nfrom core.txtsets import TXTSets\nfrom core.oddball import OddBall\nfrom core.svmlinear import SVMLinear\nfrom util.analyticaltools import AnalyticalTools\nfrom config import *\nimport cPickle as pickle\nimport os\n\n\nclass SimulationManager(object):\n \"\"\"\n A simulator object should contain all the necessary objects\n to run a lsm simulation pipeline:\n 1.) create lsm and stimulus objects\n 2.) train, x-validate, and test classifier using network outputs\n 3.) collect statistics and perform analysis\n 4.) export analytical results to files\n \"\"\"\n\n def __init__(self, neuronal_params, network_params, stimulus_params,\n txt_params, inp_params, sim_params):\n \"\"\"\n network is the lsm object\n stimulus is the stimulus object\n reps is the number of times we run the simulation.\n \"\"\"\n self.neuronal_params = neuronal_params\n self.network_params = network_params\n self.stimulus_params = stimulus_params\n self.txt_params = txt_params\n self.inp_params = inp_params\n self.sim_params = sim_params\n # now set up the neural network (kept fixed during different runs)\n params = {}\n params.update(network_params) # use update, so we don't change object.\n params.update(neuronal_params)\n self.network = LSM(**params) # params define the entire neural network\n #self.network.connect_voltmeters() # WARNING: memory expensive!\n\n\n def make_txtsets(self):\n \"\"\"\n Makes the training, cross-validation, and test sets.\n \"\"\"\n self.txtsets = TXTSets(self.stimulus, n=self.txt_params['pattern_reps'])\n\n\n def set_svmlin(self, training_set, labels):\n \"\"\"\n Given training set and labels, trains/cross-validates the linear svm\n classifier to obtain the optimal fit.\n Internally, the cross-validation is done on a grid search\n using the training data to arrive at the best hyperparameters.\n \"\"\"\n self.svmlin = SVMLinear(training_set, labels) # sets hyperparameters.\n self.svmlin.fit(training_set, labels) # trains classifier.\n\n\n def save_pickle(self, filename):\n # save the workspace into a pickle file, with the proper name.\n pickle.dump(self.__dict__, open(filename, \"wb\"))\n\n\n @classmethod\n def read_pickle(cls, filename):\n data = pickle.load(open(filename, \"rb\"))\n\n\n def simulate_network(self, stimulus):\n \"\"\"\n Runs simulation with given stimulus,\n and collect psth based on given bin_size and time_shift.\n NOTE: the returned psth is a gap psth,\n charaterized by its bin size and time shift from burst onset.\n \"\"\"\n self.network.simulate(stimulus = stimulus,\n sim_time = self.sim_params['sim_time'],\n inp_weight = self.inp_params['inp_w'],\n inp_delay = self.inp_params['inp_delay'])\n\n\n def train_and_test_input(self, bin_size, time_shift):\n \"\"\"\n Trains classifier using the training set,\n returns training score and test score.\n \"\"\"\n psth = AnalyticalTools.gap_psth(\n spike_trains = self.txtsets.training_set.spike_trains,\n gaps = self.txtsets.training_set.gaps,\n pattern_params = self.txtsets.training_set.pattern_params,\n bin_size = bin_size,\n time_shift = time_shift )\n self.set_svmlin(psth.T, self.txtsets.training_set.labels)\n training_score = self.svmlin.score(psth.T, self.txtsets.training_set.labels)\n psth = AnalyticalTools.gap_psth(\n spike_trains = self.txtsets.test_set.spike_trains,\n gaps = self.txtsets.test_set.gaps,\n pattern_params = self.txtsets.test_set.pattern_params,\n bin_size = bin_size,\n time_shift = time_shift )\n test_score = self.svmlin.score(psth.T, self.txtsets.test_set.labels)\n return training_score, test_score\n\n\n def train_and_test_network(self, bin_size, time_shift):\n \"\"\"\n Runs training stimulus and test stimulus through the network\n to collect transformed results.\n Use said results to train and test classifier.\n \"\"\"\n self.simulate_network(stimulus = self.txtsets.training_set)\n psth = AnalyticalTools.gap_psth(\n spike_trains = self.network.spike_trains(),\n gaps = self.txtsets.training_set.gaps,\n pattern_params = self.txtsets.training_set.pattern_params,\n bin_size = bin_size,\n time_shift = time_shift)\n self.set_svmlin(psth.T, self.txtsets.training_set.labels)\n training_score = self.svmlin.score(psth.T, self.txtsets.training_set.labels)\n self.simulate_network(stimulus = self.txtsets.test_set)\n psth = AnalyticalTools.gap_psth(\n spike_trains = self.network.spike_trains(),\n gaps = self.txtsets.test_set.gaps,\n pattern_params = self.txtsets.test_set.pattern_params,\n bin_size = bin_size,\n time_shift = time_shift)\n test_score = self.svmlin.score(psth.T, self.txtsets.test_set.labels)\n return training_score, test_score\n\n\n def run(self, out_path='', bin_size=30.0, time_shift=0.0):\n \"\"\"\n This is a routine written to run a batch of simulations.\n In this version, all parameters are set within the code. Hence no input parameters.\n NOTE: currently this is tailored to running gap simulations,\n but if one sets the gap sizes to be 0 then it's straight-forward\n to translate to a continuous stimulus.\n NOTE: the odd-ball stimulus usage is hard-coded as of now.\n \"\"\"\n ###if not os.path.exists(out_path): raise Exception(\"out path does not exist\")\n if not os.path.exists(out_path): out_path = os.getcwd() + '/out'\n for i in range(self.sim_params['number_of_runs']):\n # a new stimulus for each run\n self.stimulus = OddBall.periodic_bursts(**self.stimulus_params)\n self.make_txtsets() # create the training/x-validation/test sets.\n # train and test on un-transformed input data\n input_training_score, input_test_score = self.train_and_test_input(bin_size, time_shift)\n # now train on network-transformed input data\n network_training_score, network_test_score = self.train_and_test_network(bin_size, time_shift)\n with open(out_path + '/data.txt', 'a') as outfile:\n outfile.write('{},{},{},{}\\n'.format(input_training_score,\n input_test_score,\n network_training_score,\n network_test_score))\n\n\ndef main(neuronal_params, network_params, stimulus_params, txt_params,\n sim_params, inp_params):\n \"\"\"\n This is function that contains all the input keyword arguments.\n Creates the network and stimulus objects,\n and feeds them into the simulation manager.\n \"\"\"\n sim_manager = SimulationManager(neuronal_params = neuronal_params,\n network_params = network_params,\n stimulus_params = stimulus_params,\n txt_params = txt_params,\n inp_params = inp_params,\n sim_params = sim_params)\n sim_manager.run(bin_size=30.0, time_shift=0.0)\n\n\nif __name__=='__main__':\n main(neuronal_params = NEURONAL_PARAMS,\n network_params = NETWORK_PARAMS,\n stimulus_params = STIMULUS_PARAMS,\n txt_params = TXTSET_PARAMS,\n sim_params = SIMULATION_PARAMS,\n inp_params = INPUT_PARAMS)\n","sub_path":"simulation_manager.py","file_name":"simulation_manager.py","file_ext":"py","file_size_in_byte":7930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"606650620","text":"\"\"\"\nPlots normalized histograms of R^2 of observations using shuffled ensemble\nand years for paper\n\nReference : Barnes et al. [2020, JAMES]\nAuthor : Zachary M. Labe\nDate : 11 November 2020\n\"\"\"\n\n### Import packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\nimport cmocean\nimport palettable.cubehelix as cm\n\n### Set parameters\nvariables = [r'T2M']\nseasons = [r'annual']\nSAMPLEQ = 500\nSAMPLEQ2 = 100\n\n### Set directories\ndirectorydata2 = '/Users/zlabe/Documents/Research/InternalSignal/Data/FINAL/'\ndirectoryfigure = '/Users/zlabe/Documents/Projects/InternalSignal/DarkFigures/'\n\n### Read in slope data\nfilename_slope = 'Slopes_20CRv3-SHUFFLE-TIMENS_%s_RANDOMSEED_20ens.txt' % SAMPLEQ\nslopes = np.genfromtxt(directorydata2 + filename_slope,unpack=True)\n\n### Read in R2 data\nfilename_R2 = 'R2_20CRv3-SHUFFLE-TIMENS_%s_RANDOMSEED_20ens.txt' % SAMPLEQ\nr2 = np.genfromtxt(directorydata2 + filename_R2,unpack=True)\n\n### Read in other R2 data\nfilename_R2all = 'R2_20CRv3-Obs_XGHG-XAER-LENS_%s_RANDOMSEED_Medians_20ens.txt' % SAMPLEQ2\nr2_allmodel = np.genfromtxt(directorydata2 + filename_R2all,unpack=True)\nghg_r2 = r2_allmodel[0]\naer_r2 = r2_allmodel[1]\nlens_r2 = r2_allmodel[2]\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Create plot for histograms of slopes\nplt.rc('text',usetex=True)\nplt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']}) \nplt.rc('savefig',facecolor='black')\nplt.rc('axes',edgecolor='darkgrey')\nplt.rc('xtick',color='darkgrey')\nplt.rc('ytick',color='darkgrey')\nplt.rc('axes',labelcolor='darkgrey')\nplt.rc('axes',facecolor='black')\n\ndef adjust_spines(ax, spines):\n for loc, spine in ax.spines.items():\n if loc in spines:\n spine.set_position(('outward', 5))\n else:\n spine.set_color('none') \n if 'left' in spines:\n ax.yaxis.set_ticks_position('left')\n else:\n ax.yaxis.set_ticks([])\n\n if 'bottom' in spines:\n ax.xaxis.set_ticks_position('bottom')\n else:\n ax.xaxis.set_ticks([])\n \nfig = plt.figure()\nax = plt.subplot(111)\nadjust_spines(ax, ['left','bottom']) \nax.spines['top'].set_color('none')\nax.spines['right'].set_color('none') \nax.spines['bottom'].set_color('darkgrey')\nax.spines['left'].set_color('darkgrey')\nax.spines['bottom'].set_linewidth(2)\nax.spines['left'].set_linewidth(2) \nax.tick_params('both',length=5.5,width=2,which='major',color='darkgrey') \n\n### Plot histograms\nplt.axvline(x=ghg_r2,color='deepskyblue',linewidth=2,linestyle='--',dashes=(1,0.3),\n zorder=10,label=r'\\textbf{AER+}')\nplt.axvline(x=aer_r2,color='gold',linewidth=2,linestyle='--',dashes=(1,0.3),\n zorder=10,label=r'\\textbf{GHG+}')\nplt.axvline(x=lens_r2,color='crimson',linewidth=2,linestyle='--',dashes=(1,0.3),\n zorder=10,label=r'\\textbf{ALL}')\n\n\nweights = np.ones_like(r2)/len(r2)\nn, bins, patches = plt.hist(r2,bins=np.arange(0,1.01,0.025),\n density=False,alpha=1,\n label=r'\\textbf{SHUFFLE}',\n weights=weights,zorder=3,color='w')\nfor i in range(len(patches)):\n patches[i].set_facecolor('w')\n patches[i].set_edgecolor('k')\n patches[i].set_linewidth(1)\n \nleg = plt.legend(shadow=False,fontsize=7,loc='upper center',\n bbox_to_anchor=(0.5,1.1),fancybox=True,ncol=4,frameon=False,\n handlelength=3,handletextpad=1)\nfor line,text in zip(leg.get_lines(), leg.get_texts()):\n text.set_color(line.get_color())\n\nplt.text(0.763,0.3136,r'\\textbf{SHUFFLE}',fontsize=7,color='w',zorder=12)\nplt.ylabel(r'\\textbf{PROPORTION}',fontsize=10,color='w')\nplt.xlabel(r'\\textbf{R$^{2}$ OF OBSERVATIONS}',fontsize=10,color='w')\nplt.yticks(np.arange(0,1.1,0.1),map(str,np.round(np.arange(0,1.1,0.1),2)),size=6)\nplt.xticks(np.arange(0,1.1,0.1),map(str,np.round(np.arange(0,1.1,0.1),2)),size=6)\nplt.xlim([0,1]) \nplt.ylim([0,0.3])\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Read in LRP maps for shuffle data\ndata = Dataset(directorydata2 + 'LRP_Maps_%s_20ens_SHUFFLE-TIMENS.nc' % (SAMPLEQ))\nlat1 = data.variables['lat'][:]\nlon1 = data.variables['lon'][:]\nlrprandom = data.variables['LRP'][:].squeeze()\ndata.close()\n\n### Average across all 500\n# mean = np.nanmean(lrprandom,axis=0)\nmean = lrprandom[0] # example\n\nlabelq = ['LRP-RELEVANCE']\nlimitsq = [np.arange(0,0.5001,0.005)]\nbarlimq = [np.round(np.arange(0,0.6,0.1),2)]\ndatasetsq = [r'SHUFFLE']\ncolorbarendq = ['max']\ncmapq = [cm.classic_16.mpl_colormap]\n\nax1 = plt.axes([.24,.54,.4,.25])\n \nm = Basemap(projection='moll',lon_0=0,resolution='l',area_thresh=10000)\ncircle = m.drawmapboundary(fill_color='dimgrey')\ncircle.set_clip_on(False) \nm.drawcoastlines(color='w',linewidth=0.35)\n\n### Colorbar limits\nbarlim = barlimq[0]\n\nvar, lons_cyclic = addcyclic(mean, lon1)\nvar, lons_cyclic = shiftgrid(180., var, lons_cyclic, start=False)\nlon2d, lat2d = np.meshgrid(lons_cyclic, lat1)\nx, y = m(lon2d, lat2d)\n\n### Make the plot continuous\ncs = m.contourf(x,y,var,limitsq[0],\n extend=colorbarendq[0]) \ncs.set_cmap(cmapq[0])\n\nax1.annotate(r'\\textbf{%s}' % (datasetsq[0]),xy=(0,0),xytext=(0.865,0.92),\n textcoords='axes fraction',color='w',fontsize=9,\n rotation=332,ha='center',va='center')\n\ncbar = m.colorbar(cs,drawedges=False,location='bottom',extendfrac=0.07,\n extend=colorbarendq[0],pad=0.1) \ncbar.set_label(r'\\textbf{%s}' % labelq[0],fontsize=8,color='w',labelpad=1.4) \ncbar.set_ticks(barlim)\ncbar.set_ticklabels(list(map(str,barlim)))\ncbar.ax.tick_params(axis='x', size=.01,labelsize=6,labelcolor='darkgrey')\ncbar.outline.set_edgecolor('darkgrey')\n \nplt.savefig(directoryfigure + 'HistogramR2OfShuffledEns_PAPER_DARK.png',dpi=600)","sub_path":"DarkScripts/plot_R2OfShuffledSpace_PAPER.py","file_name":"plot_R2OfShuffledSpace_PAPER.py","file_ext":"py","file_size_in_byte":6256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40879834","text":"def get_result(x,y):\n if y==0:\n return 1\n elif y==2:\n return x*x\n elif y<2:\n return x\n elif y % 2 != 0:\n return get_result(x * x, (y-1)/2)*x\n elif y % 2 ==0:\n return get_result(x * x,y/2)\n else:\n return 0\n\ndef main():\n try:\n result=0\n x=2\n y=6\n if isinstance(y,int):\n result = get_result(x, y)\n print(result)\n else:\n print(\"please input int for y\")\n except BaseException as e:\n print(e)\n\nif __name__ == \"__main__\":\n main()","sub_path":"x__y.py","file_name":"x__y.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"87966931","text":"from os import abort\r\nfrom flask import Flask, request, abort\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/v1/sanitized/input/', methods=['GET', 'POST'])\r\ndef index():\r\n if request.method == \"POST\":\r\n details = request.form\r\n print(details['input'])\r\n qry=details['input']\r\n if any(item in qry.split() for item in [\"'\" ,'*' , \"-- (--%20)\", ';' , '/*' , '(' ,')' , '--' ]):\r\n print(qry.split())\r\n return {\"Code\":200, \"Message\":\"unsanitized\"},200\r\n else:\r\n return {\"Code\":404,\"Message\":\"sanitized\"},200\r\n else:\r\n return{\"Code\":404,\"Message\":\"Not Post Method\"},404\r\n\r\n\r\n\r\n\r\n # return 'success'\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"FlaskApi.py","file_name":"FlaskApi.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"383894585","text":"# -*- coding: utf-8 -*-\r\n\r\nimport re\r\nfrom requests import request\r\n\r\nimport pickle\r\n \r\nclass Person ():\r\n person_position = None\r\n IO_position = None\r\n \r\n def __init__(self, name =' ', age = ' ', stazh = ' '):\r\n self.name = name\r\n self.age = age\r\n self.stazh = stazh\r\n \r\n def SetPosition(self, person_position, IO_position):\r\n self.person_position = person_position\r\n self.IO_position = IO_position \r\n \r\n def execute(self):\r\n self.person_position.execute(self.name)\r\n \r\n def read(self):\r\n self.IO_position.read(self)\r\n \r\n def write(self):\r\n self.IO_position.write(self)\r\n \r\nclass PersonPosition():\r\n def execute(self, name):\r\n raise NotImplementedError()\r\n \r\nclass DancerPosition(PersonPosition):\r\n def execute(self, name):\r\n print('Я танцор '+ name)\r\n\r\nclass SoloistPosition(PersonPosition):\r\n def execute(self, name):\r\n print('Я солист '+ name)\r\n \r\nclass ChoreographerPosition(PersonPosition):\r\n def execute(self, name):\r\n print('Я хореограф '+ name)\r\n \r\nclass IOPosition():\r\n def read(self, person):\r\n raise NotImplementedError()\r\n def write(self, person):\r\n raise NotImplementedError()\r\n \r\nclass IOConsole(IOPosition):\r\n def read(self, person):\r\n person.name = input(\"name: \")\r\n person.age = input(\"age: \")\r\n person.stazh = input(\"stazh: \")\r\n \r\n def write(self, person):\r\n print(person.name, person.age, person.stazh)\r\n \r\nclass Dancer(Person):\r\n #SetPosition(DancerPosition(), IOConsole())\r\n person_position = DancerPosition()\r\n IO_position= IOConsole()\r\n \r\nclass Soloist(Person):\r\n person_position = SoloistPosition()\r\n IO_position= IOConsole()\r\n\r\nclass Choreographer(Person):\r\n person_position = ChoreographerPosition() \r\n IO_position = IOConsole()\r\n\r\n\r\n \r\nclass group:\r\n def __init__(self):\r\n self.group=[]\r\n self.myid = None\r\n def request(self, method, url, *, json=None):\r\n if self.myid is None:\r\n students = request(\"GET\", \"http://127.0.0.1:5000/\").text\r\n self.myid = re.findall(\r\n r'[\\W]*([st]{2}[0-9]{1,2})[\\W]*\\[1904-02\\][\\W]*', students)[0]\r\n print(self.myid)\r\n kwargs = {\r\n 'method': method,\r\n 'url': f\"http://127.0.0.1:5000/{self.myid}/api/{url}\",\r\n 'headers': {\"Content-Type\": \"application/json\"},\r\n 'json': json,\r\n }\r\n print(url)\r\n return request(**kwargs).json()\r\n\r\n def insertDancer(self):\r\n newDancer = Dancer()\r\n newDancer.read()\r\n self.group.append(newDancer)\r\n trintancor = {\r\n 'name': newDancer.name,\r\n 'stazh': newDancer.stazh,\r\n 'age': newDancer.age,\r\n 'id': -1\r\n }\r\n r = self.request(\r\n 'POST',\r\n 'entry/add',\r\n json=trintancor)\r\n print(\"\\n\" + r['status'])\r\n print('Добавлен Танцор')\r\n \r\n def insertSoloist(self):\r\n newSoloist = Soloist()\r\n newSoloist.read()\r\n self.group.append(newSoloist)\r\n trintancor = {\r\n 'name': newSoloist.name,\r\n 'stazh': newSoloist.stazh,\r\n 'age': newSoloist.age,\r\n 'id': -2\r\n }\r\n r = self.request(\r\n 'POST',\r\n 'entry/add',\r\n json=trintancor)\r\n print(\"\\n\" + r['status'])\r\n self.group.append(newSoloist)\r\n print('Добавлен Солист')\r\n \r\n def insertChoreographer(self):\r\n newChoreographer = Choreographer()\r\n newChoreographer.read()\r\n self.group.append(newChoreographer)\r\n trintancor = {\r\n 'name': newChoreographer.name,\r\n 'stazh': newChoreographer.stazh,\r\n 'age': newChoreographer.age,\r\n 'id': -3\r\n }\r\n r = self.request(\r\n 'POST',\r\n 'entry/add',\r\n json=trintancor)\r\n print(\"\\n\" + r['status'])\r\n self.group.append(newChoreographer)\r\n print('Добавлен Хореограф')\r\n \r\n def execute(self):\r\n self.show()\r\n print('Введите номер: ')\r\n i=int(input())\r\n j=self.item_id.index(i)\r\n self.group[j].execute()\r\n print('Особое действие выполнено')\r\n \r\n def show(self):\r\n self.groupp = self.request('GET', 'get-list')\r\n self.group = []\r\n if self.groupp['list'] == []:\r\n print(\"Список пуст\")\r\n return False\r\n else:\r\n self.item_id = []\r\n for item in self.groupp['list']:\r\n self.item_id.append(item[0])\r\n print(f\"Dancer {item[0]} {item[1]}, {item[2]}, {item[3]}, {item[4]}, {item[5]}\")\r\n if item[5] == \"Танцор\":\r\n newDancer = Dancer()\r\n newDancer.age = item[3]\r\n newDancer.name = item[1]\r\n newDancer.stazh = item[2]\r\n self.group.append(newDancer)\r\n elif item[5] == \"Солист\":\r\n newDancer = Soloist()\r\n newDancer.age = item[3]\r\n newDancer.name = item[1]\r\n newDancer.stazh = item[2]\r\n self.group.append(newDancer)\r\n elif item[5] == \"Хореограф\":\r\n newDancer = Choreographer()\r\n newDancer.age = item[3]\r\n newDancer.name = item[1]\r\n newDancer.stazh = item[2]\r\n self.group.append(newDancer)\r\n \r\n for (i,group) in enumerate (self.group):\r\n print(self.item_id[i])\r\n group.write()\r\n \r\n # print(type(group))\r\n\r\n def edit(self):\r\n self.show()\r\n# print(self.item_id.index(16))\r\n print('Введите номер: ')\r\n i=int(input())\r\n# print(self.item_id.index(i))\r\n j=self.item_id.index(i)\r\n self.group[j].read()\r\n print(self.group[j].name)\r\n trintancor = {\r\n 'name': self.group[j].name,\r\n 'stazh': self.group[j].stazh,\r\n 'age': self.group[j].age,\r\n 'id': i\r\n }\r\n print(self.request('PUT',\r\n f'entry/edit/{i}',\r\n json=trintancor)['status'])\r\n# print(\"\\n\" + r['status']) \r\n print('Отредактирован')\r\n \r\n\r\n def delete(self):\r\n self.show()\r\n print('Введите номер: ')\r\n i=int(input()) \r\n j=self.item_id.index(i)\r\n print(i)\r\n print(self.request('DELETE', f'entry/delete/{i}')['status'])\r\n print('Удален')\r\n\r\n def writefile(self):\r\n f=open('asm1904/st02/group.dat','wb')\r\n pickle.dump(self.group,f)\r\n print('Записано в файл')\r\n \r\n def readfile(self):\r\n f=open('asm1904/st02/group.dat','rb')\r\n self.group = pickle.load(f)\r\n print('Считано из файла')\r\n\r\n def clean(self):\r\n self.group.clear()\r\n print(self.request('DELETE', 'clear')['status'])\r\n print('Очищено')\r\n\r\n def importf(self):\r\n print(self.request('IMPORT', 'import')['status'])\r\n print('Импортировано')\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Container():\r\n def __init__(self):\r\n self.Container=[]\r\n\r\n def insertAM(self):\r\n newAM = AM()\r\n newAM.read()\r\n self.Container.append(newAM)\r\n print('Добавлен автомобиль')\r\n \r\n def insertMOTO(self):\r\n newMOTO = MOTO()\r\n newMOTO.read()\r\n self.Container.append(newMOTO)\r\n print('Добавлен мотоцикл')\r\n \r\n def insertATV(self):\r\n newATV = ATV()\r\n newATV.read()\r\n self.Container.append(newATV)\r\n print('Добавлен квадроцикл')\r\n \r\n def printlist(self):\r\n if not self.Container:\r\n \r\n print('Не найдено')\r\n return\r\n \r\n def spesial(self):\r\n self.printlist()\r\n print('Введите номер: ')\r\n i=int(input())\r\n if (i <= len (self.Container)):\r\n self.Container[i-1].spesial()\r\n else:\r\n print('Такого номера не существует!!!')\r\n\r\n \r\n def show(self):\r\n for (i,Container) in enumerate (self.Container):\r\n print(i+1)\r\n Container.write()\r\n\r\n def edit(self):\r\n self.show()\r\n print('Введите номер: ')\r\n i=int(input())\r\n if (i <= len (self.Container)):\r\n self.Container[i-1].read()\r\n print('Исправленно')\r\n else:\r\n print('Такого номера не существует!!!')\r\n \r\n\r\n def delete(self):\r\n self.show()\r\n print('Введите номер: ')\r\n i=int(input())\r\n if (i <= len (self.Container)):\r\n self.Container.pop(i-1)\r\n print('Удален')\r\n else:\r\n print('Такого номера не существует!!!')\r\n\r\n def writefile(self):\r\n #f=open('desktop/st14/technic.dat','wb')\r\n #pickle.dump(self.Container,f)\r\n with open ('technic.dat','wb') as fp:\r\n pickle.dump(self.Container,fp)\r\n print('Записано в файл')\r\n \r\n def readfile(self):\r\n # f=open('desktop/st14/technic.dat','rb')\r\n #self.Container = pickle.load(f)\r\n with open ('technic.dat','rb') as fp:\r\n self.Container.extend(pickle.load(fp))\r\n print('Считано из файла')\r\n\r\n def clean(self):\r\n self.Container.clear()\r\n print('Очищено')\r\n \r\n \r\n def importf(self):\r\n print(self.request('IMPORT', 'import')['status'])\r\n print('Импортировано')\r\n\r\n \r\n \r\n \r\n \r\n\r\n","sub_path":"clients/asm1904/st02/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":10257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"458673157","text":"###########################################################################\n# Copyright 2020 IoT.bzh\n#\n# author: Fulup Ar Foll \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# Default DNF sack class does not allow to separate system and avaliable repo load\n# This class spilt fil_sack into multiple method to allow multiple rpmdb to be loaded\n# Check dnf/base.py:fill_sack for references\n# b /opt/lib64/python3.7/site-packages/reddnf/sackload.py:39\n\nimport os\nimport dnf\nimport time\nimport datetime\nimport reddnf\nimport logging\nimport yaml\n\nlogger = logging.getLogger(\"dnf\")\n \n\ndef repo_create_empty (base, reponame):\n timer = dnf.logging.Timer('create_empty_sack ****')\n base.reset(sack=True, goal=True)\n base._sack = dnf.sack._build_sack(base)\n lock = dnf.lock.build_metadata_lock(base.conf.cachedir, base.conf.exit_on_lock)\n with lock:\n reddnf._libso._repo_create_empty(base.sack, reponame)\n timer()\n return \n\ndef repo_load_rpmdb (base, reponame, nodedir):\n timer = dnf.logging.Timer('create_empty_sack ****')\n lock = dnf.lock.build_metadata_lock(base.conf.cachedir, base.conf.exit_on_lock)\n with lock:\n reddnf._libso._repo_load_rpmdb(base.sack, reponame, nodedir)\n timer()\n return \n\n# modified fill_sack method from dnf/base.py\ndef repo_load_available(base, nodedir):\n error_repos = []\n mts = 0\n age = time.time()\n conf = base.conf\n \n timer = dnf.logging.Timer('sack_load_available_repos repo ****')\n reddnf._libso._repo_set_rootdir(base.sack, nodedir)\n lock = dnf.lock.build_metadata_lock(base.conf.cachedir, base.conf.exit_on_lock)\n with lock:\n # Iterate over installed GPG keys and check their validity using DNSSEC\n if conf.gpgkey_dns_verification:\n dnf.dnssec.RpmImportedKeys.check_imported_keys_validity()\n for r in base.repos.iter_enabled():\n try:\n base._add_repo_to_sack(r)\n if r._repo.getTimestamp() > mts:\n mts = r._repo.getTimestamp()\n if r._repo.getAge() < age:\n age = r._repo.getAge()\n logger.debug(\"%s: using metadata from %s.\", r.id,\n dnf.util.normalize_time(\n r._repo.getMaxTimestamp()))\n except dnf.exceptions.RepoError as e:\n r._repo.expire()\n if r.skip_if_unavailable is False:\n raise\n logger.warning(\"Error: %s\", e)\n error_repos.append(r.id)\n r.disable()\n if error_repos:\n logger.warning(\"Ignoring repositories: %s\", ', '.join(error_repos))\n if base.repos._any_enabled():\n if age != 0 and mts != 0:\n logger.info(\"Last metadata expiration check: %s ago on %s.\",\n datetime.timedelta(seconds=int(age)),\n dnf.util.normalize_time(mts))\n\n # Force final RPM installation and force destination\n base.conf.installroot=nodedir\n base._sack._configure(base.conf.installonlypkgs)\n base._goal = dnf.goal.Goal(base._sack)\n return","sub_path":"red-dnf/module-py/sources-py/sackload.py","file_name":"sackload.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642124925","text":"import re\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\n\r\nDOMAIN = \"https://en.wikipedia.org\"\r\nINTERNAL = \"^/wiki/\"\r\nMAX_CALLS = 1000\r\n\r\ndef get_url():\r\n url = input(\"Input a start wiki web page: \")\r\n try:\r\n response = requests.get(url)\r\n return url\r\n except Exception as error:\r\n print(\"Something wrong with an url. Write the whole adress, please.\", error)\r\n return get_url() \r\n\r\n\r\ndef get_response(url):\r\n try:\r\n response = requests.get(url)\r\n return response\r\n except Exception as error:\r\n print(url + \"does not response. \", error)\r\n return None\r\n\r\n\r\ndef links_on_page(page):\r\n links = dict([(link.text, DOMAIN + link.attrs['href']) for link in page.find_all('a', href=re.compile(INTERNAL))])\r\n return links\r\n\r\n\r\ndef add_links(url, all_links, calls=MAX_CALLS):\r\n response = get_response(url)\r\n if not response:\r\n return\r\n \r\n page = BeautifulSoup(response.content, 'html.parser')\r\n local_links = links_on_page(page)\r\n all_links.update(local_links)\r\n \r\n for url in local_links.values():\r\n calls -= 1\r\n if calls > 0:\r\n add_links(url, all_links, calls)\r\n\r\n\r\ndef open_fout():\r\n try:\r\n return open(input(\"Input output file: \"), 'w')\r\n except Exception as error:\r\n print(\"Something wrong with an output file.\", error)\r\n return open_fout()\r\n\r\n\r\ndef dump_json(data, fout):\r\n try:\r\n json.dump(data, fout)\r\n print('All https links have been written in', fout.name)\r\n except Exception as error:\r\n print(\"Something wrong with dumping. Try one more time\", error) \r\n\r\nurl = get_url()\r\nall_links = dict()\r\nadd_links(url, all_links)\r\n\r\nfout = open_fout()\r\ndump_json(all_links, fout)\r\nfout.close()","sub_path":"WebParsingInternalLinksRecursievly.py","file_name":"WebParsingInternalLinksRecursievly.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250754342","text":"from flask import Flask, render_template, request, redirect\nfrom contentfulClient.contentful import ContentfulClient\nfrom contentfulClient.model.Utils import ModelSerializer\n\n\napp = Flask(__name__)\n\nlogged_in = False\n\n\n@app.route('/')\ndef index():\n if request.headers.get('Authorization') is None:\n return redirect('http://be.contentful.com/oauth/authorize?response_type=token&client_id=74223773b0811faf2028cb0b5a3197c5a07729a3b7db30d7eac6ac6add470da4&redirect_uri=http://127.0.0.1:5000/reentry&scope=content_management_manage')\n\n client = ContentfulClient()\n message = client.get_message('5TZLutAXJewIqSakAu8SuY')\n return render_template('index.html', message=message)\n\n\n@app.route('/api/v1/blueprints', methods=['GET'])\ndef get_blueprints():\n client = ContentfulClient()\n blueprints = client.get_blueprints()\n return ModelSerializer.serialize_list(blueprints)\n\n\n@app.route('/api/v1/templates', methods=['GET'])\ndef get_templates():\n client = ContentfulClient()\n templates = client.get_templates()\n return ModelSerializer.serialize_list(templates)\n\n\n@app.route('/api/v1/messages', methods=['GET'])\ndef get_messages():\n client = ContentfulClient()\n messages = client.get_messages()\n return ModelSerializer.serialize_list(messages)\n\n@app.route('/reentry')\ndef get_oauthtoken():\n pass\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"221608184","text":"#!/usr/bin/env python\n#encoding: utf8\nimport unittest, rostest\nimport rosnode, rospy\nimport time\nfrom raspicat.msg import MotorFreqs\nfrom geometry_msgs.msg import Twist\nfrom std_srvs.srv import Trigger, TriggerResponse\nfrom raspicat.srv import TimedMotion # 追加\n\nclass MotorTest(unittest.TestCase):\n def setUp(self):\n rospy.wait_for_service('/motor_on')\n rospy.wait_for_service('/motor_off')\n rospy.wait_for_service('/timed_motion') # 追加\n on = rospy.ServiceProxy('/motor_on', Trigger)\n ret = on()\n\n def file_check(self,dev,value,message):\n with open(\"/dev/\" + dev,\"r\") as f:\n s = f.readline()\n self.assertEqual(s,str(value)+\"\\n\",message)\n\n def test_node_exist(self):\n nodes = rosnode.get_node_names()\n self.assertIn('/motors', nodes, \"node does not exist\")\n\n def test_put_freq(self):\n pub = rospy.Publisher('/motor_raw', MotorFreqs)\n m = MotorFreqs()\n m.left_hz = 123 \n m.right_hz = 456 \n for i in range(10):\n pub.publish(m)\n time.sleep(0.1)\n\n self.file_check(\"rtmotor_raw_l0\",m.left_hz,\"wrong left value from motor_raw\")\n self.file_check(\"rtmotor_raw_r0\",m.right_hz,\"wrong right value from motor_raw\")\n\n def test_put_cmd_vel(self):\n pub = rospy.Publisher('/cmd_vel', Twist)\n m = Twist()\n m.linear.x = 0.4775\n m.angular.z = 1.7115\n for i in range(10):\n pub.publish(m)\n time.sleep(0.1)\n\n self.file_check(\"rtmotor_raw_l0\",200,\"wrong left value from cmd_vel\")\n self.file_check(\"rtmotor_raw_r0\",600,\"wrong right value from cmd_vel\")\n\n time.sleep(1.1)\n self.file_check(\"rtmotor_raw_r0\",0,\"don't stop after 1[s]\")\n self.file_check(\"rtmotor_raw_l0\",0,\"don't stop after 1[s]\")\n\n def test_on_off(self):\n off = rospy.ServiceProxy('/motor_off', Trigger)\n ret = off()\n self.assertEqual(ret.success, True, \"motor off does not succeeded\")\n self.assertEqual(ret.message, \"OFF\", \"motor off wrong message\")\n with open(\"/dev/rtmotoren0\",\"r\") as f:\n data = f.readline()\n self.assertEqual(data,\"0\\n\",\"wrong value in rtmotor0 at motor off\")\n\n on = rospy.ServiceProxy('/motor_on', Trigger)\n ret = on()\n self.assertEqual(ret.success, True, \"motor on does not succeeded\")\n self.assertEqual(ret.message, \"ON\", \"motor on wrong message\")\n with open(\"/dev/rtmotoren0\",\"r\") as f:\n data = f.readline()\n self.assertEqual(data,\"1\\n\",\"wrong value in rtmotor0 at motor on\")\n\n def test_put_value_timed(self): #このメソッドを追加\n tm = rospy.ServiceProxy('/timed_motion', TimedMotion)\n tm(-321,654,1500)\n with open(\"/dev/rtmotor0\",\"r\") as f:\n data = f.readline()\n self.assertEqual(data,\"-321 654 1500\\n\",\"value does not written to rtmotor0\")\n\nif __name__ == '__main__':\n rospy.init_node('travis_test_motors')\n rostest.rosrun('raspicat','travis_test_motors', MotorTest)\n","sub_path":"raspicat_ros/test/travis_test_motors.py","file_name":"travis_test_motors.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"397114736","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 5 15:00:34 2018\n\n@author: James Jiang\n\"\"\"\n\nall_lines = [line.rstrip('\\n') for line in open('Data.txt')]\n\ngrid = [[i for i in line] for line in all_lines]\nfor y_corners in [0, 99]:\n for x_corners in [0, 99]:\n grid[y_corners][x_corners] = '#'\n\ngrid_num_neighbors = []\nfor i in range(100):\n row = [0 for j in range(100)]\n grid_num_neighbors.append(row)\n\ndef neighbors_on(x, y):\n if x_position == 0:\n neighbors = [grid[y + 1][x], grid[y - 1][x], grid[y][x + 1], grid[y + 1][x + 1], grid[y - 1][x + 1]]\n elif y_position == 0:\n neighbors = [grid[y + 1][x], grid[y][x + 1], grid[y][x - 1], grid[y + 1][x + 1], grid[y + 1][x - 1]]\n elif x_position == 99:\n neighbors = [grid[y + 1][x], grid[y - 1][x], grid[y][x - 1], grid[y + 1][x - 1], grid[y - 1][x - 1]]\n elif y_position == 99:\n neighbors = [grid[y - 1][x], grid[y][x + 1], grid[y][x - 1], grid[y - 1][x + 1], grid[y - 1][x - 1]]\n else:\n neighbors = [grid[y + 1][x], grid[y - 1][x], grid[y][x + 1], grid[y][x - 1], grid[y + 1][x + 1], grid[y + 1][x - 1], grid[y - 1][x + 1], grid[y - 1][x - 1]]\n return(neighbors.count('#'))\n \ndef next_state(x, y):\n if grid_num_neighbors[y][x] == 3:\n return('#')\n elif (grid_num_neighbors[y][x] == 2) and (grid[y][x] == '#'):\n return('#')\n else:\n return('.')\n\nfor i in range(100):\n for y_position in range(100):\n for x_position in range(100):\n if not((y_position in [0, 99]) and (x_position in [0, 99])):\n grid_num_neighbors[y_position][x_position] = neighbors_on(x_position, y_position)\n for y_position in range(100):\n for x_position in range(100):\n if not((y_position in [0, 99]) and (x_position in [0, 99])):\n grid[y_position][x_position] = next_state(x_position, y_position)\n \ntotal = 0\nfor y in range(100):\n total += grid[y].count('#')\n \nprint(total)","sub_path":"python/2015day18part2.py","file_name":"2015day18part2.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"32665312","text":"# -*- coding: latin-1 -*-\nfrom django.shortcuts import render_to_response\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse, HttpResponseForbidden\nfrom redicos.models import Redico\nfrom propositions.models import Proposition\nfrom evaluations.models import Evaluation\nfrom redicos.forms import RedicoForm\nfrom django.db.models import Count\nfrom django.template import RequestContext, loader\n#from redicos.context_processors import redicos_importants\n#from redicos.context_processors import redicos_dynamiques\nfrom django.contrib.auth.decorators import login_required\n#import pdb;\n\n# Ajout d'un nouveau redico\n@login_required\ndef ajout(request):\n red = Redico(createur=request.user) \n # La forme a ete soumise \n if request.POST:\n redform = RedicoForm(request.POST, instance=red)\n # Invalid form si user deja inscrit par ex. \n if redform.is_valid():\n #redform = redform.save(commit=False)\n #redform.createur = request.user\n redform.save()\n return HttpResponseRedirect('/redico')\n\n # On a clique sur le lien 'Nouveau redico'\n else:\n redform = RedicoForm(instance=red) # Unbound form\n \n return render_to_response('redicos/ajout.html', \n {'form': redform, 'red': red }) #'redico_id':redico_id})\n\ndef edit(request, redico_id=None):\n if redico_id:\n red = Redico.objects.get(id=redico_id)\n if red.createur != request.user:\n raise HttpResponseForbidden()\n else:\n red = Redico(createur=request.user) \n \n #pdb.set_trace()\n if request.POST:\n redform = RedicoForm(request.POST, instance=red)\n # Invalid form si user deja inscrit par ex. \n if redform.is_valid():\n #redform = redform.save(commit=False)\n #redform.createur = request.user\n redform.save()\n return HttpResponseRedirect('/redico')\n else:\n redform = RedicoForm(instance=red) # Unbound form\n \n return render_to_response('redicos/edit.html', \n {'form': redform, 'red': \n red, 'redico_id':redico_id})\n\n\n# Les details d'un redico comprennent ses propositions\n\ndef detail(request, redico_id, statsdetail=None):\n #import pdb;\n #pdb.set_trace()\n try:\n red = Redico.objects.get(pk=redico_id)\n props = Proposition.objects.filter(redico=redico_id).order_by('-id')\n participants = Evaluation.objects.filter(proposition__redico=redico_id).values('joueur__username').distinct()\n stats = calcStats(redico_id)\n red_context = {'red': red, \n 'props': props, \n 'participants': participants, 'stats': stats \n }\n except Redico.DoesNotExist:\n raise Http404\n if statsdetail:\n t = loader.get_template(\"redicos/statsdetail.html\")\n else:\n #pdb.set_trace()\n t = loader.get_template(\"redicos/detail.html\")\n \n c = RequestContext(request, \n red_context, \n #[redicos_importants, \n # redicos_dynamiques]\n )\n return HttpResponse(t.render(c)) \n #render_to_response('redicos/detail.html', # red_context, # context_instance=RequestContext(request), # )\n\n# La liste des redicos et nombre de propositions\ndef index(request):\n # Liste des redicos et du nombre de propositions\n # r[0].proposition__count\n reds = Redico.objects.filter(actif=True).annotate(Count('proposition',distinct=True)) \\\n .annotate(Count('proposition__evaluation__joueur', distinct=True)).order_by('-id')\n #red_context = { 'reds': reds} \n t = loader.get_template(\"redicos/index.html\")\n red_context = {'reds': reds } \n \n c = RequestContext(request, \n red_context) \n #[redicos_importants, \n # redicos_dynamiques])\n \n return HttpResponse(t.render(c))\n #return render_to_response('redicos/index.html', \n # red_context, \n # context_instance=RequestContext(request))\n \n \n\nimport numpy\nimport numpy.ma as ma\nimport itertools\n\n\ndef calcStats(redico_id):\n \n props = Proposition.objects.filter(redico=redico_id)\n joueurs = Evaluation.objects.filter(proposition__redico=redico_id).values('joueur_id', 'joueur__username').distinct()\n joueursList = [(joueur[\"joueur_id\"], joueur[\"joueur__username\"]) for joueur in joueurs]\n propsList = [prop.id for prop in props]\n \n #print(props)\n #print(joueurs) \n \n nbProps = len(propsList)\n tableProps = numpy.zeros(len(propsList), int) # <---------------------int\n nbJoueurs = len(joueursList)\n tableJoueurs = numpy.zeros(len(joueursList), int) # <---------------------int\n \n if nbJoueurs < 2: # NbJoueurs = 1 ou 0 (evite les index out of bounds)\n extraCols=1\n else:\n extraCols = numpy.cumsum(range(1, nbJoueurs))[-1] # Colonnes pour difference\n \n # Reserver une rangee de plus pour les stats\n # et une autre pour le nombre de masques \n extraRan = 0\n tableEvalsPlusDiff = numpy.ma.zeros((nbProps+extraRan, nbJoueurs+extraCols), int)\n \n tableEvalsPlusDiffM = numpy.ma.masked_less(tableEvalsPlusDiff, 0)\n #tableEvalsPlusDiffM.fill_value(-1)\n \n #print(tableEvalsPlusDiff)\n #print(tableEvalsPlusDiffM)\n \n \n # for propositions (horz)\n for idxseq, p in enumerate(propsList):\n p = Proposition.objects.get(id=p)\n tableProps[idxseq] = p.sequence\n # for joueurs (vert) \n for idxjou, (jid, jnom) in enumerate(joueursList): # (0, 2)\n # j = (2, u'Denis')\n tableJoueurs[idxjou] = jid\n try:\n e = p.evaluation_set.get(joueur=jid)\n tableEvalsPlusDiff[idxseq][idxjou] = e.eval\n #print(e, idxseq, idxjou)\n except Evaluation.DoesNotExist:\n tableEvalsPlusDiff[idxseq][idxjou] = -1 # Non /value\n #print(e, idxseq, idxjou)\n \n #print(tableEvalsPlusDiff)\n tableEvalsPlusDiffM = ma.masked_equal(tableEvalsPlusDiff, -1)\n #print(tableEvalsPlusDiffM)\n \n \n \n x = range(nbJoueurs)\n # z([1, 2, 3]) = [(0,1),(0, 2),(0,3), (1, 2),(1, 3),(2, 3)]\n # Combinaison de 2 elements pris parmi nj (nombre de joueurs)\n z = list(itertools.combinations(x, 2))\n #print z # [(0, 1),(0, 2),(1, 2)]\n \n # Remplir colonnes avec calcul de difference\n for ic in range(len(z)): #, c in enumerate([0,1]):\n #tableEvalsDiff[ir][ic] = abs(tableEvals[ir][z[ic][0]] - tableEvals[ir][z[ic][1]])\n \n colGauche = z[ic][0] # (0, .), (0, .), (1, .)\n colDroite = z[ic][1] # (., 1), (., 2), (., 2)\n \n tmp1 = tableEvalsPlusDiffM[:, colGauche]\n tmp2 = tableEvalsPlusDiffM[:, colDroite]\n tableEvalsPlusDiffM[:, ic+nbJoueurs] = abs(tmp1-tmp2)\n \n \n # Pour le calcul des stats, ne pas inclure la derniere rangee \n # qui est reserve pour le bn de masques ni l'avant derniere \n # pour la moyenne\n lstAvg = numpy.ma.average(tableEvalsPlusDiffM, axis=0)\n nbMask = ma.count_masked(tableEvalsPlusDiffM, axis=0)\n lstEvals = nbProps - nbMask\n \n \n # La liste des differences entre joueurs\n \n lstCouples = []\n for idx, zz in enumerate(z):\n j1 = joueurs[zz[0]][\"joueur__username\"]\n j2 = joueurs[zz[1]][\"joueur__username\"]\n lstCouples.append(j1[:4] + \"-\" + j2[:4]) # Racourcir les noms pour les tableaux\n #print(lstCouples)\n \n \n # Retourner que les stats de la table et les couples\n return [tableEvalsPlusDiffM[:, -len(z):], lstAvg[-len(z):], lstEvals[-len(z):], lstCouples]\n\n\n\n\n\n\n","sub_path":"redico/redicos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"74119806","text":"# -*- coding: utf-8 -*-\n\"\"\"Generating a cosmological summary of the H0 or D_dt H0_samples\n\nExample\n-------\nTo run this script, pass in the version ID and the sampling method as the argument::\n \n $ python summarize.py 21 simple_mc_default\n\nThe summary will be saved to the same directory level as the sample directory.\n\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport scipy.stats\nfrom baobab.configs import BaobabConfig\nfrom h0rton.configs import TestConfig\nimport h0rton.h0_inference.h0_utils as h0_utils\nimport h0rton.tdlmc_utils as tdlmc_utils\n\ndef parse_args():\n \"\"\"Parse command-line arguments\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('version_id', help='version ID', type=int)\n parser.add_argument('sampling_method', help='the sampling method (one of simple_mc_default, mcmc_default, hybrid', type=str)\n parser.add_argument('--rung_idx', help='the TDLMC rung index, if H0rton was run on TDLMC data', type=int, default=None)\n args = parser.parse_args()\n return args\n\ndef main():\n args = parse_args()\n # Folder where all the H0 samples live\n samples_dir = '/home/jwp/stage/sl/h0rton/experiments/v{:d}/{:s}'.format(args.version_id, args.sampling_method)\n # Read in test cfg for this version and sampling method\n test_cfg_path = os.path.join(samples_dir, '..', '{:s}.json'.format(args.sampling_method))\n test_cfg = TestConfig.from_file(test_cfg_path)\n if 'mcmc_default' in args.sampling_method:\n summarize_mcmc(samples_dir, test_cfg, 'mcmc_default', args.rung_idx)\n elif args.sampling_method == 'hybrid':\n summarize_mcmc(samples_dir, test_cfg, 'hybrid')\n elif args.sampling_method == 'simple_mc_default':\n summarize_simple_mc_default(samples_dir, test_cfg)\n else:\n raise ValueError(\"This sampling method is not supported. Choose one of [simple_mc_default, mcmc_default, hybrid].\")\n\ndef summarize_simple_mc_default(samples_dir, test_cfg):\n \"\"\"Summarize the output of simple_mc_default, i.e. the uniform H0 samples with corresponding weights\n\n \"\"\"\n H0_dicts = [f for f in os.listdir(samples_dir) if f.startswith('h0_dict')]\n H0_dicts.sort()\n # Read in the redshift columns of metadata\n baobab_cfg = BaobabConfig.from_file(test_cfg.data.test_baobab_cfg_path)\n metadata_path = os.path.join(baobab_cfg.out_dir, 'metadata.csv')\n meta = pd.read_csv(metadata_path, index_col=None, usecols=['z_lens', 'z_src', 'n_img'])\n\n summary_df = pd.DataFrame() # instantiate empty dataframe for storing summary\n for i, f_name in enumerate(H0_dicts):\n lens_i = int(os.path.splitext(f_name)[0].split('h0_dict_')[1])\n # Slice meta for this lensing system\n meta_i = meta.iloc[lens_i]\n z_lens = meta_i['z_lens']\n z_src = meta_i['z_src']\n n_img = meta_i['n_img']\n # Read in H0 samples using lens identifier\n H0_dict = np.load(os.path.join(samples_dir, f_name), allow_pickle=True).item()\n H0_samples = H0_dict['h0_samples']\n weights = H0_dict['h0_weights']\n H0_normal_stats = h0_utils.get_normal_stats_naive(H0_samples, weights)\n n_eff = np.sum(weights)**2.0/(np.sum(weights**2.0))\n # Convert H0 H0_samples to D_dt\n cosmo_converter = h0_utils.CosmoConverter(z_lens, z_src)\n D_dt_samples = cosmo_converter.get_D_dt(H0_samples)\n D_dt_stats = h0_utils.get_lognormal_stats_naive(D_dt_samples, weights)\n D_dt_normal_stats = h0_utils.get_normal_stats_naive(D_dt_samples, weights)\n summary_i = dict(\n id=lens_i,\n measured_td_wrt0=list(H0_dict['measured_td_wrt0']),\n H0_mean=H0_normal_stats['mean'],\n H0_std=H0_normal_stats['std'],\n D_dt_mu=D_dt_stats['mu'],\n D_dt_sigma=D_dt_stats['sigma'],\n D_dt_mean=D_dt_normal_stats['mean'],\n D_dt_std=D_dt_normal_stats['std'],\n n_eff=n_eff,\n z_lens=z_lens,\n z_src=z_src,\n n_img=n_img,\n inference_time=H0_dict['inference_time'],\n )\n summary_df = summary_df.append(summary_i, ignore_index=True)\n summary_df.to_csv(os.path.join(samples_dir, '..', 'summary.csv'))\n # Output list of problem lens IDs\n problem_id = summary_df.loc[(summary_df['n_eff'] < 3) | (summary_df['H0_std'] < 1.0)]['id'].astype(int)\n with open(os.path.join(samples_dir, '..', \"mcmc_default_candidates.txt\"), \"w\") as f:\n for pid in problem_id:\n f.write(str(pid) +\"\\n\")\n\ndef summarize_mcmc(samples_dir, test_cfg, sampling_method, rung_idx):\n \"\"\"Summarize the output of mcmc_default, i.e. MCMC samples from the D_dt posterior for each lens\n\n \"\"\"\n true_H0 = 70.0\n true_Om0 = 0.3\n if 'mcmc_default' in sampling_method:\n if rung_idx is None:\n # Read in the relevant columns of metadata, \n baobab_cfg = BaobabConfig.from_file(test_cfg.data.test_baobab_cfg_path)\n metadata_path = os.path.join(baobab_cfg.out_dir, 'metadata.csv')\n summary_df = pd.read_csv(metadata_path, index_col=None, usecols=['z_lens', 'z_src', 'n_img'], nrows=500) # FIXME: capped test set size at 500, as the stored dataset may be much larger\n else:\n summary_df = tdlmc_utils.convert_to_dataframe(rung=rung_idx, save_csv_path=None)\n summary_df.sort_values('seed', axis=0, inplace=True)\n true_H0 = summary_df.iloc[0]['H0']\n true_Om0 = 0.27\n summary_df['id'] = summary_df.index\n summary_df['D_dt_mu'] = np.nan\n summary_df['D_dt_sigma'] = np.nan\n summary_df['H0_mean'] = np.nan\n summary_df['H0_std'] = np.nan\n summary_df['inference_time'] = 0.0\n else:\n summary_df = pd.read_csv(os.path.join(samples_dir, '..', 'summary.csv'), index_col=None) \n\n D_dt_dicts = [f for f in os.listdir(samples_dir) if f.startswith('D_dt_dict')]\n D_dt_dicts.sort()\n oversampling = 20\n threshold = 1000\n # Initialize list for catastrophic lenses not solved by MCMC\n lenses_to_rerun = []\n lenses_run = []\n for i, f_name in enumerate(D_dt_dicts):\n lens_i = int(os.path.splitext(f_name)[0].split('D_dt_dict_')[1])\n lenses_run.append(lens_i)\n meta = summary_df.loc[summary_df['id']==lens_i, ['z_lens', 'z_src']].squeeze()\n # Read in D_dt samples using lens identifier\n D_dt_dict = np.load(os.path.join(samples_dir, f_name), allow_pickle=True).item()\n # Rescale D_dt samples to correct for k_ext\n uncorrected_D_dt_samples = D_dt_dict['D_dt_samples'] # [old_n_samples,]\n uncorrected_D_dt_samples = h0_utils.remove_outliers_from_lognormal(uncorrected_D_dt_samples, 3).reshape(-1, 1) # [n_samples, 1] \n k_ext_rv = getattr(scipy.stats, test_cfg.kappa_ext_prior.dist)(**test_cfg.kappa_ext_prior.kwargs)\n k_ext = k_ext_rv.rvs(size=[len(uncorrected_D_dt_samples), oversampling]) # [n_samples, oversampling]\n if test_cfg.kappa_ext_prior.transformed:\n D_dt_samples = (uncorrected_D_dt_samples*k_ext).flatten()\n else:\n D_dt_samples = (uncorrected_D_dt_samples/(1.0 - k_ext)).flatten() # [n_samples,]\n # Compute lognormal params for D_dt and update summary\n try:\n D_dt_stats = h0_utils.get_lognormal_stats(D_dt_samples)\n D_dt_normal_stats = h0_utils.get_normal_stats(D_dt_samples)\n except:\n print(\"lens\", lens_i)\n print(\"==========\")\n lenses_to_rerun.append(lens_i)\n #continue\n summary_df.loc[summary_df['id']==lens_i, 'D_dt_mu'] = D_dt_stats['mu']\n summary_df.loc[summary_df['id']==lens_i, 'D_dt_sigma'] = D_dt_stats['sigma']\n summary_df.loc[summary_df['id']==lens_i, 'D_dt_mean'] = D_dt_normal_stats['mean']\n summary_df.loc[summary_df['id']==lens_i, 'D_dt_std'] = D_dt_normal_stats['std']\n # Convert D_dt samples to H0\n D_dt_samples = scipy.stats.lognorm.rvs(scale=np.exp(D_dt_stats['mu']), s=D_dt_stats['sigma'], size=oversampling*threshold)\n D_dt_samples = D_dt_samples[np.isfinite(D_dt_samples)]\n cosmo_converter = h0_utils.CosmoConverter(meta['z_lens'], meta['z_src'], H0=true_H0, Om0=true_Om0)\n H0_samples = cosmo_converter.get_H0(D_dt_samples)\n # Reject H0 samples outside H0 prior\n H0_samples = H0_samples[np.isfinite(H0_samples)]\n if len(H0_samples) > 0:\n H0_samples = H0_samples[np.logical_and(H0_samples > 50.0, H0_samples < 90.0)]\n if len(H0_samples) < threshold:\n lenses_to_rerun.append(lens_i)\n summary_df.loc[summary_df['id']==lens_i, 'H0_mean'] = np.mean(H0_samples)\n summary_df.loc[summary_df['id']==lens_i, 'H0_std'] = np.std(H0_samples)\n summary_df.loc[summary_df['id']==lens_i, 'inference_time'] += D_dt_dict['inference_time']\n # Replace existing summary\n summary_df.to_csv(os.path.join(samples_dir, '..', 'summary.csv'))\n # Output list of catastrophic/no-good lens IDs\n if sampling_method == 'mcmc_default':\n # List of lenses that skipped MCMC\n total_lenses = np.arange(test_cfg.data.n_test)\n lenses_not_run = set(list(total_lenses)) - set(list(lenses_run))\n lenses_for_hybrid = list(lenses_not_run.union(set(lenses_to_rerun)))\n with open(os.path.join(samples_dir, '..', \"hybrid_candidates.txt\"), \"w\") as f:\n for lens_i in lenses_for_hybrid:\n f.write(str(lens_i) +\"\\n\")\n else: # hybrid case\n with open(os.path.join(samples_dir, '..', \"no_good_candidates.txt\"), \"w\") as f:\n for lens_i in lenses_to_rerun:\n f.write(str(lens_i) +\"\\n\")\n\nif __name__ == '__main__':\n main()","sub_path":"h0rton/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":9880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"353254521","text":"# Copyright (c) 2021 The Regents of the University of California\n# Copyright (c) 2021 The University of Texas at Austin\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met: 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 the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (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\"\"\"\nThe purpose of this Suite of tests is to check that the simulator can be forked\nwith the KVM cpu then switch to a different cpu and run in the child.\n\"\"\"\n\nimport os\n\nfrom testlib import *\n\nif config.bin_path:\n resource_path = config.bin_path\nelse:\n resource_path = joinpath(absdirpath(__file__), \"..\", \"resources\")\n\n\ndef test_kvm_fork_run(cpu: str, num_cpus: int, mem_system: str, length: str):\n\n if not os.access(\"/dev/kvm\", mode=os.R_OK | os.W_OK):\n # Don't run the tests if KVM is unavailable.\n return\n\n name = f\"{cpu}-cpu_{str(num_cpus)}-cores_{mem_system}_kvm-fork-run-test\"\n verifiers = []\n\n if mem_system == \"mesi_two_level\":\n protocol_to_use = None\n isa_to_use = constants.all_compiled_tag\n elif mem_system == \"mi_example\":\n protocol_to_use = \"MI_example\"\n isa_to_use = constants.x86_tag\n else:\n protocol_to_use = None\n isa_to_use = constants.all_compiled_tag\n\n gem5_verify_config(\n name=name,\n verifiers=verifiers,\n fixtures=(),\n config=joinpath(\n config.base_dir, \"tests\", \"gem5\", \"configs\", \"boot_kvm_fork_run.py\"\n ),\n config_args=[\n \"--cpu\",\n cpu,\n \"--num-cpus\",\n str(num_cpus),\n \"--num-forks\",\n \"4\",\n \"--mem-system\",\n mem_system,\n \"--resource-directory\",\n resource_path,\n \"--kernel-args=''\",\n ],\n valid_isas=(isa_to_use,),\n valid_hosts=(constants.host_x86_64_tag,),\n protocol=protocol_to_use,\n length=length,\n uses_kvm=True,\n )\n\n\n#### The quick (pre-submit/Kokoro) tests ####\n\ntest_kvm_fork_run(\n cpu=\"atomic\", num_cpus=1, mem_system=\"classic\", length=constants.quick_tag\n)\ntest_kvm_fork_run(\n cpu=\"timing\", num_cpus=1, mem_system=\"classic\", length=constants.quick_tag\n)\ntest_kvm_fork_run(\n cpu=\"o3\", num_cpus=1, mem_system=\"classic\", length=constants.quick_tag\n)\ntest_kvm_fork_run(\n cpu=\"timing\", num_cpus=4, mem_system=\"classic\", length=constants.quick_tag\n)\n\n### The long (nightly) tests ####\n\ntest_kvm_fork_run(\n cpu=\"timing\",\n num_cpus=4,\n mem_system=\"mi_example\",\n length=constants.long_tag,\n)\n\ntest_kvm_fork_run(\n cpu=\"timing\",\n num_cpus=1,\n mem_system=\"mesi_two_level\",\n length=constants.long_tag,\n)\ntest_kvm_fork_run(\n cpu=\"o3\",\n num_cpus=8,\n mem_system=\"mesi_two_level\",\n length=constants.long_tag,\n)\n\ntest_kvm_fork_run(\n cpu=\"timing\",\n num_cpus=2,\n mem_system=\"mesi_two_level\",\n length=constants.long_tag,\n)\n","sub_path":"tests/gem5/kvm-fork-tests/test_kvm_fork_run.py","file_name":"test_kvm_fork_run.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"93562755","text":"import torch\nimport torch.nn.functional as F\n\nfrom visualize_glimpse import visualize_glimpse\n\n\nclass GlimpseSensor:\n \"\"\"\n Module for the glimpse sensor for the glimpse network. This is responsible\n for generating \"glimpses\" of a given region from an image.\n \"\"\"\n\n def __init__(self, glimpse_size, num_zooms, zoom_amt):\n super().__init__()\n\n self.glimpse_size = glimpse_size\n self.num_zooms = num_zooms\n self.zoom_amt = zoom_amt\n\n def glimpse(self, images, location):\n \"\"\"\n Function that returns the glimpse of the sensor at a given location.\n For now, this will just be the single image itself. In future iterations,\n it will support several zoom levels.\n \"\"\"\n visualize = False\n\n dist = self.glimpse_size // 2\n\n # get the image size to be used to convert the coordinates\n location = self.convert_location(location, images.shape[2])\n\n # factor to \"zoom out\" images\n factor = 1\n patches = []\n\n # generate patches for each zoom level\n for i in range(self.num_zooms):\n patch = self.get_zoomed_patch(images, location, factor)\n patches.append(patch)\n factor = factor * self.zoom_amt\n\n # reshape zoomed out images to smallest size\n for i in range(len(patches)):\n zoom_factor = patches[i].shape[-1] // self.glimpse_size\n patches[i] = F.avg_pool2d(patches[i], zoom_factor)\n\n if visualize:\n # to visualize given glimpses\n visualize_glimpse(patches, images, location)\n\n # concatenate into tensor, and flatten\n patches = torch.cat(patches, 1)\n patches = patches.view(patches.shape[0], -1)\n\n return patches\n\n def get_zoomed_patch(self, img, location, factor):\n \"\"\"\n Gets the patch for a given image at a location l, with scaling size.\n \"\"\"\n\n # total image size scaled by factor of zoom\n total_size = self.glimpse_size * factor\n\n dist = total_size // 2\n\n # pad image so there's no bad indexing\n img = F.pad(img, (dist, dist, dist, dist))\n\n patches = []\n # over each image in the batch\n for i in range(location.shape[0]):\n # get coordinates of glimpse\n x = location[i, 0].int()\n y = location[i, 1].int()\n\n # factor padding into initial location\n x_start = x + dist\n y_start = y + dist\n\n # extract the patch\n patch = img[i, :, x_start - dist: x_start + dist,\n y_start - dist: y_start + dist]\n\n # add the patch to the current set\n patches.append(patch)\n\n # return list of patches as a tensor\n return torch.stack(patches)\n\n def convert_location(self, location, image_size):\n \"\"\"\n Image coordinates need to be represented as a value in the range of\n [-1, 1]. In order to index the given image, these coordinates need\n to be scaled to [0, img_size] where img_size is the size of the image\n \"\"\"\n # gives range [0, 2*image_size]\n loc_2 = (1 + location) * image_size\n\n # return values in range [0, image_size]\n return (loc_2 * 0.5).long()\n","sub_path":"glimpse_sensor.py","file_name":"glimpse_sensor.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"341998742","text":"import os\nimport socket\n\nimport httplib2\nfrom django.core.files.base import ContentFile\nfrom django.core.files.storage import default_storage\n\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaFileUpload\nfrom django.http import HttpResponseBadRequest\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\n\nfrom SaveWiki.utils import WikipediaController\nfrom app_user.forms import Upload\nfrom app_user.models import CredentialsModel\nfrom oauth2client.contrib import xsrfutil\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.contrib.django_util.storage import DjangoORMStorage\nfrom django.shortcuts import render\nfrom httplib2 import Http\n\n\n\nFLOW = flow_from_clientsecrets(\n settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,\n scope='https://www.googleapis.com/auth/drive',\n redirect_uri='http://127.0.0.1:8000/index',\n prompt='consent')\n\n\ndef gmail_authenticate(request):\n storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')\n credential = storage.get()\n\n if credential is None or credential.invalid:\n FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,\n request.user)\n authorize_url = FLOW.step1_get_authorize_url()\n return HttpResponseRedirect(authorize_url)\n else:\n http = httplib2.Http()\n http = credential.authorize(http)\n service = build('drive', 'v3', http=http)\n print('access_token = ', credential.access_token)\n status = True\n\n return render(request, 'index.html', {'status': status})\n\n\ndef auth_return(request):\n get_state = bytes(request.GET.get('state'), 'utf8')\n if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,\n request.user):\n return HttpResponseBadRequest()\n credential = FLOW.step2_exchange(request.GET.get('code'))\n storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')\n storage.put(credential)\n print(\"access_token: %s\" % credential.access_token)\n return HttpResponseRedirect(\"/\")\n\n\ndef home(request):\n status = True\n\n if not request.user.is_authenticated:\n return HttpResponseRedirect('admin')\n\n storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')\n credential = storage.get()\n\n try:\n access_token = credential.access_token\n resp, cont = Http().request(\"https://www.googleapis.com/auth/gmail.readonly\",\n headers={'Host': 'www.googleapis.com',\n 'Authorization': access_token})\n print(\"dfdf\",resp,cont)\n except:\n status = False\n print('Not Found')\n\n if request.method == \"POST\":\n form = Upload(request.POST,request.FILES)\n if form.is_valid():\n\n wiki_obj = WikipediaController(form.cleaned_data.get(\"wiki\"))\n path, name = wiki_obj.download_pdf()\n\n\n tmp_file = os.path.join(settings.MEDIA_ROOT, path)\n\n socket.setdefaulttimeout(600) # set timeout to 10 minutes\n\n # file upload\n service = build('drive', 'v3', credentials=credential)\n media = MediaFileUpload(tmp_file, mimetype='application/pdf')\n # media = MediaFileUpload(tmp_file, mimetype='image/jpeg')\n file = service.files().create(body={\"name\":name},\n media_body=media,\n fields='id').execute()\n\n print(file.get('id'))\n\n else:\n form = Upload()\n\n return render(request, 'test.html', {'status': status, \"form\":form})","sub_path":"app_user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"542552171","text":"\n\nfrom xai.brain.wordbase.adjectives._elite import _ELITE\n\n#calss header\nclass _ELITES(_ELITE, ):\n\tdef __init__(self,): \n\t\t_ELITE.__init__(self)\n\t\tself.name = \"ELITES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"elite\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_elites.py","file_name":"_elites.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138088993","text":"import sys\n\norig_stdout = sys.stdout\nf = open('out_600_01.txt', 'w')\nsys.stdout = f\n\nfrom scipy.optimize import fsolve\nfrom first_1000_zeta import first_1000_zeta\nfrom utility import Ht_real\n\nfirst_1000_H0_zero = [x*2 for x in first_1000_zeta]\n\nfor j in range(0, 50):\n t = .01*1\n for i, nearby_root in enumerate(first_1000_H0_zero[600:700]):\n Ht_root = fsolve(Ht_real, nearby_root, args=(t,))[0]\n print(t, i, Ht_root)\n\nsys.stdout = orig_stdout\nf.close()\n","sub_path":"dbn_upper_bound/python/H_t_probable_first_1000_zeroes.py","file_name":"H_t_probable_first_1000_zeroes.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649344619","text":"from __future__ import absolute_import\nfrom tornado.httpclient import HTTPClient, HTTPRequest\nfrom tornado.ioloop import IOLoop\nimport tornado.options\nimport json\nimport time\nimport calendar\nimport email.utils\nimport mailbox\nimport email\nimport quopri\nimport chardet\nfrom DelegatingEmailParser import DelegatingEmailParser\nfrom AmazonEmailParser import AmazonEmailParser\nfrom SteamEmailParser import SteamEmailParser\nimport logging\n\nhttp_client = HTTPClient()\n\nDEFAULT_BATCH_SIZE = 500\nDEFAULT_ES_URL = \"http://localhost:9200\"\nDEFAULT_INDEX_NAME = \"gmail\"\n\n\ndef delete_index():\n try:\n url = \"%s/%s?refresh=true\" % (tornado.options.options.es_url, tornado.options.options.index_name)\n request = HTTPRequest(url, method=\"DELETE\", request_timeout=240)\n body = {\"refresh\": True}\n response = http_client.fetch(request)\n logging.info('Delete index done %s' % response.body)\n except:\n pass\n\n\ndef create_index():\n\n schema = {\n \"settings\": {\n \"number_of_shards\": tornado.options.options.num_of_shards,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"email\": {\n \"_source\": {\"enabled\": True},\n \"properties\": {\n \"from\": {\"type\": \"string\", \"index\": \"not_analyzed\"},\n \"return-path\": {\"type\": \"string\", \"index\": \"not_analyzed\"},\n \"delivered-to\": {\"type\": \"string\", \"index\": \"not_analyzed\"},\n \"message-id\": {\"type\": \"string\", \"index\": \"not_analyzed\"},\n \"to\": {\"type\": \"string\", \"index\": \"not_analyzed\"},\n \"date_ts\": {\"type\": \"date\"},\n },\n }\n },\n \"refresh\": True\n }\n\n body = json.dumps(schema)\n url = \"%s/%s\" % (tornado.options.options.es_url, tornado.options.options.index_name)\n try:\n request = HTTPRequest(url, method=\"PUT\", body=body, request_timeout=240)\n response = http_client.fetch(request)\n logging.info('Create index done %s' % response.body)\n except:\n pass\n\n\ntotal_uploaded = 0\n\n\ndef upload_batch(upload_data):\n upload_data_txt = \"\"\n for item in upload_data:\n cmd = {'index': {'_index': tornado.options.options.index_name, '_type': 'email', '_id': item['message-id']}}\n upload_data_txt += json.dumps(cmd) + \"\\n\"\n upload_data_txt += json.dumps(item) + \"\\n\"\n\n request = HTTPRequest(tornado.options.options.es_url + \"/_bulk\", method=\"POST\", body=upload_data_txt, request_timeout=240)\n response = http_client.fetch(request)\n result = json.loads(response.body)\n\n global total_uploaded\n total_uploaded += len(upload_data)\n res_txt = \"OK\" if not result['errors'] else \"FAILED\"\n logging.info(\"Upload: %s - upload took: %4dms, total messages uploaded: %6d\" % (res_txt, result['took'], total_uploaded))\n\n\ndef normalize_email(email_in):\n parsed = email.utils.parseaddr(email_in)\n return parsed[1]\n\n\ndef convert_msg_to_json(msg):\n result = {'parts': []}\n if not 'message-id' in msg:\n return None\n\n for (k, v) in msg.items():\n result[k.lower()] = v.decode('utf-8', 'ignore')\n\n for k in ['to', 'cc', 'bcc']:\n if not result.get(k):\n continue\n emails_split = result[k].replace('\\n', '').replace('\\t', '').replace('\\r', '').replace(' ', '').encode('utf8').decode('utf-8', 'ignore').split(',')\n result[k] = [normalize_email(e) for e in emails_split]\n\n if \"from\" in result:\n result['from'] = normalize_email(result['from'])\n\n if \"date\" in result:\n try:\n tt = email.utils.parsedate_tz(result['date'])\n tz = tt[9] if len(tt) == 10 and tt[9] else 0\n result['date_ts'] = int(calendar.timegm(tt) - tz) * 1000\n except:\n return None\n\n labels = []\n if \"x-gmail-labels\" in result:\n labels = [l.strip().lower() for l in result[\"x-gmail-labels\"].split(',')]\n del result[\"x-gmail-labels\"]\n result['labels'] = labels\n\n parts = result.get(\"parts\", [])\n result['content_size_total'] = 0\n for part in parts:\n result['content_size_total'] += len(part.get('content', \"\"))\n\n return result\n\n\ndef load_from_file():\n\n if tornado.options.options.init:\n delete_index()\n create_index()\n\n if tornado.options.options.skip:\n logging.info(\"Skipping first %d messages from mbox file\" % tornado.options.options.skip)\n\n count = 0\n upload_data = list()\n logging.info(\"Starting import from file %s\" % tornado.options.options.infile)\n mbox = mailbox.UnixMailbox(open(tornado.options.options.infile, 'rb'), email.message_from_file)\n\n emailParser = DelegatingEmailParser([AmazonEmailParser(), SteamEmailParser()])\n\n for msg in mbox:\n count += 1\n if count < tornado.options.options.skip:\n continue\n item = convert_msg_to_json(msg)\n if item:\n upload_data.append(item)\n if len(upload_data) == tornado.options.options.batch_size:\n upload_batch(upload_data)\n upload_data = list()\n\n # upload remaining items in `upload_batch`\n if upload_data:\n upload_batch(upload_data)\n\n logging.info(\"Import done - total count %d\" % count)\n\n\nif __name__ == '__main__':\n\n tornado.options.define(\"es_url\", type=str, default=DEFAULT_ES_URL,\n help=\"URL of your Elasticsearch node\")\n\n tornado.options.define(\"index_name\", type=str, default=DEFAULT_INDEX_NAME,\n help=\"Name of the index to store your messages\")\n\n tornado.options.define(\"infile\", type=str, default=None,\n help=\"The mbox input file\")\n\n tornado.options.define(\"init\", type=bool, default=False,\n help=\"Force deleting and re-initializing the Elasticsearch index\")\n\n tornado.options.define(\"batch_size\", type=int, default=DEFAULT_BATCH_SIZE,\n help=\"Elasticsearch bulk index batch size\")\n\n tornado.options.define(\"skip\", type=int, default=0,\n help=\"Number of messages to skip from the mbox file\")\n\n tornado.options.define(\"num_of_shards\", type=int, default=2,\n help=\"Number of shards for ES index\")\n\n tornado.options.parse_command_line()\n\n if tornado.options.options.infile:\n IOLoop.instance().run_sync(load_from_file)\n else:\n tornado.options.print_help()\n","sub_path":"src/index_emails.py","file_name":"index_emails.py","file_ext":"py","file_size_in_byte":6460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"167323187","text":"import pandas as pd\nimport seaborn\nfrom bokeh.plotting import figure, show\nfrom bokeh.models import ColumnDataSource, FactorRange, Legend, HoverTool\nimport os\n\nfile_path = os.path.dirname(os.path.abspath(__file__))\n\npalette = seaborn.color_palette(\"RdYlGn\").as_hex()\npalette = [palette[0], palette[round(len(palette)/2)], palette[-1]]\n\ncb_palette = seaborn.color_palette(\"Blues_r\").as_hex()\ncb_palette = [cb_palette[0], cb_palette[round(len(cb_palette)/2)], cb_palette[-1]]\n\ncolors = [\"red\", \"yellow\", \"green\"]\ncb_colors = [\"high\", \"medium\", \"low\"]\ncolor_map = {}\ncb_color_map = {}\n\nfor p in palette:\n color_map.update({colors[palette.index(p)]: p})\n\nfor cp in cb_palette:\n cb_color_map.update({cb_colors[cb_palette.index(cp)]: cp})\n\n\ndf = pd.read_excel(\"app/data/Rubric.xlsx\", \"Rubric v3\")\ndf = df.drop([\"Category\", \"Grading Scale\", \"Definition\"], axis=1)#df[[\"Criteria\", \"Atlas.ti\", \"Dedoose\", \"MAXQDA\", \"NVivo\", \"Transana\", \"TOM\", \"QDA Miner\"]]\n\ndefinitions = pd.read_excel(\"app/data/Rubric.xlsx\", \"Definitions\")\n\ndefinitions[\"Definition\"] = definitions[\"Definition\"].str.replace(\"\\n\", \"
\")\n\ndefinitions[\"Definition\"].fillna(\"\", inplace=True)\n\ndf = df.melt(id_vars=[\"Criteria\"], var_name=\"Tool\", value_name=\"Score\")\ndf = df.merge(definitions, how=\"left\", on=[\"Criteria\", \"Score\"])\n\ndf.loc[df.Score == \"Excellent\", \"color\"] = color_map[\"green\"]\ndf.loc[df.Score == \"Good\", \"color\"] = color_map[\"yellow\"]\ndf.loc[df.Score == \"Poor\", \"color\"] = color_map[\"red\"]\n\ndf.loc[df.Score == \"Excellent\", \"cb_color\"] = cb_color_map[\"high\"]\ndf.loc[df.Score == \"Good\", \"cb_color\"] = cb_color_map[\"medium\"]\ndf.loc[df.Score == \"Poor\", \"cb_color\"] = cb_color_map[\"low\"]\n\ndf['Score'] = pd.Categorical(df['Score'], [\"Excellent\", \"Good\", \"Poor\"])\ndf['Tool'] = pd.Categorical(df['Tool'], [\"NVivo\", \"Dedoose\", \"QDA Miner\", \"Atlas.ti\", \"Transana\", \"TOM\", \"MAXQDA\"])\n\ndf_excellent = df.loc[df.Score == \"Excellent\"]\ndf_fair = df.loc[df.Score == \"Good\"]\ndf_poor = df.loc[df.Score == \"Poor\"]\n\n\ny_range = FactorRange(factors=df[\"Criteria\"].drop_duplicates().tolist()[::-1])\nx_range = FactorRange(factors=df[\"Tool\"].drop_duplicates().tolist())\n\n\nexcellent_source = ColumnDataSource(data=dict(criteria=df_excellent[\"Criteria\"].tolist(),\n tool=df_excellent[\"Tool\"].tolist(),\n score=df_excellent[\"Score\"].tolist(),\n color=df_excellent[\"color\"].tolist(),\n cb_color=df_excellent[\"cb_color\"].tolist(),\n desc=df_excellent[\"Definition\"].tolist()))\n\nfair_source = ColumnDataSource(data=dict(criteria=df_fair[\"Criteria\"].tolist(), tool=df_fair[\"Tool\"].tolist(),\n score=df_fair[\"Score\"].tolist(), color=df_fair[\"color\"].tolist(),\n cb_color=df_fair[\"cb_color\"].tolist(), desc=df_fair[\"Definition\"].tolist()))\n\npoor_source = ColumnDataSource(data=dict(criteria=df_poor[\"Criteria\"].tolist(), tool=df_poor[\"Tool\"].tolist(),\n score=df_poor[\"Score\"].tolist(), color=df_poor[\"color\"].tolist(),\n cb_color=df_poor[\"cb_color\"].tolist(), desc=df_poor[\"Definition\"].tolist()))\n\nhover = HoverTool(tooltips=\"\"\"\n

\n @desc{safe}\n

\n \"\"\")\n\np = figure(y_range=y_range, x_range=x_range, plot_width=1900, plot_height=900, x_axis_location=\"above\", tools=[hover, \"save\"])\n\np.xaxis.major_label_text_font_size = \"15pt\"\np.yaxis.major_label_text_font_size = \"15pt\"\n\nexcellent = p.rect(x=\"tool\", y=\"criteria\", color=\"cb_color\", height=1, width=.96, source=excellent_source,\n line_color=\"cb_color\", alpha=.75)\n\nfair = p.rect(x=\"tool\", y=\"criteria\", color=\"cb_color\", height=1, width=.96, source=fair_source,\n line_color=\"cb_color\", alpha=.75)\n\npoor = p.rect(x=\"tool\", y=\"criteria\", color=\"cb_color\", height=1, width=.96, source=poor_source,\n line_color=\"cb_color\", alpha=.75)\n\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = None\n\np.xaxis.major_label_orientation = .85\n\nlegend = Legend(items=[(\"Excellent\", [excellent]),\n (\"Good\", [fair]),\n (\"Poor\", [poor])])\n\n# legend.label_text_font = \"opensans\"\n\n# p.xaxis[0].major_label_text_font = \"opensans\"\n# p.yaxis[0].major_label_text_font = \"opensans\"\n\nlegend.label_text_font_size = \"15pt\"\np.add_layout(legend, 'right')\n\n","sub_path":"app/rubric.py","file_name":"rubric.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38614388","text":"__author__ = 'abodalevsky'\n\nimport logging\nfrom time import time\nfrom market.config import Config\nfrom market.connector import get_shares\nfrom market.adapters import response_to_values\n\n\nclass MarketProxy():\n \"\"\" Implements proxy for optimization access to online sources\n\n When request for share is received it checks if data exists in cache:\n - if yes, verifies if data valid (updated):\n - if yes, answer be sent back;\n - if no, all data will be updated, and answer will be sent back;\n - if no, share code be added to cache, all data will be updated, answer will be sent back\n\n Interface should be similar to Market class\n\n\n Contains data that is retrieved from online, in format\n id: [time, answer]\n where:\n time - is time of last request, before update cache from server this info is being analized\n and old data will be removed from the cache\n answer - is in format:\n {\n 'price': float,\n 'summary':string\n },\n\n for example:\n {\n '25': [1234567, {'price': 55.640, 'summary':'sell'}],\n '23': [1234568, {'price': 15.405, 'summary':'buy'}]\n }\n \"\"\"\n\n # last time when cache was updated\n __last_update = 0\n\n def __init__(self):\n self.__cache = dict()\n logging.info('cache: Initialized')\n\n def get_share(self, code):\n \"\"\"\n :param code: code {string} of share from class Shares\n :return: value for given share in format\n {\n 'price': 55.640,\n 'summary':'sell'\n }\n \"\"\"\n logging.debug('Request for share {0}'.format(code))\n answer = self.__get_from_cache(code)\n\n if answer == {}:\n self.__add_share_to_cache(code)\n self.__update_cache()\n answer = self.__get_from_cache(code)\n\n return answer\n\n def __get_from_cache(self, code):\n \"\"\"\n Gets data from cache, if data invalid updates cache\n update time to access data, to be sure that data is requested\n :param code: code of share\n :return: answer\n \"\"\"\n try:\n logging.debug('cache: request')\n answer = self.__cache[code]\n\n # verify if data is up to dated\n current_time = round(time())\n if current_time - self.__last_update > Config.cache_time_to_update():\n logging.info('cache: out of date')\n self.__update_cache()\n answer = self.__cache[code]\n\n logging.debug('cache: data returned')\n return answer[1]\n\n except KeyError: # no code in the cache\n logging.debug('cache: data not found')\n return {}\n\n def __add_share_to_cache(self, code):\n \"\"\" adds share to cache\n :param code: code of share\n :return: none\n \"\"\"\n\n data = self.__format_data_for_cache('0', 'neutral')\n self.__cache[code] = data\n\n def __update_cache(self):\n \"\"\" updates all records in cache\n :return: none\n \"\"\"\n\n logging.info('cache: update')\n\n if len(self.__cache) == 0:\n return\n\n # prepare list of shares for request\n # check old data, if data is old remove from cache\n shares = str()\n new_cache = dict()\n for i in self.__cache:\n if not self.__should_be_removed(i):\n new_cache[i] = self.__cache[i]\n shares += i + ', '\n\n self.__cache = new_cache\n\n # got response in json format\n logging.debug('cache: request for shares[{0}]'.format(shares))\n shares = response_to_values(get_shares(shares.rstrip(', ')))\n\n self.__last_update = round(time())\n\n # update cache\n for share, value in shares.items():\n logging.info('cache: update for {0}'.format(share))\n data = self.__format_data_for_cache(value['summaryLast'], value['technicalSummaryClass'])\n self.__cache[share.strip()] = data\n logging.debug('cache: updates with {0}'.format(data))\n\n def __format_data_for_cache(self, price, recommendation):\n \"\"\"\n Time will be inserted automatically\n price from string will be converted to float\n :param price: string\n :param recommendation: string\n :return: list\n \"\"\"\n\n try:\n pr = round(float(price.replace(',', '.')), 3)\n except ValueError as e:\n logging.error('cache: wrong format: ' + repr(e))\n pr = 0\n\n return [round(time()), {'price': pr, 'summary': recommendation}]\n\n def __should_be_removed(self, code):\n last_update = self.__cache[code][0]\n current_time = round(time())\n return current_time - last_update > Config.cache_time_to_remove()\n","sub_path":"src/market/market_proxy.py","file_name":"market_proxy.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486417792","text":"import argparse\nimport logging\nimport logging.handlers\nimport os\nimport threading\n\nfrom concord232 import api\nfrom concord232 import concord\n\nLOG_FORMAT = \"%(asctime)-15s %(module)s %(levelname)s %(message)s\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--config\", default=\"config.ini\", metavar=\"FILE\", help=\"Path to config file\"\n )\n parser.add_argument(\"--debug\", default=False, action=\"store_true\", help=\"Enable debug\")\n parser.add_argument(\"--log\", default=None, metavar=\"FILE\", help=\"Path to log file\")\n parser.add_argument(\n \"--serial\", default=None, metavar=\"PORT\", help=\"Serial port to open for stream\"\n )\n parser.add_argument(\n \"--listen\",\n default=\"0.0.0.0\",\n metavar=\"ADDR\",\n help=\"Listen address (defaults to 0.0.0.0 (all interfaces))\",\n )\n parser.add_argument(\"--port\", default=5007, type=int, help=\"Listen port (defaults to 5007)\")\n args = parser.parse_args()\n\n LOG = logging.getLogger()\n LOG.setLevel(logging.DEBUG)\n formatter = logging.Formatter(LOG_FORMAT)\n istty = os.isatty(0)\n\n if args.debug and not istty:\n debug_handler = logging.handlers.RotatingFileHandler(\n \"debug.log\", maxBytes=1024 * 1024 * 10, backupCount=3\n )\n debug_handler.setFormatter(formatter)\n debug_handler.setLevel(logging.DEBUG)\n LOG.addHandler(debug_handler)\n\n if istty:\n verbose_handler = logging.StreamHandler()\n verbose_handler.setFormatter(formatter)\n verbose_handler.setLevel(args.debug and logging.DEBUG or logging.INFO)\n LOG.addHandler(verbose_handler)\n\n if args.log:\n log_handler = logging.handlers.RotatingFileHandler(\n args.log, maxBytes=1024 * 1024 * 10, backupCount=3\n )\n log_handler.setFormatter(formatter)\n log_handler.setLevel(logging.DEBUG)\n LOG.addHandler(log_handler)\n\n LOG.info(\"Ready\")\n logging.getLogger(\"connectionpool\").setLevel(logging.WARNING)\n\n if args.serial:\n ctrl = concord.AlarmPanelInterface(args.serial, 0.25, LOG)\n else:\n LOG.error(\"Serial and baudrate are required\")\n return\n\n api.CONTROLLER = ctrl\n\n t = threading.Thread(target=ctrl.message_loop)\n t.daemon = True\n t.start()\n\n api.app.run(debug=False, host=args.listen, port=args.port, threaded=True)\n","sub_path":"concord232/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130097705","text":"from __future__ import absolute_import, division, print_function\nimport pathlib\nimport random\nimport tensorflow as tf\n\ntf.enable_eager_execution()\ntf.VERSION\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\n\nDATA_PATH = '/Users/aboga/repos/car-damage-dataset/data2a/training'\ndata_root = pathlib.Path(DATA_PATH)\n\nall_image_paths = list(data_root.glob('*/*'))\nall_image_paths = [str(path) for path in all_image_paths]\nrandom.shuffle(all_image_paths)\n\nimage_count = len(all_image_paths)\n\nlabel_names = sorted(\n item.name for item in data_root.glob('*/') if item.is_dir())\nlabel_to_index = dict((name, index) for index, name in enumerate(label_names))\n\nall_image_labels = [label_to_index[pathlib.Path(\n path).parent.name] for path in all_image_paths]\n\n\ndef preprocess_image(image):\n image = tf.image.decode_jpeg(image, channels=3)\n image = tf.image.resize_images(image, [192, 192])\n image /= 255.0 # normalize to [0,1] range\n return image\n\n\ndef load_and_preprocess_image(path):\n image = tf.read_file(path)\n return preprocess_image(image)\n\n\npath_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)\nimage_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)\n\nlabel_ds = tf.data.Dataset.from_tensor_slices(\n tf.cast(all_image_labels, tf.int64))\n\nfor label in label_ds.take(10):\n print(label_names[label.numpy()])\n\nds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))\n\n\ndef load_and_preprocess_from_path_label(path, label):\n return load_and_preprocess_image(path), label\n\n\nimage_label_ds = ds.map(load_and_preprocess_from_path_label)\n\nBATCH_SIZE = 32\n\nds = image_label_ds.shuffle(buffer_size=image_count)\nds = ds.repeat()\nds = ds.batch(BATCH_SIZE)\n\nds.prefetch(buffer_size=AUTOTUNE)\n\nmobile_net = tf.keras.applications.MobileNetV2(\n input_shape=(192, 192, 3), weights='imagenet', include_top=False)\nmobile_net.trainable = False\n\nres_net = tf.keras.applications.ResNet50(\n input_shape=(192, 192, 3), weights=None, include_top=False, pooling='avg')\nres_net.trainable = True\n\n\ndef change_range(image, label):\n return 2*image-1, label\n\n\nkeras_ds = ds.map(change_range)\n\nimage_batch, label_batch = next(iter(keras_ds))\n\nfeature_map_batch = res_net(image_batch)\nprint(feature_map_batch.shape)\n\nmodel = tf.keras.Sequential([\n mobile_net,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(len(label_names), activation='relu'),\n tf.keras.layers.Activation('softmax')\n])\n\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(),\n loss=tf.keras.losses.sparse_categorical_crossentropy,\n metrics=[\"accuracy\"])\n\nmodel.summary()\n\n\nsteps_per_epoch = int(tf.ceil(len(all_image_paths)/BATCH_SIZE).numpy())\n\n\nfrom tensorflow.keras.callbacks import TensorBoard\n\nimport time\n\ntensorboard = TensorBoard(log_dir=\"logs/{}\".format(time.time()))\n\nmodel.fit(keras_ds, batch_size=BATCH_SIZE, steps_per_epoch=steps_per_epoch, callbacks=[tensorboard])\n\n\n\n\n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519734870","text":"def sudokuChk(x):\n for i in x:\n rs=0\n for j in i:\n rs+= int(j)\n print(\"Row Sum is for row number :\",rs)\n if rs != 45:\n my_val=\"No\"\n break\n else:\n continue\n for i in range(9):\n cs=0\n for j in range(9):\n cs += int(x[i][j])\n print(\"Column \",i ,\":\", cs)\n if cs !=45:\n my_val=\"No\"\n break\n else:\n my_val=\"Yes\"\n return my_val\n\nrow=0\nx=[]\nwhile row<9:\n x.append(input(\"Enter 9 digits between 1 to 9 to check the sudoku entries\"))\n #print(x[row])\n row+=1\n\nprint(x)\n\n\nprint(sudokuChk(x))\n","sub_path":"linuxacademy/chkSudoku.py","file_name":"chkSudoku.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"366476654","text":"\"\"\"Определяет схемы URL для otlivy\"\"\"\nfrom django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n # Home page\n url(r'^$', views.index, name='index'),\n # окно с заказами на отливы\n url(r'^zakazy/$', views.zakazy, name='zakazy'),\n # окно с формой добавления заказа\n url(r'^new_order/$', views.new_order, name='new_order'),\n]\n","sub_path":"otlivy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"162836823","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 17 15:43:23 2017\r\n\r\n@author: Rei\r\n\"\"\"\r\n#Extra uses\r\n\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.gridlayout import GridLayout\r\nfrom kivy.uix.textinput import TextInput\r\n\r\n#Note: for MenuScreen SwitchA function, change self.manager.current from 'choice' to 'input'\r\n\r\nclass InputScreen(Screen):\r\n def __init__(self, **kwargs):\r\n Screen.__init__(self,**kwargs)\r\n self.layout = BoxLayout(orientation='vertical')\r\n self.innerlayout = GridLayout(cols=2)\r\n self.title = Label(text='Due to our group only having one prototype for just 1 bin, we have to choose values for the other 2 bins')\r\n self.layout.add_widget(self.title)\r\n self.bus = Label(text='Bin B Ultrasonic Value (Lower indicates more rubbish)')\r\n self.b_us = (TextInput(multiline=False, text = '0', input_filter='float'))\r\n self.innerlayout.add_widget(self.bus)\r\n self.innerlayout.add_widget(self.b_us)\r\n self.bms = Label(text='Bin B Methane Value (Higher indicates greater methane emission)')\r\n self.b_ms = (TextInput(multiline=False, text = '0',input_filter='float'))\r\n self.innerlayout.add_widget(self.bms)\r\n self.innerlayout.add_widget(self.b_ms)\r\n self.cus = Label(text='Bin C Ultrasonic Value (Lower indicates more rubbish)')\r\n self.c_us = (TextInput(multiline=False, text = '0',input_filter='float'))\r\n self.innerlayout.add_widget(self.cus)\r\n self.innerlayout.add_widget(self.c_us)\r\n self.cms = Label(text='Bin C Methane Value (Higher indicates greater methane emission)')\r\n self.c_ms = (TextInput(multiline=False, text = '0',input_filter='float'))\r\n self.innerlayout.add_widget(self.cms)\r\n self.innerlayout.add_widget(self.c_ms)\r\n self.layout.add_widget(self.innerlayout)\r\n self.btn = Button(text='Next', on_press=self.switchB)\r\n self.layout.add_widget(self.btn)\r\n self.add_widget(self.layout)\r\n def switchB(self,instance):\r\n self.manager.current = 'choice'\r\n self.manager.transition.direction = 'left'\r\n \r\nclass TrashHold(App):\r\n def build(self):\r\n sm = ScreenManager()\r\n s = MapScreen(name='map')\r\n i = InputScreen(name='input')\r\n c = ChoiceScreen(name='choice')\r\n m = MenuScreen(name='menu')\r\n sm.add_widget(s)\r\n sm.add_widget(i)\r\n sm.add_widget(c)\r\n sm.add_widget(m)\r\n sm.current = 'menu'\r\n return sm","sub_path":"input screen.py","file_name":"input screen.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326208954","text":"'''\n给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。\n'''\n\n\n# 下边这个算法好啊!\n'''\n中心拓展法\n回文串的中心可能是!!!一个字符或者两个字符!!!。因此,我们遍历每一个字符和每一对相邻的字符\n\n1.特判,若ss长度为1或0,返回s\n\n2.初试化最长回文子串的开始索引和结束索引start=0,end=0\n\n3.拓展函数expand(l,r),l表示传入中心字符的左界,r表示传入字符中心的右界。\n\n 若满足条件0<=l and rend-start+1,表示当前长度大于之前的最长长度,更新start和end\n start=i-(len\\_long-1)//2\n end=i+len\\_long//2\n 解释!start和end的更新公式\n //表示向下取整\n 因为有两种情况,拓展中心为一个字符或者两个字符。无论是一个还是两个,令字符串长度(len−1)//2总能得到拓展中心左侧元素的个数。\n 同理,令len//2总能得到拓展中心右侧的个数。\n\n5.返回s[start,...,end]s[start,...,end]\n'''\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n def expand(l,r):\n while(0<=l and rend-start):\n start=i-(len_long-1)//2\n end=i+(len_long)//2\n return s[start:end+1]\n\n","sub_path":"_5-LongestPalindromicSubstring/LongestPalindromicSubstring3.py","file_name":"LongestPalindromicSubstring3.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"502740487","text":"import os\nimport sys\nimport logging\n\nfrom sylvia import log\n\nWORK_DIR = os.path.normpath(os.path.dirname(__file__))\nLOG_DIR = os.path.normpath(os.path.join(WORK_DIR, \"log\"))\n\nLOG = log.Log(\"Volga.Project.SylViA\")\nif not os.path.exists(LOG_DIR):\n os.mkdir(LOG_DIR)\nlogfile = os.path.join(LOG_DIR, \"system.log\")\nif not os.path.exists(logfile):\n with open(logfile, 'a') as f:\n os.utime(logfile, None)\n\nLOG.addHandler(log.Log.fileHandler(logfile, log.BASE_FORMAT, logging.INFO))\n\n\nif __name__ == \"__main__\":\n from websocket import create_connection\n ws = create_connection(\"ws://localhost:9024/ws\")\n\n if len(sys.argv) > 1:\n message = sys.argv[1]\n else:\n message = 'hello world!'\n\n print(ws.send(message))\n print(ws.recv())\n\n ws.close()\n","sub_path":"project/volga/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"425678866","text":"\"\"\"\ntitle : data_sleep_file_load\ndescription : \nauthor : Elizabeth Zhu (nnx896)\ndate : Oct 04, 2016\n\"\"\"\n\nimport sqlite3\nfrom datetime import datetime\n\ndef create_file_table():\n # If table doesn't exist, create it\n #c.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='FILE_DATA';\")\n conn = sqlite3.connect('data.db')\n c = conn.cursor()\n q = '''\n CREATE TABLE FILE_DATA (\n SKU VARCHAR (10) NOT NULL,\n NAME VARCHAR (35) NOT NULL,\n TYPE VARCHAR (10),\n PRIMARY KEY (SKU)\n );\n '''\n c.execute(q)\n conn.close()\n\ncreate_file_table()\n","sub_path":"sqlite/file_load.py","file_name":"file_load.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"551419266","text":"from django.template.loader import render_to_string\nfrom tasks.const import STATUS_SUCCESS, STATUS_FAILED\nfrom .base import library\n\n\n@library.register('pep8')\ndef pep8_violation(data):\n \"\"\"PEP8 violation parser\"\"\"\n count = len(data['raw'].split('\\n')) - 1\n data['status'] = STATUS_SUCCESS if count == 0 else STATUS_FAILED\n data['preview'] = render_to_string('violations/pep8/preview.html', {\n 'count': count,\n })\n data['prepared'] = render_to_string('violations/pep8/prepared.html', {\n 'raw': data['raw'],\n })\n data['plot'] = {\n 'count': count,\n }\n return data\n","sub_path":"violations/pep8.py","file_name":"pep8.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184939032","text":"import sqlite3\nfrom PIL import Image, ImageFont, ImageDraw, ImageEnhance\nfrom IPython.display import display\nfrom IPython import get_ipython\n\n##################\n#\n# Type of script\n#\n##################\ndef type_of_script():\n try:\n shell = get_ipython().__class__.__name__\n print(shell)\n if shell == 'ZMQInteractiveShell':\n return True # Jupyter notebook or qtconsole\n elif shell == 'TerminalInteractiveShell':\n return False # Terminal running IPython\n else:\n return False # Other type (?)\n except NameError:\n return False # Probably standard Python interpreter\n \n# Page filename\npage_number = '601'\npage_file_name = 'page' + page_number.zfill(3) + '.png'\n\n# Open the image\nsource_img = Image.open(page_file_name).convert(\"RGBA\")\ngolden_source_img = Image.open(page_file_name).convert(\"RGBA\")\n\n# Get a draw object\ndraw = ImageDraw.Draw(source_img)\ngolden_draw = ImageDraw.Draw(golden_source_img)\n\n# Get the rows from ayahinfo_1260.db\nconn = sqlite3.connect(\"ayahinfo_1260.db\")\nconn.row_factory = sqlite3.Row\ncur = conn.cursor()\nQUERY = 'select * from glyphs where page_number=' + page_number + ' order by glyph_id'\ncur.execute(QUERY)\n\n# Loop over rows and draw boxes\nfor row in cur:\n draw.rectangle(((row['min_x'], row['min_y']), (row['max_x'], row['max_y'])), outline=\"black\")\n\n# Get the rows from Golden Quran db\ngolden_conn = sqlite3.connect(\"Warsh_new_1260.db\")\ngolden_conn.row_factory = sqlite3.Row\ngolden_cur = golden_conn.cursor()\nQUERY = 'select * from page where page_number=' + page_number + ' order by id'\ngolden_cur.execute(QUERY)\n\n# Loop over rows and draw boxes\nfor golden_row in golden_cur:\n x = int(golden_row['x'])\n y = int(golden_row['y'])\n max_x = x + int(golden_row['width'])\n max_y = y + int(golden_row['height'])\n golden_draw.rectangle(((x, y), (max_x, max_y)), outline=\"black\")\n\nif not type_of_script():\n print('----terminal----')\n print('-')\n print('** Original DB **')\n source_img.show()\n print('-')\n print('** Golden Quran DB **')\n golden_source_img.show()\nelse:\n print('----iPython notebook----')\n print('-')\n print('** Original DB **')\n display(source_img)\n print('-')\n print('** Golden Quran DB **')\n display(golden_source_img)","sub_path":"Warsh1260/Warsh1260.py","file_name":"Warsh1260.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"158064120","text":"import re\r\n\r\nclass DateRangeParser:\r\n\t@classmethod\r\n\tdef getDateRange (cls, datestr):\r\n\t\tif cls.isDateTime(datestr):\r\n\t\t\tdtRange = cls.parseDateTime(datestr)\r\n\t\telif cls.isSingleDay(datestr):\r\n\t\t\tdtRange = cls.parseSingleDay(datestr)\r\n\t\telif cls.isDayRange(datestr):\r\n\t\t\tdtRange = cls.parseDayRange(datestr)\r\n\t\telse:\r\n\t\t\traise Exception(\"Invalid datestr %s\" % datestr)\r\n\t\treturn dtRange\r\n\r\n\r\n\t@classmethod\r\n\tdef isDateTime (cls, datestr):\r\n\t\trx = \"^\\d{12}$\"\r\n\t\tflag = re.search(rx, datestr)\r\n\t\treturn flag\r\n\r\n\r\n\t@classmethod\r\n\tdef isDayRange (cls, datestr):\r\n\t\trx = \"^\\d{8}-\\d{8}$\"\r\n\t\tflag = re.search(rx, datestr)\r\n\t\treturn flag\r\n\r\n\r\n\t@classmethod\r\n\tdef isSingleDay (cls, datestr):\r\n\t\trx = \"^\\d{8}$\"\r\n\t\tflag = re.search(rx, datestr)\r\n\t\treturn flag \r\n\r\n\r\n\t@classmethod\r\n\tdef isValid (cls, datestr):\r\n\t\tflag = cls.isDateTime(datestr) or cls.isSingleDay(datestr) or cls.isDayRange(datestr)\r\n\t\treturn flag\r\n\r\n\t@classmethod\r\n\tdef parseDateTime (cls, datestr):\r\n\t\tdtRange = (datestr, datestr)\r\n\t\treturn dtRange\r\n\r\n\t@classmethod\r\n\tdef parseDayRange (cls, datestr):\r\n\t\trx = \"^(\\d{8})-(\\d{8})$\"\r\n\t\tgroups = re.search(rx, datestr)\r\n\t\tdtStart = groups.group(1) + '000000'\r\n\t\tdtEnd = groups.group(2) + '235959'\r\n\t\tdtRange = (dtStart, dtEnd)\r\n\t\treturn dtRange\r\n\r\n\t@classmethod\r\n\tdef parseSingleDay (cls, datestr):\r\n\t\tdtStart = datestr + \"000000\"\r\n\t\tdtEnd = datestr + \"235959\"\r\n\t\tdtRange = (dtStart, dtEnd)\r\n\t\treturn dtRange\r\n\t\tdtRange = (\"No Clue\", \"No Clue\")\r\n","sub_path":"py/wsgi/DateRangeParser.py","file_name":"DateRangeParser.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"633626850","text":"\nfrom doh.private import CRISISNET_APIKEY\nimport json\nimport requests\n\ndef query_crisis(endpoint, **custom_params):\n params = {'apikey': CRISISNET_APIKEY}\n params.update(custom_params)\n baseurl = 'http://api.crisis.net/'\n fullurl = baseurl + endpoint\n r = requests.get(fullurl, params=params)\n return r.json()\n\n\nif __name__ == '__main__':\n dlurl('sources')\n","sub_path":"crisisweb/explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272478849","text":"from rest_framework import serializers\n\nfrom project.api.call.models import Call\nfrom .models import CallOption\n\n\nclass CallOptionSerializer(serializers.ModelSerializer):\n class Meta:\n model = CallOption\n fields = '__all__'\n\n\nclass CallOptionSerializerNotNested(serializers.ModelSerializer):\n class Meta:\n model = CallOption\n fields = '__all__'\n read_only_fields = ['call']\n\n def create(self, validated_data):\n call_id = self.context.get('view').kwargs.get('call_id')\n if call_id is None:\n raise serializers.ValidationError(\"Must set the call_id kwarg to use this serializer.\")\n validated_data['call'] = Call.objects.get(pk=call_id)\n return super(CallOptionSerializerNotNested, self).create(validated_data)\n","sub_path":"backend/project/api/call_option/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"208667493","text":"#!/usr/bin/env python3\nimport socket\nimport threading\nimport curses\nfrom time import sleep\n\nmax_len_data = 1024\nclass windows():\n\n def __init__(self):\n\n self.stdscr = curses.initscr()\n\n curses.echo()\n curses.start_color()\n curses.use_default_colors()\n\n self.stdscr.clear()\n self.stdscr.scrollok( True )\n self.ymax, self.xmax = self.stdscr.getmaxyx()\n\n self.create_login_win()\n\n self.output_pos = 0\n\n def create_login_win(self):\n\n self.win_login_width = 36\n self.win_login = curses.newwin( 3, self.win_login_width, self.ymax//2-1,\\\n self.xmax//2-self.win_login_width//2 )\n self.win_login.border()\n self.init_single_win( self.win_login, 'server' )\n self.win_login.addstr( 1, 1, '[IP:port]:' )\n self.win_login.refresh()\n\n def server_err(self):\n self.init_single_win( self.win_login, 'server' )\n self.win_login.addstr( 1, 1, 'server is closed', curses.A_BLINK )\n self.win_login.refresh()\n sleep(2)\n\n def get_server(self):\n self.server = self.win_login.getstr( 1, 12, self.win_login_width-12-2 ).decode('utf-8')\n return self.server\n\n def get_input(self):\n y,x = self.win_input.getmaxyx()\n r = self.win_input.getstr( 1, 1, x-2 ).decode('utf-8')\n self.reset_win_input()\n return r\n\n def get_username(self):\n self.init_single_win( self.win_login, 'username' )\n self.username = self.win_login.getstr( 1, 1, self.win_login_width ).decode('utf-8')\n return self.username\n\n def reget_username(self):\n self.win_login.addstr( 1, 1, '`%s` exist!'%self.username, curses.A_BLINK)\n self.win_login.refresh()\n sleep(2)\n self.init_single_win( self.win_login, 'username' )\n self.username = self.win_login.getstr( 1, 1, self.win_login_width ).decode('utf-8')\n return self.username\n\n def create_chat_win(self):\n\n self.win_login.clear()\n\n self.height_input = 3\n self.height_list = 5\n self.height_output = self.ymax - self.height_input - self.height_list\n\n self.win_list = curses.newwin( self.height_list, 0, 0, 0 )\n self.init_single_win( self.win_list, 'list' )\n\n self.win_output = curses.newwin( self.height_output, 0, self.height_list, 0 )\n self.init_single_win( self.win_output, 'output' )\n\n self.win_input = curses.newwin( self.height_input, 0, self.height_output+self.height_list, 0 )\n self.init_single_win( self.win_input, 'input' )\n\n def close(self):\n curses.endwin()\n\n def init_single_win( self, win, title ):\n win.clear()\n win.border()\n #y,x = win.getmaxyx()\n #win.addstr( 0, (x-len(title))//2, title )\n win.addstr( 0, 1, title )\n win.refresh()\n\n def reset_win_input( self ):\n self.init_single_win( self.win_input, 'input' )\n\n def reset_win_login( self ):\n self.init_single_win( self.win_longin, 'server' )\n\n def reset_win_output( self ):\n self.init_single_win( self.win_output, 'output' )\n\n def win_list_clear( self ):\n self.init_single_win( self.win_list, 'list' )\n\n def output( self, s ):\n s = s.split( '\\n' )\n y, x = self.win_output.getmaxyx()\n x = x-2\n for ss in s:\n l = len(ss)\n while l>x:\n self.output_pos += 1\n if self.output_pos == y-1:\n self.output_pos = 1\n self.reset_win_output() # should be scrolling\n\n self.win_output.addstr( self.output_pos, 1, ss[:x] )\n ss = ss[x:]\n l = len(ss)\n if len(ss) > 0:\n self.output_pos += 1\n if self.output_pos == y-1:\n self.output_pos = 1\n self.reset_win_output() # should be scrolling\n\n self.win_output.addstr( self.output_pos, 1, ss )\n\n self.win_output.refresh()\n\n def output_list( self, s ):\n n = 1\n self.win_list_clear()\n s = s.split( '\\n' )\n for ss in s:\n self.win_list.addstr( n, 1, ss )\n n += 1\n if n == self.height_list:\n n = 1\n self.reset_win_list() # should be scrolling\n self.win_list.refresh()\n\n\ndef make_data( s, h=0 ):\n if len(s) == 0:\n s = ' '\n r = '%i%s'%(h,s)\n return r\n\ndef get_data( s ):\n if len(s) == 1:\n s += ' '\n return (s[0], s[1:])\n\ndef my_recv( client, wins ):\n while True:\n recv = ''\n try:\n recv = client.recv( max_len_data ).decode( 'utf-8' )\n except OSError:\n return\n if len(recv) != 0:\n h, recv = get_data( recv )\n if h == '0':\n wins.output( recv )\n if h == '1':\n wins.output_list( recv )\n\n\ndef main():\n\n wins = windows()\n\n address = wins.get_server()\n\n host,port = address.split( ':' )\n port = int(port)\n client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )\n\n try:\n client.connect( (host,port) )\n except ConnectionRefusedError:\n client.close()\n wins.server_err()\n wins.close()\n exit()\n\n\n username = wins.get_username()\n while True:\n if username == 'q':\n wins.close()\n client.close()\n exit()\n username = make_data( username )\n client.send( username.encode( 'utf-8' ) )\n data = client.recv( wins.xmax-2 ).decode( 'utf-8' )\n h, r = get_data( data )\n\n if h == '3':\n break\n\n username = wins.reget_username()\n\n wins.create_chat_win()\n\n t = threading.Thread( target=my_recv, args=(client, wins) )\n t.start()\n\n while True:\n\n send = wins.get_input()\n if send == 'q':\n send = make_data( ' ', 2 )\n client.send( send.encode( 'utf-8' ) )\n break\n send = make_data( send )\n client.send( send.encode( 'utf-8' ) )\n #wins.output( send )\n\n client.close()\n curses.endwin()\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"chat/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"503591525","text":"#! /usr/bin/env python3\n\n# <>\n# Copyright 2022, Lawrence Livermore National Security, LLC.\n# See the top-level COPYRIGHT file for details.\n# \n# SPDX-License-Identifier: BSD-3-Clause\n# <>\n\n\"\"\"\nTranslate GNDS/HDF5 to GNDS/XML\n\"\"\"\nimport sys\nimport os\n\nfrom xml.etree import cElementTree as etree\nimport numpy\nimport h5py\n\nfrom pqu import PQU\n\ndef addNode( parent, node ):\n \"\"\"\n recursively copy HDF data (one node at a time) to xml\n\n :param parent: xml element\n :param node: HDF group or dataset to be added to xml\n \"\"\"\n attrs = dict( node.attrs )\n for key in attrs:\n if type(attrs[key]) is numpy.bytes_:\n attrs[key] = attrs[key].decode(\"utf8\")\n name = attrs.pop( \"_xmltag\" )\n\n try:\n xmlnode = etree.Element( name )\n for key,val in attrs.items():\n if key.startswith(\"_xml\"): continue\n xmlnode.set( str(key), str(val) )\n if isinstance( parent, etree.ElementTree ): parent._setroot( xmlnode )\n else: parent.append( xmlnode )\n newParent = xmlnode\n\n if isinstance( node, h5py.Dataset ):\n addDataset( xmlnode, node )\n else:\n for child in sorted( node.values(), key=lambda tmp: tmp.attrs[\"_xmlindex\"] ):\n addNode( newParent, child )\n except:\n print( \"addNode backtrace: node=%s, name=%s\" % ( node, name ) )\n raise\n\ndef addDataset( parent, dataset ):\n \"\"\"\n Convert HDF5 dataset into text\n\n :param parent: xml element corresponding to the dataset\n :param dataset: HDF5 dataset to be converted\n \"\"\"\n if str(dataset.dtype).startswith(\"|S\"):\n parent.text = dataset[()].decode(\"utf8\")\n else:\n parent.text = ' '.join( map( PQU.toShortestString, dataset[()].flatten() ) )\n\n\nif __name__ == '__main__':\n if len(sys.argv)<2:\n print( \"Usage: python HDFtoXML.py \" )\n sys.exit(1)\n\n h5file = sys.argv[1]\n h5 = h5py.File( h5file, \"r\" )\n\n xdoc = etree.ElementTree()\n\n root = list(h5.values())[0]\n addNode( xdoc, root )\n\n xdoc.write( os.path.splitext(h5file)[0] + \".hdf5.xml\" )\n","sub_path":"bin/HDFtoXML.py","file_name":"HDFtoXML.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190796067","text":"import pandas as pd\nfrom tbrs import TermBasedRandomSampling\nfrom preprocessing import Preprocessing\nfrom naivebayes import NBMultinomial\nfrom weighting import Weighting\nfrom kfold import KFold\nfrom confusionmatrix import ConfusionMatrix\n\ndata = pd.read_excel(\n r'C:\\Users\\PPATK\\Desktop\\Code 2\\Code\\Skripsi.xlsx',\"Data Coding\")\ndata_tweet = data['Tweet']\ndata_target = data['Label']\n\nkfold = KFold(data_tweet,data_target,10)\ndata_train, data_test = kfold.get_data_sequence()\n\nx_array = []\ny_array = []\nl_array = []\nkfold_per_combination = []\nlist_acc = []\nlist_prec = []\nlist_recall = []\nlist_fmeasure = []\nfold_accuracy = []\nfold_precision = []\nfold_recall = []\nfold_fmeasure = []\n\ncount=1\nfor l in range(10,60,10):\n for y in range (10,60,10):\n for x in range (10,60,10):\n print(\"PERULANGAN \" + str(count))\n count+=1\n print('X={}, Y={}, L={}'.format(x,y,l))\n x_array.append(x)\n y_array.append(y)\n l_array.append(l)\n for i in range(9):\n x_array.append(\" \")\n y_array.append(\" \")\n l_array.append(\" \") \n\n accuracy_total_accumulation = 0\n precision_total_accumulation = 0\n recall_total_accumulation = 0\n fmeasure_total_accumulation = 0\n\n for i in range(len(data_train)):\n kfold_per_combination.append(i+1)\n y_test = []\n y_pred = []\n\n prepro = Preprocessing()\n cleaned_data, terms = prepro.preprocessing(data_train[i][\"tweet\"])\n \n tbrs = TermBasedRandomSampling(X=x, Y=y, L=l)\n stopwords = tbrs.create_stopwords(cleaned_data,terms)\n\n prepro2 = Preprocessing()\n new_cleaned_data, new_terms = prepro2.remove_stopword(cleaned_data, stopwords)\n\n weight = Weighting(new_cleaned_data, new_terms)\n tfidf = weight.get_tf_idf_weighting()\n idf = weight.get_idf()\n\n nb = NBMultinomial()\n nb.fit(new_cleaned_data,new_terms,data_train[i][\"target\"],stopwords,idf,tfidf)\n \n for j in range(len(data_test[i][\"tweet\"])):\n prediction = nb.predict(data_test[i][\"tweet\"][j])\n y_test.append(data_test[i][\"target\"][j])\n y_pred.append(prediction)\n\n cm = ConfusionMatrix()\n accuracy, precision, recall, fmeasure = cm.score(y_test, y_pred)\n list_acc.append(accuracy)\n list_prec.append(precision)\n list_recall.append(recall)\n list_fmeasure.append(fmeasure)\n\n accuracy_total_accumulation+=accuracy\n precision_total_accumulation+=precision\n recall_total_accumulation+=recall\n fmeasure_total_accumulation+=fmeasure\n\n accuracy_total = float(accuracy_total_accumulation/len(data_train))\n precision_total = float(precision_total_accumulation/len(data_train))\n recall_total = float(recall_total_accumulation/len(data_train))\n fmeasure_total = float(fmeasure_total_accumulation/len(data_train))\n for i in range(len(data_train)):\n fold_accuracy.append(accuracy_total)\n fold_precision.append(precision_total)\n fold_recall.append(recall_total)\n fold_fmeasure.append(fmeasure_total)\n break\n # if count >= 2:\n # break\n # break\n # break\n\ndf = pd.DataFrame({'X':x_array,'Y':y_array,'L':l_array,'K-Fold':kfold_per_combination,'Accuracy':list_acc,'Precision':list_prec,'Recall':list_recall,'F-Measure':list_fmeasure,'Fold Accuracy':fold_accuracy,'Fold Precision':fold_precision,'Fold Recall':fold_recall,'Fold F-Measure':fold_fmeasure})\nprint(df)\n# df.to_excel(r'cobabarunih.xlsx', index = False, header=True)\n","sub_path":"Keperluan Sidang/Code - Copy/sentimentanalysiswithkfold.py","file_name":"sentimentanalysiswithkfold.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"571850540","text":"import itertools\nimport calendar\nfrom pulp import *\n\n\ndef create_boolean_list(skills, workers, worker_skill_dict, H, S):\n\n dummy_dict = {}\n for h in H:\n dummy_list = []\n for s in S:\n flag = False\n for check_s in worker_skill_dict[workers[h].name]:\n if str(skills[s]) == str(check_s):\n dummy_list.append(1)\n flag = True\n if flag == False:\n dummy_list.append(0)\n dummy_dict[workers[h].name] = dummy_list\n\n return dummy_dict\n\n\ndef create_any_flag_list(S, skills):\n\n tomari_list, ake_list, yasumi_list = [], [], []\n\n for d in S:\n if skills[d].tomari_flag == True:\n tomari_list.append(d)\n elif skills[d].ake_flag == True:\n ake_list.append(d)\n elif skills[d].yasumi_flag == True and skills[d].exclusion_flag == False:\n yasumi_list.append(d)\n\n return tomari_list, ake_list, yasumi_list\n\n\ndef nsProblem(skills, workers, worker_skill_dict):\n\n _, last_day = calendar.monthrange(2019, 12)\n H, D, S = range(len(workers)), range(last_day), range(len(skills))\n\n boolean_skill_list = create_boolean_list(skills, workers, worker_skill_dict, H, S)\n tomari_flag_list, ake_flag_list, yasumi_flag_list = create_any_flag_list(S, skills)\n\n s2y_penalty = 1\n s2_penalty = 100\n s7_penalty = 100\n DS = [ (d, s) for d in D for s in S ]\n DSy = [ (d, s_y) for d in D for s_y in yasumi_flag_list ]\n\n prob = LpProblem(\"NSP\", LpMinimize)\n x = LpVariable.dicts(\"x\", (H, D, S), 0, 1, \"Integer\")\n V2_y = LpVariable.dicts(\"V2_y\", (D, yasumi_flag_list), 0, 1000)\n V2 = LpVariable.dicts(\"V2\", (D, S), 0, 1000)\n V7 = LpVariable.dicts(\"V7\", H, 0, 1000)\n \n \n #目的関数\n prob += ( s2y_penalty * lpSum( V2_y[d][s_y] for (d, s_y) in DSy ) +\n s2_penalty * lpSum( V2[d][s] for (d, s) in DS ) +\n s7_penalty * lpSum( V7[h] for h in H )\n )\n\n #01:各人毎日つける勤務は最高で一つ\n for h, d in itertools.product(H, D):\n prob += lpSum( x[h][d][s] for s in S ) <= 1\n\n #02:各勤務毎日必要な人数は1人\n ##分割勤務については後で考える\n ##必要人数モデルから必要人数は引っ張ってくるようにする\n for d, s, s_y in itertools.product(D, S, yasumi_flag_list):\n if s == s_y and skills[s].exclusion_flag == False:\n prob += V2_y[d][s_y] >= ( lpSum(x[h][d][s] for h in H) - 20 )\n prob += V2_y[d][s_y] >= -( lpSum(x[h][d][s] for h in H) - 20 )\n if skills[s].exclusion_flag == True:\n #print (str(workers[h].name) + str(d) + skills[s].skill_name)\n prob += lpSum(x[h][d][s] for h in H) <= 0\n else:\n prob += V2[d][s] >= ( lpSum(x[h][d][s] for h in H) - 1 )\n prob += V2[d][s] >= -( lpSum(x[h][d][s] for h in H) - 1 )\n\n #03:各人持っているスキルの勤務にしかつけない\n for h, d, s in itertools.product(H, D, S):\n prob += x[h][d][s] <= boolean_skill_list[workers[h].name][s]\n \n #04:泊まりの翌日は明け\n for h, d, s, s_a in itertools.product(H, range(last_day-1), tomari_flag_list, ake_flag_list):\n if str(skills[s].relation_flag) == str(skills[s_a].skill_name):\n prob += x[h][d][s] == x[h][d+1][s_a]\n\n #05:明けの前日は泊まり\n for h, d, s, s_t in itertools.product(H, range(1, last_day), ake_flag_list, tomari_flag_list):\n if str(skills[s].relation_flag) == str(skills[s_t].skill_name):\n prob += x[h][d-1][s_t] == x[h][d][s]\n\n #06:なるべく原則勤務に従う\n\n #07:休みはなるべく毎月8日前後\n for h, s in itertools.product(H, yasumi_flag_list):\n prob += V7[h] >= ( lpSum(x[h][d][s] for d in D) - 8)\n prob += V7[h] >= -( lpSum(x[h][d][s] for d in D) - 8)\n \n finish_state = prob.solve()\n print (LpStatus[finish_state])\n print (value(prob.objective))\n\n x_rep = {}\n for h in H:\n dummy = []\n for d in D:\n flag = False\n for s in S:\n if int(x[h][d][s].value()) == 1:\n dummy.append(skills[s].skill_name)\n flag = True\n if flag == False:\n dummy.append(\"\")\n x_rep[workers[h].name] = dummy\n \n return x_rep\n","sub_path":"shiftManage/nurseScheduling.py","file_name":"nurseScheduling.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"430393370","text":"#Euler 9\ndef pythagtrip():\n # Again, no input here because of the specificity.\n a = 1\n b = 2\n c = 3\n condition = 0\n while condition == 0:\n for i in range(1,501):\n if condition == 1: #Want to stop as soon as the conditions are met.\n break\n a = i\n for j in range(1,501):\n if condition == 1:\n break\n b = j\n c = 1000 - (b+a) # a+b+c always = 1000\n if (((a**2) + (b**2)) == c**2):\n condition = 1\n print(\"The numbers are\",a,b,c,\"and the product is\",a*b*c)\npythagtrip()\n","sub_path":"euler9.py","file_name":"euler9.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"219466807","text":"import pandas\nfrom rdkit.Chem import AllChem\nfrom rdkit import Chem\nfrom rdkit.Chem import Draw\nimport pandas as pd\nimport openbabel\nimport numpy as np \nimport os \nfrom biopandas.mol2 import PandasMol2\nimport openbabel\nimport argparse\n\ndef SYBYL(row):\n try:\n obconversion = openbabel.OBConversion()\n obconversion.SetInAndOutFormats(\"smi\", \"mol2\")\n mol = openbabel.OBMol()\n obconversion.ReadString(mol,row[\"SMILES\"]) # read molecule from database \n mol.AddHydrogens()\n output_mol2 = obconversion.WriteString(mol) # transform smiles into mol2\n file = open(\"molecule.mol2\",\"w+\") # write mol2 format into the file, molecule.mol2.\n file.write(output_mol2)\n file.close()\n molecule_mol2 = PandasMol2().read_mol2(\"molecule.mol2\") # use biopandas to static the discriptors\n for element in molecule_mol2.df['atom_type'].value_counts().index:\n if element == 'Al':\n row['Al'] = molecule_mol2.df['atom_type'].value_counts()['Al']\n if element == 'B':\n row['B'] = molecule_mol2.df['atom_type'].value_counts()['B']\n if element == 'Br':\n row['Br'] = molecule_mol2.df['atom_type'].value_counts()['Br']\n if element == 'C.1':\n row['C.1'] = molecule_mol2.df['atom_type'].value_counts()['C.1']\n if element == 'C.2':\n row['C.2'] = molecule_mol2.df['atom_type'].value_counts()['C.2']\n if element == 'C.3':\n row['C.3'] = molecule_mol2.df['atom_type'].value_counts()['C.3']\n if element == 'C.ar':\n row['C.ar'] = molecule_mol2.df['atom_type'].value_counts()['C.ar']\n if element == 'C.cat':\n row['C.cat'] = molecule_mol2.df['atom_type'].value_counts()['C.cat']\n if element == 'Ca':\n row['Ca'] = molecule_mol2.df['atom_type'].value_counts()['Ca']\n if element == 'Cl':\n row['Cl'] = molecule_mol2.df['atom_type'].value_counts()['Cl']\n if element == 'F':\n row['F'] = molecule_mol2.df['atom_type'].value_counts()['F']\n if element == 'H':\n row['H'] = molecule_mol2.df['atom_type'].value_counts()['H'] \n if element == 'Li':\n row['Li'] = molecule_mol2.df['atom_type'].value_counts()['Li'] \n if element == 'Mg':\n row['Mg'] = molecule_mol2.df['atom_type'].value_counts()['Mg'] \n if element == 'N.1':\n row['N.1'] = molecule_mol2.df['atom_type'].value_counts()['N.1'] \n if element == 'N.2':\n row['N.2'] = molecule_mol2.df['atom_type'].value_counts()['N.2'] \n if element == 'N.3':\n row['N.3'] = molecule_mol2.df['atom_type'].value_counts()['N.3'] \n if element == 'N.4':\n row['N.4'] = molecule_mol2.df['atom_type'].value_counts()['N.4'] \n if element == 'N.am':\n row['N.am'] = molecule_mol2.df['atom_type'].value_counts()['N.am'] \n if element == 'N.ar':\n row['N.ar'] = molecule_mol2.df['atom_type'].value_counts()['N.ar'] \n if element == 'N.pl3':\n row['N.pl3'] = molecule_mol2.df['atom_type'].value_counts()['N.pl3'] \n if element == 'Na':\n row['Na'] = molecule_mol2.df['atom_type'].value_counts()['Na'] \n if element == 'O.2':\n row['O.2'] = molecule_mol2.df['atom_type'].value_counts()['O.2'] \n if element == 'O.3':\n row['O.3'] = molecule_mol2.df['atom_type'].value_counts()['O.3'] \n if element == 'O.co2':\n row['O.co2'] = molecule_mol2.df['atom_type'].value_counts()['O.co2'] \n if element == 'P.3':\n row['P.3'] = molecule_mol2.df['atom_type'].value_counts()['P.3'] \n if element == 'S.2':\n row['S.2'] = molecule_mol2.df['atom_type'].value_counts()['S.2'] \n if element == 'S.3':\n row['S.3'] = molecule_mol2.df['atom_type'].value_counts()['S.3']\n if element == 'S.O2':\n row['S.O2'] = molecule_mol2.df['atom_type'].value_counts()['S.O2'] \n if element == 'S.O':\n row['S.O'] = molecule_mol2.df['atom_type'].value_counts()['S.O'] \n if element == 'Si':\n row['Si'] = molecule_mol2.df['atom_type'].value_counts()['Si'] \n if element == 'Zn':\n row['Zn'] = molecule_mol2.df['atom_type'].value_counts()['Zn'] \n return row\n except:\n print(row[\"SMILES\"],\"SYBYL something is wrong!!\")\n\n\ndef ECFP(row):\n try:\n mol = Chem.MolFromSmiles(row['SMILES'])\n fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=nbits).ToBitString()\n for i in range(nbits):\n row[str(i)] = fp[i]\n return row \n except:\n print(row[\"SMILES\"],\"ECFP feature something is wrong!!\")\n\n\ndef smile2ECFP_number(row):\n from rdkit.Chem import AllChem\n from rdkit import Chem\n from rdkit.Chem import Draw\n import pandas\n from collections import Counter\n m = Chem.MolFromSmiles(row['SMILES'])\n \n info={}\n fp = AllChem.GetMorganFingerprintAsBitVect(m,radius,nBits=nbits,bitInfo=info).ToBitString()\n \n try:\n for bit in info:\n row[\"num_\"+str(bit)] = len(info[bit])\n return row \n except:\n print(row[\"SMILES\"],\"ECFP feature something is wrong!!\")\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--smile_file',\n help='experiment file', default=None)\n parser.add_argument('-n', '--nbits',\n help='how many bits of ECFP', default=2048, type=int)\n parser.add_argument('-r', '--radius',\n help='ECFP radius', default=2, type=int)\n \n \n args = vars(parser.parse_args())\n\n\n # load data \n data = pd.read_csv(args[\"smile_file\"])\n # set parameter of ECFP, namely nbits, radius\n nbits = args[\"nbits\"]\n radius = args[\"radius\"]\n # discriptor ECFP \n data_ECFP = data.reindex(columns = data.columns.tolist() + [str(i) for i in range(nbits)]) \n data_ECFP = data_ECFP.apply(ECFP, axis=1)\n\n data_ECFP.to_csv(\"ECFP.csv\",index=False)\n\n # discriptor ECFP_number \n data_ECFP_num = data.reindex(columns = data.columns.tolist() + [\"num_\"+str(i) for i in range(nbits)]) \n data_ECFP_num = data_ECFP_num.apply(smile2ECFP_number, axis=1).fillna(0)\n data_ECFP_num.to_csv(\"ECFP_num.csv\",index=False)\n # discriptor SYBYL \n atom_type=['Al','B','Br','C.1','C.2','C.3','C.ar','C.cat','Ca','Cl','F','H',\n 'Li','Mg','N.1','N.2','N.3','N.4','N.am','N.ar','N.pl3','Na',\n 'O.2','O.3','O.co2','P.3','S.2','S.3','S.O','S.O2','Si','Zn']\n\n data_SYBYL = data.reindex(columns = data.columns.tolist() + atom_type) \n data_SYBYL = data_SYBYL.apply(SYBYL, axis=1).fillna(0)\n data_SYBYL.to_csv(\"SYBYL.csv\",index=False)\n os.remove(\"./molecule.mol2\")\n","sub_path":".ipynb_checkpoints/featurize-checkpoint.py","file_name":"featurize-checkpoint.py","file_ext":"py","file_size_in_byte":7180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"615133511","text":"\"\"\"Make screenshot after given time.\"\"\"\nimport os\nimport re\nfrom time import sleep\n\n# pip install Pillow\nfrom PIL import ImageGrab\n\nprint(\"Provide time:\")\nprint(\"Format: Xh Xm Xs\")\n\ntext = input()\n\nhours_match = re.search('(\\d+)h', text)\nminutes_match = re.search('(\\d+)m', text)\nseconds_match = re.search('(\\d+)s', text)\n\nhours = 0\nminutes = 0\nseconds = 0\n\nif hours_match is not None:\n hours = int(hours_match.group(1))\nif minutes_match is not None:\n minutes = int(minutes_match.group(1))\nif seconds_match is not None:\n seconds = int(seconds_match.group(1))\n\ntime = hours * 3600 + minutes * 60 + seconds\nprint('Seconds: ' + str(time))\n\nprint(\"File path to save screenshot\")\nfilepath = input()\n\nprint('Sleeping...')\nsleep(time)\n\nim = ImageGrab.grab()\nim.save(filepath)\nprint('Screenshot! Saved as ' + filepath)\n","sub_path":"screenshot-t.py","file_name":"screenshot-t.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609429296","text":"import random\r\nclass Vigenere:\r\n\tdef __init__(self, arg):\r\n\t\tself.banderas = len(arg)\r\n\t\tself.clave = arg[5]\r\n\t\tself.lenguaje = \"es\"\r\n\t\tif self.banderas == 8:\r\n\t\t\tself.lenguaje = arg[7]\r\n\t\tif arg[2] == \"-c\":\r\n\t\t\tcifrar(arg[3], self.clave, self.lenguaje)\r\n\t\tif arg[2] == \"-d\":\r\n\t\t\tdescifrar(arg[3], self.clave, self.lenguaje)\r\n\r\ndef cifrar(archivo, clave, lenguaje):\r\n\tabc = alfabeto(lenguaje)\r\n\tm = mensaje(archivo)\r\n\tcifrado = []\r\n\tno = []\r\n\tcont = 0\r\n\tfor i in m:\r\n\t\tif i in abc:\r\n\t\t\tposClave = abc.index(clave[cont])\r\n\t\t\tpos = abc.index(i)\r\n\t\t\tcifrado.append(abc[(pos+posClave)%len(abc)])\r\n\t\t\tcont += 1\r\n\t\t\tif cont == len(clave):\r\n\t\t\t\tcont = 0\r\n\t\telse:\r\n\t\t\tif i not in no:\r\n\t\t\t\tno.append(i)\r\n\tif len(no) > 0:\r\n\t\tprint(\"No se puede encriptar porque le falta caracteres al alfabeto\")\r\n\t\tprint(\"Los caracteres que falta son:\")\r\n\t\tprint(sorted((list(no))))\r\n\telse:\r\n\t\tf = open (archivo+\".cif\", \"w\", encoding ='ISO-8859-1')\r\n\t\tfor i in cifrado:\r\n\t\t\tf.write(i)\r\n\t\tf.close()\r\n\t\tprint(\"================================================\")\r\n\t\tprint()\r\n\t\tprint(\"OPERACION TERMINADA CON EXITO!!!\")\r\n\t\tprint()\r\n\t\tprint(\"================================================\")\r\n\r\ndef descifrar(archivo, clave, lenguaje):\r\n\tabc = alfabeto(lenguaje)\r\n\tm = mensaje(archivo)\r\n\tdescifrado = []\r\n\tcont = 0\r\n\tfor i in m:\r\n\t\tif i in abc:\r\n\t\t\tposClave = abc.index(clave[cont])\r\n\t\t\tpos = abc.index(i)\r\n\t\t\tdescifrado.append(abc[(pos-posClave)%len(abc)])\r\n\t\t\tcont += 1\r\n\t\t\tif cont == len(clave):\r\n\t\t\t\tcont = 0\r\n\t\telse:\r\n\t\t\taux = random.randint(0,len(abc)-1)\r\n\t\t\tdescifrado.append(abc[aux])\r\n\tf = open (archivo+\".dec\", \"w\", encoding ='ISO-8859-1')\r\n\tfor i in descifrado:\r\n\t\tf.write(i)\r\n\tf.close()\r\n\tprint(\"================================================\")\r\n\tprint()\r\n\tprint(\"OPERACION TERMINADA CON EXITO!!!\")\r\n\tprint()\r\n\tprint(\"================================================\")\r\n\r\ndef mensaje(mensaje):\r\n\tarchivo = open(mensaje, \"r\", encoding ='ISO-8859-1')\r\n\ttexto = archivo.read()\r\n\tarchivo.close()\r\n\treturn texto\r\n\r\ndef alfabeto(lenguaje):\r\n\tif lenguaje == \"es\":\r\n\t\tarchivo = open(\"Alfabetos/es.txt\", \"r\", encoding ='ISO-8859-1')\r\n\t\ttexto = archivo.read()\r\n\t\tarchivo.close()\r\n\t\treturn texto\r\n\tif lenguaje == \"en\":\r\n\t\tarchivo = open(\"Alfabetos/en.txt\", \"r\", encoding ='ISO-8859-1')\r\n\t\ttexto = archivo.read()\r\n\t\tarchivo.close()\r\n\t\treturn texto\r\n\telse:\r\n\t\tarchivo = open(lenguaje, \"r\", encoding ='ISO-8859-1')\r\n\t\ttexto = archivo.read()\r\n\t\tarchivo.close()\r\n\t\treturn texto","sub_path":"vigenere.py","file_name":"vigenere.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"517184844","text":"# pylint: disable=missing-function-docstring disable=missing-module-docstring\n\nfrom unittest.mock import call\n\nimport pytest\n\nfrom nestor_api.config.config import Configuration\nfrom nestor_api.errors.config.aggregated_configuration_error import AggregatedConfigurationError\nfrom nestor_api.errors.config.app_configuration_not_found_error import AppConfigurationNotFoundError\nimport nestor_api.lib.config as config\nimport nestor_api.lib.io as io\n\n\ndef test_change_environment(mocker):\n spy = mocker.patch.object(io, \"execute\")\n\n config.change_environment(\"environment\", \"path/to/config\")\n\n spy.assert_has_calls(\n [\n call(\"git stash\", \"path/to/config\"),\n call(\"git fetch origin\", \"path/to/config\"),\n call(\"git checkout environment\", \"path/to/config\"),\n call(\"git reset --hard origin/environment\", \"path/to/config\"),\n ]\n )\n\n\n@pytest.mark.usefixtures(\"config\")\ndef test_create_temporary_config_copy(mocker):\n spy = mocker.patch.object(io, \"create_temporary_copy\", return_value=\"/temporary/path\")\n\n path = config.create_temporary_config_copy()\n\n spy.assert_called_once_with(\"/fixtures-nestor-config\", \"config\")\n assert path == \"/temporary/path\"\n\n\ndef test_get_app_config(mocker):\n mocker.patch.object(Configuration, \"get_config_path\", return_value=\"tests/__fixtures__/config\")\n\n app_config = config.get_app_config(\"backoffice\")\n\n assert app_config == {\n \"domain\": \"website.com\",\n \"sub_domain\": \"backoffice\",\n \"variables\": {\n \"ope\": {\n \"VARIABLE_OPE_1\": \"ope_1\",\n \"VARIABLE_OPE_2\": \"ope_2_override\",\n \"VARIABLE_OPE_3\": \"ope_3\",\n },\n \"app\": {\n \"VARIABLE_APP_1\": \"app_1\",\n \"VARIABLE_APP_2\": \"app_2_override\",\n \"VARIABLE_APP_3\": \"app_3\",\n },\n },\n }\n\n\n@pytest.mark.usefixtures(\"config\")\ndef test_get_app_config_when_not_found(mocker):\n mocker.patch.object(io, \"exists\", return_value=False)\n\n with pytest.raises(AppConfigurationNotFoundError):\n config.get_app_config(\"app_not_here\")\n\n\ndef test_get_project_config(mocker):\n mocker.patch.object(Configuration, \"get_config_path\", return_value=\"tests/__fixtures__/config\")\n\n environment_config = config.get_project_config()\n\n assert environment_config == {\n \"domain\": \"website.com\",\n \"variables\": {\n \"ope\": {\"VARIABLE_OPE_1\": \"ope_1\", \"VARIABLE_OPE_2\": \"ope_2\"},\n \"app\": {\"VARIABLE_APP_1\": \"app_1\", \"VARIABLE_APP_2\": \"app_2\"},\n },\n }\n\n\n@pytest.mark.usefixtures(\"config\")\ndef test_get_project_config_when_not_found(mocker):\n mocker.patch.object(io, \"exists\", return_value=False)\n\n with pytest.raises(FileNotFoundError):\n config.get_project_config()\n\n\ndef test_resolve_variables_deep():\n # pylint: disable=protected-access\n result = config._resolve_variables_deep(\n {\n \"A\": \"value_a\",\n \"B\": \"value_b\",\n \"C\": {\n \"C1\": \"__{{A}}__\",\n \"C2\": \"__{{key_not_present}}__\",\n \"C3\": \"__{{A}}__{{B}}__{{key_not_present}}__\",\n \"C4\": \"A\",\n \"C5\": \"{{C1}}__{{key-with.special_characters}}\",\n },\n \"D\": [\n \"value_d1\",\n \"__{{A}}__\",\n \"__{{key_not_present}}__\",\n \"__{{A}}__{{B}}__{{key_not_present}}__\",\n ],\n \"E\": [{\"E1\": {\"E11\": \"deep__{{A}}__\"}}],\n \"F\": 42,\n \"key-with.special_characters\": \"amazing-value\",\n }\n )\n\n assert result == {\n \"A\": \"value_a\",\n \"B\": \"value_b\",\n \"C\": {\n \"C1\": \"__value_a__\",\n \"C2\": \"__{{key_not_present}}__\",\n \"C3\": \"__value_a__value_b__{{key_not_present}}__\",\n \"C4\": \"A\",\n \"C5\": \"{{C1}}__amazing-value\",\n },\n \"D\": [\n \"value_d1\",\n \"__value_a__\",\n \"__{{key_not_present}}__\",\n \"__value_a__value_b__{{key_not_present}}__\",\n ],\n \"E\": [{\"E1\": {\"E11\": \"deep__value_a__\"}}],\n \"F\": 42,\n \"key-with.special_characters\": \"amazing-value\",\n }\n\n\ndef test_resolve_variables_deep_with_invalid_reference():\n with pytest.raises(AggregatedConfigurationError) as err:\n # pylint: disable=protected-access\n config._resolve_variables_deep(\n {\n \"error\": {},\n \"simple_key\": \"__{{error}}__\",\n \"array\": [\"0\", \"1\", \"2__{{error}}__\",],\n \"dict\": {\"a\": \"val_a\", \"b\": \"{{error}}\",},\n \"deep_dict\": {\n \"sub_dict\": {\"a\": \"val_a\", \"b\": \"{{error}}\"},\n \"sub_array\": [\n {\"a\": \"{{error}}\", \"b\": \"val_b\"},\n {\"a\": \"val_a\", \"b\": \"{{error}}\"},\n ],\n },\n }\n )\n\n assert str(err.value) == \"Invalid configuration\"\n\n assert err.value.errors[0].path == \"CONFIG.simple_key\"\n assert err.value.errors[0].message == \"Referenced variable should resolved to a string\"\n\n assert err.value.errors[1].path == \"CONFIG.array[2]\"\n assert err.value.errors[1].message == \"Referenced variable should resolved to a string\"\n\n assert err.value.errors[2].path == \"CONFIG.dict.b\"\n assert err.value.errors[2].message == \"Referenced variable should resolved to a string\"\n\n assert err.value.errors[3].path == \"CONFIG.deep_dict.sub_dict.b\"\n assert err.value.errors[3].message == \"Referenced variable should resolved to a string\"\n\n assert err.value.errors[4].path == \"CONFIG.deep_dict.sub_array[0].a\"\n assert err.value.errors[4].message == \"Referenced variable should resolved to a string\"\n\n assert err.value.errors[5].path == \"CONFIG.deep_dict.sub_array[1].b\"\n assert err.value.errors[5].message == \"Referenced variable should resolved to a string\"\n","sub_path":"tests/lib/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"199475370","text":"import os\r\nimport time\r\nfrom threading import Thread\r\n\r\n\r\ndef create_files(file_name_to_write):\r\n with open(f\"{file_name_to_write}.txt\", \"w\") as f:\r\n f.write(\"This is a file and is filled with\\n\")\r\n f.write(\"random text that has no real meaning but it is here\\n\")\r\n f.write(\"anyway so please enjoy reading just before it deletes\\n\")\r\n f.write(\"its self during stage three of the program.\\n\")\r\n print(\"File created\")\r\n time.sleep(.5)\r\n append_to_file(file_name_to_write)\r\n\r\n\r\ndef append_to_file(file_to_append_to):\r\n with open(f\"{file_to_append_to}.txt\", \"a\") as af:\r\n af.write(\"This is an appended section to the file.\\n\")\r\n af.write(\"This means it was not part of the initial\\n\")\r\n af.write(\"text written to this file.\")\r\n read_files(file_to_append_to)\r\n\r\n\r\ndef read_files(file_name):\r\n with open(f\"{file_name}.txt\", \"r\") as rf:\r\n print(rf)\r\n reading = rf.read()\r\n print(reading)\r\n time.sleep(2)\r\n\r\n\r\ndef del_files(file_name_to_del):\r\n if os.path.exists(f\"{file_name_to_del}.txt\"):\r\n os.remove(f\"{file_name_to_del}.txt\")\r\n print(f\"\\n{file_name_to_del}.txt has been deleted\")\r\n else:\r\n print(f\"The file {file_name_to_del}.txt does not exist\")\r\n\r\n\r\ncre_files = []\r\ndel_files_list = []\r\nlist_of_files = [\"test1\", \"test2\", \"test3\", \"test4\", \"test5\", \"test6\", \"test7\", \"test8\", \"test9\", \"test10\", \"test11\"]\r\n\r\nstart = time.time()\r\n\r\nfor item in list_of_files:\r\n threads = Thread(target=create_files, args=(item, ))\r\n cre_files.append(threads)\r\n threads.start()\r\nfor file in cre_files:\r\n file.join()\r\n\r\ntime.sleep(10)\r\n\r\nfor files in list_of_files:\r\n del_threads = Thread(target=del_files, args=(files,))\r\n del_files_list.append(del_threads)\r\n del_threads.start()\r\n\r\nfor delt in del_files_list:\r\n delt.join()\r\n\r\nend = time.time()\r\ntime_taken = end - start\r\nprint(\"It took the program\", time_taken, \"seconds to finish\")\r\n","sub_path":"CreatingFilesThreaded.py","file_name":"CreatingFilesThreaded.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"139434378","text":"import random\nimport sys\nimport numpy as np\nimport tensorflow as tf\nfrom os import path\n\ncurrent_path = path.dirname(path.abspath(__file__))\nparent_path = path.dirname(current_path)\nsys.path.append(parent_path)\nfrom models import lstm_fn\n\nnum_epochs = 10\ntruncated_backprop_length = 15\nstate_size = 4\nnum_classes = 2\necho_step = 3\nbatch_size = 5\ninput_dimension = 1\ntrain_steps = 100\nmodel_path = path.join(parent_path, 'resources/model_checkpoint/another_test')\n\n\ndef generate_data(number_of_batch):\n data = []\n label = []\n for _ in range(0, number_of_batch):\n for __ in range(0, batch_size):\n p = random.random()\n if p > 0.5:\n q = random.random()\n for index in range(0, truncated_backprop_length):\n data.append(np.float32(q + 0.1 * index))\n label.append(1)\n else:\n q = random.random()\n for index in range(0, truncated_backprop_length):\n data.append(np.float32(q - 0.1 * index))\n label.append(0)\n\n data = np.array(data)\n label = np.array(label)\n data = data.reshape(-1, truncated_backprop_length, input_dimension)\n return data, label\n\n\nx_train, y_train = generate_data(100)\nx_test, y_test = generate_data(10)\nx_train = {'feature': x_train}\nx_test = {'feature': x_test}\n\n\ndef train_input_fn(features, labels, batch):\n \"\"\"An input function for training\"\"\"\n # Convert the inputs to a Dataset.\n dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))\n\n # Shuffle, repeat, and batch the examples.\n return dataset.batch(batch)\n\n\nclassifier = tf.estimator.Estimator(\n model_fn=lstm_fn.lstm_model_fn,\n params={\n 'batch_size': batch_size,\n 'state_size': state_size,\n 'truncated_backprop_length': truncated_backprop_length,\n 'input_dimension': input_dimension,\n 'num_classes': num_classes\n },\n model_dir=model_path,\n config=tf.estimator.RunConfig().replace(save_summary_steps=5))\n\nclassifier.train(\n input_fn=lambda: train_input_fn(x_train, y_train, batch_size), steps=100,)\n\neval_result = classifier.evaluate(\n input_fn=lambda: train_input_fn(x_test, y_test, batch_size), steps=10)\n\nprint('\\nTest set accuracy: {accuracy:0.3f}\\n'.format(**eval_result))","sub_path":"tests/script_test/basic_estimator_test.py","file_name":"basic_estimator_test.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"299609964","text":"# coding: utf-8\n\"\"\"\nFile ID: 8yVHVsZ\n\"\"\"\n\nimport codecs\nimport locale\nimport os\nimport sys\nimport traceback\n\n#/ define a raisex func that is compatible with both Py2 and Py3.\n##\n## Modified from |six|:\n## https://bitbucket.org/gutworth/six/src/cc9fce6016db076497454f9352e55b4758ccc07c/six.py?at=default#cl-632\n##\n## ---BEG\nif sys.version_info[0] == 3:\n def raisex(exc, tb=None):\n if tb is not None and exc.__traceback__ is not tb:\n raise exc.with_traceback(tb)\n else:\n raise exc\nelse:\n def exec_(_code_, _globs_=None, _locs_=None):\n \"\"\"Execute code in a namespace.\"\"\"\n if _globs_ is None:\n frame = sys._getframe(1)\n _globs_ = frame.f_globals\n if _locs_ is None:\n _locs_ = frame.f_locals\n del frame\n elif _locs_ is None:\n _locs_ = _globs_\n exec(\"\"\"exec _code_ in _globs_, _locs_\"\"\")\n\n exec_(\"\"\"def raisex(exc, tb=None):\n raise exc, None, tb\n\"\"\")\n\ndef reraisex(exc):\n raisex(exc, tb=sys.exc_info()[2])\n## ---END\n\nclass SixyIO(object):\n \n #/\n DEBUG_ON = False\n \n #/\n IS_PY2 = sys.version_info[0] == 2\n \n #/\n BTXT_CLS = str if IS_PY2 else bytes\n \n UTXT_CLS = str if IS_PY2 else str\n \n #/\n _LCE = locale.getdefaultlocale()[1]\n ## stxt or None\n \n LCE = _LCE or 'utf-8'\n ## stxt\n\n LCE_UTXT = LCE.decode('ascii', 'replace') if IS_PY2 else LCE\n \n #/\n _STDIE = sys.stdin.encoding\n ## stxt or None\n \n STDIE = _STDIE or LCE\n\n STDIE_UTXT = STDIE.decode('ascii', 'replace') if IS_PY2 else STDIE\n \n #/\n _STDOE = sys.stdout.encoding\n ## stxt or None\n \n STDOE = _STDOE or STDIE\n ## stxt\n\n STDOE_UTXT = STDOE.decode('ascii', 'replace') if IS_PY2 else STDOE\n \n #/\n _STDEE = sys.stderr.encoding\n ## stxt or None\n \n STDEE = _STDEE or STDIE\n ## stxt\n\n STDEE_UTXT = STDEE.decode('ascii', 'replace') if IS_PY2 else STDEE\n \n #/\n CAE = STDIE\n ## stxt\n\n CAE_UTXT = CAE.decode('ascii', 'replace') if IS_PY2 else CAE\n \n FSE = sys.getfilesystemencoding() or 'utf-8'\n \n FSE_UTXT = FSE.decode('ascii', 'replace') if IS_PY2 else FSE\n \n IFE = 'utf-8'\n \n IFE_UTXT = IFE.decode('ascii', 'replace') if IS_PY2 else IFE\n \n OFE = 'utf-8'\n \n OFE_UTXT = OFE.decode('ascii', 'replace') if IS_PY2 else OFE\n \n SPCE = 'utf-8'\n \n SPCE_UTXT = SPCE.decode('ascii', 'replace') if IS_PY2 else SPCE\n \n SPIE = 'utf-8'\n \n SPIE_UTXT = SPIE.decode('ascii', 'replace') if IS_PY2 else SPIE\n \n SPOE = 'utf-8'\n \n SPOE_UTXT = SPOE.decode('ascii', 'replace') if IS_PY2 else SPOE\n \n SPEE = 'utf-8'\n \n SPEE_UTXT = SPEE.decode('ascii', 'replace') if IS_PY2 else SPEE\n \n SIXYIO_CLS_NOT_ALLOW_CREATING_OBJ = '9gwa3bx'\n STDEE_NOT_VALID = '5jNUcjC'\n STDOE_NOT_VALID = '2bGFZgx'\n STDIE_NOT_VALID = '8fy6R9g'\n CAE_NOT_VALID = '8dB7OzL'\n FSE_NOT_VALID = '5msQt8M'\n IFE_NOT_VALID = '3zxd6jZ'\n OFE_NOT_VALID = '9eaiwe8'\n SPCE_NOT_VALID = '8dcQynl'\n SPIE_NOT_VALID = '5uyXWxm'\n SPOE_NOT_VALID = 'C49VtSM'\n SPEE_NOT_VALID = 'GmH4cDl'\n \n TT_D = {\n STDEE_NOT_VALID: 'Error: Stderr encoding is not valid.\\nEncoding is |{}|.\\nPlease use env var |PYTHONIOENCODING| or cmd arg |--stdee| to specify a correct one.\\n',\n STDOE_NOT_VALID: 'Error: Stdout encoding is not valid.\\nEncoding is |{}|.\\nPlease use env var |PYTHONIOENCODING| or cmd arg |--stdoe| to specify a correct one.\\n',\n STDIE_NOT_VALID: 'Error: Stdin encoding is not valid.\\nEncoding is |{}|.\\nPlease use env var |PYTHONIOENCODING| or cmd arg |--stdie| to specify a correct one.\\n',\n CAE_NOT_VALID: 'Error: Cmdarg encoding is not valid.\\nEncoding is |{}|.\\n',\n FSE_NOT_VALID: 'Error: Filesystem encoding is not valid.\\nEncoding is |{}|.\\n',\n IFE_NOT_VALID: 'Error: Input file encoding is not valid.\\nEncoding is |{}|.\\n',\n OFE_NOT_VALID: 'Error: Output file encoding is not valid.\\nEncoding is |{}|.\\n',\n SPCE_NOT_VALID: 'Error: Subproc command encoding is not valid.\\nEncoding is |{}|.\\n',\n SPIE_NOT_VALID: 'Error: Subproc stdin encoding is not valid.\\nEncoding is |{}|.\\n',\n SPOE_NOT_VALID: 'Error: Subproc stdout encoding is not valid.\\nEncoding is |{}|.\\n',\n SPEE_NOT_VALID: 'Error: Subproc stderr encoding is not valid.\\nEncoding is |{}|.\\n',\n }\n \n def __init__(self):\n msg = 'Can not create object of class SixyIO. Use class SixyIOObj instead.'\n \n raisex(AssertionError(SixyIO.SIXYIO_CLS_NOT_ALLOW_CREATING_OBJ, msg))\n \n @staticmethod\n def get_traceback_stxt():\n \"\"\"\n Result is (bytes) str type on Python 2 and (unicode) str type on Python 3.\n \"\"\"\n #/\n exc_cls, exc_obj, tb_obj = sys.exc_info()\n \n #/\n txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj)\n \n #/\n res = ''.join(txt_s)\n \n return res\n \n @staticmethod\n def get_traceback_utxt(encoding='utf-8', errors='replace'):\n #/\n txt = SixyIO.get_traceback_stxt()\n \n #/\n if sys.version_info.major == 2:\n utxt = txt.decode(encoding, errors)\n else:\n utxt = txt\n \n #/\n return utxt\n \n @staticmethod\n def get_default_locale(self, lower=False):\n #/\n lang, encoding = locale.getdefaultlocale()\n ## can both be None\n \n #/\n if lower:\n if lang:\n lang = lang.lower()\n \n if encoding:\n encoding = encoding.lower()\n \n #/\n return lang, encoding\n \n @staticmethod\n def get_default_locale_lang(lower=False):\n return SixyIO.get_default_locale(lower=lower)[0]\n \n @staticmethod\n def get_default_locale_encoding(lower=False):\n return SixyIO.get_default_locale(lower=lower)[1]\n \n @staticmethod\n def get_native_encodings_info():\n #/\n txt_s = []\n \n txt_s.append(SixyIO.format('{:<25}{}', 'PYTHONIOENCODING', SixyIO.cae_to_u_safe(os.environ.get('PYTHONIOENCODING') or '')))\n \n #/\n loc_lang, loc_encoding = locale.getdefaultlocale()\n \n txt_s.append(SixyIO.format('{:<25}{}', 'locale lang', SixyIO.to_u_safe(loc_lang or '')))\n txt_s.append(SixyIO.format('{:<25}{}', 'locale enco', SixyIO.to_u_safe(loc_encoding or '')))\n \n #/\n txt_s.append(SixyIO.format('{:<25}{}', 'stdin', SixyIO.to_u_safe(sys.stdin.encoding or '')))\n txt_s.append(SixyIO.format('{:<25}{}', 'stdout', SixyIO.to_u_safe(sys.stdout.encoding or '')))\n txt_s.append(SixyIO.format('{:<25}{}', 'stderr', SixyIO.to_u_safe(sys.stderr.encoding or '')))\n \n #/\n txt_s.append(SixyIO.format('{:<25}{}', 'fs', SixyIO.to_u_safe(sys.getfilesystemencoding() or '')))\n \n #/\n txt_s.append(SixyIO.format('{:<25}{}', 'default', SixyIO.to_u_safe(sys.getdefaultencoding() or '')))\n \n #/\n res = '\\n'.join(txt_s)\n \n return res\n \n @staticmethod\n def encoding_is_valid(encoding):\n #/\n try:\n codecs.lookup(encoding)\n return True\n except Exception:\n return False\n \n @staticmethod\n def reload_default_encoding(encoding):\n if SixyIO.IS_PY2:\n reload(sys)\n sys.setdefaultencoding(encoding) #@UndefinedVariable\n \n @staticmethod\n def register_codec_cp65001():\n try:\n codecs.lookup('cp65001')\n except Exception:\n def lookup_func(name):\n if name.lower() == 'cp65001':\n return codecs.lookup('utf-8')\n codecs.register(lookup_func)\n \n @staticmethod\n def register_special_codecs():\n SixyIO.register_codec_cp65001()\n \n @staticmethod\n def stdin_make_reader(encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.STDIE\n \n errors = errors or 'strict'\n \n #/\n buf = sys.stdin if SixyIO.IS_PY2 else sys.stdin.buffer\n \n #/\n reader = codecs.getreader(encoding)(buf, errors)\n \n return reader\n \n #/ \n stdout_write_b = sys.stdout.write if IS_PY2 else sys.stdout.buffer.write\n \n @staticmethod\n def stdout_write(utxt, encoding=None, errors=None):\n #/\n if SixyIO.DEBUG_ON:\n assert SixyIO.is_u(utxt)\n \n #/\n encoding = encoding or SixyIO.STDOE\n \n errors = errors or 'strict'\n \n #/\n btxt = utxt.encode(encoding, errors)\n \n #/\n SixyIO.stdout_write_b(btxt)\n \n @staticmethod\n def stdout_print(utxt, encoding=None, errors=None):\n SixyIO.stdout_write(utxt, encoding=encoding, errors=errors)\n SixyIO.stdout_write('\\n', encoding=encoding, errors=errors)\n \n @staticmethod\n def stdout_write_safe(utxt, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n SixyIO.stdout_write(utxt, encoding=encoding, errors=errors)\n \n @staticmethod\n def stdout_print_safe(utxt, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n SixyIO.stdout_write(utxt, encoding=encoding, errors=errors)\n SixyIO.stdout_write('\\n', encoding=encoding, errors=errors)\n \n @staticmethod\n def stdout_write_fmt(fmt, *args, **kwargs):\n #/\n _encoding = kwargs.pop('_encoding', None)\n \n _errors = kwargs.pop('_errors', None)\n \n #/\n utxt = SixyIO.format(fmt, *args, **kwargs)\n \n #/\n SixyIO.stdout_write(utxt, encoding=_encoding, errors=_errors)\n \n @staticmethod\n def stdout_print_fmt(fmt, *args, **kwargs):\n #/\n _encoding = kwargs.pop('_encoding', None)\n \n _errors = kwargs.pop('_errors', None)\n \n #/\n utxt = SixyIO.format(fmt, *args, **kwargs)\n \n #/\n SixyIO.stdout_write(utxt, encoding=_encoding, errors=_errors)\n SixyIO.stdout_write('\\n', encoding=_encoding, errors=_errors)\n \n @staticmethod\n def stdout_write_fmt_safe(fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_errors', 'replace')\n \n #/\n SixyIO.stdout_write_fmt(fmt, *args, **kwargs)\n \n @staticmethod\n def stdout_print_fmt_safe(fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_errors', 'replace')\n \n #/\n SixyIO.stdout_print_fmt(fmt, *args, **kwargs)\n \n @staticmethod\n def stdout_write_tb_safe(utxt=None, fmt=None, encoding=None):\n #/\n if SixyIO.DEBUG_ON:\n assert utxt is None or SixyIO.is_u(utxt)\n \n assert fmt is None or SixyIO.is_u(fmt)\n \n #/\n utxt = utxt or ''\n \n #/\n fmt = fmt or '{}---\\n{}---\\n'\n \n #/\n tb_utxt = SixyIO.get_traceback_utxt()\n \n #/\n res_utxt = fmt.format(utxt, tb_utxt)\n \n #/\n SixyIO.stdout_write_safe(res_utxt, encoding=encoding)\n \n @staticmethod\n def stdout_make_writer(encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.STDOE\n \n errors = errors or 'strict'\n \n #/\n buf = sys.stdout if SixyIO.IS_PY2 else sys.stdout.buffer\n \n #/\n return codecs.getwriter(encoding)(buf, errors)\n \n #/\n stderr_write_b = sys.stderr.write if IS_PY2 else sys.stderr.buffer.write\n \n @staticmethod\n def stderr_write(utxt, encoding=None, errors=None):\n #/\n if SixyIO.DEBUG_ON:\n assert SixyIO.is_u(utxt)\n \n #/\n encoding = encoding or SixyIO.STDEE\n \n errors = errors or 'strict'\n \n #/\n btxt = utxt.encode(encoding, errors)\n \n #/\n SixyIO.stderr_write_b(btxt)\n \n @staticmethod\n def stderr_print(utxt, encoding=None, errors=None):\n SixyIO.stderr_write(utxt, encoding=encoding, errors=errors)\n SixyIO.stderr_write('\\n', encoding=encoding, errors=errors)\n \n @staticmethod\n def stderr_write_safe(utxt, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n SixyIO.stderr_write(utxt, encoding=encoding, errors=errors)\n \n @staticmethod\n def stderr_print_safe(utxt, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n SixyIO.stderr_write(utxt, encoding=encoding, errors=errors)\n SixyIO.stderr_write('\\n', encoding=encoding, errors=errors)\n \n @staticmethod\n def stderr_write_fmt(fmt, *args, **kwargs):\n #/\n _encoding = kwargs.pop('_encoding', None)\n \n _errors = kwargs.pop('_errors', None)\n \n #/\n utxt = SixyIO.format(fmt, *args, **kwargs)\n \n #/\n SixyIO.stderr_write(utxt, encoding=_encoding, errors=_errors)\n \n @staticmethod\n def stderr_print_fmt(fmt, *args, **kwargs):\n #/\n _encoding = kwargs.pop('_encoding', None)\n \n _errors = kwargs.pop('_errors', None)\n \n #/\n utxt = SixyIO.format(fmt, *args, **kwargs)\n \n #/\n SixyIO.stderr_write(utxt, encoding=_encoding, errors=_errors)\n SixyIO.stderr_write('\\n', encoding=_encoding, errors=_errors)\n \n @staticmethod\n def stderr_write_fmt_safe(fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_errors', 'replace')\n \n #/\n SixyIO.stderr_write_fmt(fmt, *args, **kwargs)\n \n @staticmethod\n def stderr_print_fmt_safe(fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_errors', 'replace')\n \n #/\n SixyIO.stderr_print_fmt(fmt, *args, **kwargs)\n \n @staticmethod\n def stderr_write_tb_safe(utxt=None, fmt=None, encoding=None):\n #/\n if SixyIO.DEBUG_ON:\n assert utxt is None or SixyIO.is_u(utxt)\n \n assert fmt is None or SixyIO.is_u(fmt)\n \n #/\n utxt = utxt or ''\n \n #/\n fmt = fmt or '{}---\\n{}---\\n'\n \n #/\n tb_utxt = SixyIO.get_traceback_utxt()\n \n #/\n res_utxt = fmt.format(utxt, tb_utxt)\n \n #/\n SixyIO.stderr_write_safe(res_utxt, encoding=encoding)\n \n @staticmethod\n def stderr_make_writer(encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.STDEE\n \n errors = errors or 'strict'\n \n #/\n buf = sys.stderr if SixyIO.IS_PY2 else sys.stderr.buffer\n \n #/\n return codecs.getwriter(encoding)(buf, errors)\n \n @staticmethod\n def is_u(obj):\n if SixyIO.IS_PY2:\n unicode_cls = str\n else:\n unicode_cls = str\n \n return isinstance(obj, unicode_cls)\n \n @staticmethod\n def to_u(obj, encoding=None, errors=None):\n #/\n encoding = encoding or 'utf-8'\n \n errors = errors or 'strict'\n \n #/\n if isinstance(obj, SixyIO.UTXT_CLS):\n res = obj\n elif isinstance(obj, SixyIO.BTXT_CLS):\n res = SixyIO.UTXT_CLS(obj, encoding=encoding, errors=errors)\n else:\n res = SixyIO.UTXT_CLS(obj)\n \n return res\n \n @staticmethod\n def to_u_safe(obj, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n return SixyIO.to_u(obj, encoding=encoding, errors=errors)\n \n @staticmethod\n def to_b(txt, encoding=None, errors=None):\n #/\n encoding = encoding or 'utf-8'\n \n #/\n errors = errors or 'strict'\n \n #/\n if isinstance(txt, SixyIO.UTXT_CLS):\n res = txt.encode(encoding, errors)\n elif isinstance(txt, SixyIO.BTXT_CLS):\n res = txt\n else:\n assert False\n \n return res\n \n @staticmethod\n def to_b_safe(txt, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n return SixyIO.to_b(txt=txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def to_str(obj, encoding=None, errors=None):\n #/\n if encoding is None:\n encoding = 'utf-8'\n \n #/\n if errors is None:\n errors = 'strict'\n \n #/\n if SixyIO.IS_PY2:\n if isinstance(obj, str):\n res = obj\n elif isinstance(obj, str):\n res = obj.decode(encoding, errors)\n else:\n res = str(obj)\n else:\n if isinstance(obj, str):\n res = obj\n else:\n res = str(obj)\n \n return res\n \n @staticmethod\n def to_str_safe(obj, encoding=None, errors=None):\n #/\n errors = errors or 'replace'\n \n #/\n return SixyIO.to_str(obj=obj, encoding=encoding, errors=errors)\n \n @staticmethod\n def cae_to_u(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.CAE\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def cae_to_u_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.CAE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def fse_to_u(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.FSE\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def fse_to_u_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.FSE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n\n @staticmethod\n def spce_to_b(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPCE\n \n #/\n return SixyIO.to_b(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spce_to_b_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPCE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_b(txt, encoding=encoding, errors=errors)\n\n @staticmethod\n def spie_to_b(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPIE\n \n #/\n return SixyIO.to_b(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spie_to_b_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPIE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_b(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spoe_to_u(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPOE\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spoe_to_u_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPOE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spee_to_u(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPEE\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def spee_to_u_safe(txt, encoding=None, errors=None):\n #/\n encoding = encoding or SixyIO.SPEE\n \n errors = errors or 'replace'\n \n #/\n return SixyIO.to_u(txt, encoding=encoding, errors=errors)\n \n @staticmethod\n def format(fmt, *args, **kwargs):\n #/\n if SixyIO.DEBUG_ON:\n assert SixyIO.is_u(fmt)\n \n if args:\n for arg in args:\n assert SixyIO.is_u(arg)\n \n if kwargs:\n for key, val in list(kwargs.items()):\n assert SixyIO.is_u(key)\n assert SixyIO.is_u(val)\n \n #/\n txt = fmt.format(*args, **kwargs)\n \n return txt\n \n @staticmethod\n def open(filename, mode, **kwargs):\n #/\n assert SixyIO.is_u(filename)\n \n #/\n return codecs.open(filename, mode, **kwargs)\n \nclass FileForceWriteUnicodeWrapper(object):\n \n def __init__(self, file_obj, debug_on):\n self.file = file_obj\n self.debug_on = debug_on\n \n def __getattr__(self, name):\n return getattr(self.file, name)\n \n def __enter__(self, *args, **kwargs):\n \"\"\"\n __enter__ is special that __getattr__ does not cover\n \"\"\"\n return self.file.__enter__(*args, **kwargs)\n\n def __exit__(self, *args, **kwargs):\n \"\"\"\n __exit__ is special that __getattr__ does not cover\n \"\"\"\n return self.file.__exit__(*args, **kwargs)\n \n def write(self, txt):\n #/\n if self.debug_on:\n assert SixyIO.is_u(txt)\n \n #/\n return self.file.write(txt)\n \n def write_fmt(self, fmt, *args, **kwargs):\n #/\n if self.debug_on:\n assert SixyIO.is_u(fmt)\n \n if args:\n for arg in args:\n assert SixyIO.is_u(arg)\n \n if kwargs:\n for key, val in list(kwargs.items()):\n assert SixyIO.is_u(key)\n assert SixyIO.is_u(val)\n \n #/\n if not args and not kwargs:\n txt = fmt\n else:\n txt = fmt.format(*args, **kwargs)\n \n #/\n return self.file.write(txt)\n \nclass SixyIOObj(object):\n \n def __init__(self,\n stdioe=None,\n stdie=None,\n stdoe=None,\n stdee=None,\n cae=None,\n fse=None,\n ife=None,\n ofe=None,\n spce=None,\n spie=None,\n spoe=None,\n spee=None,\n exit_code=None,\n tt=None,\n debug_on=False,\n ):\n \"\"\"\n stdie: Stdin encoding.\n stdoe: Stdout encoding.\n stdee: Stderr encoding.\n cae: Command argument encoding.\n fse: Filesystem encoding.\n ife: Input file encoding.\n ofe: Output file encoding.\n spce: Subproc command encoding.\n spie: Subproc stdin encoding.\n spoe: Subproc stdout encoding.\n spee: Subproc stderr encoding.\n exit_code: Exit code on init error. If none, raise exception instead of exit. \n \"\"\"\n #/\n self.exit_code = exit_code\n \n #/\n self.debug_on = debug_on\n \n if self.debug_on is None:\n self.debug_on = SixyIO.DEBUG_ON\n \n #/\n if tt is None:\n def tt(key):\n return SixyIO.TT_D[key]\n \n #/\n self.stdee = stdee or stdioe or SixyIO.STDEE\n \n assert self.stdee\n \n self.stdee_utxt = SixyIO.to_u_safe(self.stdee, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.stdee):\n #/ 6xW0Tns\n msg = SixyIO.format(tt(SixyIO.STDEE_NOT_VALID), self.stdee_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.STDEE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_tb_safe(msg, encoding=SixyIO.STDEE)\n ## |self.stdee| is not valid so use |SixyIO.STDEE| as fallback.\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.stdoe = stdoe or stdioe or SixyIO.STDOE\n \n assert self.stdoe\n \n self.stdoe_utxt = SixyIO.to_u_safe(self.stdoe, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.stdoe):\n #/\n msg = SixyIO.format(tt(SixyIO.STDOE_NOT_VALID), self.stdoe_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.STDOE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.stdie = stdie or stdioe or SixyIO.STDIE\n \n assert self.stdie\n \n self.stdie_utxt = SixyIO.to_u_safe(self.stdie, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.stdie):\n #/\n msg = SixyIO.format(tt(SixyIO.STDIE_NOT_VALID), self.stdie_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.STDIE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.cae = cae or SixyIO.CAE\n \n assert self.cae\n \n self.cae_utxt = SixyIO.to_u_safe(self.cae, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.cae):\n #/\n msg = SixyIO.format(tt(SixyIO.CAE_NOT_VALID), self.cae_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.CAE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.fse = fse or SixyIO.FSE\n \n assert self.fse\n \n self.fse_utxt = SixyIO.to_u_safe(self.fse, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.fse):\n #/\n msg = SixyIO.format(tt(SixyIO.FSE_NOT_VALID), self.fse_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.FSE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.ife = ife or SixyIO.IFE\n \n assert self.ife\n \n self.ife_utxt = SixyIO.to_u_safe(self.ife, encoding='ascii')\n \n if not SixyIO.encoding_is_valid(self.ife):\n #/\n msg = SixyIO.format(tt(SixyIO.IFE_NOT_VALID), self.ife_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.IFE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.ofe = ofe or SixyIO.OFE\n \n assert self.ofe\n \n self.ofe_utxt = SixyIO.to_u_safe(self.ofe, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.ofe):\n #/\n msg = SixyIO.format(tt(SixyIO.OFE_NOT_VALID), self.ofe_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.OFE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.spce = spce or SixyIO.SPCE\n \n assert self.spce\n \n self.spce_utxt = SixyIO.to_u_safe(self.spce, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.spce):\n #/\n msg = SixyIO.format(tt(SixyIO.SPCE_NOT_VALID), self.spce_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.SPCE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.spie = spie or SixyIO.SPIE\n \n assert self.spie\n \n self.spie_utxt = SixyIO.to_u_safe(self.spie, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.spie):\n #/\n msg = SixyIO.format(tt(SixyIO.SPIE_NOT_VALID), self.spie_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.SPIE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.spoe = spoe or SixyIO.SPOE\n \n assert self.spoe\n \n self.spoe_utxt = SixyIO.to_u_safe(self.spoe, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.spoe):\n #/\n msg = SixyIO.format(tt(SixyIO.SPOE_NOT_VALID), self.spoe_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.SPOE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n #/\n self.spee = spee or SixyIO.SPEE\n \n assert self.spee\n \n self.spee_utxt = SixyIO.to_u_safe(self.spee, encoding='ascii')\n \n #/\n if not SixyIO.encoding_is_valid(self.spee):\n #/\n msg = SixyIO.format(tt(SixyIO.SPEE_NOT_VALID), self.spee_utxt)\n \n #/\n if exit_code is None:\n raisex(AssertionError(SixyIO.SPEE_NOT_VALID, msg))\n \n #/\n SixyIO.stderr_write_safe(msg, encoding=self.stdee)\n \n #/\n sys.exit(self.exit_code)\n \n def __str__(self):\n #/\n res = self.__unicode__()\n \n #/\n if SixyIO.IS_PY2:\n res = res.encode('utf-8', 'replace')\n \n #/\n return res\n \n def __unicode__(self):\n return self.get_sixyio_encodings_info()\n \n def __repr__(self):\n return self.__str__()\n \n def get_sixyio_encodings_info(self):\n return \"\"\"%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\n%-25s%s\"\"\" % (\n \"stdin:\", self.stdie_utxt,\n \"stdout:\", self.stdoe_utxt,\n \"stderr:\", self.stdee_utxt,\n \"cae:\", self.cae_utxt,\n \"fse:\", self.fse_utxt,\n \"ife:\", self.ife_utxt,\n \"ofe:\", self.ofe_utxt,\n \"spce:\", self.spce_utxt,\n \"spie:\", self.spie_utxt,\n \"spoe:\", self.spoe_utxt,\n )\n \n def stdin_make_reader(self, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdie\n \n #/\n return SixyIO.stdin_make_reader(encoding=encoding, errors=errors)\n\n def stdout_write(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n SixyIO.stdout_write(utxt, encoding=encoding, errors=errors)\n \n def stdout_print(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n SixyIO.stdout_print(utxt, encoding=encoding, errors=errors)\n \n def stdout_write_safe(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n SixyIO.stdout_write_safe(utxt, encoding=encoding, errors=errors)\n \n def stdout_print_safe(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n SixyIO.stdout_print_safe(utxt, encoding=encoding, errors=errors)\n \n def stdout_write_fmt(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdoe)\n \n #/\n SixyIO.stdout_write_fmt(fmt, *args, **kwargs)\n \n def stdout_print_fmt(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdoe)\n \n #/\n SixyIO.stdout_print_fmt(fmt, *args, **kwargs)\n \n def stdout_write_fmt_safe(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdoe)\n \n #/\n SixyIO.stdout_write_fmt_safe(fmt, *args, **kwargs)\n \n def stdout_print_fmt_safe(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdoe)\n \n #/\n SixyIO.stdout_print_fmt_safe(fmt, *args, **kwargs)\n \n def stdout_write_tb_safe(self, utxt=None, fmt=None, encoding=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n SixyIO.stdout_write_tb_safe(utxt, fmt=fmt, encoding=encoding)\n \n def stdout_make_writer(self, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdoe\n \n #/\n return SixyIO.stdout_make_writer(encoding=encoding, errors=errors)\n\n def stderr_write(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdee \n \n #/\n SixyIO.stderr_write(utxt, encoding=encoding, errors=errors)\n \n def stderr_print(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdee \n \n #/\n SixyIO.stderr_print(utxt, encoding=encoding, errors=errors)\n \n def stderr_write_safe(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdee \n \n #/\n SixyIO.stderr_write_safe(utxt, encoding=encoding, errors=errors)\n \n def stderr_print_safe(self, utxt, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdee \n \n #/\n SixyIO.stderr_print_safe(utxt, encoding=encoding, errors=errors)\n \n def stderr_write_fmt(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdee)\n \n #/\n SixyIO.stderr_write_fmt(fmt, *args, **kwargs)\n \n def stderr_print_fmt(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdee)\n \n #/\n SixyIO.stderr_print_fmt(fmt, *args, **kwargs)\n \n def stderr_write_fmt_safe(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdee)\n \n #/\n SixyIO.stderr_write_fmt_safe(fmt, *args, **kwargs)\n \n def stderr_print_fmt_safe(self, fmt, *args, **kwargs):\n #/\n kwargs.setdefault('_encoding', self.stdee)\n \n #/\n SixyIO.stderr_print_fmt_safe(fmt, *args, **kwargs)\n \n def stderr_write_tb_safe(self, utxt=None, fmt=None, encoding=None):\n #/\n encoding = encoding or self.stdee\n \n #/\n SixyIO.stderr_write_tb_safe(utxt, fmt=fmt, encoding=encoding)\n \n def stderr_make_writer(self, encoding=None, errors=None):\n #/\n encoding = encoding or self.stdee\n \n #/\n return SixyIO.stderr_make_writer(encoding=encoding, errors=errors)\n \n def cae_to_u(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.cae\n \n #/\n return SixyIO.cae_to_u(txt, encoding=encoding, errors=errors)\n \n def cae_to_u_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.cae\n \n #/\n return SixyIO.cae_to_u_safe(txt, encoding=encoding, errors=errors)\n \n def fse_to_u(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.fse\n \n #/\n return SixyIO.fse_to_u(txt, encoding=encoding, errors=errors)\n \n def fse_to_u_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.fse\n \n #/\n return SixyIO.fse_to_u_safe(txt, encoding=encoding, errors=errors)\n \n def spce_to_b(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spce\n \n #/\n return SixyIO.spce_to_b(txt, encoding=encoding, errors=errors)\n \n def spce_to_b_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spce\n \n #/\n return SixyIO.spce_to_b_safe(txt, encoding=encoding, errors=errors)\n \n def spie_to_b(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spie\n \n #/\n return SixyIO.spie_to_b(txt, encoding=encoding, errors=errors)\n \n def spie_to_b_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spie\n \n #/\n return SixyIO.spie_to_b_safe(txt, encoding=encoding, errors=errors)\n \n def spoe_to_u(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spoe\n \n #/\n return SixyIO.spoe_to_u(txt, encoding=encoding, errors=errors)\n \n def spoe_to_u_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spoe\n \n #/\n return SixyIO.spoe_to_u_safe(txt, encoding=encoding, errors=errors)\n \n def spee_to_u(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spee\n \n #/\n return SixyIO.spee_to_u(txt, encoding=encoding, errors=errors)\n \n def spee_to_u_safe(self, txt, encoding=None, errors=None):\n #/\n encoding = encoding or self.spee\n \n #/\n return SixyIO.spee_to_u_safe(txt, encoding=encoding, errors=errors)\n \n def open_in(self, filename, mode='r', **kwargs):\n #/\n assert SixyIO.is_u(filename)\n \n #/\n return codecs.open(filename, mode, self.ife, **kwargs)\n \n def open_out(self, filename, mode='w', **kwargs):\n #/\n assert SixyIO.is_u(filename)\n \n #/\n file_obj = codecs.open(filename, mode, self.ofe, **kwargs)\n \n #/\n file_obj = FileForceWriteUnicodeWrapper(file_obj, debug_on=self.debug_on)\n \n #/\n return file_obj\n","sub_path":"src/aoiksixyio/aoiksixyio_.py","file_name":"aoiksixyio_.py","file_ext":"py","file_size_in_byte":38812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579593509","text":"def length(str):\n\t'''Checks length of a string'''\n\t# Start counter at 0\n\tnumber = 0\n\t# Loops over each letter in the string\n\tfor letter in str:\n\t\t# Adds 1 to number for every letter in string\n\t\tnumber += 1\n\treturn number\n\nl = length('Nadav')\nprint(l)\n\n","sub_path":"hw3_q1_for.py","file_name":"hw3_q1_for.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642664041","text":"\"\"\"\nModule to run tests on arcoadd\n\"\"\"\nimport os\n\nimport pytest\n\nfrom astropy.table import Table\n\nfrom pypeit.core.datacube import coadd_cube\nfrom pypeit.spectrographs.util import load_spectrograph\nfrom pypeit import inputfiles\nfrom astropy.io import ascii\n\nfrom IPython import embed\n\nimport warnings\nwarnings.simplefilter(\"ignore\", UserWarning)\n\n\ndef test_coadd_datacube(redux_out):\n \"\"\" Test the coaddition of spec2D files into datacubes \"\"\"\n droot = os.path.join(redux_out,\n 'keck_kcwi', \n 'bh2_4200', \n 'Science')\n files = ['spec2d_KB.20191219.56886-BB1245p4238_KCWI_20191219T154806.538.fits',\n 'spec2d_KB.20191219.57662-BB1245p4238_KCWI_20191219T160102.755.fits']\n config = ['[rdx]',\n ' spectrograph = keck_kcwi']\n output_filename = \"BB1245p4238_KCWI_20191219.fits\"\n # Fake data table\n #tbl = ascii.read([files], header_start=0, data_start=1, delimiter='|', format='basic')\n tbl = Table()\n tbl['filename'] = files\n\n # Generate a mock coadd3dfile\n coadd3dfile = inputfiles.Coadd3DFile(config=config,\n file_paths=[droot],\n data_table=tbl,\n setup=None)\n # Grab the spectrograph and parset\n spec = load_spectrograph(\"keck_kcwi\")\n parset = spec.default_pypeit_par()\n parset['reduce']['cube']['output_filename'] = output_filename\n parset['reduce']['cube']['combine'] = True \n coadd_cube(coadd3dfile.filenames, coadd3dfile.options, parset=parset, overwrite=True)\n # Now test the fluxing - make a shorter set of files to speed it up\n files = ['spec2d_KB.20191219.56886-BB1245p4238_KCWI_20191219T154806.538.fits']\n tbl = Table()\n tbl['filename'] = files\n #tbl = ascii.read([files], header_start=0, data_start=1, delimiter='|', format='basic')\n\n # Generate a mock coadd3dfile\n coadd3dfile = inputfiles.Coadd3DFile(config=config,\n file_paths=[droot],\n data_table=tbl,\n setup=None)\n output_fileflux = \"BB1245p4238_KCWI_20191219_fluxing.fits\"\n parset['reduce']['cube']['output_filename'] = output_fileflux\n parset['reduce']['cube']['combine'] = False\n parset['reduce']['cube']['standard_cube'] = output_filename\n coadd_cube(coadd3dfile.filenames, coadd3dfile.options, parset=parset, overwrite=True)\n # Check the files exist\n assert(os.path.exists(output_filename))\n assert(os.path.exists(output_fileflux))\n # Remove the created files\n os.remove(output_filename)\n os.remove(output_fileflux)\n\n\n","sub_path":"vet_tests/test_datacube.py","file_name":"test_datacube.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634993753","text":"import numpy as np\n\nnp.random.seed(1)\nnp.set_printoptions(precision=6, suppress=True)\n\ntrainInput = np.array([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]])\n\ntrainOutput = np.array([[0, 1, 1, 0]]).T\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef sigmoidDerivative(x):\n return sigmoid(x) * (1 - sigmoid(x))\n\n\ndef relu(x):\n return x * (x > 0)\n\n\ndef reluDerivative(x):\n return 1. * (x > 0)\n\n\ndef neuralNetwork(hidFunc, hidDerFunc, outFunc, outDerFunc):\n predictedOutput = 0\n synapticWeightsHidden = 2 * np.random.rand(trainInput.shape[1], trainInput.shape[0]) - 1\n synapticWeightsOutput = 2 * np.random.rand(trainOutput.shape[0], trainOutput.shape[1]) - 1\n print(\"\\n\\nThe train input is\\n\", trainInput)\n print(\"Testing for attributes: [{}] used as hidden function, \"\n \"[{}] used as derivative for hidden function, [{}] used as out function, \"\n \"[{}] used as derivative for out function\\n\".format(hidFunc, hidDerFunc, outFunc, outDerFunc))\n for i in range(2000):\n # Feedforward\n hiddenLayerWeights = np.dot(trainInput, synapticWeightsHidden)\n predictedHiddenOutput = sigmoid(hiddenLayerWeights) if hidFunc is \"sigmoid\" else relu(hiddenLayerWeights)\n\n outputLayerWeights = np.dot(predictedHiddenOutput, synapticWeightsOutput)\n predictedOutput = sigmoid(outputLayerWeights) if outFunc is \"sigmoid\" else relu(outputLayerWeights)\n\n # Back propagation of hidden-output layer\n errorOutput = predictedOutput - trainOutput\n derivativeHidden = reluDerivative(outputLayerWeights) if hidDerFunc is \"derivative Relu\" else sigmoidDerivative(outputLayerWeights)\n pho = predictedHiddenOutput\n adjustmentHidden = np.dot(pho.T, errorOutput * derivativeHidden)\n # Back propagation of input-hidden layer\n inputLayerOut = trainInput\n erdh = errorOutput * derivativeHidden\n swo = synapticWeightsOutput\n hiddenLayerError = np.dot(erdh, swo.T)\n derivativeOutput = reluDerivative(hiddenLayerWeights) if outDerFunc is \"derivative Relu\" else sigmoidDerivative(hiddenLayerWeights)\n adjustmentOutput = np.dot(inputLayerOut.T, derivativeOutput * hiddenLayerError)\n\n synapticWeightsOutput -= adjustmentHidden\n synapticWeightsHidden -= adjustmentOutput\n\n print(\"Hidden weights\\n\", synapticWeightsHidden)\n print(\"Output weights\\n\", synapticWeightsOutput)\n print(\"Predicted output\\n\", predictedOutput)\n\n\nneuralNetwork(\"relu\", \"derivative Relu\", \"relu\", \"derivative Relu\")\nneuralNetwork(\"relu\", \"derivative Relu\", \"sigmoid\", \"derivative Sigmoid\")\nneuralNetwork(\"sigmoid\", \"derivative Sigmoid\", \"relu\", \"derivative Relu\")\nneuralNetwork(\"sigmoid\", \"derivative Relu\", \"sigmoid\", \"derivative Relu\")\nneuralNetwork(\"relu\", \"derivative Sigmoid\", \"relu\", \"derivative Sigmoid\")\nneuralNetwork(\"sigmoid\", \"derivative Sigmoid\", \"sigmoid\", \"derivative Sigmoid\")\n\n","sub_path":"L6/XORPerceptronWithHL.py","file_name":"XORPerceptronWithHL.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"253029622","text":"class Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n tarDict={}\n for i,num in enumerate(nums):\n targetnum = target-num\n if num in tarDict:\n return [tarDict[num],i]\n else:\n tarDict[targetnum]=i","sub_path":"Leetcode/source/1_two_sum/1_two_sum_hash.py","file_name":"1_two_sum_hash.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"443076791","text":"#!/usr/bin/env python3\r\n# coding: utf-8 \r\nimport socketserver\r\nimport os\r\n\r\n# Copyright 2013 Abram Hindle, Eddie Antonio Santos\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n# \r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n#\r\n# Copyright 2020 Dylan Alcock \r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n# \r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Furthermore it is derived from the Python documentation examples thus\r\n# some of the code is Copyright © 2001-2013 Python Software\r\n# Foundation; All Rights Reserved\r\n#\r\n# http://docs.python.org/2/library/socketserver.html\r\n#\r\n# run: python freetests.py\r\n\r\n# try: curl -v -X GET http://127.0.0.1:8080/\r\n\r\n\r\nclass MyWebServer(socketserver.BaseRequestHandler):\r\n \r\n def handle(self):\r\n self.data = self.request.recv(1024).strip()\r\n #print (\"Got a request of: %s\\n\" % self.data)\r\n\r\n header = self.data.decode().split('\\n')\r\n \r\n req = header[0].split(\" \")\r\n if req[0] == \"GET\":\r\n \r\n #Get the path of the request\r\n url = \"./www\" + req[1]\r\n #print(\"URL\", url)\r\n \r\n #if the path leads to a file, set the the FILE_TYPE and send 200 OK \r\n # if the path doesnt try to move up directories\r\n if os.path.isfile(url):\r\n file_type = url.split(\".\")[-1]\r\n \r\n #Check if url tries to move up directories if so return 404 error\r\n if \"/../\" not in url:\r\n page = open(url, 'rb').read()\r\n content_length = str(len(page))\r\n send = bytearray(req[2][:-1] + \" 200 OK\\r\\nContent-Type:text/\" + file_type + \"\\r\\n\" + \"Content-length:\"+ content_length + \"\\r\\n\\r\\n\",\"utf-8\")\r\n \r\n else:\r\n page = \"\\nHTTP/1.1 404 Path Not Found\"\r\n content_length = str(len(page))\r\n send = bytearray(req[2][:-1] + \" 404 Not Found\\r\\nContent-Type: text/html\\r\\nContent-Length:\" + content_length + \"\\r\\n\\r\\n\", \"utf-8\")\r\n page = page.encode()\r\n \r\n #if the path is a directory and has / at the end, open index.html at that directory \r\n elif req[1].endswith(\"/\") and os.path.isdir(url):\r\n url = url + \"index.html\"\r\n page = open(url, 'rb').read()\r\n content_length = str(len(page))\r\n send = bytearray(req[2][:-1] + \" 200 OK\\r\\nLocation: http://127.0.0.1:8080/\\r\\nContent-Type:text/html\\r\\nContent-Length:\" + content_length + \"\\r\\n\\r\\n\",\"utf-8\")\r\n \r\n #If the path is a directory and doesn't have a / at the end \r\n # add a / to the path and open index.html at that directory \r\n elif req[1][-1].isalpha() and os.path.isdir(url):\r\n url = url + \"/index.html\"\r\n page = open(url, 'rb').read()\r\n #print(page)\r\n content_length = str(len(page)) \r\n send = bytearray(req[2][:-1] + \" 301 Moved Permanently\\r\\nLocation: http://127.0.0.1:8080\" + req[1] + \"/\\r\\n\\r\\n\", \"utf-8\") \r\n \r\n #If path is not a file or directory return 404 error\r\n else:\r\n page = \"\\nHTTP/1.1 404 Path Not Found \"+ url+ \"\"\r\n content_length = str(len(page)) \r\n send = bytearray(req[2][:-1] + \" 404 Not Found\\r\\nContent-Type: text/html\\r\\nContent-Length:\" + content_length + \"\\r\\n\\r\\n\", \"utf-8\")\r\n page = page.encode()\r\n\r\n #If request is not a GET return a 405 error\r\n else:\r\n page = \"\\nHTTP/1.1 405 Method Not Allowed \"+ req[0] + \"\"\r\n content_length = str(len(page)) \r\n send = bytearray(\"HTTP/1.1 405 Method Not Allowed\\r\\nContent-Type: text/html\\r\\nContent-Length:\" + content_length + \"\\r\\n\\r\\n<\", \"utf-8\")\r\n page = page.encode()\r\n\r\n #Send the response and the page\r\n self.request.send(send)\r\n self.request.send(page)\r\n \r\n \r\nif __name__ == \"__main__\":\r\n HOST, PORT = \"localhost\", 8080\r\n\r\n socketserver.TCPServer.allow_reuse_address = True\r\n # Create the server, binding to localhost on port 8080\r\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\r\n\r\n # Activate the server; this will keep running until you\r\n # interrupt the program with Ctrl-C\r\n server.serve_forever()\r\n \r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"321973771","text":"import sys\nimport pandas as pd\nimport numpy as np\nimport json as js\nimport glob as gl\nimport csv\nfrom collections import defaultdict\n\nclientIdToClientName = pd.read_csv(\"data/clients.csv\")\nclientToBrands = pd.read_csv(\"data/clientBrandMap2.csv\")\n\nclient_id_to_client_name = defaultdict(str)\n\ndef client_ids_to_map(row):\n client_id = row['id']\n client_id_to_client_name[client_id] = row['name']\n\nx = clientIdToClientName.apply(client_ids_to_map, axis=1)\n\nclient_ids = [key for key in client_id_to_client_name]\n\nclientToBrands.head(10)\nclientToBrands = clientToBrands.replace(np.nan, ' ', regex=True)\nclientToBrands['array_agg'] = clientToBrands['array_agg'].str.slice(1,-1)\n\nquery_id_to_client_id = defaultdict(str)\n\ndef query_ids_to_map(row):\n query_ids = row['array_agg'].split(',')\n for query_id in query_ids:\n query_id_to_client_id[query_id] = row['client_id']\n\nx = clientToBrands.apply(query_ids_to_map, axis=1)\n\nquery_ids = [key for key in query_id_to_client_id]\n\npath = './data/jsons/*.json'\nfiles = gl.glob(path)\n\nquery_id_doc_frequency = {}\nfor name in files:\n with open(name) as json_file:\n x = js.load(json_file)\n buckets = x['posts']['buckets'][0]['query_id']['buckets']\n for i in range(len(buckets)):\n y = x['posts']['buckets'][0]['query_id']['buckets'][i]['val']\n z = x['posts']['buckets'][0]['query_id']['buckets'][i]['count']\n if y in query_id_doc_frequency.keys():\n query_id_doc_frequency[y] += z\n else:\n query_id_doc_frequency[y] = z\n\nclientTotal = {}\n\nfor k, v in query_id_to_client_id.items():\n newValue = query_id_doc_frequency.get(int(k))\n if newValue == None:\n print(\"None\")\n else:\n if v in clientTotal.keys():\n clientTotal[v] += newValue\n else:\n clientTotal[v] = newValue\n\nclientPercentage = {}\ncount = 0;\n\nfor v in clientTotal.values():\n count += v\n\nfor k,v in clientTotal.items():\n client_name = client_id_to_client_name.get(k)\n clientPercentage[client_name] = v/count\n\nwith open('clientPercentage.csv','w') as f:\n w = csv.writer(f)\n w.writerow(clientPercentage.keys())\n w.writerow(clientPercentage.values())\n","sub_path":"client_percentage.py","file_name":"client_percentage.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45704666","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimg = cv.imread('4x4_orig.jpg')\nrows, cols, colors = img.shape\nimg = (0.3*img[:,:,2] + 0.6*img[:,:,1] + 0.1*img[:,:,0]).astype(np.uint8)\nimg = cv.resize(img, None, fy = 512/rows, fx = 512/cols)\n\nimg[img < 100] = 0;\nimg[img >= 100] = 255\n\nimg = cv.erode(img, np.ones((2,2)))\n\nplt.imshow(img)\nplt.show()\ncv.imwrite('4x4.jpg', img)\n","sub_path":"puzzle_generator/patterns/adjust_pattern_4x4.py","file_name":"adjust_pattern_4x4.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"466693879","text":"import time\nfrom selenium import webdriver\nimport pandas as pd\nimport re\nimport pickle\nimport os\nfrom tqdm import tqdm\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('headless')\nbrowser = webdriver.Chrome(options=options)\n\nurls = {\n \"page_idx\": 1,\n \"urls\" : set(),\n}\n\n# preload urls pickle if it exists\ntry:\n with open('urls.pickle', 'rb') as f:\n urls = pickle.load(f)\n print('urls.pickle found and loaded!')\nexcept:\n print('urls.pickle not found. File will be created.')\n pass\n\n# populate urls with check4scam scrape\nfake_news_url = r\"https://check4spam.com/category/internet-rumours/\"\n\npattern = \"^https://check4spam.com/[^/]*-[^/]*/$\"\n\nblacklist = [\n \"https://check4spam.com/contact-us/\",\n\t\"https://check4spam.com/fact-search-engine/\",\n\t\"https://check4spam.com/coronavirus-fake-news/\",\n\t\"https://check4spam.com/about-us/\",\n\t\"https://check4spam.com/media-coverage/\",\n]\n\npages_to_scrape_for_article_links = 10\n\nfor page in tqdm(range(pages_to_scrape_for_article_links)):\n new_url = fake_news_url + r\"page/\" + str(urls[\"page_idx\"])\n browser.get(new_url)\n time.sleep(7)\n links = browser.find_elements_by_tag_name('a')\n for link in tqdm(links):\n url = link.get_attribute('href')\n if re.match(pattern, url) and url not in blacklist and r'/author/' not in url:\n try:\n urls[\"urls\"].add(url)\n except:\n continue\n urls[\"page_idx\"] += 1\n if urls[\"page_idx\"] % 5 == 0:\n with open('urls.pickle', 'wb+') as f:\n pickle.dump(urls, f)\n print('+1 cycle, 5 new pages scraped for article links')\n\n page += 1\n\ncnt = 1\n\ninit = {\n \"url\": [],\n \"raw_text\": [],\n \"image_links\": [],\n \"tweets_text\": [],\n \"tweet_ids\": [],\n}\n\n# check if data.pickle exists.\n# load if it does\ntry:\n with open('data.pickle', 'rb') as f:\n init = pickle.load(f)\n print(\"data.pickle found and loaded!\")\nexcept:\n print(\"data.pickle not found. File will be created.\")\n pass\n\nfor url in tqdm(urls[\"urls\"]):\n if url in init[\"url\"]:\n continue\n\n browser.get(url)\n time.sleep(10)\n\n try:\n article = browser.find_element_by_class_name('entry-content')\n except:\n continue\n\n paras = article.find_elements_by_tag_name('p')\n text = \"\"\n for p in paras:\n text += p.text\n text += '\\n'\n\n text = text.replace('\\n', ' ')\n\n images = article.find_elements_by_tag_name('img')\n\n links = []\n for img in images:\n link = img.get_attribute('srcset').split(' ')[0]\n links.append(link)\n\n links = ','.join([i for i in links if i is not None])\n\n tweet_obj = article.find_elements_by_tag_name('twitter-widget')\n tweets_text = \"\"\n tweet_ids = []\n for obj in tweet_obj:\n tweets_text += obj.text\n tweets_text += '^'\n tweet_ids.append(obj.get_attribute('data-tweet-id'))\n\n tweets_text = tweets_text.replace('\\n', ' ')\n tweet_ids = [i for i in tweet_ids if i is not None]\n tweet_ids = ','.join(tweet_ids)\n\n init[\"raw_text\"].append(text)\n init[\"image_links\"].append(links)\n init[\"tweets_text\"].append(tweets_text)\n init[\"tweet_ids\"].append(tweet_ids)\n init[\"url\"].append(url)\n\n if cnt % 5 == 0:\n with open('data.pickle', 'wb+') as f:\n pickle.dump(init, f)\n print(\"+5 pages scraped and dumped\")\n \n cnt += 1\n\nos.replace('data.csv', 'data_backup.csv')\ndf = pd.DataFrame(init, columns=[\"url\", \"raw_text\", \"image_links\", \"tweets_text\", \"tweet_ids\"])\ndf.to_csv('data.csv', index=True, header=True, sep=\">\")\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"11294915","text":"from asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nimport json\nfrom .models import RoomData\nclass ChatConsumer(WebsocketConsumer):\n def connect(self):\n self.room_name = None\n if len(self.scope['url_route']['kwargs'])> 0:\n self.room_name = self.scope['url_route']['kwargs']['room_name']\n if not self.room_name:\n self.room_name = self.scope.get(\"client\")[0]\n print(self.scope['url_route']['kwargs'], '__________________')\n\n self.room_group_name = 'chat_%s' % self.room_name\n # Join room group\n\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name,\n self.channel_name\n )\n\n self.accept()\n try:\n room_data_obj = RoomData.objects.get(room_ip=self.room_name)\n print(room_data_obj.room_data)\n except Exception as e:\n print(e)\n else:\n self.chat_message({\"message\":room_data_obj.room_data})\n def disconnect(self, close_code):\n # Leave room group\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name,\n self.channel_name\n )\n\n # Receive message from WebSocket\n def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n self.store_message_into_database(message)\n\n # Send message to room group\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name,\n {\n 'type': 'chat_message',\n 'message': message\n }\n )\n\n def store_message_into_database(self, message):\n room_data_obj = None\n self.room_name = self.scope.get(\"client\")[0]\n try:\n room_data_obj = RoomData.objects.get(room_ip=self.room_name)\n except Exception as e:\n print(e)\n else:\n room_data_obj.room_data = message\n room_data_obj.save()\n\n if not room_data_obj:\n try:\n room_data_obj = RoomData(room_ip=self.room_name , room_data=message)\n except Exception as e:\n print(e,\"Second\")\n else:\n room_data_obj.save()\n print(room_data_obj)\n\n # Receive message from room group\n def chat_message(self, event):\n message = event['message']\n # Send message to WebSocket\n self.send(text_data=json.dumps({\n 'message': message\n }))\n","sub_path":"chat/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"68579604","text":"import sys, os\n\n\nfrom framework import Framework,Testbed\nimport pybox2d as b2\n\n\n\nclass CollisionFiltering(Framework):\n name = \"CollisionFiltering\"\n description = \"This demonstrates a soft distance joint. Press: (b) to delete a body, (j) to delete a joint\"\n bodies = []\n joints = []\n\n def __init__(self, gui):\n super(CollisionFiltering, self).__init__(gui=gui)\n\n # Ground body\n world = self.world\n ground = world.create_body(\n shapes=b2.edge_shape(vertices=[(-40, 0), (40, 0)])\n )\n\n # Define the groups that fixtures can fall into\n # Note that negative groups never collide with other negative ones.\n smallGroup = 1\n largeGroup = -1\n\n # And the categories\n # Note that these are bit-locations, and as such are written in\n # hexadecimal.\n # defaultCategory = 0x0001\n triangleCategory = 0x0002\n boxCategory = 0x0004\n circleCategory = 0x0008\n\n # And the masks that define which can hit one another\n # A mask of 0xFFFF means that it will collide with everything else in\n # its group. The box mask below uses an exclusive OR (XOR) which in\n # effect toggles the triangleCategory bit, making boxMask = 0xFFFD.\n # Such a mask means that boxes never collide with triangles. (if\n # you're still confused, see the implementation details below)\n\n triangleMask = 0xFFFF\n boxMask = 0xFFFF ^ triangleCategory\n circleMask = 0xFFFF\n\n # The actual implementation determining whether or not two objects\n # collide is defined in the C++ source code, but it can be overridden\n # in Python (with b2ContactFilter).\n # The default behavior goes like this:\n # if (filterA.group_index == filterB.group_index and filterA.group_index != 0):\n # collide if filterA.group_index is greater than zero (negative groups never collide)\n # else:\n # collide if (filterA.mask_bits & filterB.category_bits) != 0 and (filterA.category_bits & filterB.mask_bits) != 0\n #\n # So, if they have the same group index (and that index isn't the\n # default 0), then they collide if the group index is > 0 (since\n # negative groups never collide)\n # (Note that a body with the default filter settings will always\n # collide with everything else.)\n # If their group indices differ, then only if their bitwise-ANDed\n # category and mask bits match up do they collide.\n #\n # For more help, some basics of bit masks might help:\n # -> http://en.wikipedia.org/wiki/Mask_%28computing%29\n\n # Small triangle\n triangle = b2.fixture_def(\n shape=b2.polygon_shape(vertices=[(-1, 0), (1, 0), (0, 2)]),\n density=1,\n shape_filter=b2.shape_filter(\n group_index=smallGroup,\n category_bits=triangleCategory,\n mask_bits=triangleMask,\n )\n )\n world.create_dynamic_body(\n position=(-5, 2),\n fixtures=triangle,\n )\n\n\n # ?!?!?!?!\n # triangle.shape.vertices = [\n # b2.vec2(v) *2.0 for v in triangle.shape.vertices]\n \n triangle.filter.group_index = largeGroup\n\n trianglebody = world.create_dynamic_body(\n position=(-5, 6),\n fixtures=triangle,\n fixed_rotation=True, # <--\n )\n # note that the large triangle will not rotate\n \n # Small box\n box = b2.fixture_def(\n shape=b2.polygon_shape(box=(1, 0.5)),\n density=1,\n restitution=0.1,\n shape_filter = b2.shape_filter(\n group_index=smallGroup,\n category_bits=boxCategory,\n mask_bits=boxMask,\n )\n )\n\n world.create_dynamic_body(\n position=(0, 2),\n fixtures=box,\n )\n\n # Large box\n box.shape = b2.polygon_shape(box=(1, 0.5))\n box.filter.group_index = largeGroup\n world.create_dynamic_body(\n position=(0, 6),\n fixtures=box,\n )\n\n # Small circle\n circle = b2.fixture_def(\n shape=b2.circle_shape(radius=1),\n density=1,\n shape_filter=b2.shape_filter(\n group_index=smallGroup,\n category_bits=circleCategory,\n mask_bits=circleMask,\n )\n )\n\n world.create_dynamic_body(\n position=(5, 2),\n fixtures=circle,\n )\n\n # Large circle\n circle.shape.radius *= 2\n circle.filter.group_index = largeGroup\n world.create_dynamic_body(\n position=(5, 6),\n fixtures=circle,\n )\n\n # Create a joint for fun on the big triangle\n # Note that it does not inherit or have anything to do with the\n # filter settings of the attached triangle.\n box = b2.fixture_def(shape=b2.polygon_shape(box=(0.5, 1)), density=1)\n\n testbody = world.create_dynamic_body(\n position=(-5, 10),\n fixtures=box,\n )\n world.create_distance_joint(\n body_a=trianglebody,\n body_b=testbody,\n frequency_hz=1.0,\n damping_ratio=2.1,\n #enable_limit=True,\n #local_anchor_a=(0, 4),\n local_anchor_b=(0, 0),\n #local_axis_a=(0, 1),\n #lower_translation=-1,\n # upper_translation=1,\n )\n\nif __name__ == \"__main__\":\n\n testbed = Testbed(guiType='pg')\n testbed.setExample(CollisionFiltering)\n testbed.run()\n","sub_path":"liquidfun/Box2D/pybox2d/testbed/examples/collsion_filtering.py","file_name":"collsion_filtering.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"435331237","text":"import operator\nimport random, time\nimport math\n\nfrom Individual.individual import Individual\nfrom PopulationComputer import PopulationComputer\n\n\nclass Environment(object):\n def __init__(self,population = [], size = 100,maxgenerations = 100,\n crossover_rate = 0.87, mutation_rate = 0.04 ,optimum = 60):\n\n self.optimum = optimum\n # Size of the population\n self.size = size\n # Initialize the population\n self.population = population or self.__makePopulation()\n # Start the evaluation of the population\n for individual in self.population:\n individual.evaluate()\n # Crossover rate\n self.crossover_rate = crossover_rate\n # Mutation rate\n self.mutation_rate = mutation_rate\n # Max number of generations\n self.maxGenerations = maxgenerations\n # Initialize the generation\n self.generation = 0\n # Report the algorithm running status\n self.best = self.population[0]\n\n self.report()\n\n\n # Initialize the population (Generate the individuals)\n def __makePopulation(self):\n return [Individual() for individual in range(self.size)]\n\n # The step-by-step running algorithm\n def run(self):\n while not self.__goal():\n self.step()\n # The conditions to stop the algorithm.\n\n def __goal(self):\n return (self.generation > self.maxGenerations) or (self.best.getScore() > self.optimum)\n ##return (self.best.getScore() > self.optimum)\n # The step done by the genetic algorithm\n\n def step(self):\n # Sort the individuals of the population based on their score\n self.population = PopulationComputer.heapSort(self.population)\n\n if self.best < self.population[-1]:\n self.best = self.population[-1]\n\n\n # Make the crossover\n self.__crossover()\n\n # Increments the generation\n self.generation += 1\n # Report the current status\n self.report()\n\n # Selection method of the individuals for crossover\n def __select(self):\n return self.__tournament()\n\n # sample selection method\n def __tournament(self):\n competitors = []\n total_score = sum([self.population[i].getScore() for i in range(self.population.__len__())])\n for index in range(self.size):\n ## {key:value} = { index: Aptidão do cromossomo como uma portcetagem da apitidão total}\n percentual = {\"index\":index,\"score\":(math.ceil(self.population[index].getScore()*100.0 )/total_score)}\n competitors.append(percentual)\n\n competitors_sorted = sorted(competitors,key = lambda k: k[\"score\"])\n competitors_sorted.reverse()\n\n individual_sorted = None\n while individual_sorted is None:\n index = 0\n number_sorted = random.randrange(100)\n russian_roulette = [\n {\n \"interval\": (0, competitors_sorted[0][\"score\"]),\n \"element\": competitors_sorted[0][\"index\"]\n }\n ]\n while russian_roulette.__len__() < competitors_sorted.__len__():\n if self.__russian_roulette(russian_roulette, number_sorted, index):\n individual_sorted = self.population[russian_roulette[index][\"element\"]]\n break\n else:\n index = index + 1\n russian_roulette.append(\n {\n \"interval\": (russian_roulette[-1][\"interval\"][1],\n competitors_sorted[index][\"score\"] + russian_roulette[-1][\"interval\"][1]),\n \"element\": competitors_sorted[index][\"index\"]\n }\n )\n\n del russian_roulette\n\n return individual_sorted\n\n def __russian_roulette(self, russian_roulette,number_sorted, index):\n if number_sorted > russian_roulette[index][\"interval\"][0] and number_sorted <= russian_roulette[index][\"interval\"][1]:\n return True\n return False\n\n def __crossover(self):\n # Elistism proccess (best individual is copied to the next generation)\n next_population = [self.best]\n\n while len(next_population) < self.size:\n\n mate1 = self.__select()\n random.seed(time.clock())\n if random.random()< self.crossover_rate:\n mate2 = self.__select()\n offspring = mate1.crossover(mate2)\n else:\n # make a copy of individual\n offspring = [mate1.copy()]\n\n for individual in offspring:\n self.__mutate(individual)\n individual.evaluate()\n next_population.append(individual)\n\n self.population = next_population[:self.size]\n\n\n # Mutation method.\n # @param individual: Individual to be mutated.\n def __mutate(self,individual):\n random.seed(time.clock())\n if random.random() < self.mutation_rate:\n index_gene = random.randrange(67)\n individual.mutate(index_gene)\n\n # Shows the results report\n def report(self):\n total_score = sum([self.population[i].getScore() for i in range(self.size)])\n\n\n print(\"generation: \", self.generation)\n print(\"Score total: \",total_score, \" , Score media:\", math.trunc(total_score/self.size))\n print(\"best\", self.best)\n","sub_path":"Environment/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577784086","text":"# -*- coding: utf8 -*-\n\"\"\"\nCore application model unittests\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.template.defaultfilters import slugify\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom django.utils.crypto import get_random_string\n\nfrom core import factories\n\n\nclass GenericEntryTestCaseMixin(object):\n\n def test_string_representation(self):\n \"\"\" Should print valid string \"\"\"\n\n title = get_random_string()\n factory = self.factory(\n title=title\n )\n self.assertIn(str(title), factory.__str__())\n\n def test_get_admin_url_unsaved_objects(self):\n \"\"\" Should generate valid django admin urls for unsaved objects \"\"\"\n factory = self.factory()\n factory.pk = None\n self.assertEqual(factory.get_admin_url(), None)\n\n def _test_generate_slug(self):\n title = get_random_string()\n factory1 = self.factory(title=title)\n self.assertEqual(factory1.slug, slugify(title))\n factory2 = self.factory(title=title)\n self.assertEqual(factory2.slug, slugify(title))\n\n\nclass PageModelTestCase(GenericEntryTestCaseMixin, TestCase):\n \"\"\"\n Tests for core.models.Page\n \"\"\"\n\n factory = factories.PageFactory\n\n def test_absolute_url_front_page(self):\n \"\"\" Should generate correct absolute url for the front page \"\"\"\n page = self.factory(custom_slug=settings.PAGES[0][0])\n self.assertEqual(reverse('first_page'), page.get_absolute_url())\n\n def test_absolute_url_all_pages(self):\n \"\"\" Should generate correct absolute url for the front page \"\"\"\n page = self.factory(custom_slug=settings.PAGES[1][0])\n self.assertEqual(reverse('single_page', kwargs={'category': page.custom_slug}), page.get_absolute_url())\n","sub_path":"core/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"102549012","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time \nadslink=[]\n\nadsdata=[]\n\nfor s in range(2,3):\n\tsrc=requests.get(\"https://bikroy.com/bn/ads?by_paying_member=0&sort=date&order=desc&buy_now=0&page=\"+str(s)).text\n\n\tsoup=BeautifulSoup(src,'lxml')\n\n\tbdy=soup.find('body')\n\n\t#adblock=bdy.find_all('li',class_='normal--2QYVk gtm-normal-ad').a['title']\n\n\tfor addtitle in bdy.find_all('li',class_='normal--2QYVk gtm-normal-ad'):\n\t\tatitle=addtitle.a['href']\n\t\tadslink.append(atitle)\n\ttime.sleep(2)\n\nfor ad in adslink:\n\tsrc2=requests.get(\"https://bikroy.com\"+ad).text\n\tsoup2=BeautifulSoup(src2,'lxml')\n\n\tbdy2=soup2.find('body')\n\t\n\tff=''\n\tfor address in bdy2.find_all('nav',class_=\"ui-crumbs\"):\n\t\tfor xx in address.find_all('li','ui-crumb breadcrumb'):\n\t\t\ttt=xx.a.text\n\t\t\tff=ff+'-'+tt\n\t\tadsdata.append(ff)\n\ttime.sleep(1)\n\n\n\nfor i in adsdata:\n\tprint(i)\n#print(adblock)","sub_path":"bikroy_script.py","file_name":"bikroy_script.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"471079877","text":"import kafka\n\n\n\nfrom kafka.protocol import metadata\n\n\n\n\n\ntopic = \"event_topic\"\nclient_id = \"kafka-python-fzj\"\nbootstrap_servers = [\"10.100.103.20:9092\",\"10.100.103.16:9092\",\"10.100.103.17:9092\"]\ngroup_id = \"group_test\"\n# auto_offset_reset ='latest'\nauto_offset_reset ='earliest'\nenable_auto_commit = False\napi_version=(0,10)\n\n\n\n\n\n\n","sub_path":"learn/mykafka/cluster_metadata.py","file_name":"cluster_metadata.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"500766824","text":"import cv2 \nimport numpy as np\nfrom . import imageProcessing as imgProc\n\n# In order to get the best result, the image used should be GREYSCALE\ndef convolve(image, kernel, padding=0, strides=1):\n # Apply cross correlation to our kernel\n kernel = np.flipud(np.fliplr(kernel))\n\n # Compute the matrix size of our outputted image\n # This is done by gathering the shapes of the kernel, image and padding\n xKernShape = kernel.shape[0] \n yKernShape = kernel.shape[1] \n xImgShape = image.shape[0] \n yImgShape = image.shape[1]\n\n # We can then get the shape of the Output Convolution\n xOutput = int(((xImgShape - xKernShape + 2 * padding) / strides) + 1)\n yOutput = int(((yImgShape - yKernShape + 2 * padding) / strides) + 1)\n\n # New matrix with deduced dimensions \n output = np.zeros((xOutput, yOutput))\n\n # Apply padding to each side of the matrix\n # This is especially important, since the method relies on the padding being even\n # We check whether or not the padding is 0, and if it's not, we apply operations to correct it.\n if padding != 0:\n imagePadded = np.zeros((image.shape[0] + padding*2, image.shape[1] + padding*2))\n imagePadded[int(padding):int(-1 * padding), int(padding):int(-1 * padding)] = image\n print(imagePadded)\n else: \n imagePadded = image\n\n # Iterate through the image\n for y in range(image.shape[1]):\n # Exit\n if y > image.shape[1] - yKernShape: \n break\n # Check if end of image on y-axis is reached\n # Convolution is completed once we reach the bottom right of the image matrix\n if y % strides == 0:\n for x in range(image.shape[0]):\n # Check if kernel is out of bounce (reached the very right of the image).\n # Once reached, break the x-loop and move down 1 on the y-axis to repeat the convolution process\n if x > image.shape[0] - xKernShape: \n break\n try:\n # Only Convolve if x has moved by the specified Strides\n if x % strides == 0:\n output[x, y] = (kernel * imagePadded[x: x + xKernShape, y: y + yKernShape]).sum()\n except:\n break\n return output","sub_path":"app/scripts/imageConvolution.py","file_name":"imageConvolution.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113261401","text":"# This is a histogram \n\ndef hist(my_string,char_count):\n \"\"\" This takes a string and goes through each char and counts it in a dict\"\"\"\n #check if string\n if not isinstance(my_string,str):\n print (\"Gimme a str\")\n return None\n #Go through the string\n for my_char in my_string:\n if my_char in char_count:\n char_count[my_char] +=1\n else:\n char_count[my_char] = 1\n return char_count\n\ndef print_hist(my_hist):\n \"\"\" This prints the hist \"\"\"\n if not isinstance(my_hist,dict):\n print (\"Gimme a dict\")\n return None \n else: \n for key in my_hist:\n print ( str(key) + \" -> \" + str(my_hist[key]))\n\n \n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106152716","text":"import freezegun\nimport pytest\nfrom django.urls import reverse\nfrom model_bakery import baker\nfrom rest_framework import status\nfrom rest_framework.utils import json\n\nfrom menu_cards.models import FOOD_TYPE_CHOICES, Dish, DishPhoto\nfrom menu_cards.tests.test_menu_endpoint_api import TIMESTAMP\n\nDISHES_URL = \"dishes\"\nDISHES_LIST_URL = f\"{DISHES_URL}-list\"\nDISHES_DETAIL_URL = f\"{DISHES_URL}-detail\"\n\npytestmark = pytest.mark.django_db\n\n\ndef test_dishes__list_all_dishes(superadmin_client, vegan_menu):\n url = reverse(DISHES_LIST_URL)\n response = superadmin_client.get(url)\n db_names = vegan_menu.dishes.only(\"name\").values_list(\"name\", flat=True)\n for item in response.data:\n assert item.get(\"name\") in db_names\n assert response.status_code == status.HTTP_200_OK\n\n\ndef test_dishes__get_shows_name_of_menu_card(superadmin_client, vegetarian_menu):\n url = reverse(DISHES_LIST_URL)\n response = superadmin_client.get(url)\n\n assert all([item.get(\"menu_card\") for item in response.data])\n assert response.status_code == status.HTTP_200_OK\n\n\ndef test_dishes__retrieve_single_dish(superadmin_client, vegetarian_dish):\n dish_from_db = Dish.objects.only(\"id\").first()\n url = reverse(DISHES_DETAIL_URL, args=(dish_from_db.id,))\n response = superadmin_client.get(url)\n assert dish_from_db.id == response.data.get(\"id\")\n assert response.status_code == status.HTTP_200_OK\n\n\ndef test_dishes__single_dish_creation(superadmin_client, valid_data_for_dish_creation):\n url = reverse(DISHES_LIST_URL)\n response = superadmin_client.post(\n url, data=valid_data_for_dish_creation, format=\"json\"\n )\n created_dish = response.data\n dish_exists = Dish.objects.filter(id=created_dish.get(\"id\")).exists()\n assert dish_exists\n assert response.status_code == status.HTTP_201_CREATED\n\n\ndef test_dishes__dish_creation_error_on_wrong_data(\n superadmin_client, invalid_data_for_dish_creation\n):\n url = reverse(DISHES_LIST_URL)\n response = superadmin_client.post(\n url, data=invalid_data_for_dish_creation, format=\"json\"\n )\n assert response.status_code == status.HTTP_400_BAD_REQUEST\n\n\n@pytest.mark.parametrize(\n \"field, values, ordered, reverse_ordered\",\n [\n (\n \"price\",\n [1.01, 5.01, 2.01],\n [1.01, 2.01, 5.01],\n [5.01, 2.01, 1.01],\n ),\n (\n \"food_type\",\n [\n FOOD_TYPE_CHOICES.meat,\n FOOD_TYPE_CHOICES.vegan,\n FOOD_TYPE_CHOICES.meat,\n ],\n [\n FOOD_TYPE_CHOICES.meat,\n FOOD_TYPE_CHOICES.meat,\n FOOD_TYPE_CHOICES.vegan,\n ],\n [\n FOOD_TYPE_CHOICES.vegan,\n FOOD_TYPE_CHOICES.meat,\n FOOD_TYPE_CHOICES.meat,\n ],\n ),\n ],\n)\ndef test_dishes__are_ordered_by_field(\n superadmin_client, field, values, ordered, reverse_ordered\n):\n for value in values:\n baker.make(Dish, **{field: value})\n\n url = reverse(DISHES_LIST_URL)\n response = superadmin_client.get(url, {\"ordering\": field})\n assert all(\n [\n str(item[field]) == str(expected)\n for item, expected in zip(response.json(), ordered)\n ]\n )\n response = superadmin_client.get(url, {\"ordering\": f\"-{field}\"})\n assert all(\n [\n str(item[field]) == str(expected)\n for item, expected in zip(response.json(), reverse_ordered)\n ]\n )\n\n\n@freezegun.freeze_time(TIMESTAMP)\ndef test_dishes__patch_updates_timestamps(\n superadmin_client, meat_dish, valid_data_to_update_dish\n):\n\n url = reverse(DISHES_DETAIL_URL, args=(meat_dish.id,))\n response = superadmin_client.patch(\n url,\n data=json.dumps(valid_data_to_update_dish),\n content_type=\"application/json\",\n )\n\n assert Dish.objects.first().modified == TIMESTAMP\n assert response.status_code == status.HTTP_200_OK\n\n\ndef test_dishes__added_photo_to_dish(superadmin_client, meat_dish, photo):\n url = reverse(f\"{DISHES_URL}-photo\", args=(meat_dish.id,))\n\n response = superadmin_client.post(\n url,\n data={\"image\": photo},\n )\n assert Dish.objects.first().photos\n assert response.status_code == status.HTTP_201_CREATED\n\n\ndef test_dishes__photo_included_in_response(superadmin_client, meat_dish):\n url = reverse(f\"{DISHES_DETAIL_URL}\", args=(meat_dish.id,))\n photo = baker.make(DishPhoto, dish=meat_dish)\n response = superadmin_client.get(\n url,\n )\n assert response.data[\"photos\"][0][\"id\"] == photo.id\n assert response.status_code == status.HTTP_200_OK\n\n\n@pytest.mark.parametrize(\n \"method, expected_response\",\n [\n (\"get\", status.HTTP_405_METHOD_NOT_ALLOWED),\n (\"post\", status.HTTP_201_CREATED),\n (\"patch\", status.HTTP_405_METHOD_NOT_ALLOWED),\n (\"delete\", status.HTTP_405_METHOD_NOT_ALLOWED),\n ],\n)\ndef test_dishes__add_photo_accepts_only_post_method(\n superadmin_client, method, expected_response, meat_dish, photo\n):\n url = reverse(f\"{DISHES_URL}-photo\", args=(meat_dish.id,))\n http_method = getattr(superadmin_client, method)\n response = http_method(\n url,\n data={\"image\": photo},\n )\n assert response.status_code == expected_response\n","sub_path":"src/menu_cards/tests/test_dishes_endpoint_api.py","file_name":"test_dishes_endpoint_api.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"191186399","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('message', '0002_message_locations'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='message',\n name='locations',\n ),\n migrations.AddField(\n model_name='message',\n name='groups_include_locations',\n field=models.BooleanField(default=True),\n ),\n migrations.AddField(\n model_name='message',\n name='groups_include_subgroups',\n field=models.BooleanField(default=True),\n ),\n ]\n","sub_path":"message/migrations/0003_auto_20160701_1635.py","file_name":"0003_auto_20160701_1635.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"39065171","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport time\nimport random\nimport socket\nimport hashlib\nimport json\nimport threading\n\nfrom ThreadPool import ThreadPoolManger\n\n\nfoldername_Client = 'files_Client'\n#foldername_WebServer = 'files_WebServer'\nfiles_Client_Path = os.getcwd() + '\\\\' + foldername_Client + '\\\\'\nif not os.path.exists(files_Client_Path):\n os.mkdir(files_Client_Path)\n# 已知files_WebServer上的文件\nfiles_WebServer_Path = './files_WebServer/'\nbalancerAddr = '127.0.0.1'\nbalancerPort = 8888\nWebServerPort = 9000\nrecvBytes = 1024\n\n\n'''\n向WebServerAddr上传filelist中的文件\n《多个文件按次序上传》\n'''\ndef uploading(WebServerAddr, filelist):\n try:\n conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn_socket.connect((WebServerAddr, WebServerPort))\n for file in filelist:\n filename = files_Client_Path + file\n # 文件不存在则跳过\n if os.path.isfile(filename):\n inputs = 'upload ' + file\n conn_socket.send(inputs.encode())# cmd + file\n confirm = conn_socket.recv(recvBytes)\n IsRecv = confirm.decode()\n print(IsRecv)\n if IsRecv != 'ok':\n continue\n # 发送文件大小\n conn_socket.send(str(os.stat(filename).st_size).encode())\n confirm = conn_socket.recv(recvBytes)\n IsRecv = confirm.decode()\n print(IsRecv)\n if IsRecv != 'Prepared':\n continue\n # 生成md5对象\n m = hashlib.md5()\n with open(filename, 'rb') as fn:\n # 开始发文件,发一行更新一下md5的值,因为不能直接md5文件\n # 到最后读完就是整个文件的md5的值\n for line in fn:\n m.update(line)\n conn_socket.send(line)\n fn.close()\n origin_file_md5 = m.hexdigest()\n # 接收服务器接收成功\n confirm = conn_socket.recv(recvBytes)\n # send md5\n conn_socket.send(origin_file_md5.encode())\n server_file_md5 = conn_socket.recv(recvBytes)\n new_file_md5 = server_file_md5.decode()\n print('file md5:',origin_file_md5,'\\nrecved file md5:',new_file_md5)\n if origin_file_md5 == new_file_md5:\n print(filename, '===> sended ===>', WebServerAddr)\n else:\n print(filename, 'send Error! Check for the Network.')\n conn_socket.close()\n except socket.error as msg:\n print('文件上传失败!', WebServerAddr, '可能无法有bug...醉了...')\n\n\n'''\n从WebServerAddr下载filelist中的文件\n《多个文件按次序下载》\n'''\ndef downloading(WebServerAddr, filelist):\n try:\n print('hhhhh', WebServerAddr)\n conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn_socket.connect((WebServerAddr, WebServerPort))\n for file in filelist:\n inputs = 'download ' + file\n conn_socket.send(inputs.encode())\n file_size = conn_socket.recv(recvBytes)\n file_size = int(file_size.decode())\n if file_size == 0:\n print('File not exist in Server!')\n continue\n # 去除重复的文件名\n filename = files_Client_Path + file\n if os.path.isfile(filename):\n namewhat = 1\n nametmp = filename\n while os.path.isfile(filename):\n name, ext = os.path.splitext(nametmp)# 分离文件名和文件格式后缀\n filename = name + '(%d)'%namewhat + ext\n namewhat += 1\n # 开始下载\n conn_socket.send('Prepared'.encode())\n # 赋值方便最后打印大小\n new_file_size = file_size\n # 生成md5对象\n m = hashlib.md5()\n with open(filename, 'wb') as fn:\n while new_file_size > 0:\n data = conn_socket.recv(recvBytes)\n new_file_size -= len(data)# 收多少减多少\n m.update(data)# 同步发送端,收一次更新一次md5\n fn.write(data)\n fn.flush\n fn.close()\n # 得到下载完的文件的md5\n new_file_md5 = m.hexdigest()\n #print('file recv:', file_size)\n #print('file saved in:', filename)\n conn_socket.send('ok'.encode())\n # 接收服务器端的文件的md5\n server_file_md5 = conn_socket.recv(recvBytes)\n origin_file_md5 = server_file_md5.decode()\n # 打印两端的md5值,看是否相同\n print('server file md5:',origin_file_md5,'\\nrecved file md5:',new_file_md5)\n if origin_file_md5 == new_file_md5:\n print('文件下载成功', '%d(bytes)'%file_size, '已保存到',filename)\n else:\n print(filename, '文件无效,删除文件!')\n os.remove(filename)\n conn_socket.close()\n except socket.error as msg:\n print('文件下载失败!', WebServerAddr, '可能无法有bug...醉了...')\n\n\n'''\n发送端上传文件:先向balancer请求,再上传到一个WebServer\n'''\ndef Upload(files):\n print('thread %s is running, ' % threading.current_thread().name, files)\n '''连接balancer,获得目标地址'''\n conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn_socket.connect((balancerAddr, balancerPort))\n # 向balancer发upload命令\n cmd = ['upload']\n json_string = json.dumps(cmd)\n conn_socket.send(json_string.encode())\n # 接收一个WebServerAddr\n recv_data = conn_socket.recv(recvBytes)\n WebServerAddr = recv_data.decode()\n conn_socket.close()\n\n #连接目标地址的WebServer,上传文件\n uploading(WebServerAddr, files)\n\n\n'''\n接收端下载文件:先向balancer请求,再从多个WebServer上下载\n'''\ndef Download(files):\n print('thread %s is running, ' % threading.current_thread().name, files)\n '''连接balancer,获得可上传文件列表和目标地址'''\n conn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn_socket.connect((balancerAddr, balancerPort))\n # 向balancer发文件列表\n files.append('download')\n json_string = json.dumps(files)\n conn_socket.send(json_string.encode())# cmd + files\n # 接收WebServerAddrList,与files[1:]一一对应\n recv_data = conn_socket.recv(recvBytes)# WebServerAddrList\n json_string = recv_data.decode()\n WebServerAddrList = json.loads(json_string)\n #print(WebServerAddrList)\n conn_socket.close()\n\n # 依次访问不重复的WebServerAddr\n print(WebServerAddrList)\n length = len(WebServerAddrList)\n ConnAddrList = list(set(WebServerAddrList))\n for ConnAddr in ConnAddrList:\n filelist = [files[i] for i in range(length) if WebServerAddrList[i]==ConnAddr]\n downloading(ConnAddr, filelist)\n\n\n'''\n多线程模拟客户端请求\n'''\nthread_pool = ThreadPoolManger(4)\n\ndef handle_Input(Req=0, Cnt=6, Threads=4, fileNum=1):\n '''\n Req=0: 上传\n Req=1: 下载\n '''\n if Req==0:\n for root, dirs, files in os.walk(files_Client_Path):\n for C in range(Cnt):\n rs = random.sample(files, fileNum)\n thread_pool.add_job(Upload, *(rs, ))\n elif Req==1:\n for root, dirs, files in os.walk(files_WebServer_Path):\n for C in range(Cnt):\n rs = random.sample(files, fileNum)\n thread_pool.add_job(Download, *(rs, ))\n\n\nif __name__ == '__main__':\n Addr = input('\\nInput balancerAddr(such as 127.0.0.1):').strip()\n if Addr == '127':\n Addr = '127.0.0.1'\n balancerAddr = Addr\n handle_Input()\n #thread_pool.wait_jobs(60)\n time.sleep(60)\n cmd = input('\\n确实要退出吗?Y(y)/N(n):').strip()","sub_path":"Distributed_Web_System/_Newest/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"507525379","text":"# encoding=utf8\nimport os\nfrom tqdm import tqdm\nimport zipfile\n\n\ndef listdir(dst_dir, ext_list=None): #传入存储的list\n xlist = list()\n for root, dirs, files in os.walk(dst_dir):\n # print(root) #当前目录路径\n # print(dirs) #当前路径下所有子目录\n # print(files) #当前路径下所有非目录子文件\n if ext_list:\n for file in files:\n ext = os.path.splitext(file)[-1]\n if ext not in ext_list:\n continue\n xlist.append(os.path.join(root, file))\n else:\n for file in files:\n xlist.append(os.path.join(root, file))\n return xlist\n\n\ndef zip_dir(srcPath, dstName):\n import zipfile\n basename = os.path.basename(srcPath)\n f = zipfile.ZipFile(dstName,'w',zipfile.ZIP_DEFLATED)\n f.write(srcPath, basename)\n f.close()\n\n\nif __name__ == \"__main__\":\n from optparse import OptionParser\n usage = 'python BtZipRoms.py --ext=.nds --roms= --use_splitext=0'\n parser = OptionParser(usage)\n parser.add_option(\"--roms\")\n parser.add_option(\"--ext\")\n parser.add_option(\"--use_splitext\")\n\n (options, args) = parser.parse_args()\n\n if not options.use_splitext:\n options.use_splitext = 1\n else:\n options.use_splitext = int(options.use_splitext)\n\n rom_list = listdir(options.roms, [options.ext])\n\n index = 0\n pbar = tqdm(rom_list)\n for file in pbar:\n index = index + 1\n\n pbar.set_description(u\"处理 %s\" % file)\n pbar.update()\n\n if options.use_splitext == 1:\n dstname = os.path.splitext(file)[0] + '.zip'\n else:\n dstname = file + '.zip'\n if os.path.exists(dstname):\n continue\n zip_dir(file, dstname)\n\n","sub_path":"dist/BtZipRoms.py","file_name":"BtZipRoms.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"346335902","text":"import socket\nimport threading\nimport csv\nrows = []\npresent = []\ndef main():\n\thost = '10.10.9.107'\n\tport = 4000\n\n\ts = socket.socket()\n\ts.bind((host,port))\n\tprint(\"server started\")\n\tfile = \"data.csv\"\n\n\t#reading csv file and store it in rows\n\twith open(file,'r') as csvfile:\n\t\tcsvreader = csv.reader(csvfile)\n\t\tfor row in csvreader:\n\t\t\trows.append(row)\n\n\ts.listen(10)\n\twhile True:\n\t\tclient,addr = s.accept()\n\t\tthreading.Thread(target = info, args=(client, )).start()\n\n\tclient.close()\ndef info(client):\n\tlimit = 0\n\tmessage = client.recv(1024).decode()\n\tli = message.split(' ')\n\trollnumber = li[1]\n\tpresent.append(li[1])\n\tprint(\"present rollnumbers connected to server are:\")\n\tprint(present)\n\twhile True:\n\t\tif li[0] == 'MARK-ATTENDANCE':\n\t\t\tflag = False\n\n\t\t\tfor i in rows:\n\t\t\t\ttemp = i\n\t\t\t\tif str(temp[0]) == str(li[1]):\n\t\t\t\t\tflag = True\n\t\t\t\t\tclient.send(temp[1].encode())\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\tif not flag:\t\n\t\t\t\ttext = 'ROLLNUMBER-NOTFOUND'\n\t\t\t\tclient.send(text.encode())\n\t\tif li[0] == 'SECRETANSWER':\n\t\t\t# limt = limt+1\n\t\t\tf = True\n\t\t\tfor i in rows:\n\t\t\t\ttemp = i\n\t\t\t\tif temp[0] == rollnumber:\n\t\t\t\t\tif temp[2] == li[1]:\n\t\t\t\t\t\ttext = 'ATTENDANCE SUCCESS' \n\t\t\t\t\t\tclient.send(text.encode())\n\t\t\t\t\t\tf = False\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse :\n\t\t\t\t\t\t# if limit == 5:\n\t\t\t\t\t\t# \twarn = \"limit exceeded\"\n\t\t\t\t\t\t# \tclient.send(warn.encode())\n\t\t\t\t\t\t# \tf = False\n\t\t\t\t\t\ttext = 'ATTENDANCE FAILUE'+\"\\n\"+str(temp[1])\n\t\t\t\t\t\tclient.send(text.encode())\n\t\t\t\t\t\tbreak\n\t\t\tif not f:\n\t\t\t\tbreak\n\n\t\tmessage = client.recv(1024).decode()\n\t\tli = message.split(' ')\n\n\n\t\nif __name__ ==\"__main__\":\n\tmain()\t\t\n","sub_path":"week2/CNF_Week_2/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"216694705","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 1999-2015 Mag. Christian Tanzer. All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# ****************************************************************************\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.subdirs\n#\n# Purpose\n# Get all subdirectories of a directory\n#\n# Revision Dates\n# 3-May-1999 (CT) Creation\n# 26-Jul-1999 (CT) `-exclude` and `-re_exclude` added\n# 22-Dec-1999 (CT) `-separator` added\n# 13-Jun-2000 (CT) Use `sos.listdir_full` instead of home-grown code\n# 13-Apr-2004 (CT) Filter links from `subdirs`\n# 13-Apr-2004 (CT) Output sorted\n# 6-Oct-2004 (CT) `subdir_names` added\n# 6-Oct-2004 (CT) `-basenames` and `-lstrip` added\n# 14-Feb-2006 (CT) Moved into package `TFL`\n# 16-Jun-2013 (CT) Use `TFL.CAO`, not `TFL.Command_Line`\n# ««revision-date»»···\n#--\n\nfrom __future__ import print_function\n\nfrom _TFL import TFL\nfrom _TFL import sos\n\nimport _TFL.CAO\n\ndef subdirs (of_dir = None) :\n \"\"\"Return list of all subdirectories contained in `of_dir`\"\"\"\n return \\\n [ f for f in sos.listdir_full (of_dir)\n if sos.path.isdir (f) and not sos.path.islink (f)\n ]\n# end def subdirs\n\ndef subdir_names (of_dir = None) :\n \"\"\"Return list of the (base)-names of all subdirectories contained in\n `of_dir`.\n \"\"\"\n return [sos.path.split (s) [-1] for s in subdirs (of_dir)]\n# end def subdir_names\n\ndef subdirs_transitive (of_dir = None) :\n \"\"\"Return transitive list of all subdirectories contained in `of_dir`.\"\"\"\n result = subdirs (of_dir)\n for d in result :\n result.extend (subdirs_transitive (d))\n return result\n# end def subdirs_transitive\n\ndef _main (cmd) :\n import sys\n dirs = cmd.argv or (\".\", )\n if cmd.newlines :\n sep = \"\\n\"\n else :\n sep = cmd.separator\n if cmd.transitive :\n fct = subdirs_transitive\n elif cmd.basenames :\n fct = subdir_names\n else :\n fct = subdirs\n result = []\n for d in dirs :\n result.extend (fct (d))\n for exc in cmd.exclude :\n result = [r for r in result if r != exc]\n if cmd.re_exclude :\n from _TFL.Regexp import Regexp\n exc = Regexp (cmd.re_exclude)\n result = [r for r in result if not exc.search (r)]\n if cmd.lstrip :\n result = [r.lstrip (cmd.lstrip) for r in result]\n if result :\n result.sort ()\n sys.stdout.write (sep.join (result) + \"\\n\")\n# end def _main\n\n_Command = TFL.CAO.Cmd \\\n ( handler = _main\n , opts =\n ( \"-basenames:B\"\n \"?Print basenames of directories instead of full pathes \"\n \"(beware: doesn't work if -transitive is also specified)\"\n , \"-exclude:S #100?List of directories to exclude (space separated)\"\n , \"-lstrip:S?String to strip from front of directories\"\n , \"-newlines:B?print new lines between subdirs\"\n , \"-re_exclude:S?Exclude all directories matching regular expression\"\n , \"-separator:S= ?Separator between subdirs\"\n , \"-transitive:B?Print closure of subdirs\"\n )\n )\nif __name__ != \"__main__\" :\n TFL._Export (\"*\")\nelse :\n _Command ()\n### __END__ TFL.subdirs\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/subdirs.py","file_name":"subdirs.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356059988","text":"#!/usr/bin/python\r\n\r\ndef get_dirt_position(board):\r\n global bot_r, bot_c, dim_r, dim_c\r\n dist=10000\r\n next_goal=[0,0]\r\n for row in range(dim_r):\r\n if 'd' in board[row]:\r\n for col in range(dim_c):\r\n if board[row][col] == 'd':\r\n d = manhattan_dist(row,col)\r\n if d dirt_c:\r\n print(\"LEFT\")\r\n elif bot_r < dirt_r:\r\n print(\"DOWN\")\r\n elif bot_r > dirt_r:\r\n print(\"UP\")\r\n\r\n\r\ndef next_move(bot_r, bot_c, board):\r\n dirt_r, dirt_c = get_dirt_position(board)\r\n clean_the_dirt(dirt_r,dirt_c)\r\n\r\n# Tail starts here\r\nif __name__ == \"__main__\":\r\n bot_ = [int(i) for i in input().strip().split()]\r\n dim = [int(i) for i in input().strip().split()]\r\n board = [[j for j in input().strip()] for i in range(dim[0])]\r\n global bot_r, bot_c, dim_r, dim_c\r\n dim_r, dim_c = dim[0], dim[1]\r\n bot_r,bot_c = bot_[0], bot_[1]\r\n next_move(bot_r,bot_c, board)\r\n","sub_path":"artificial_intelligence/botcleanlarge.py","file_name":"botcleanlarge.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86291352","text":"# pylint: skip-file\nimport mxnet as mx\nimport numpy as np\nimport os, gzip\nimport pickle as pickle\nfrom common import get_data\n#from PIL import Image\n\n\ndef test_MNISTIter():\n # prepare data\n get_data.GetMNIST_ubyte()\n\n batch_size = 100\n train_dataiter = mx.io.MNISTIter(\n image=\"data/train-images-idx3-ubyte\",\n label=\"data/train-labels-idx1-ubyte\",\n batch_size=batch_size, shuffle=1, flat=1, silent=0, seed=10)\n val_dataiter = mx.io.MNISTIter(\n image=\"data/t10k-images-idx3-ubyte\",\n label=\"data/t10k-labels-idx1-ubyte\",\n batch_size=batch_size, shuffle=0, flat=1, silent=0)\n # test_loop\n nbatch = 60000 / batch_size\n batch_count = 0\n for data, label in train_dataiter:\n batch_count += 1\n assert(nbatch == batch_count)\n # test_reset\n train_dataiter.reset()\n train_dataiter.iter_next()\n label_0 = train_dataiter.getlabel().asnumpy().flatten()\n train_dataiter.iter_next()\n train_dataiter.iter_next()\n train_dataiter.iter_next()\n train_dataiter.iter_next()\n train_dataiter.reset()\n train_dataiter.iter_next()\n label_1 = train_dataiter.getlabel().asnumpy().flatten()\n assert(sum(label_0 - label_1) == 0)\n\n'''\ndef test_ImageRecIter():\n dataiter = mx.io.ImageRecordIter(\n path_imgrec=\"data/val_cxxnet.rec\",\n mean_img=\"data/smallset/image_net_mean.bin\",\n rand_crop=True,\n mirror=True,\n input_shape=(3,227,227),\n batch_size=100,\n nthread=1,\n seed=10)\n labelcount = [0 for i in range(1000)] \n batchcount = 0\n for data, label in dataiter:\n npdata = data.numpy\n print npdata[0,:,:,:]\n imgdata = np.zeros([227, 227, 3], dtype=np.uint8)\n imgdata[:,:,0] = npdata[10,2,:,:]\n imgdata[:,:,1] = npdata[10,1,:,:]\n imgdata[:,:,2] = npdata[10,0,:,:]\n img = Image.fromarray(imgdata)\n imgpath = \"data/smallset/test_3.jpg\"\n img.save(imgpath, format='JPEG')\n exit(0)\n print batchcount\n sys.stdout.flush()\n batchcount += 1\n nplabel = label.numpy\n for i in range(nplabel.shape[0]):\n labelcount[int(nplabel[i])] += 1\n\ndef test_Cifar10Rec():\n dataiter = mx.io.ImageRecordIter(\n path_imgrec=\"data/cifar/test.rec\",\n mean_img=\"data/cifar/cifar10_mean.bin\",\n rand_crop=True,\n rand_mirror=True,\n input_shape=(3,28,28),\n batch_size=100,\n nthread=1)\n labelcount = [0 for i in range(10)] \n batchcount = 0\n for data, label in dataiter:\n npdata = data.numpy\n print npdata[0,:,:,:]\n imgdata = np.zeros([28, 28, 3], dtype=np.uint8)\n imgdata[:,:,0] = npdata[0,2,:,:]\n imgdata[:,:,1] = npdata[0,1,:,:]\n imgdata[:,:,2] = npdata[0,0,:,:]\n img = Image.fromarray(imgdata)\n imgpath = \"data/cifar/test.jpg\"\n img.save(imgpath, format='JPEG')\n exit(0)\n print \"Batch: \", batchcount\n sys.stdout.flush()\n batchcount += 1\n nplabel = label.numpy\n for i in range(nplabel.shape[0]):\n labelcount[int(nplabel[i])] += 1\n for i in range(10):\n assert(labelcount[i] == 1000)\n'''\n\nif __name__ == \"__main__\":\n test_MNISTIter()\n","sub_path":"tests/python/unittest/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"550248178","text":"#!/usr/bin/env python2\r\nfrom __future__ import print_function\r\nimport sys\r\nsys.path.append('../lib')\r\nimport os\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.path import Path\r\nfrom matplotlib.patches import PathPatch\r\nimport string\r\n\r\nimport protocols\r\nimport model_ikr as m\r\nfrom releakcorrect import I_releak, score_leak, protocol_leak_check\r\n\r\nfrom scipy.optimize import fmin\r\n# Set seed\r\nnp.random.seed(101)\r\n\r\ntry:\r\n file_id = sys.argv[1]\r\nexcept IndexError:\r\n print('Usage: python %s [file_id]' % __file__)\r\n sys.exit()\r\n\r\nsavedir = './figs/paper'\r\nif not os.path.isdir(savedir):\r\n os.makedirs(savedir)\r\n\r\nrefcell = 'D13'\r\nplot_ref = False\r\n\r\n\r\n#\r\n# Protocol info\r\n#\r\nprotocol_funcs = {\r\n 'staircaseramp': protocols.leak_staircase,\r\n 'pharma': protocols.pharma, # during drug application\r\n 'apab': 'protocol-apab.csv',\r\n 'apabv3': 'protocol-apabv3.csv',\r\n 'ap05hz': 'protocol-ap05hz.csv',\r\n 'ap1hz': 'protocol-ap1hz.csv',\r\n 'ap2hz': 'protocol-ap2hz.csv',\r\n 'sactiv': protocols.sactiv,\r\n 'sinactiv': protocols.sinactiv,\r\n}\r\nprotocol_dir = '../protocol-time-series'\r\nprotocol_list = [\r\n 'staircaseramp',\r\n # 'sactiv',\r\n # 'sinactiv',\r\n 'pharma',\r\n 'apab',\r\n 'apabv3',\r\n # 'ap05hz',\r\n 'ap1hz',\r\n 'ap2hz',\r\n]\r\nvalidation_idx = [\r\n None,\r\n # 1,\r\n # 2,\r\n 3,\r\n 4,\r\n 5,\r\n # 6,\r\n 7,\r\n 8,\r\n]\r\n\r\n# IV protocol special treatment\r\nprotocol_iv = [\r\n 'sactiv',\r\n 'sinactiv',\r\n]\r\nprotocol_iv_times = {\r\n 'sactiv': protocols.sactiv_times,\r\n 'sinactiv': protocols.sinactiv_times,\r\n}\r\nprotocol_iv_convert = {\r\n 'sactiv': protocols.sactiv_convert,\r\n 'sinactiv': protocols.sinactiv_convert,\r\n}\r\nprotocol_iv_args = {\r\n 'sactiv': protocols.sactiv_iv_arg,\r\n 'sinactiv': protocols.sinactiv_iv_arg,\r\n}\r\nprotocol_iv_v = {\r\n 'sactiv': protocols.sactiv_v,\r\n 'sinactiv': protocols.sinactiv_v,\r\n}\r\n\r\ndata_dir_staircase = '../data'\r\ndata_dir = '../data-autoLC'\r\nfile_dir = './out'\r\nfile_list_tmp = { # TODO\r\n 'herg25oc': 'herg25oc1',\r\n 'herg27oc': 'herg27oc1',\r\n 'herg30oc': 'herg30oc1',\r\n 'herg33oc': 'herg33oc1',\r\n 'herg37oc': 'herg37oc3',\r\n }\r\ntemperatures = {\r\n 'herg25oc': 25.0,\r\n 'herg27oc': 27.0,\r\n 'herg30oc': 30.0,\r\n 'herg33oc': 33.0,\r\n 'herg37oc': 37.0,\r\n }\r\nfit_seed = '542811797'\r\n\r\nfile_name = file_list_tmp[file_id]\r\ntemperature = temperatures[file_id] + 273.15 # in K\r\n\r\n# Load RMSD matrix\r\nrmsd_matrix_file = './figs/rmsd-hist-%s-autoLC-releak/rmsd-matrix.txt' \\\r\n % file_name\r\nrmsd_cells_file = './figs/rmsd-hist-%s-autoLC-releak/rmsd-matrix-cells.txt' \\\r\n % file_name\r\n\r\nrmsd_matrix = np.loadtxt(rmsd_matrix_file)\r\n\r\nwith open(rmsd_matrix_file, 'r') as f:\r\n rmsd_prt = f.readline().strip('\\n').strip('#').split()\r\n\r\nrmsd_cells = []\r\nwith open(rmsd_cells_file, 'r') as f:\r\n for l in f:\r\n if not l.startswith('#'):\r\n rmsd_cells.append(l.strip('\\n').split('-')[1])\r\n\r\nrankedcolours = ['#1a9850',\r\n '#fc8d59',\r\n '#d73027',\r\n '#7f7f7f']\r\nrankedlabels = [r'$*$',\r\n u'\\u2021',\r\n r'#',\r\n u'\\u2666']\r\n\r\n\r\n#\r\n# Do a very very tailored version........ :(\r\n#\r\nfig = plt.figure(figsize=(16, 15))\r\nbigxgap = 12\r\nn_xgrid = 84\r\nbigygap = 5\r\nn_ygrid = 31\r\ngrid = plt.GridSpec(2 * n_ygrid + 1 * bigygap, 3 * n_xgrid + 2 * bigxgap,\r\n hspace=0.0, wspace=0.0)\r\naxes = np.empty([10, int(len(protocol_list) / 2)], dtype=object)\r\n# long list here:\r\nfor i in range(int(len(protocol_list) / 2)):\r\n i_grid = i * (n_xgrid + bigxgap)\r\n f_grid = (i + 1) * n_xgrid + i * bigxgap\r\n\r\n # First 'row'\r\n axes[0, i] = fig.add_subplot(grid[0:3, i_grid:f_grid])\r\n axes[0, i].set_xticklabels([])\r\n axes[1, i] = fig.add_subplot(grid[3:9, i_grid:f_grid])\r\n axes[1, i].set_xticklabels([])\r\n axes[2, i] = fig.add_subplot(grid[9:15, i_grid:f_grid])\r\n axes[2, i].set_xticklabels([])\r\n axes[3, i] = fig.add_subplot(grid[15:21, i_grid:f_grid])\r\n # Histogram\r\n axes[4, i] = fig.add_subplot(grid[24:31, i_grid:f_grid])\r\n\r\n # Second 'row'\r\n n_shift = n_ygrid + bigygap\r\n axes[5, i] = fig.add_subplot(grid[n_shift+0:n_shift+3, i_grid:f_grid])\r\n axes[5, i].set_xticklabels([])\r\n axes[6, i] = fig.add_subplot(grid[n_shift+3:n_shift+9, i_grid:f_grid])\r\n axes[6, i].set_xticklabels([])\r\n axes[7, i] = fig.add_subplot(grid[n_shift+9:n_shift+15, i_grid:f_grid])\r\n axes[7, i].set_xticklabels([])\r\n axes[8, i] = fig.add_subplot(grid[n_shift+15:n_shift+21, i_grid:f_grid])\r\n # Histogram\r\n axes[9, i] = fig.add_subplot(grid[n_shift+24:n_shift+31, i_grid:f_grid])\r\n\r\n # Set x-labels\r\n axes[3, i].set_xlabel('Time [s]', fontsize=14)\r\n axes[4, i].set_xlabel('RRMSE', fontsize=14)\r\n axes[8, i].set_xlabel('Time [s]', fontsize=14)\r\n axes[9, i].set_xlabel('RRMSE', fontsize=14)\r\n\r\n# Set labels\r\naxes[0, 0].set_ylabel('Voltage\\n[mV]', fontsize=14)\r\naxes[1, 0].set_ylabel(r'Best ($*$)', fontsize=14, color=rankedcolours[0])\r\naxes[2, 0].set_ylabel(u'Median (\\u2021)', fontsize=14, color=rankedcolours[1])\r\naxes[3, 0].set_ylabel(r'90%ile (#)', fontsize=14, color=rankedcolours[2])\r\naxes[4, 0].set_ylabel('Frequency\\n[N=%s]' % len(rmsd_cells), fontsize=14)\r\naxes[5, 0].set_ylabel('Voltage\\n[mV]', fontsize=14)\r\naxes[6, 0].set_ylabel(r'Best ($*$)', fontsize=14, color=rankedcolours[0])\r\naxes[7, 0].set_ylabel(u'Median (\\u2021)', fontsize=14, color=rankedcolours[1])\r\naxes[8, 0].set_ylabel(r'90%ile (#)', fontsize=14, color=rankedcolours[2])\r\naxes[9, 0].set_ylabel('Frequency\\n[N=%s]' % len(rmsd_cells), fontsize=14)\r\n\r\naxes[2, 0].text(-0.25, 0.5, 'Current [pA]', rotation=90, fontsize=18,\r\n transform=axes[2, 0].transAxes, ha='center', va='center')\r\naxes[7, 0].text(-0.25, 0.5, 'Current [pA]', rotation=90, fontsize=18,\r\n transform=axes[7, 0].transAxes, ha='center', va='center')\r\n\r\n# Set y-ticklabels for protocols\r\n# TODO\r\n\r\n\r\n#\r\n# Model\r\n#\r\nprt2model = {}\r\nfor prt in protocol_list:\r\n\r\n protocol_def = protocol_funcs[prt]\r\n if type(protocol_def) is str:\r\n protocol_def = '%s/%s' % (protocol_dir, protocol_def)\r\n\r\n prt2model[prt] = m.Model('../mmt-model-files/kylie-2017-IKr.mmt',\r\n protocol_def=protocol_def,\r\n temperature=temperature, # K\r\n transform=None,\r\n useFilterCap=False) # ignore capacitive spike\r\n\r\n\r\n#\r\n# Plot\r\n#\r\nfor i_prt, prt in enumerate(protocol_list):\r\n\r\n # Calculate axis index\r\n ai, aj = 5 * int(i_prt / 3), i_prt % 3\r\n\r\n # Title\r\n if prt == 'staircaseramp':\r\n axes[ai, aj].set_title('Calibration', fontsize=16)\r\n else:\r\n axes[ai, aj].set_title('Validation %s' % validation_idx[i_prt],\r\n fontsize=16)\r\n\r\n # Add label!\r\n axes[ai, aj].text(-0.1, 1.4, string.ascii_uppercase[i_prt],\r\n transform=axes[ai, aj].transAxes, size=20,\r\n weight='bold')\r\n\r\n # Time point\r\n if prt == 'staircaseramp':\r\n times = np.loadtxt('%s/%s-%s-times.csv' % (data_dir_staircase,\r\n file_name, prt), delimiter=',', skiprows=1)\r\n else:\r\n times = np.loadtxt('%s/%s-%s-times.csv' % (data_dir, file_name,\r\n prt), delimiter=',', skiprows=1)\r\n\r\n # Protocol\r\n model = prt2model[prt]\r\n if prt not in protocol_iv:\r\n times_sim = np.copy(times)\r\n voltage = model.voltage(times_sim) * 1000\r\n else:\r\n times_sim = protocol_iv_times[prt](times[1] - times[0])\r\n voltage = model.voltage(times_sim) * 1000\r\n voltage, t = protocol_iv_convert[prt](voltage, times_sim)\r\n assert(np.mean(np.abs(t - times)) < 1e-8)\r\n axes[ai, aj].set_ylim((np.min(voltage) - 10, np.max(voltage) + 15))\r\n\r\n # Plot protocol\r\n if prt not in protocol_iv:\r\n axes[ai, aj].plot(times, voltage, c='#696969')\r\n else:\r\n # protocol\r\n for i in range(voltage.shape[1]):\r\n axes[ai, aj].plot(times, voltage[:, i], c='#696969')\r\n\r\n # Calculate ranking\r\n rmsd = rmsd_matrix[:, rmsd_prt.index(prt)]\r\n best_cell = np.argmin(rmsd)\r\n median_cell = np.argsort(rmsd)[len(rmsd)//2]\r\n p90_cell = np.argsort(rmsd)[int(len(rmsd)*0.9)]\r\n rankedcells = [rmsd_cells[best_cell],\r\n rmsd_cells[median_cell],\r\n rmsd_cells[p90_cell]]\r\n rankedvalues = [rmsd[best_cell],\r\n rmsd[median_cell],\r\n rmsd[p90_cell],]\r\n if plot_ref:\r\n rankedvalues.append(rmsd[rmsd_cells.index(refcell)])\r\n\r\n for i_cell, cell in enumerate(rankedcells):\r\n # Data\r\n if prt == 'staircaseramp':\r\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir_staircase,\r\n file_name, prt, cell), delimiter=',', skiprows=1)\r\n elif prt not in protocol_iv:\r\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir, file_name,\r\n prt, cell), delimiter=',', skiprows=1)\r\n # Re-leak correct the leak corrected data...\r\n g_releak = fmin(score_leak, [0.0], args=(data, voltage, times,\r\n protocol_leak_check[prt]), disp=False)\r\n data = I_releak(g_releak[0], data, voltage)\r\n else:\r\n data = np.loadtxt('%s/%s-%s-%s.csv' % (data_dir, file_name,\r\n prt, cell), delimiter=',', skiprows=1)\r\n for i in range(data.shape[1]):\r\n g_releak = fmin(score_leak, [0.0], args=(data[:, i],\r\n voltage[:, i], times,\r\n protocol_leak_check[prt]), disp=False)\r\n data[:, i] = I_releak(g_releak[0], data[:, i], voltage[:, i])\r\n assert(len(data) == len(times))\r\n\r\n # Fitted parameters\r\n param_file = '%s/%s/%s-staircaseramp-%s-solution-%s.txt' % \\\r\n (file_dir, file_name, file_name, cell, fit_seed)\r\n obtained_parameters = np.loadtxt(param_file)\r\n\r\n # Simulation\r\n simulation = model.simulate(obtained_parameters, times_sim)\r\n if prt in protocol_iv:\r\n simulation, t = protocol_iv_convert[prt](simulation, times_sim)\r\n assert(np.mean(np.abs(t - times)) < 1e-8)\r\n\r\n # Plot\r\n if prt not in protocol_iv:\r\n # recording\r\n axes[ai + i_cell + 1, aj].plot(times, data, lw=1, alpha=0.8,\r\n c='#1f77b4', label='data')\r\n # simulation\r\n if prt == 'staircaseramp':\r\n axes[ai + i_cell + 1, aj].plot(times, simulation, lw=2,\r\n c='#d62728', label='model fit to data')\r\n else:\r\n axes[ai + i_cell + 1, aj].plot(times, simulation, lw=2,\r\n c='#d62728', label='model prediction')\r\n else:\r\n iv_v = protocol_iv_v[prt]() * 1000 # V -> mV\r\n # recording\r\n iv_i = protocols.get_corrected_iv(data, times,\r\n *protocol_iv_args[prt]())\r\n axes[ai + i_cell + 1, aj].plot(iv_v, iv_i / np.max(iv_i), lw=2,\r\n alpha=1, c='#1f77b4', label='data')\r\n # simulation\r\n iv_i = protocols.get_corrected_iv(simulation, times,\r\n *protocol_iv_args[prt]())\r\n axes[ai + i_cell + 1, aj].plot(iv_v, iv_i / np.max(iv_i), lw=2,\r\n alpha=1, c='#d62728', label='model prediction')\r\n \r\n # Plot rmsd histogram\r\n n, b, _ = axes[ai + 4, aj].hist(rmsd, bins=15, color='#9e9ac8')\r\n\r\n # Add labels\r\n rankedidx = []\r\n for i, v in enumerate(rankedvalues):\r\n idx = np.where(b <= v)[0][-1]\r\n if idx in rankedidx:\r\n print('Ref. marker might clash with other markers...')\r\n axes[ai + 4, aj].text(\r\n (b[idx] + b[idx + 1]) / 2.,\r\n n[idx] + 0.12 * np.max(n),\r\n rankedlabels[i], fontsize=16, color=rankedcolours[i],\r\n ha='center', va='center')\r\n if n[idx] == np.max(n):\r\n axes[ai + 4, aj].set_ylim([0, n[idx] + 6])\r\n rankedidx.append(idx)\r\n\r\n axes[ai + 4, aj].set_ylim(0, 1.25 * np.max(n))\r\n\r\n\r\n#\r\n# Final adjustment and save\r\n#\r\naxes[1, 0].legend()\r\naxes[1, 1].legend()\r\ngrid.tight_layout(fig, pad=0.6, rect=(0.02, 0.0, 1, 0.99))\r\ngrid.update(wspace=0.2, hspace=0.0)\r\nplt.savefig('%s/rmsd-hist-%s.png' % (savedir, file_id), bbox_inch='tight',\r\n pad_inches=0, dpi=300)\r\nif '--pdf' in sys.argv:\r\n plt.savefig('%s/rmsd-hist-%s.pdf' % (savedir, file_id), format='pdf',\r\n bbox_inch='tight', pad_inches=0)\r\n\r\nprint('Done')\r\n","sub_path":"temperature-dependency/paper-rmsd-hist.py","file_name":"paper-rmsd-hist.py","file_ext":"py","file_size_in_byte":12811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"177195162","text":"# *-* coding: utf-8 *-*\n\nfrom Matrix import *\n\ndef input_matrix():\n print('Введите два числа через пробел - размер матрицы: ')\n n, m = map(int, input().split())\n \n print('Введите матрицу построчно, разделяя числа пробелами: ')\n result = [0] * n\n for i in range(n):\n result[i] = list(map(float, input().split()))\n \n return Matrix(result)\n\ndef input_vector():\n print('Введите одно число - размер вектора: ')\n n = int(input())\n \n print('Введите вектор (по одному числу в строке): ')\n result = [0] * n\n for i in range(n):\n result[i] = float(input())\n \n return Matrix.vector(result)\n\ndef input_eps():\n print('Введите точность: ')\n eps = float(input())\n return eps","sub_path":"src/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429064260","text":"__weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\norigin = 3 # 2004/01/01 is Thursday\n\ndef solve():\n while True:\n m, d = map(int, input().strip().split())\n if m == 0 and d == 0:\n break\n off = offset(m, d)\n index = (origin + off) % len(__weekdays)\n print(__weekdays[index])\n\ndef offset(m, d):\n days = [ 0, #dummy \\\n 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n off = sum(days[ : m])\n off += d - 1\n return off % 7\n\nif __name__ == '__main__':\n solve()\n","sub_path":"aoj/0000-/0027.py","file_name":"0027.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"510441481","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# lp_logic_test.py\n\nimport sys\nimport unittest\nfrom pprint import pprint\n\nimport pytest\n\nfrom pp.latchpony.model import (\n LatchPonyError, CompetitionError, DuplicateNodeError,\n CompetitionFormatError, CompetitionValidationError, CompetitionDataError,\n LatchPonyNode,\n Rider, Pony, Action, Latch,\n Competition, ActionWithPermission,\n NODE_GROUPS,\n LATCH_DENY_ALL, UUID_LENGTH,\n get_orgs_from_mongo, data_for_org,\n )\n\nskip = pytest.mark.skip\n\n# Go to this directory:\n# bitbucket/project-admin/projects/latchpony/pp-latchpony-restservice/Model/pp\n# and run\n# py.test\n# or\n# py.test --cov-config .coveragerc --cov-report term-missing --cov latchpony\n\n\n#TEST_COMPETITION_DICT = {\n # This would be a strange set of rules, but they are there to allow the\n # testing of various conditions. For instance, you wouldn't actually have\n # one rule that says Jane can edit salaries, and another that contradicts\n # it, with a different weight.\n ##'action': [{'name': 'create', 'groups': ['edit', 'maintain']},\n ##{'name': 'maintain', 'groups': ['view']},\n ##{'name': 'market', 'groups': ['view']},\n ##{'name': 'edit', 'groups': ['view']},\n ##{'name': 'view', 'groups': ['action']},\n ##],\n ##'anyone': [{'name': 'accounts-dept', 'groups': ['staff']},\n ##{'name': 'admin', 'groups': ['staff']},\n ##{'name': 'jane', 'groups': ['admin'], 'tags': ['pilates']},\n ##{'name': 'jim', 'groups': ['accounts-dept', 'admin']},\n ##{'name': 'staff', 'groups': ['anyone']},\n ##],\n ##'anything': [{'name': 'accounts', 'groups': ['financial']},\n ##{'name': 'financial', 'groups': ['anything']},\n ##{'name': 'salaries', 'groups': ['accounts']},\n ##{'name': 'share-price', 'groups': ['financial']},\n ##],\n ##'created': '2012-09-18T12:12:12',\n ##'name': 'comp_data_01',\n ##'permissions': ['deny anyone to action anything wt 10',\n ##'allow jane to market share-price wt 30',\n ##'allow anyone to view share-price wt 40',\n ##'deny admin to view accounts wt 60',\n ##'allow accounts-dept to create accounts wt 70',\n ##'allow jane to edit salaries wt 85',\n ##'deny accounts-dept to edit salaries wt 85',\n ##'allow jim to create salaries wt 90',\n ##'deny jane to view salaries wt 125'],\n##}\nTEST_COMPETITION_TREE = \"\"\"\\\n... action\n ... view\n ... maintain\n ... create\n ... market\n ... edit\n ... create\n... anyone\n ... staff\n ... accounts-dept\n ... jim\n ... admin\n ... jane\n ... jim\n... anything\n ... financial\n ... accounts # comment 1\n # comment 2\n ... salaries\n ... share-price\n... permissions\n ... deny anyone to action anything wt 10\n ... allow jane to market share-price wt 30\n ... allow anyone to view share-price wt 40\n ... deny admin to view accounts wt 60\n ... allow accounts-dept to create accounts wt 70\n ... allow jane to edit salaries wt 85\n ... deny accounts-dept to edit salaries wt 85\n ... allow jim to create salaries wt 90\n ... deny jane to view salaries wt 125\n... doc\n ... doc_name: Winter 2012\n ... doc_id: cfccd77f-9088-43bd-aedf-b1b5cd67d855\n ... organisation: massaaage.com\n ... org_id: mass01\n ... author: Rob The Demo\n ... created: 2012-09-18T12:12:12\n ... updated: 2012-11-20T14:29:49\n ... version: 0.1.7\n\"\"\"\n\n\n### This prints as tree thus:\n##\"\"\"\n##... action\n ##... view\n ##... maintain\n ##... create\n ##... market\n ##... edit\n ##... create\n##... anyone\n ##... staff\n ##... accounts-dept\n ##... jim\n ##... admin\n ##... jane\n ##... jim\n##... anything\n ##... financial\n ##... accounts\n ##... salaries\n ##... share-price\n##... permissions\n ##... deny anyone to action anything wt 10\n ##... allow jane to market share-price wt 30\n ##... allow anyone to view share-price wt 40\n ##... deny admin to view accounts wt 60\n ##... allow accounts-dept to create accounts wt 70\n ##... allow jane to edit salaries wt 85\n ##... deny accounts-dept to edit salaries wt 85\n ##... allow jim to create salaries wt 90\n ##... deny jane to view salaries wt 125\n##\"\"\"\n\n\nclass DebugPrintingTestCase(unittest.TestCase):\n\n def debug_print(self, competition):\n print(\"-\" * 50)\n pprint(competition.dump())\n print(\"-\" * 50)\n competition.print_tree()\n print(\"-\" * 50)\n\n\nclass TestNewLatchPonyNode(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_make_competitor_node(self):\n name = 'jane'\n data_dict = {'groups': ['admin'], 'tags': ['tag95']}\n node = LatchPonyNode(name=name, **data_dict)\n assert node.name == name\n assert node.groups == ['admin']\n assert node.tags == ['tag95']\n assert node.members == []\n assert node.data == None\n\n def test_make_permission_node(self):\n data = \"allow jane to edit salaries wt 85\"\n node = LatchPonyNode(data=data)\n assert node.data == data\n\n\nclass TestMongoDB(DebugPrintingTestCase):\n\n def setUp(self):\n pass\n\n def test_get_orgs(self):\n orgs = get_orgs_from_mongo()\n sample = [u'com_example_massage', u'com_example_pilates']\n # Check that each of sample is found in orgs\n assert set(sample) & set(orgs) == set(sample)\n\n def test_load_data_for_org(self):\n assert data_for_org(u'com_example_massage') == dict(a=1, b=2)\n assert data_for_org(u'com_example_pilates') == dict(a=3, b=4)\n\n\nclass TestActionWithPermission(DebugPrintingTestCase):\n\n def setUp(self):\n self.act_with_perm = ActionWithPermission('test-action')\n\n @skip\n def test_add_permit(self):\n self.act_with_perm.add_permit('allow', 20)\n self.act_with_perm.add_permit('deny', 30)\n self.act_with_perm.add_permit('allow', 40)\n self.assertItemsEqual(self.act_with_perm.weighted_permits,\n set([('allow', 20), ('deny', 30),\n ('allow', 40)]))\n\n @skip\n def test_add_duplicate_permit(self):\n self.act_with_perm.add_permit('allow', 20)\n self.act_with_perm.add_permit('deny', 30)\n self.act_with_perm.add_permit('allow', 20)\n self.assertItemsEqual(self.act_with_perm.weighted_permits,\n set([('allow', 20), ('deny', 30)]))\n\n @skip\n def test_add_conflicting_permit(self):\n with self.assertRaises(CompetitionDataError):\n self.act_with_perm.add_permit('allow', 20)\n self.act_with_perm.add_permit('deny', 30)\n self.act_with_perm.add_permit('deny', 20)\n\n def test_sorted_permits(self):\n self.act_with_perm.add_permit('allow', 70)\n self.act_with_perm.add_permit('deny', 80)\n self.act_with_perm.add_permit('allow', 90)\n self.assertEqual(self.act_with_perm._sorted_permits(),\n [('allow', 90), ('deny', 80), ('allow', 70)])\n\n def test_allowed(self):\n self.act_with_perm.add_permit('allow', 70)\n self.act_with_perm.add_permit('deny', 80)\n self.assertFalse(self.act_with_perm.allowed)\n self.act_with_perm.add_permit('allow', 90)\n self.assertTrue(self.act_with_perm.allowed)\n\n def test_representation(self):\n self.act_with_perm.add_permit('allow', 70)\n self.act_with_perm.add_permit('deny', 80)\n self.assertEqual(self.act_with_perm.__repr__(),\n '\")\n\n\nclass TestEmptyCompetition(DebugPrintingTestCase):\n\n def setUp(self):\n self.competition = Competition(name='Empty competition')\n\n @skip\n def test_create_competition(self):\n self.assertEqual(self.competition.name, 'empty_competition')\n self.assertEqual(self.competition.caption, 'Empty Competition')\n descs = self.competition.descendants\n self.assertEqual(descs('anyone'), set())\n self.assertEqual(descs('anything'), set())\n self.assertEqual(descs('action'), set())\n self.assertEqual(descs('permissions'), {LATCH_DENY_ALL})\n\n @skip\n def test_adding_rider(self):\n rider = Rider(name='jim')\n self.competition.add(rider)\n self.assertEqual(self.competition.nodes['jim'], rider)\n\n @skip\n def test_removing_rider(self):\n rider = Rider(name='jane')\n self.competition.add(rider)\n self.competition.remove(rider)\n self.debug_print(self.competition)\n self.assertItemsEqual(self.competition.nodes.keys(),\n NODE_GROUPS | {LATCH_DENY_ALL})\n\n @skip\n def test_removing_non_existent_rider(self):\n rider = Rider(name='jim')\n with self.assertRaises(CompetitionError) as ctxmgr:\n self.competition.remove(rider)\n self.assertIn(\"Unknown node key\", ctxmgr.exception.message)\n\n @skip\n def test_removing_duplicate_rider(self):\n rider1 = Rider(name='jane')\n rider2 = Rider(name='jane')\n self.competition.add(rider1)\n with self.assertRaises(DuplicateNodeError) as ctxmgr:\n self.competition.remove(rider2)\n self.assertIn(\"Duplicate node\", ctxmgr.exception.message)\n\n @skip\n def test_adding_pony(self):\n pony = Pony(name='salaries')\n self.competition.add(pony)\n self.assertEqual(self.competition.nodes['salaries'], pony)\n\n @skip\n def test_removing_pony(self):\n pony = Pony(name='finance')\n self.competition.add(pony)\n self.competition.remove(pony)\n self.assertItemsEqual(self.competition.nodes.keys(),\n NODE_GROUPS | {LATCH_DENY_ALL})\n\n @skip\n def test_adding_latch(self):\n latch_data = 'allow admin to view accounts wt 60'\n latch = Latch(latch_data)\n self.competition.add(latch)\n self.assertItemsEqual(self.competition.nodes.keys(),\n NODE_GROUPS | {latch_data, LATCH_DENY_ALL})\n\n @skip\n def test_removing_latch(self):\n latch_data = 'allow admin to view accounts wt 60'\n latch = Latch(latch_data)\n self.competition.add(latch)\n self.competition.remove(latch)\n self.assertItemsEqual(self.competition.nodes.keys(),\n NODE_GROUPS | {LATCH_DENY_ALL})\n\n @skip\n def test_adding_unknown_class(self):\n class Jumper(LatchPonyNode):\n collection_name = '_jumpers'\n def __init__(self, name, **kwargs):\n super(Jumper, self).__init__(**kwargs)\n self.name = name\n\n jumper = Jumper('oops')\n self.competition.add(jumper)\n with self.assertRaises(CompetitionValidationError):\n self.competition.validate()\n\n def test_load_with_unknown_format(self):\n with self.assertRaises(CompetitionFormatError):\n competition = Competition.load({}, data_format='xml')\n with self.assertRaises(CompetitionFormatError):\n competition = Competition.load({}, data_format='soap')\n\n\nclass TestLatches(DebugPrintingTestCase):\n\n def setUp(self):\n self.competition = Competition.load(TEST_COMPETITION_TREE)\n\n def test_make_latch(self):\n latch = Latch('deny admin to view accounts wt 60')\n self.assertEqual(str(latch),\n \"\")\n\n def test_latches_for_rider(self):\n self.debug_print(self.competition)\n self.competition._make_latch_dicts()\n jims_latches = self.competition.latches_for('jim')\n self.assertListEqual(jims_latches,\n [LATCH_DENY_ALL,\n 'allow anyone to view share-price wt 40',\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70',\n 'deny accounts-dept to edit salaries wt 85',\n 'allow jim to create salaries wt 90'])\n\n def test_latches_for_pony(self):\n self.debug_print(self.competition)\n salaries_latches = self.competition.latches_for('salaries')\n pprint(salaries_latches)\n self.assertListEqual(salaries_latches,\n [LATCH_DENY_ALL,\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70',\n 'allow jane to edit salaries wt 85',\n 'deny accounts-dept to edit salaries wt 85',\n 'allow jim to create salaries wt 90',\n 'deny jane to view salaries wt 125'])\n accounts_latches = self.competition.latches_for('accounts')\n pprint(accounts_latches)\n self.assertListEqual(accounts_latches,\n [LATCH_DENY_ALL,\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70'])\n\n def test_latches_for_both(self):\n latches3 = self.competition.latches_for('jim', 'salaries')\n self.assertListEqual(latches3,\n [LATCH_DENY_ALL,\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70',\n 'deny accounts-dept to edit salaries wt 85',\n 'allow jim to create salaries wt 90'])\n latches4 = self.competition.latches_for('jim', 'accounts')\n self.assertListEqual(latches4,\n [LATCH_DENY_ALL,\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70'])\n latches5 = self.competition.latches_for('jane', 'salaries')\n self.assertListEqual(latches5,\n [LATCH_DENY_ALL,\n 'deny admin to view accounts wt 60',\n 'allow jane to edit salaries wt 85',\n 'deny jane to view salaries wt 125'])\n\n def test_expand_deny_permissions(self):\n cept = self.competition.expand_permission_type\n aie = self.assertItemsEqual\n aie(cept('deny', 'edit'), set([('deny', 'edit'),\n ('deny', 'create')]))\n aie(cept('deny', 'action'), set([('deny', 'view'),\n ('deny', 'maintain'),\n ('deny', 'create'),\n ('deny', 'market'),\n ('deny', 'edit')]))\n aie(cept('deny', 'market'), set([('deny', 'market')]))\n\n def test_expand_allow_permissions(self):\n cept = self.competition.expand_permission_type\n aie = self.assertItemsEqual\n aie(cept('allow', 'edit'), set([('allow', 'edit'),\n ('allow', 'view')]))\n aie(cept('allow', 'create'), set([('allow', 'view'),\n ('allow', 'maintain'),\n ('allow', 'edit'),\n ('allow', 'create')]))\n aie(cept('allow', 'action'), set())\n\n @pytest.mark.skip\n # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n def test_gate_for(self):\n gf = self.competition.gate_for\n saleq = self.assertListEqual\n saleq(gf('jim', 'accounts'), ['create', 'edit', 'maintain', 'view'])\n saleq(gf('jim', 'salaries'), ['create', 'edit', 'maintain', 'view'])\n saleq(gf('jim', 'financial'), [])\n saleq(gf('jim', 'share-price'), ['view'])\n saleq(gf('jane', 'share-price'), ['market', 'view'])\n saleq(gf('jane', 'salaries'), [])\n saleq(gf('admin', 'accounts'), [])\n self.assertEqual(str(self.competition.ancestors.cache_info()),\n \"CacheInfo(hits=10, misses=20, maxsize=1000, currsize=20)\")\n self.assertEqual(str(self.competition.descendants.cache_info()),\n \"CacheInfo(hits=12, misses=15, maxsize=1000, currsize=15)\")\n\n @pytest.mark.skip\n def test_cache_on_gate_for(self):\n gf = self.competition.gate_for\n saleq = self.assertListEqual\n saleq(gf('jim', 'share-price'), ['view'])\n saleq(gf('jim', 'share-price'), ['view'])\n saleq(gf('jane', 'salaries'), [])\n saleq(gf('jim', 'share-price'), ['view'])\n saleq(gf('jim', 'share-price'), ['view'])\n self.assertEqual(str(gf.cache_info()),\n \"CacheInfo(hits=3, misses=2, maxsize=1000, currsize=2)\")\n self.assertEqual(str(self.competition.ancestors.cache_info()),\n \"CacheInfo(hits=0, misses=6, maxsize=1000, currsize=6)\")\n self.assertEqual(str(self.competition.descendants.cache_info()),\n \"CacheInfo(hits=2, misses=9, maxsize=1000, currsize=9)\")\n\n def test_ponies_for_rider(self):\n pfr = self.competition.ponies_for_rider\n sadeq = self.assertDictEqual\n sadeq(pfr('jim'), {'accounts': ['create', 'edit', 'maintain', 'view'],\n 'salaries': ['create', 'edit', 'maintain', 'view'],\n 'share-price': ['view']})\n sadeq(pfr('jane'), {'share-price': ['market', 'view']})\n sadeq(pfr('admin'), {'share-price': ['view']})\n sadeq(pfr('accounts-dept'),\n {'accounts': ['create', 'edit', 'maintain', 'view'],\n 'salaries': ['maintain', 'view'],\n 'share-price': ['view']})\n sadeq(pfr('staff'), {'share-price': ['view']})\n sadeq(pfr('anyone'), {'share-price': ['view']})\n\n def test_riders_for_pony(self):\n rfp = self.competition.riders_for_pony\n sadeq = self.assertDictEqual\n sadeq(rfp('share-price'), {'accounts-dept': ['view'],\n 'admin': ['view'],\n 'anyone': ['view'],\n 'jane': ['market', 'view'],\n 'jim': ['view'],\n 'staff': ['view']})\n sadeq(rfp('salaries'), {'accounts-dept': ['maintain', 'view'],\n 'jim': ['create', 'edit', 'maintain', 'view'],\n })\n sadeq(rfp('accounts'),\n {'accounts-dept': ['create', 'edit', 'maintain', 'view'],\n 'jim': ['create', 'edit', 'maintain', 'view']})\n sadeq(rfp('financial'), {})\n sadeq(rfp('anything'), {})\n\n\nclass TestLatchPonyHandBuiltGraph(DebugPrintingTestCase):\n\n def setUp(self):\n self.maxDiff = None\n\n @pytest.mark.skip\n # Data has changed\n def test_build_graph_by_hand(self):\n # Check that this graph is dumped identical with the auto-loaded\n # graph. Then run the tests with auto-loaded. Easier to change data.\n competition = Competition(name='comp_data_01')\n competition.created = '2012-09-18T12:12:12'\n\n cp_add = competition.add\n nodes = competition.nodes\n # Add riders and groups\n cp_add(Rider('staff', groups=['anyone']))\n cp_add(Rider('admin', groups=['staff']))\n cp_add(Rider('accounts-dept'))\n cp_add(Rider('jane', groups=['admin']))\n cp_add(Rider('jim', groups=['admin', 'accounts-dept']))\n\n # Add other rider groups\n nodes['accounts-dept'].add_groups(['staff'])\n\n # Add ponies and groups\n cp_add(Pony('financial', groups=['anything']))\n cp_add(Pony('share-price'))\n cp_add(Pony('accounts'))\n cp_add(Pony('salaries', groups=['accounts']))\n\n # Add other pony groups\n nodes['share-price'].add_groups(['financial'])\n nodes['accounts'].add_groups(['financial'])\n\n # Add action\n\n cp_add(Action('view', groups=['action']))\n cp_add(Action('maintain', groups=['view']))\n cp_add(Action('market', groups=['view']))\n cp_add(Action('edit', groups=['view']))\n cp_add(Action('create'))\n nodes['create'].add_groups(['edit', 'maintain'])\n\n # Add latches\n cp_add(Latch('allow jane market share-price 30'))\n cp_add(Latch('allow anyone view share-price 40'))\n cp_add(Latch('deny admin view accounts 60'))\n cp_add(Latch('allow accounts-dept create accounts 70'))\n cp_add(Latch('allow jane edit salaries 85'))\n cp_add(Latch('deny accounts-dept edit salaries 85'))\n cp_add(Latch('allow jim create salaries 90'))\n cp_add(Latch('deny jane view salaries 125'))\n\n competition.validate()\n\n self.assertDictEqual(competition.dump(), TEST_COMPETITION_DICT)\n\n\nclass TestLatchPonyStandardGraph(DebugPrintingTestCase):\n\n def setUp(self):\n self.competition = Competition.load(TEST_COMPETITION_TREE)\n\n def __getattr__(self, attr):\n \"\"\"Allow nodes to be found from test case, which delegates to\n self.competition.nodes\n \"\"\"\n if attr == 'nodes':\n return self.competition.nodes\n else:\n raise AttributeError(\"{} attribute not found\".format(attr))\n\n def tearDown(self):\n pass\n\n def test_competition_dump(self):\n self.assertDictEqual(self.competition.dump(), TEST_COMPETITION_DICT)\n\n def test_cant_make_instance_of_abstract_base_class(self):\n with self.assertRaises(TypeError) as ctxmgr:\n obj = LatchPonyNode('abstract')\n self.assertIn(\"Can't instantiate abstract class\",\n ctxmgr.exception.message)\n\n def test_rider_groups(self):\n self.assertEqual(self.nodes['jane'].groups, {'admin'})\n self.assertEqual(self.nodes['jim'].groups, {'admin', 'accounts-dept'})\n self.assertEqual(self.nodes['admin'].groups, {'staff'})\n self.assertEqual(self.nodes['staff'].groups, {'anyone'})\n self.assertEqual(self.nodes['anyone'].groups, set())\n\n def test_rider_members(self):\n self.assertEqual(self.nodes['anyone'].members, {'staff'})\n self.assertEqual(self.nodes['staff'].members,\n {'admin', 'accounts-dept'})\n self.assertEqual(self.nodes['accounts-dept'].members, {'jim'})\n self.assertEqual(self.nodes['admin'].members, {'jane', 'jim'})\n\n def test_all_ponies(self):\n self.assertItemsEqual(self.competition.all_ponies,\n ['accounts', 'anything', 'financial',\n 'salaries', 'share-price'])\n\n def test_all_riders(self):\n self.assertItemsEqual(self.competition.all_riders,\n ['accounts-dept', 'admin', 'anyone',\n 'jane', 'jim', 'staff'])\n\n def test_latches(self):\n expected_latch_keys = {LATCH_DENY_ALL,\n 'allow jane to market share-price wt 30',\n 'allow anyone to view share-price wt 40',\n 'deny admin to view accounts wt 60',\n 'allow accounts-dept to create accounts wt 70',\n 'allow jane to edit salaries wt 85',\n 'deny accounts-dept to edit salaries wt 85',\n 'allow jim to create salaries wt 90',\n 'deny jane to view salaries wt 125'}\n self.assertItemsEqual(expected_latch_keys,\n self.competition.descendants('permissions'))\n #self.debug_print(self.competition)\n #assert 0\n\n def test_add_duplicate_rider_changes_names_with_uuid(self):\n jim_duplicate = Rider(name='jim')\n self.assertEqual(jim_duplicate.name, 'jim')\n self.competition.add(jim_duplicate)\n self.assertTrue(jim_duplicate.name.startswith('jim$'))\n self.assertEqual(len(jim_duplicate.name), UUID_LENGTH + 4)\n\n def test_remove_group(self):\n self.nodes['admin'].remove_groups(['staff'])\n self.competition.validate()\n self.assertEqual(self.nodes['staff'].members, set(['accounts-dept']))\n self.assertEqual(self.nodes['admin'].groups, set())\n\n @pytest.mark.skip\n def test_rider_ancestors(self):\n ancs = self.competition.ancestors\n self.assertItemsEqual(ancs('jane'), {'admin', 'anyone', 'staff'})\n self.assertItemsEqual(ancs('jim'), {'accounts-dept', 'admin',\n 'anyone', 'staff'})\n self.assertItemsEqual(ancs('accounts-dept'), {'anyone', 'staff'})\n self.assertItemsEqual(ancs('admin'), {'anyone', 'staff'})\n self.assertItemsEqual(ancs('staff'), {'anyone'})\n self.assertEqual(str(ancs.cache_info()),\n \"CacheInfo(hits=128, misses=69, maxsize=1000, currsize=69)\")\n\n\n @pytest.mark.skip\n def test_pony_ancestors(self):\n ancs = self.competition.ancestors\n sae = self.assertItemsEqual\n sae(ancs('accounts'), {'anything', 'financial'})\n sae(ancs('salaries'), {'accounts', 'anything', 'financial'})\n sae(ancs('share-price'), {'anything', 'financial'})\n sae(ancs('financial'), {'anything'})\n self.assertEqual(str(ancs.cache_info()),\n \"CacheInfo(hits=128, misses=64, maxsize=1000, currsize=64)\")\n\n def test_action_ancestors_for_deny(self):\n #self.debug_print(self.competition)\n ancs = self.competition.ancestors\n sae = self.assertItemsEqual\n sae(ancs('view'), {'action'})\n sae(ancs('edit'), {'action', 'view'})\n sae(ancs('create'), {'action', 'edit', 'maintain', 'view'})\n\n @pytest.mark.skip\n # Data has changed\n def test_descendants(self):\n descs = self.competition.descendants\n self.assertItemsEqual(descs('financial'),\n {'accounts', 'salaries', 'share-price'})\n self.assertItemsEqual(descs('staff'),\n {'accounts-dept', 'admin', 'jane', 'jim'})\n self.assertItemsEqual(descs('jane'), set())\n self.assertItemsEqual(descs('jim'), set())\n self.assertEqual(str(descs.cache_info()),\n \"CacheInfo(hits=93, misses=45, maxsize=1000, currsize=45)\")\n\n def test_action_descendants_for_allow(self):\n descs = self.competition.descendants\n sae = self.assertItemsEqual\n sae(descs('action'), {'create', 'maintain', 'market', 'edit',\n 'view'})\n sae(descs('view'), {'create', 'maintain', 'market', 'edit'})\n sae(descs('maintain'), {'create'})\n sae(descs('market'), set())\n\n def test_expand_permission_type(self):\n ept = self.competition.expand_permission_type\n self.assertEqual(ept('deny', 'view'),\n set([('deny', 'market'), ('deny', 'view'),\n ('deny', 'create'), ('deny', 'maintain'),\n ('deny', 'edit')]))\n with self.assertRaises(CompetitionError):\n ept('probably', 'view')\n\n @pytest.mark.skip\n # Data has changed\n def test_competition_dump(self):\n output = self.competition.dump()\n # Fix the creation date/time to be the same\n output['created'] = TEST_COMPETITION_DICT['created']\n self.assertDictEqual(output, TEST_COMPETITION_DICT)\n\n\nclass TestRider(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_setting_name(self):\n # We need to test these methods in a subclass of LatchPonyNode\n # because that class is abstract\n rider = Rider(name='jim')\n self.assertEqual(rider.name, 'jim')\n self.assertEqual(rider.caption, 'Jim')\n rider = Rider(name='jim')\n self.assertEqual(rider.name, 'jim')\n self.assertEqual(rider.caption, 'Jim')\n\n def test_add_and_remove_groups(self):\n rider = Rider(name='andrew')\n rider.add_groups(['red', 'blue'])\n self.assertItemsEqual(rider.groups, {'red', 'blue'})\n rider.remove_groups(['green', 'red'])\n self.assertItemsEqual(rider.groups, {'blue'})\n\n\nif __name__ == '__main__':\n print(\"Starting...\\n\")\n #TestCompetition('test_load_with_unknown_format').run()\n #TestLatchPonyHandBuiltGraph('test_build_graph_by_hand').run()\n\n #TestLatches('test_latch_gates').run()\n #TestLatches('test_riders_for_pony').run()\n #TestCompetitionLoading('test_competition_load_and_dump').run()\n #TestLatchPonyStandardGraph('test_action_ancestors_for_deny').run()\n #TestActionWithPermission('test_allowed').run()\n #TestEmptyCompetition('test_adding_latch').run()\n TestNewLatchPonyNode('test_make_node').run()\n\n print(\"\\nFinished.\")\n\n\n\n","sub_path":"Model/pp/latchpony/model/tests/lp_logic_teXst.py","file_name":"lp_logic_teXst.py","file_ext":"py","file_size_in_byte":29345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"414529078","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 13 11:40:23 2020\n\n@author: user\n\"\"\"\n\n\n'''\nGiven an integer array nums, find the contiguous subarray \n(containing at least one number) which has the largest sum and return its sum.\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4],\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\nFollow up:\n\nIf you have figured out the O(n) solution, try coding\n another solution using the divide and conquer approach, which is more subtle.\n '''\nclass Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n max_sum = nums[0]\n for i in range(1, len(nums)):\n if nums[i - 1] > 0:\n nums[i] += nums[i - 1] \n max_sum = max(nums[i], max_sum)\n\n return max_sum\n\ny=Solution()\nnums=[-2,1,-3,4,-1,2,1,-5,4]\nprint(y.maxSubArray(nums))\nnums=[-1]\nprint(y.maxSubArray(nums))","sub_path":"LeetCodeInterviewCollections/Easy/maxSubArray.py","file_name":"maxSubArray.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"536159307","text":"import glob\nimport numpy as np\nimport matplotlib.image as mpimg\nimport cv2\nimport copy\n\ndef calibrate():\n \n images = glob.glob('./camera_cal/*.jpg')\n\n #number of x and y corners\n nx = 9\n ny = 6\n\n #map the coordinates of corners in this 2D image\n imgpoints = [] #2D points in image plane\n\n # to the 3D coordinates of the real world, undistorted chessboard corners\n objpoints = [] #3D points in real world space\n\n #prepare object points, like (0, 0, 0) (2, 0, 0) ... (8, 5, 0)\n objp = np.zeros((nx * ny, 3), np.float32) \n objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1, 2) # x, y coordinates\n\n for path in images:\n\n img = mpimg.imread(path)\n\n #convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n\n #draw the corners\n if ret == True:\n cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n\n imgpoints.append(corners)\n objpoints.append(objp)\n\n # gets the first image to gets the shape\n img_sample = mpimg.imread(images[0])\n\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img_sample.shape[0:2], None, None)\n \n return ret, mtx, dist, rvecs, tvecs\n\n# calibrates and exposes the variables for the other methods\nret, mtx, dist, rvecs, tvecs = calibrate()\n\n# given two points and a new_x, we define an y equivalent\n# good to change the size of line\ndef find_y_line(x_min, x_max, y_min, y_max, new_x):\n del_y = y_min - y_max\n del_x = x_max - x_min\n slope = del_y / del_x\n\n b = y_min - (x_max * slope)\n \n # y = mx + b\n y = (slope * new_x) + b\n return y\n\ndef extract_points_mask(img):\n imshape = img.shape\n \n rows = imshape[0]\n cols = imshape[1]\n\n x_bl = int(.15 * cols)\n x_tl = int(.469 * cols)\n x_tr = int(.532 * cols)\n x_br = int(.875 * cols)\n\n y_top = int(0.62 * rows)\n \n return x_bl, x_tl, x_tr, x_br, y_top\n\ndef warp(img, src, dest):\n \n img_size = (img.shape[1], img.shape[0])\n \n M = cv2.getPerspectiveTransform(src, dest)\n Minv = cv2.getPerspectiveTransform(dest, src)\n \n warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)\n \n return warped, Minv\n\ndef undist(img):\n return cv2.undistort(img, mtx, dist, None, mtx)\n\n\n\n# gradients\n\ndef abs_sobel_thresh(img, orient='x', thresh=(0, 255), use_S_channel=False, sobel_kernel=3):\n \n img_src = None\n \n if use_S_channel:\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n img_src = hls[:,:,2]\n else:\n img_src = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # 2) Take the derivative in x or y given orient = 'x' or 'y'\n sobel = None\n if orient == 'x':\n sobel = cv2.Sobel(img_src, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n elif orient == 'y':\n sobel = cv2.Sobel(img_src, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n else:\n raise Exception('The param ' + orient + ' is unknow')\n \n abs_sobel = np.absolute(sobel)\n\n # Scale to 8-bit (0 - 255) then convert to type = np.uint8\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n \n binary_output = np.zeros_like(scaled_sobel)\n binary_output[(scaled_sobel > thresh[0]) & (scaled_sobel < thresh[1])] = 1 \n return binary_output\n\ndef hls_threshold(img, thresh=(0, 255)):\n \n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n s_channel = hls[:,:,2]\n \n binary_output = np.zeros_like(s_channel)\n binary_output[(s_channel >= thresh[0]) & (s_channel <= thresh[1])] = 1\n return binary_output\n\n\n\n\n# Define a class to receive the characteristics of each line detection\nclass Line():\n def __init__(self):\n # was the line detected in the last iteration?\n self.detected = False \n # x values of the last n fits of the line\n self.recent_xfitted = [] \n #average x values of the fitted line over the last n iterations\n self.bestx = None \n #polynomial coefficients averaged over the last n iterations\n self.best_fit = None \n #polynomial coefficients for the most recent fit\n self.current_fit = [np.array([False])] \n #radius of curvature of the line in some units\n self.radius_of_curvature = None \n #distance in meters of vehicle center from the line\n self.line_base_pos = None \n #difference in fit coefficients between last and new fits\n self.diffs = np.array([0,0,0], dtype='float') \n #x values for detected line pixels\n self.allx = None \n #y values for detected line pixels\n self.ally = None\n \n # polynomial coefficients of the last n fit\n self.recent_fit = []\n \n # number of rollbacks in a row\n self.n_rollbacks = 0\n \n # x values of polynomial\n def add_xfitted(self, xfitted):\n self.recent_xfitted.append(xfitted)\n # matem n ultimos elementos\n n = 5\n self.recent_xfitted = self.recent_xfitted[-n:]\n self.bestx = np.average(self.recent_xfitted, axis=0)\n \n def set_current_fit(self, current_fit):\n self.current_fit = current_fit\n \n self.recent_fit.append(current_fit)\n \n # matem n ultimos elementos\n n = 5\n self.recent_fit = self.recent_fit[-n:]\n self.best_fit = np.average(self.recent_fit, axis=0)\n \n def get_indexes_of_line(self, img, nonzero, x_base):\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n\n minpx = 100\n margin = 100\n\n lines_inds = []\n \n if self.detected == False:\n self.detected = True\n \n cur_x_base = x_base\n \n height_img = img.shape[0]\n nwindows = 10\n window_height = height_img//nwindows\n\n for i in range(nwindows):\n\n # finds the left top point in the rectangle\n y_top = height_img - ((i + 1) * window_height)\n # finds the right bottom point in the rectangle\n y_bottom = height_img - (i * window_height)\n\n\n # defines the left window\n win_x_low = cur_x_base - margin\n win_x_high = cur_x_base + margin\n\n # where True we gets the indices\n good_ind = ((nonzerox >= win_x_low) & (nonzerox <= win_x_high) & \n (nonzeroy >= y_top) & (nonzeroy <= y_bottom)).nonzero()[0]\n\n # stores the indexes of the pixels that make up the line\n lines_inds.append(good_ind)\n\n # recenter\n if len(good_ind) > minpx:\n cur_x_base = np.int(np.mean(nonzerox[good_ind]))\n\n lines_inds = np.concatenate(lines_inds)\n else:\n # onde tiver pixel (nonzeroy) definimos uma fronteira de pesquisa\n search_area_x_low = self.best_fit[0]*nonzeroy**2 + \\\n self.best_fit[1]*nonzeroy + \\\n self.best_fit[2] - margin\n search_area_x_high = self.best_fit[0]*nonzeroy**2 + \\\n self.best_fit[1]*nonzeroy + \\\n self.best_fit[2] + margin\n\n # now we don't need to build the windows\n lines_inds = ((nonzerox >= search_area_x_low) & (nonzerox <= search_area_x_high)).nonzero()[0]\n \n # gets the indexes of pixel that make up the line\n self.allx = nonzerox[lines_inds]\n self.ally = nonzeroy[lines_inds]\n \n def sanity_check(self, other_curverad, bases_left_right=(0, 0)):\n good_measurement = True\n \n # checking that they have similar curvature\n min_curvature_diff = self.radius_of_curvature - (self.radius_of_curvature/2)\n max_curvature_diff = self.radius_of_curvature + (self.radius_of_curvature/2)\n \n if (other_curverad < min_curvature_diff) | (other_curverad > max_curvature_diff):\n good_measurement = False\n \n # checking that they are separated by approximately the right distance horizontally\n xm_per_pix = 3.7/700\n dist_hor = (bases_left_right[1] - bases_left_right[0]) * xm_per_pix\n if dist_hor > 4 or dist_hor < 3:\n print('irregular distance horizontally', dist_hor)\n good_measurement = False\n \n if good_measurement:\n # if we gets a good measurement we reset the number of roolbacks\n self.n_rollbacks = 0\n \n return good_measurement\n \n def rollback(self, previous_state):\n self.detected = previous_state.detected \n self.recent_xfitted = previous_state.recent_xfitted\n self.bestx = previous_state.bestx\n self.best_fit = previous_state.best_fit\n self.current_fit = previous_state.current_fit\n self.radius_of_curvature = previous_state.radius_of_curvature\n self.line_base_pos = previous_state.line_base_pos\n self.diffs = previous_state.diffs\n self.allx = previous_state.allx\n self.ally = previous_state.ally\n self.recent_fit = previous_state.recent_fit\n \n self.n_rollbacks += 1\n \n if self.n_rollbacks > 15:\n # init from stratch\n print('init search from stratch')\n self.n_rollbacks = 0\n self.detected = False\n\ndef detect_lines(image, left_line, right_line):\n \n # allow rollback in case of bad detection\n left_previous_state = copy.deepcopy(left_line)\n right_previous_state = copy.deepcopy(right_line)\n \n image = cv2.undistort(image, mtx, dist, None, mtx)\n \n grad_x = abs_sobel_thresh(image, thresh=(20, 130), sobel_kernel=5)\n #grad_x = abs_sobel_thresh(img_sobel, thresh=(20, 130), sobel_kernel=9)\n\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n H = hls[:,:,0]\n\n thresh = (100, 200)\n h_binary = np.zeros_like(H)\n h_binary[(H > thresh[0]) & (H <= thresh[1])] = 1\n\n\n #project\n #s_tresh = hls_threshold(image, thresh=(130, 255))\n s_tresh = hls_threshold(image, thresh=(90, 255))\n\n combined = np.zeros_like(s_tresh)\n combined[((s_tresh == 1) & (s_tresh != h_binary)) | ((grad_x == 1) ) ] = 1\n\n imshape = image.shape\n\n rows = imshape[0]\n cols = imshape[1]\n\n x_bl, x_tl, x_tr, x_br, y_top = extract_points_mask(image)\n\n # points that will be used in source points to transform\n #offset = 40\n offset = -15\n new_left_x = x_tl + offset\n new_left_y = find_y_line(x_bl, x_tl, y_top, rows, new_left_x)\n new_right_x = x_tr - offset\n new_right_y = find_y_line(x_br, x_tr, y_top, rows, new_right_x)\n\n src = np.float32([\n [x_bl, rows], \n [new_left_x, new_left_y], \n [new_right_x, new_right_y], \n [x_br, rows] \n ])\n\n # increase the size of line (mask area)\n increase_value = 150\n x_left = x_bl + increase_value\n x_right = x_br - increase_value\n\n dest = np.float32([\n [x_left, rows], \n [x_left, 0],\n [x_right, 0], \n [x_right, rows]\n ])\n\n warped_img, Minv = warp(combined, src, dest)\n \n half_index = warped_img.shape[0]//2\n histogram = np.sum(warped_img[half_index:,:], axis=0)\n\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0]/2)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint\n\n # gets the nonzero indices in an array (1 dim) inner a tuple (0=dim1 and 1=dim2)\n nonzero = warped_img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n \n # get indexes of line\n left_line.get_indexes_of_line(warped_img, nonzero, leftx_base)\n right_line.get_indexes_of_line(warped_img, nonzero, rightx_base)\n \n # gets a vector of coefficients of deegre 2\n # pass the y, x and the deegre\n left_line.set_current_fit(np.polyfit(left_line.ally, left_line.allx, 2))\n right_line.set_current_fit(np.polyfit(right_line.ally, right_line.allx, 2))\n\n # generates x and y values\n start = 0\n stop = warped_img.shape[0]-1\n nsamples = warped_img.shape[0]\n # returns an array of numbers for y\n ploty = np.linspace(start, stop, nsamples)\n\n # polynomial f(y) = a*yˆ2 + b*y + c\n left_line.add_xfitted(left_line.best_fit[0]*ploty**2 + \\\n left_line.best_fit[1]*ploty + \\\n left_line.best_fit[2])\n right_line.add_xfitted(right_line.best_fit[0]*ploty**2 + \\\n right_line.best_fit[1]*ploty + \\\n right_line.best_fit[2])\n\n # measuring the curvature\n\n # maximum y-value, corresponding to the bottom of the image\n y_eval = warped_img.shape[0]\n\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30/warped_img.shape[0] # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # polynomial coefficients with meters\n left_fit_m = np.polyfit(left_line.ally*ym_per_pix, left_line.allx*xm_per_pix, 2)\n right_fit_m = np.polyfit(right_line.ally*ym_per_pix, right_line.allx*xm_per_pix, 2)\n\n y_eval_m = y_eval*ym_per_pix\n\n # calculates the new radii of curvature\n left_line.radius_of_curvature = ((1 + (2*left_fit_m[0]*y_eval_m + left_fit_m[1])**2)**1.5) / np.absolute(2*left_fit_m[0])\n right_line.radius_of_curvature = ((1 + (2*right_fit_m[0]*y_eval_m + right_fit_m[1])**2)**1.5) / np.absolute(2*right_fit_m[0])\n \n polycolor = (0,255, 0) \n \n if (left_line.sanity_check(\n right_line.radius_of_curvature, bases_left_right=(leftx_base,rightx_base)) == False):\n \n if left_previous_state.bestx is not None: # if we have previous state\n left_line.rollback(left_previous_state)\n if right_previous_state.bestx is not None: # if we have previous state\n right_line.rollback(right_previous_state)\n \n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped_img).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_line.bestx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_line.bestx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_(pts), polycolor)\n \n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)\n \n # print texts\n\n # curvature\n mean_curvature = (left_line.radius_of_curvature + right_line.radius_of_curvature) // 2\n \n # distance from center\n center_point_lane = (leftx_base + rightx_base) / 2\n center_image = cols // 2\n distance = (center_image - center_point_lane) * xm_per_pix\n \n ## for debug (shows center of lane and the distance from center)\n ## draw_lines(result, [[center_image, 0, center_image, rows]], color=(255, 0, 0))\n ## draw_lines(result, [[int(center_point_lane), 0, int(center_point_lane), rows]], color=(0, 0, 255))\n \n \n text_curvature = \"Radius of Curvature = {0:.0f}(m)\".format(mean_curvature)\n text_distance = \"Vehicle is {0:.2f}m {1} of center\".format(\n abs(distance), \"right\" if distance > 0 else \"left\")\n \n cv2.putText(result, text_curvature, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2)\n cv2.putText(result, text_distance, (50,100), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2)\n \n return result","sub_path":"laneline_detection.py","file_name":"laneline_detection.py","file_ext":"py","file_size_in_byte":16001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373769609","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2011 Sybren A. Stüvel \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"RSA key generation code.\n\nCreate new keys with the newkeys() function. It will give you a PublicKey and a\nPrivateKey object.\n\nLoading and saving keys requires the pyasn1 module. This module is imported as\nlate as possible, such that other functionality will remain working in absence\nof pyasn1.\n\n.. note::\n\n Storing public and private keys via the `pickle` module is possible.\n However, it is insecure to load a key from an untrusted source.\n The pickle module is not secure against erroneous or maliciously\n constructed data. Never unpickle data received from an untrusted\n or unauthenticated source.\n\n\"\"\"\n\nimport logging\nimport warnings\n\nfrom rsa._compat import range\nimport rsa.prime\nimport rsa.pem\nimport rsa.common\nimport rsa.randnum\nimport rsa.core\n\n\nlog = logging.getLogger(__name__)\nDEFAULT_EXPONENT = 65537\n\n\nclass AbstractKey(object):\n \"\"\"Abstract superclass for private and public keys.\"\"\"\n\n __slots__ = ('n', 'e')\n\n def __init__(self, n, e):\n self.n = n\n self.e = e\n\n @classmethod\n def _load_pkcs1_pem(cls, keyfile):\n \"\"\"Loads a key in PKCS#1 PEM format, implement in a subclass.\n\n :param keyfile: contents of a PEM-encoded file that contains\n the public key.\n :type keyfile: bytes\n\n :return: the loaded key\n :rtype: AbstractKey\n \"\"\"\n\n @classmethod\n def _load_pkcs1_der(cls, keyfile):\n \"\"\"Loads a key in PKCS#1 PEM format, implement in a subclass.\n\n :param keyfile: contents of a DER-encoded file that contains\n the public key.\n :type keyfile: bytes\n\n :return: the loaded key\n :rtype: AbstractKey\n \"\"\"\n\n def _save_pkcs1_pem(self):\n \"\"\"Saves the key in PKCS#1 PEM format, implement in a subclass.\n\n :returns: the PEM-encoded key.\n :rtype: bytes\n \"\"\"\n\n def _save_pkcs1_der(self):\n \"\"\"Saves the key in PKCS#1 DER format, implement in a subclass.\n\n :returns: the DER-encoded key.\n :rtype: bytes\n \"\"\"\n\n @classmethod\n def load_pkcs1(cls, keyfile, format='PEM'):\n \"\"\"Loads a key in PKCS#1 DER or PEM format.\n\n :param keyfile: contents of a DER- or PEM-encoded file that contains\n the key.\n :type keyfile: bytes\n :param format: the format of the file to load; 'PEM' or 'DER'\n :type format: str\n\n :return: the loaded key\n :rtype: AbstractKey\n \"\"\"\n\n methods = {\n 'PEM': cls._load_pkcs1_pem,\n 'DER': cls._load_pkcs1_der,\n }\n\n method = cls._assert_format_exists(format, methods)\n return method(keyfile)\n\n @staticmethod\n def _assert_format_exists(file_format, methods):\n \"\"\"Checks whether the given file format exists in 'methods'.\n \"\"\"\n\n try:\n return methods[file_format]\n except KeyError:\n formats = ', '.join(sorted(methods.keys()))\n raise ValueError('Unsupported format: %r, try one of %s' % (file_format,\n formats))\n\n def save_pkcs1(self, format='PEM'):\n \"\"\"Saves the key in PKCS#1 DER or PEM format.\n\n :param format: the format to save; 'PEM' or 'DER'\n :type format: str\n :returns: the DER- or PEM-encoded key.\n :rtype: bytes\n \"\"\"\n\n methods = {\n 'PEM': self._save_pkcs1_pem,\n 'DER': self._save_pkcs1_der,\n }\n\n method = self._assert_format_exists(format, methods)\n return method()\n\n def blind(self, message, r):\n \"\"\"Performs blinding on the message using random number 'r'.\n\n :param message: the message, as integer, to blind.\n :type message: int\n :param r: the random number to blind with.\n :type r: int\n :return: the blinded message.\n :rtype: int\n\n The blinding is such that message = unblind(decrypt(blind(encrypt(message))).\n\n See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29\n \"\"\"\n\n return (message * pow(r, self.e, self.n)) % self.n\n\n def unblind(self, blinded, r):\n \"\"\"Performs blinding on the message using random number 'r'.\n\n :param blinded: the blinded message, as integer, to unblind.\n :param r: the random number to unblind with.\n :return: the original message.\n\n The blinding is such that message = unblind(decrypt(blind(encrypt(message))).\n\n See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29\n \"\"\"\n\n return (rsa.common.inverse(r, self.n) * blinded) % self.n\n\n\nclass PublicKey(AbstractKey):\n \"\"\"Represents a public RSA key.\n\n This key is also known as the 'encryption key'. It contains the 'n' and 'e'\n values.\n\n Supports attributes as well as dictionary-like access. Attribute access is\n faster, though.\n\n >>> PublicKey(5, 3)\n PublicKey(5, 3)\n\n >>> key = PublicKey(5, 3)\n >>> key.n\n 5\n >>> key['n']\n 5\n >>> key.e\n 3\n >>> key['e']\n 3\n\n \"\"\"\n\n __slots__ = ('n', 'e')\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n def __repr__(self):\n return 'PublicKey(%i, %i)' % (self.n, self.e)\n\n def __getstate__(self):\n \"\"\"Returns the key as tuple for pickling.\"\"\"\n return self.n, self.e\n\n def __setstate__(self, state):\n \"\"\"Sets the key from tuple.\"\"\"\n self.n, self.e = state\n\n def __eq__(self, other):\n if other is None:\n return False\n\n if not isinstance(other, PublicKey):\n return False\n\n return self.n == other.n and self.e == other.e\n\n def __ne__(self, other):\n return not (self == other)\n\n def __hash__(self):\n return hash((self.n, self.e))\n\n @classmethod\n def _load_pkcs1_der(cls, keyfile):\n \"\"\"Loads a key in PKCS#1 DER format.\n\n :param keyfile: contents of a DER-encoded file that contains the public\n key.\n :return: a PublicKey object\n\n First let's construct a DER encoded key:\n\n >>> import base64\n >>> b64der = 'MAwCBQCNGmYtAgMBAAE='\n >>> der = base64.standard_b64decode(b64der)\n\n This loads the file:\n\n >>> PublicKey._load_pkcs1_der(der)\n PublicKey(2367317549, 65537)\n\n \"\"\"\n\n from pyasn1.codec.der import decoder\n from rsa.asn1 import AsnPubKey\n\n (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey())\n return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))\n\n def _save_pkcs1_der(self):\n \"\"\"Saves the public key in PKCS#1 DER format.\n\n :returns: the DER-encoded public key.\n :rtype: bytes\n \"\"\"\n\n from pyasn1.codec.der import encoder\n from rsa.asn1 import AsnPubKey\n\n # Create the ASN object\n asn_key = AsnPubKey()\n asn_key.setComponentByName('modulus', self.n)\n asn_key.setComponentByName('publicExponent', self.e)\n\n return encoder.encode(asn_key)\n\n @classmethod\n def _load_pkcs1_pem(cls, keyfile):\n \"\"\"Loads a PKCS#1 PEM-encoded public key file.\n\n The contents of the file before the \"-----BEGIN RSA PUBLIC KEY-----\" and\n after the \"-----END RSA PUBLIC KEY-----\" lines is ignored.\n\n :param keyfile: contents of a PEM-encoded file that contains the public\n key.\n :return: a PublicKey object\n \"\"\"\n\n der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY')\n return cls._load_pkcs1_der(der)\n\n def _save_pkcs1_pem(self):\n \"\"\"Saves a PKCS#1 PEM-encoded public key file.\n\n :return: contents of a PEM-encoded file that contains the public key.\n :rtype: bytes\n \"\"\"\n\n der = self._save_pkcs1_der()\n return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')\n\n @classmethod\n def load_pkcs1_openssl_pem(cls, keyfile):\n \"\"\"Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.\n\n These files can be recognised in that they start with BEGIN PUBLIC KEY\n rather than BEGIN RSA PUBLIC KEY.\n\n The contents of the file before the \"-----BEGIN PUBLIC KEY-----\" and\n after the \"-----END PUBLIC KEY-----\" lines is ignored.\n\n :param keyfile: contents of a PEM-encoded file that contains the public\n key, from OpenSSL.\n :type keyfile: bytes\n :return: a PublicKey object\n \"\"\"\n\n der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')\n return cls.load_pkcs1_openssl_der(der)\n\n @classmethod\n def load_pkcs1_openssl_der(cls, keyfile):\n \"\"\"Loads a PKCS#1 DER-encoded public key file from OpenSSL.\n\n :param keyfile: contents of a DER-encoded file that contains the public\n key, from OpenSSL.\n :return: a PublicKey object\n :rtype: bytes\n\n \"\"\"\n\n from rsa.asn1 import OpenSSLPubKey\n from pyasn1.codec.der import decoder\n from pyasn1.type import univ\n\n (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey())\n\n if keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'):\n raise TypeError(\"This is not a DER-encoded OpenSSL-compatible public key\")\n\n return cls._load_pkcs1_der(keyinfo['key'][1:])\n\n\nclass PrivateKey(AbstractKey):\n \"\"\"Represents a private RSA key.\n\n This key is also known as the 'decryption key'. It contains the 'n', 'e',\n 'd', 'p', 'q' and other values.\n\n Supports attributes as well as dictionary-like access. Attribute access is\n faster, though.\n\n >>> PrivateKey(3247, 65537, 833, 191, 17)\n PrivateKey(3247, 65537, 833, 191, 17)\n\n exp1, exp2 and coef will be calculated:\n\n >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)\n >>> pk.exp1\n 55063\n >>> pk.exp2\n 10095\n >>> pk.coef\n 50797\n\n \"\"\"\n\n __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')\n\n def __init__(self, n, e, d, p, q):\n AbstractKey.__init__(self, n, e)\n self.d = d\n self.p = p\n self.q = q\n\n # Calculate exponents and coefficient.\n self.exp1 = int(d % (p - 1))\n self.exp2 = int(d % (q - 1))\n self.coef = rsa.common.inverse(q, p)\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n def __repr__(self):\n return 'PrivateKey(%(n)i, %(e)i, %(d)i, %(p)i, %(q)i)' % self\n\n def __getstate__(self):\n \"\"\"Returns the key as tuple for pickling.\"\"\"\n return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef\n\n def __setstate__(self, state):\n \"\"\"Sets the key from tuple.\"\"\"\n self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state\n\n def __eq__(self, other):\n if other is None:\n return False\n\n if not isinstance(other, PrivateKey):\n return False\n\n return (self.n == other.n and\n self.e == other.e and\n self.d == other.d and\n self.p == other.p and\n self.q == other.q and\n self.exp1 == other.exp1 and\n self.exp2 == other.exp2 and\n self.coef == other.coef)\n\n def __ne__(self, other):\n return not (self == other)\n\n def __hash__(self):\n return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef))\n\n def blinded_decrypt(self, encrypted):\n \"\"\"Decrypts the message using blinding to prevent side-channel attacks.\n\n :param encrypted: the encrypted message\n :type encrypted: int\n\n :returns: the decrypted message\n :rtype: int\n \"\"\"\n\n blind_r = rsa.randnum.randint(self.n - 1)\n blinded = self.blind(encrypted, blind_r) # blind before decrypting\n decrypted = rsa.core.decrypt_int(blinded, self.d, self.n)\n\n return self.unblind(decrypted, blind_r)\n\n def blinded_encrypt(self, message):\n \"\"\"Encrypts the message using blinding to prevent side-channel attacks.\n\n :param message: the message to encrypt\n :type message: int\n\n :returns: the encrypted message\n :rtype: int\n \"\"\"\n\n blind_r = rsa.randnum.randint(self.n - 1)\n blinded = self.blind(message, blind_r) # blind before encrypting\n encrypted = rsa.core.encrypt_int(blinded, self.d, self.n)\n return self.unblind(encrypted, blind_r)\n\n @classmethod\n def _load_pkcs1_der(cls, keyfile):\n \"\"\"Loads a key in PKCS#1 DER format.\n\n :param keyfile: contents of a DER-encoded file that contains the private\n key.\n :type keyfile: bytes\n :return: a PrivateKey object\n\n First let's construct a DER encoded key:\n\n >>> import base64\n >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt'\n >>> der = base64.standard_b64decode(b64der)\n\n This loads the file:\n\n >>> PrivateKey._load_pkcs1_der(der)\n PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)\n\n \"\"\"\n\n from pyasn1.codec.der import decoder\n (priv, _) = decoder.decode(keyfile)\n\n # ASN.1 contents of DER encoded private key:\n #\n # RSAPrivateKey ::= SEQUENCE {\n # version Version,\n # modulus INTEGER, -- n\n # publicExponent INTEGER, -- e\n # privateExponent INTEGER, -- d\n # prime1 INTEGER, -- p\n # prime2 INTEGER, -- q\n # exponent1 INTEGER, -- d mod (p-1)\n # exponent2 INTEGER, -- d mod (q-1)\n # coefficient INTEGER, -- (inverse of q) mod p\n # otherPrimeInfos OtherPrimeInfos OPTIONAL\n # }\n\n if priv[0] != 0:\n raise ValueError('Unable to read this file, version %s != 0' % priv[0])\n\n as_ints = map(int, priv[1:6])\n key = cls(*as_ints)\n\n exp1, exp2, coef = map(int, priv[6:9])\n\n if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef):\n warnings.warn(\n 'You have provided a malformed keyfile. Either the exponents '\n 'or the coefficient are incorrect. Using the correct values '\n 'instead.',\n UserWarning,\n )\n\n return key\n\n def _save_pkcs1_der(self):\n \"\"\"Saves the private key in PKCS#1 DER format.\n\n :returns: the DER-encoded private key.\n :rtype: bytes\n \"\"\"\n\n from pyasn1.type import univ, namedtype\n from pyasn1.codec.der import encoder\n\n class AsnPrivKey(univ.Sequence):\n componentType = namedtype.NamedTypes(\n namedtype.NamedType('version', univ.Integer()),\n namedtype.NamedType('modulus', univ.Integer()),\n namedtype.NamedType('publicExponent', univ.Integer()),\n namedtype.NamedType('privateExponent', univ.Integer()),\n namedtype.NamedType('prime1', univ.Integer()),\n namedtype.NamedType('prime2', univ.Integer()),\n namedtype.NamedType('exponent1', univ.Integer()),\n namedtype.NamedType('exponent2', univ.Integer()),\n namedtype.NamedType('coefficient', univ.Integer()),\n )\n\n # Create the ASN object\n asn_key = AsnPrivKey()\n asn_key.setComponentByName('version', 0)\n asn_key.setComponentByName('modulus', self.n)\n asn_key.setComponentByName('publicExponent', self.e)\n asn_key.setComponentByName('privateExponent', self.d)\n asn_key.setComponentByName('prime1', self.p)\n asn_key.setComponentByName('prime2', self.q)\n asn_key.setComponentByName('exponent1', self.exp1)\n asn_key.setComponentByName('exponent2', self.exp2)\n asn_key.setComponentByName('coefficient', self.coef)\n\n return encoder.encode(asn_key)\n\n @classmethod\n def _load_pkcs1_pem(cls, keyfile):\n \"\"\"Loads a PKCS#1 PEM-encoded private key file.\n\n The contents of the file before the \"-----BEGIN RSA PRIVATE KEY-----\" and\n after the \"-----END RSA PRIVATE KEY-----\" lines is ignored.\n\n :param keyfile: contents of a PEM-encoded file that contains the private\n key.\n :type keyfile: bytes\n :return: a PrivateKey object\n \"\"\"\n\n der = rsa.pem.load_pem(keyfile, b'RSA PRIVATE KEY')\n return cls._load_pkcs1_der(der)\n\n def _save_pkcs1_pem(self):\n \"\"\"Saves a PKCS#1 PEM-encoded private key file.\n\n :return: contents of a PEM-encoded file that contains the private key.\n :rtype: bytes\n \"\"\"\n\n der = self._save_pkcs1_der()\n return rsa.pem.save_pem(der, b'RSA PRIVATE KEY')\n\n\ndef find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):\n \"\"\"Returns a tuple of two different primes of nbits bits each.\n\n The resulting p * q has exacty 2 * nbits bits, and the returned p and q\n will not be equal.\n\n :param nbits: the number of bits in each of p and q.\n :param getprime_func: the getprime function, defaults to\n :py:func:`rsa.prime.getprime`.\n\n *Introduced in Python-RSA 3.1*\n\n :param accurate: whether to enable accurate mode or not.\n :returns: (p, q), where p > q\n\n >>> (p, q) = find_p_q(128)\n >>> from rsa import common\n >>> common.bit_size(p * q)\n 256\n\n When not in accurate mode, the number of bits can be slightly less\n\n >>> (p, q) = find_p_q(128, accurate=False)\n >>> from rsa import common\n >>> common.bit_size(p * q) <= 256\n True\n >>> common.bit_size(p * q) > 240\n True\n\n \"\"\"\n\n total_bits = nbits * 2\n\n # Make sure that p and q aren't too close or the factoring programs can\n # factor n.\n shift = nbits // 16\n pbits = nbits + shift\n qbits = nbits - shift\n\n # Choose the two initial primes\n log.debug('find_p_q(%i): Finding p', nbits)\n p = getprime_func(pbits)\n log.debug('find_p_q(%i): Finding q', nbits)\n q = getprime_func(qbits)\n\n def is_acceptable(p, q):\n \"\"\"Returns True iff p and q are acceptable:\n\n - p and q differ\n - (p * q) has the right nr of bits (when accurate=True)\n \"\"\"\n\n if p == q:\n return False\n\n if not accurate:\n return True\n\n # Make sure we have just the right amount of bits\n found_size = rsa.common.bit_size(p * q)\n return total_bits == found_size\n\n # Keep choosing other primes until they match our requirements.\n change_p = False\n while not is_acceptable(p, q):\n # Change p on one iteration and q on the other\n if change_p:\n p = getprime_func(pbits)\n else:\n q = getprime_func(qbits)\n\n change_p = not change_p\n\n # We want p > q as described on\n # http://www.di-mgt.com.au/rsa_alg.html#crt\n return max(p, q), min(p, q)\n\n\ndef calculate_keys_custom_exponent(p, q, exponent):\n \"\"\"Calculates an encryption and a decryption key given p, q and an exponent,\n and returns them as a tuple (e, d)\n\n :param p: the first large prime\n :param q: the second large prime\n :param exponent: the exponent for the key; only change this if you know\n what you're doing, as the exponent influences how difficult your\n private key can be cracked. A very common choice for e is 65537.\n :type exponent: int\n\n \"\"\"\n\n phi_n = (p - 1) * (q - 1)\n\n try:\n d = rsa.common.inverse(exponent, phi_n)\n except rsa.common.NotRelativePrimeError as ex:\n raise rsa.common.NotRelativePrimeError(\n exponent, phi_n, ex.d,\n msg=\"e (%d) and phi_n (%d) are not relatively prime (divider=%i)\" %\n (exponent, phi_n, ex.d))\n\n if (exponent * d) % phi_n != 1:\n raise ValueError(\"e (%d) and d (%d) are not mult. inv. modulo \"\n \"phi_n (%d)\" % (exponent, d, phi_n))\n\n return exponent, d\n\n\ndef calculate_keys(p, q):\n \"\"\"Calculates an encryption and a decryption key given p and q, and\n returns them as a tuple (e, d)\n\n :param p: the first large prime\n :param q: the second large prime\n\n :return: tuple (e, d) with the encryption and decryption exponents.\n \"\"\"\n\n return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT)\n\n\ndef gen_keys(nbits, getprime_func, accurate=True, exponent=DEFAULT_EXPONENT):\n \"\"\"Generate RSA keys of nbits bits. Returns (p, q, e, d).\n\n Note: this can take a long time, depending on the key size.\n\n :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and\n ``q`` will use ``nbits/2`` bits.\n :param getprime_func: either :py:func:`rsa.prime.getprime` or a function\n with similar signature.\n :param exponent: the exponent for the key; only change this if you know\n what you're doing, as the exponent influences how difficult your\n private key can be cracked. A very common choice for e is 65537.\n :type exponent: int\n \"\"\"\n\n # Regenerate p and q values, until calculate_keys doesn't raise a\n # ValueError.\n while True:\n (p, q) = find_p_q(nbits // 2, getprime_func, accurate)\n try:\n (e, d) = calculate_keys_custom_exponent(p, q, exponent=exponent)\n break\n except ValueError:\n pass\n\n return p, q, e, d\n\n\ndef newkeys(nbits, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT):\n \"\"\"Generates public and private keys, and returns them as (pub, priv).\n\n The public key is also known as the 'encryption key', and is a\n :py:class:`rsa.PublicKey` object. The private key is also known as the\n 'decryption key' and is a :py:class:`rsa.PrivateKey` object.\n\n :param nbits: the number of bits required to store ``n = p*q``.\n :param accurate: when True, ``n`` will have exactly the number of bits you\n asked for. However, this makes key generation much slower. When False,\n `n`` may have slightly less bits.\n :param poolsize: the number of processes to use to generate the prime\n numbers. If set to a number > 1, a parallel algorithm will be used.\n This requires Python 2.6 or newer.\n :param exponent: the exponent for the key; only change this if you know\n what you're doing, as the exponent influences how difficult your\n private key can be cracked. A very common choice for e is 65537.\n :type exponent: int\n\n :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`)\n\n The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires\n Python 2.6 or newer.\n\n \"\"\"\n\n if nbits < 16:\n raise ValueError('Key too small')\n\n if poolsize < 1:\n raise ValueError('Pool size (%i) should be >= 1' % poolsize)\n\n # Determine which getprime function to use\n if poolsize > 1:\n from rsa import parallel\n import functools\n\n getprime_func = functools.partial(parallel.getprime, poolsize=poolsize)\n else:\n getprime_func = rsa.prime.getprime\n\n # Generate the key components\n (p, q, e, d) = gen_keys(nbits, getprime_func, accurate=accurate, exponent=exponent)\n\n # Create the key objects\n n = p * q\n\n return (\n PublicKey(n, e),\n PrivateKey(n, e, d, p, q)\n )\n\n\n__all__ = ['PublicKey', 'PrivateKey', 'newkeys']\n\nif __name__ == '__main__':\n import doctest\n\n try:\n for count in range(100):\n (failures, tests) = doctest.testmod()\n if failures:\n break\n\n if (count % 10 == 0 and count) or count == 1:\n print('%i times' % count)\n except KeyboardInterrupt:\n print('Aborted')\n else:\n print('Doctests done')\n","sub_path":"courses/machine_learning/deepdive2/structured/labs/serving/application/lib/rsa/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":24270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179155127","text":"import os\nfrom collections import defaultdict\nfrom functools import partial\nfrom typing import Optional\n\n# Disable tensorflow verbose output. Needs to be done before importing tf\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\nimport scipy.signal\nimport tensorflow as tf\nfrom dask.distributed import Client, get_worker\n\nfrom params import benchmark_3_params\nfrom util import (create_and_save_tf_model, create_documents, create_image,\n create_image_filters, run_trials)\n\nDASK_CLIENT = None # type: Optional[Client]\n\n\ndef init_dask(n_jobs: int) -> None:\n # Usually, you have to avoid using globals, but this was the most convenient\n global DASK_CLIENT\n DASK_CLIENT = Client(n_workers=n_jobs, threads_per_worker=1)\n\n\ndef shutdown_dask() -> None:\n global DASK_CLIENT\n DASK_CLIENT.close()\n\n\n######################################\n# Benchmark 1: numerical computation #\n######################################\n\n\ndef process_image(image, random_filter):\n # Do some image processing.\n return scipy.signal.convolve2d(image, random_filter)[::5, ::5]\n\n\ndef benchmark_1(filters, _):\n image = create_image()\n image_b = DASK_CLIENT.scatter(image, broadcast=True)\n for _ in DASK_CLIENT.gather([DASK_CLIENT.submit(process_image, image_b,\n filter_)\n for filter_ in filters]):\n pass\n\n\n#####################################\n# Benchmark 2: stateful computation #\n#####################################\n\n\nclass StreamingPrefixCount:\n def __init__(self):\n self.prefix_count = defaultdict(int)\n\n def add_document(self, document):\n for word in document:\n for i in range(1, len(word)):\n prefix = word[:i]\n self.prefix_count[prefix] += 1\n\n def get_popular(self):\n return {prefix for prefix, cnt in self.prefix_count.items() if cnt > 3}\n\n\ndef accumulate_prefixes(document):\n worker = get_worker()\n if not hasattr(worker, \"streaming_actor\"):\n worker.streaming_actor = StreamingPrefixCount()\n if document is None:\n return worker.streaming_actor.get_popular()\n else:\n worker.streaming_actor.add_document(document)\n\n\ndef benchmark_2(documents, n_jobs):\n # I'm aware that doing a prefix count this way is not guaranteed to return\n # the correct prefixes over all documents. This is merely to illustrate\n # stateful computation\n\n # I would implement this using Dask actors, but that implementation\n # (provided below) failed to run for some unknown reason.\n DASK_CLIENT.gather([DASK_CLIENT.submit(accumulate_prefixes, document)\n for document in documents])\n\n # Add sentinel to each individual worker\n workers = DASK_CLIENT.scheduler_info()['workers'].keys()\n futures = [DASK_CLIENT.submit(accumulate_prefixes, None, workers=[worker])\n for worker in workers]\n\n # Aggregate\n popular_prefixes = set()\n for future in futures:\n popular_prefixes |= future.result()\n\n\ndef benchmark_2_actors(documents, n_jobs):\n # I'm aware that doing a prefix count this way is not guaranteed to return\n # the correct prefixes over all documents. This is merely to illustrate\n # stateful computation\n streaming_actors = [DASK_CLIENT.submit(StreamingPrefixCount,\n actor=True).result()\n for _ in range(n_jobs)]\n\n # Client.gather() doesn't work for ActorFuture objects\n futures = [streaming_actors[idx % n_jobs].add_document(document)\n for idx, document in enumerate(documents)]\n [future.result() for future in futures]\n\n # Aggregate\n popular_prefixes = set()\n for actor in streaming_actors:\n popular_prefixes |= actor.get_popular().result()\n\n\n#########################################\n# Benchmark 3: expensive initialization #\n#########################################\n\n\nclass Model:\n def __init__(self, filename):\n # Load the model and some data.\n self.model = tf.keras.models.load_model(filename)\n mnist = tf.keras.datasets.mnist.load_data()\n self.x_test = mnist[1][0] / 255.0\n\n def evaluate_next_batch(self, idx):\n # Note that we reuse the same data over and over, but in a real\n # application, the data would be different each time. To simulate the\n # latter we add idx (this avoids libraries to use caching mechanisms)\n return self.model.predict(self.x_test) + idx\n\n\ndef evaluate_next_batch(filename, idx):\n worker = get_worker()\n if not hasattr(worker, 'model_actor'):\n worker.model_actor = Model(filename)\n return worker.model_actor.evaluate_next_batch(idx)\n\n\ndef benchmark_3(filename, n_jobs):\n # We run it multiple times to better see the effect of initialization.\n for _ in range(benchmark_3_params[\"n_runs\"]):\n for _ in DASK_CLIENT.gather([\n DASK_CLIENT.submit(evaluate_next_batch, filename, idx)\n for idx in range(benchmark_3_params[\"n_evals\"])\n ]):\n pass\n\n\ndef benchmark_3_actors(filename, n_jobs):\n actors = [DASK_CLIENT.submit(Model, filename, actor=True).result()\n for _ in range(n_jobs)]\n\n # We run it multiple times to better see the effect of initialization.\n # Client.gather() doesn't work for ActorFuture objects\n for _ in range(benchmark_3_params[\"n_runs\"]):\n futures = [actors[idx % n_jobs].evaluate_next_batch()\n for idx in range(benchmark_3_params[\"n_evals\"])]\n for future in futures:\n future.result()\n\n\n##################\n# Run benchmarks #\n##################\n\n\ndef main():\n print(\"====\")\n print(\"Dask\")\n print(\"====\")\n library_name = \"Dask\"\n\n print(\"Setting up benchmark 1 ...\")\n filters = create_image_filters()\n\n print(\"Benchmark #1 started\")\n run_trials(partial(benchmark_1, filters), \"Numerical computation\",\n library_name, init_function=init_dask,\n exit_function=shutdown_dask)\n\n print(\"Setting up benchmark 2 ...\")\n documents = create_documents()\n\n print(\"Benchmark #2 started\")\n run_trials(partial(benchmark_2, documents), \"Stateful computation\",\n library_name, init_function=init_dask,\n exit_function=shutdown_dask)\n\n print(\"Setting up benchmark 3 ...\")\n filename = \"/tmp/model\"\n create_and_save_tf_model(filename)\n\n print(\"Benchmark #3 started\")\n run_trials(partial(benchmark_3, filename), \"Expensive initialization\",\n library_name, init_function=init_dask,\n exit_function=shutdown_dask)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"benchmark_dask.py","file_name":"benchmark_dask.py","file_ext":"py","file_size_in_byte":6670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281350072","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 14 13:19:02 2018\n\n@author: shubhamsinha\n\"\"\"\n\nimport math\nimport numpy as np\nimport time\nimport random\n\ntrain_images=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/train_images.npy')\ntrain_labels=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/train_labels.npy')\ntest_images=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/test_images.npy')\ntest_labels=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/test_labels.npy')\nvalidation_images=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/validation_images.npy')\nvalidation_labels=np.load('/Users/shubhamsinha/Documents/data (1)/facedata/validation_labels.npy' )\n\n\n#percentage=100\n#length=int(5000*(percentage/100))\n#train_images=train_images[0:length][:]\n#train_labels=train_labels[0:length][:]\n\n\niterations=5\nl=train_images.shape[1]\nweight_vectors=np.zeros((10,l+1),dtype=int)\nbias=1\nclasses=[0,1,2,3,4,5,6,7,8,9]\n\ndef train(images,labels):\n for _ in range(iterations):\n for i in range(0,len(images)):\n featurelist=images[i]#taking one training vector\n feature_vector=np.append(featurelist,bias)#adding 1 to make it same as weight because bias\n \n \n #initializing\n arg_max, predicted_class = 0, classes[0]\n \n # Multi-Class Decision Rule:\n for c in classes:\n current_activation = np.dot(feature_vector, weight_vectors[c])\n if current_activation >= arg_max:\n arg_max, predicted_class = current_activation, c\n\n # Update Rule:\n if not (labels[i] == predicted_class):\n weight_vectors[labels[i]] += feature_vector\n weight_vectors[predicted_class] -= feature_vector\n \n\ndef test(images):\n predicted=[]\n for i in range(0,len(images)):\n featurelist=images[i]#taking one training vector\n feature_vector=np.append(featurelist,bias)#adding 1 to make it same as weight because bias\n \n \n #initializing\n arg_max, predicted_class = 0, classes[0]\n \n # Multi-Class Decision Rule:\n for c in classes:\n current_activation = np.dot(feature_vector, weight_vectors[c])\n if current_activation >= arg_max:\n arg_max, predicted_class = current_activation, c\n \n predicted.append(predicted_class)\n \n return predicted\n \ndef getAccuracy(testLabels, predictions):\n\tcorrect = 0\n\tfor x in range(len(testLabels)):\n\t\tif testLabels[x] == predictions[x]:\n\t\t\tcorrect += 1\n\treturn (correct/float(len(testLabels))) \n\n\narr=[]\nnewtrain_images=[]\nnewtrain_labels=[]\nolen=len(train_labels)\npercentage=100\nlength=int(olen*(percentage/100))\nprint(length)\nfor _ in range(10):\n \n rand=random.sample(range(0, olen), length)\n for i in range(0,length):\n newtrain_images.append(train_images[rand[i]][:])\n newtrain_labels.append(train_labels[rand[i]])\n\n iterations=5\n l=train_images.shape[1]\n weight_vectors=np.zeros((10,l+1),dtype=int)\n bias=1\n classes=[0,1,2,3,4,5,6,7,8,9]\n\n start_time=time.time()\n train(newtrain_images,newtrain_labels)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n p=test(validation_images)\n# p2=test(train_images)\n a=getAccuracy(validation_labels,p)\n \n# a2=getAccuracy(train_labels,p2)*100\n arr.append(1-a)\n newtrain_images=[]\n newtrain_labels=[]\n\nprint(\"mean: \"+str(np.mean(arr)))\nprint(\"std: \"+str(np.std(arr)))","sub_path":"facedata/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"195176528","text":"# coding: utf-8\n# Copyright 2013 The Font Bakery 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# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.\nimport os\nimport os.path as op\nfrom os.path import dirname, abspath\n\nDEBUG = True\nBACKGROUND = True\nSECRET_KEY = \\\n '\\xa8\\xad%\\x07kL\\x8f\\x04D\\xf4\\xbf\"\\xe0a\\xb52\\x1d\\xb2\\xf3\\xe9\\xf7\\xcfag'\n\nSQLALCHEMY_DATABASE_URI = \\\n 'sqlite:////%s/data.sqlite' % op.join(dirname(abspath(__file__)))\n\n# default babel values\nBABEL_DEFAULT_LOCALE = 'en'\nBABEL_DEFAULT_TIMEZONE = 'UTC'\nACCEPT_LANGUAGES = ['en']\n\n# make sure that you have started debug mail server using command\n# $ make mail\n\nMAIL_SERVER = 'localhost'\nMAIL_PORT = 20025\nMAIL_USE_SSL = False\nMAIL_USERNAME = 'm@xen.ru'\n#MAIL_PASSWORD = 'topsecret'\n\n# github app data\nGITHUB_CONSUMER_KEY = '4a1a8295dacab483f1b5'\nGITHUB_CONSUMER_SECRET = 'ec494ff274b5a5c7b0cb7563870e4a32874d93a6'\n\nGITAUTH_LOGIN_LIST = ['offline', ]\n# flatpages\nFLATPAGES_EXTENSION = '.md'\nFLATPAGES_ROOT = op.join(op.dirname(op.realpath(__file__)), '..', 'docs')\nDATA_ROOT = op.join(op.dirname(op.realpath(__file__)), '..', 'data')\nDATA_URL = '/data/'\nROOT = op.join(op.abspath(op.dirname(op.realpath(__file__))), '..')\n\nHOOK_URL = 'http://bakery.fontforge.org/api/webhook/{id}'\n\n# Path to binary ot-sanitizer\nOTS_BINARY_PATH = os.path.join(ROOT, 'ots/out/Default/ot-sanitise')\nPYFTSUBSET_BINARY_PATH = 'pyftsubset'\n\ndel os\n","sub_path":"bakery/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"445558632","text":"from django.db import models\n\nclass Product(models.Model):\n name=models.CharField(max_length=400)\n price=models.FloatField()\n description=models.TextField()\n count=models.IntegerField()\n is_active=models.BooleanField()\n\n def to_json(self):\n return {\n 'id':self.id,\n 'name':self.name,\n 'price':self.price,\n 'description':self.description,\n 'count':self.count,\n 'is_active':self.is_active\n }\n\nclass Category(models.Model):\n name=models.CharField(max_length=400)\n def to_json(self):\n return {\n 'id':self.id,\n 'name':self.name\n }\n","sub_path":"lab8.2/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"435358189","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: wuyue\n@contact: wuyue92tree@163.com\n@software: IntelliJ IDEA\n@file: urls.py\n@create at: 2018-09-08 22:13\n\n这一行开始写关于本文件的说明与解释\n\"\"\"\n\nfrom django.urls import path, include\nfrom rest_framework import routers\nfrom .views import *\n\nrouter = routers.DefaultRouter()\nrouter.register('config', ConfigViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('get_process_list/', GetProcessListView.as_view()),\n path('process/', ProcessView.as_view()),\n]\n","sub_path":"rest_backend/apps/Supervisor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356258528","text":"from Token import Token\nfrom SyntacticCategory import Invalid\nfrom abc import ABCMeta, abstractmethod\nfrom ScannerGlobals import ScannerGlobals\nfrom ScannerGenerator import ScannerGenerator\n\n\nclass Scanner(object):\n \"\"\"\n\n \"\"\"\n\n __metaclass__ = ABCMeta #\n\n def __init__(self, dfa, token_type_table):\n \"\"\"\n\n \"\"\"\n self.__dfa = dfa\n self.__token_type_table = list(token_type_table)\n\n self.__classifier_table, self.__transition_matrix = ScannerGenerator.generate_scanner_tables(dfa)\n\n Scanner.__is_valid(self)\n\n def __str__(self):\n \"\"\"\n\n \"\"\"\n return_string = \"Deterministic Finite Automaton:\\n\" + str(self.dfa) + \"Token Type Table:\\n\"\n\n for index in range(len(self.token_type_table)):\n if index < len(self.token_type_table) - 1:\n return_string += \"State ID: \" + str(index) + \"\\nToken Type: \" + str(self.token_type_table[index])\n else:\n return_string += \"State ID: -1\\nToken Type: \" + str(self.token_type_table[index])\n\n return return_string\n\n def __hash__(self):\n \"\"\"\n\n \"\"\"\n return hash(str(self))\n\n def __eq__(self, other):\n \"\"\"\n\n \"\"\"\n return \\\n self.dfa.__eq__(other.dfa) and \\\n self.token_type_table.__eq__(other.token_type_table)\n\n def same_obj(self, other):\n \"\"\"\n\n \"\"\"\n return self is other\n\n @abstractmethod\n def initialize(self, input_stream):\n \"\"\"\n\n \"\"\"\n pass\n\n @abstractmethod\n def next_token(self):\n \"\"\"\n\n \"\"\"\n pass\n\n @property\n def dfa(self):\n \"\"\"\n\n \"\"\"\n return self.__dfa\n\n @dfa.setter\n def dfa(self, dfa):\n \"\"\"\n\n \"\"\"\n self.__dfa = dfa\n\n @property\n def token_type_table(self):\n \"\"\"\n\n \"\"\"\n return self.__token_type_table\n\n @token_type_table.setter\n def token_type_table(self, token_type_table):\n \"\"\"\n\n \"\"\"\n self.__token_type_table = list(token_type_table)\n\n @property\n def classifier_table(self):\n \"\"\"\n\n \"\"\"\n return self.__classifier_table\n\n @property\n def transition_matrix(self):\n \"\"\"\n\n \"\"\"\n return self.__transition_matrix\n\n @staticmethod\n def __check_token_type_table_validity(scanner):\n \"\"\"\n\n \"\"\"\n for index in range(len(scanner.token_type_table)):\n state = scanner.dfa.find_state(index)\n if state.is_accepting_state() and scanner.token_type_table[index].is_invalid():\n return False\n if not state.is_accepting_state() and not scanner.token_type_table[index].is_invalid():\n return False\n return True\n\n @staticmethod\n def __is_valid(scanner):\n \"\"\"\n\n \"\"\"\n if not Scanner.__check_token_type_table_validity(scanner):\n raise \\\n Exception(\n \" \".join(list([\n \"Input token type table is not valid!\",\n ScannerGlobals.ERROR_SUFFIX\n ]))\n )\n\n\nclass TableDrivenScanner(Scanner, object):\n \"\"\"\n\n \"\"\"\n def __init__(self, dfa, token_type_table, input_stream=str()):\n \"\"\"\n\n \"\"\"\n Scanner.__init__(self, dfa, token_type_table)\n\n self.__input_pos = 0\n self.__input_stream = str(input_stream)\n self.__initialized = not self.input_stream.__eq__(str())\n\n self.__failed = list([list([False for _ in range(len(self.input_stream) + 1)]) for _ in self.dfa.states])\n\n def initialize(self, input_stream):\n \"\"\"\n\n \"\"\"\n self.input_pos = 0\n self.input_stream = str(input_stream)\n\n self.failed = list([list([False for _ in range(len(self.input_stream) + 1)]) for _ in self.dfa.states])\n\n def next_token(self):\n \"\"\"\n\n \"\"\"\n lexeme = str()\n stack = list([tuple((None, 1))])\n current_state = self.dfa.initial_state\n\n while not current_state.is_error_state():\n if self.failed[current_state.state_id][self.input_pos]:\n current_state, self.input_pos = stack.pop()\n if self.input_pos < len(self.input_stream):\n lexeme = lexeme[:len(lexeme) - 1]\n break\n\n current_char = self.next_char()\n lexeme += str(current_char)\n\n if current_state.is_accepting_state():\n stack = list([tuple((None, 1))])\n\n stack.append(tuple((current_state, self.input_pos)))\n\n column_index = self.compute_transition_column_index(current_char)\n current_state = self.transition_matrix[current_state.state_id][column_index]\n\n self.input_pos += 1\n\n while not current_state.is_accepting_state():\n if not current_state.is_error_state():\n self.__failed[current_state.state_id][self.input_pos] = True\n\n current_state, self.input_pos = stack.pop()\n\n if self.input_pos < len(self.input_stream):\n lexeme = lexeme[:len(lexeme) - 1]\n\n if current_state is None:\n return Token(Invalid(ScannerGlobals.INVALID_CATEGORY), lexeme)\n\n if current_state.is_accepting_state():\n return Token(self.token_type_table[current_state.state_id], lexeme)\n\n def next_char(self):\n \"\"\"\n\n \"\"\"\n if self.input_pos < len(self.input_stream):\n return self.input_stream[self.input_pos]\n return str()\n\n def compute_transition_column_index(self, character):\n \"\"\"\n\n \"\"\"\n for column_index in range(len(self.classifier_table)):\n if character in self.classifier_table[column_index]:\n return column_index\n\n @property\n def input_pos(self):\n \"\"\"\n\n \"\"\"\n return self.__input_pos\n\n @input_pos.setter\n def input_pos(self, input_pos):\n \"\"\"\n\n \"\"\"\n self.__input_pos = input_pos\n\n @property\n def input_stream(self):\n \"\"\"\n\n \"\"\"\n return self.__input_stream\n\n @input_stream.setter\n def input_stream(self, input_stream):\n \"\"\"\n\n \"\"\"\n self.__input_stream = str(input_stream)\n\n @property\n def initialized(self):\n \"\"\"\n\n \"\"\"\n return not self.input_stream.__eq__(str())\n\n @property\n def failed(self):\n \"\"\"\n\n \"\"\"\n return self.__failed\n\n @failed.setter\n def failed(self, failed):\n \"\"\"\n\n \"\"\"\n self.__failed = list([list([element for element in row]) for row in failed])\n","sub_path":"Scanner/Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":6657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"223308459","text":"import io\nimport numpy as np\nimport random\n\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\nfrom config import MiningConfig\n\n\ndef split_training_dev_data(input_file_path,\n train_file_path,\n dev_file_path,\n index_label,\n test_size):\n X = []\n y = []\n header = None\n with io.open(input_file_path, 'r', encoding='utf-8') as f:\n for line in f:\n if line.startswith('ID\\t'):\n header = line\n continue\n X.append(line)\n y.append(line.strip().split('\\t')[index_label])\n\n X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=test_size, random_state=777, stratify=y)\n\n with io.open(train_file_path, 'w', encoding='utf-8') as f:\n if header:\n f.write(header)\n f.writelines(X_train)\n\n with io.open(dev_file_path, 'w', encoding='utf-8') as f:\n if header:\n f.write(header)\n f.writelines(X_val)\n\n print('saved.')\n\n\ndef split_training_dev_test_data(input_file_path,\n train_file_path,\n dev_file_path,\n test_file_path,\n index_label,\n test_size):\n X = []\n y = []\n header = None\n with io.open(input_file_path, 'r', encoding='utf-8') as f:\n for line in f:\n if line.startswith('ID\\t'):\n header = line\n continue\n X.append(line)\n y.append(line.strip().split('\\t')[index_label])\n\n X_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=test_size, random_state=777, stratify=y)\n X_train, X_dev, y_train, y_dev = train_test_split(X_train, y_train,\n test_size=test_size, random_state=777, stratify=y_train)\n\n with io.open(train_file_path, 'w', encoding='utf-8') as f:\n if header:\n f.write(header)\n f.writelines(X_train)\n\n with io.open(dev_file_path, 'w', encoding='utf-8') as f:\n if header:\n f.write(header)\n f.writelines(X_dev)\n\n with io.open(test_file_path, 'w', encoding='utf-8') as f:\n if header:\n f.write(header)\n f.writelines(X_test)\n\n print('saved.')\n\n\ndef prepare_fasttext_data(input_file_path, output_file_path, index_text, index_label, has_header):\n print('reading from %s' % input_file_path)\n print('saving to %s' % output_file_path)\n with open(input_file_path, encoding='utf-8') as f_in, \\\n open(output_file_path, 'w', encoding='utf-8') as f_out:\n if has_header:\n next(f_in)\n for line in f_in:\n line = line.strip().split('\\t')\n text = line[index_text]\n label = line[index_label]\n ft_label = '__label__' + label\n\n f_out.write(text + '\\t' + ft_label + '\\n')\n print('saved.')\n\n\ndef prepare_cv_data(x, y, n_fold,\n train_path, dev_path, test_path,\n clean_text):\n\n x = np.array(x)\n y = np.array(y)\n\n skf = StratifiedKFold(n_splits=n_fold)\n\n index = 1\n for train_index, test_index in skf.split(x, y):\n x_train, x_test = x[train_index], x[test_index]\n y_train, y_test = y[train_index], y[test_index]\n\n x_train, x_dev, y_train, y_dev = train_test_split(x_train, y_train,\n test_size=0.1, random_state=42,\n stratify=y_train)\n\n assert len(x_train) == len(y_train)\n assert len(x_dev) == len(y_dev)\n assert len(x_test) == len(y_test)\n\n n_train = len(x_train)\n with open(train_path + '%s.txt' % index, 'w', encoding='utf-8') as f:\n for i in range(n_train):\n f.write(y_train[i] + '\\t' + clean_text(x_train[i], remove_hashtag=True) + '\\n')\n print('Saved %s to %s.' % (n_train, train_path + '%s.txt' % index))\n\n n_dev = len(x_dev)\n with open(dev_path + '%s.txt' % index, 'w', encoding='utf-8') as f:\n for i in range(n_dev):\n f.write(y_dev[i] + '\\t' + clean_text(x_dev[i], remove_hashtag=True) + '\\n')\n print('Saved %s to %s.' % (n_dev, dev_path + '%s.txt' % index))\n\n n_test = len(x_test)\n with open(test_path + '%s.txt' % index, 'w', encoding='utf-8') as f:\n for i in range(n_test):\n f.write(y_test[i] + '\\t' + clean_text(x_test[i], remove_hashtag=True) + '\\n')\n print('Saved %s to %s.' % (n_test, test_path + '%s.txt' % index))\n index += 1\n\n\ndef sample_data(input_file_path, output_file_path, ratio):\n print(input_file_path)\n print(output_file_path)\n\n with open(input_file_path) as f:\n lines = f.readlines()\n\n samples = random.sample(lines, int(len(lines) * ratio))\n\n with open(output_file_path, 'w', encoding='utf-8') as f:\n f.writelines(samples)\n print('done')\n\n\nif __name__ == '__main__':\n ratio = 0.75\n for fold in ['1', '2', '3', '4', '5']:\n sample_data(input_file_path=MiningConfig.rc_train_fold_path % 'mining3' + '%s.txt' % fold,\n output_file_path=MiningConfig.rc_train_fold_path % 'mining3' + '%s_%s.txt' % (fold, ratio),\n ratio=ratio)\n","sub_path":"data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"170061216","text":"# -*- coding: utf-8 -*-\nimport math\n\nfrom ps_code.ml_components.optim.learning import get_lr_scheduler\n\n\ndef define_lr_scheduler(args):\n return _define_lr_scheduler(args)\n\n\ndef adjust_learning_rate(args, optimizer, lr_scheduler):\n \"\"\"Sets the learning rate to the initial LR decayed by # of accessed sample\n We should decay the learning rate based on the number of samples that\n we have accessed.\n \"\"\"\n # adjust and assign learning rate.\n lr = lr_scheduler(args.epoch_)\n\n # adjust the lr with the local updates\n lr = adjust_lr_within_local_updates(args, lr)\n\n if lr is None:\n lr = args.old_learning_rate\n\n if args.old_learning_rate != lr:\n args.old_learning_rate = lr\n update_lr(optimizer, lr)\n\n\ndef update_lr(optimizer, lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef adjust_lr_within_local_updates(args, lr):\n # NOTE: a dirty lr scheduler\n # NOTE: without considering local step warmup.\n # NOTE: not sure the effect of lr warmup.\n def get_step():\n if args.local_index % args.local_step == 0:\n step = args.local_step\n else:\n step = args.local_index % args.local_step\n return step\n\n if args.lr_local_cycle is None or \\\n (args.lr_warmup and args.epoch_ < args.lr_warmup_epochs and\n args.lr_local_cycle_nodecay_on_warmup):\n return lr\n else:\n # get learning rate for cyclic local update steps.\n local_step = args.local_step\n lr_cur_min = max(\n lr / args.graph.n_workers,\n lr / local_step\n if args.lr_local_cycle_decay_factor is None\n else lr / args.lr_local_cycle_decay_factor\n )\n lr_gap = lr - lr_cur_min\n\n if 'cosine' in args.lr_local_cycle:\n return lr_cur_min + 1. / 2 * lr_gap * (\n 1 + math.cos((get_step() - 1) * math.pi / (local_step - 1))\n )\n elif 'linear' in args.lr_local_cycle:\n return lr - lr_gap * (get_step() - 1) / (local_step - 1)\n elif 'step' in args.lr_local_cycle:\n if get_step() == 1:\n return lr\n else:\n return lr_cur_min\n\n\ndef _define_lr_scheduler(args):\n # get the learning rate per sample.\n args.learning_rate_per_samples = args.lr / args.base_batch_size\n\n # get a valid learning rate.\n args.init_warmup_lr = args.lr\n\n if args.lr_scaleup:\n if args.lr_scaleup_type == 'linear':\n _lr = args.learning_rate_per_samples * args.batch_size\n _scale = args.graph.n_workers\n elif args.lr_scaleup_type == 'sqrt':\n _lr = args.lr\n _scale = (\n 1. * args.graph.n_workers * args.batch_size /\n args.base_batch_size) ** 0.5\n else:\n raise NotImplementedError\n args.learning_rate = _lr * _scale\n else:\n _lr = args.learning_rate_per_samples * args.batch_size\n _scale = 1\n args.learning_rate = _lr * _scale\n\n # just backup the current learning rate.\n args.old_learning_rate = args.learning_rate\n\n # define the learning rate scheduler.\n lr_scheduler = get_lr_scheduler(args)\n return lr_scheduler\n","sub_path":"frameworks/sync-pytorch-ps/ps_code/ml_components/create_scheduler.py","file_name":"create_scheduler.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605825570","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn.metrics import *\nfrom scipy.optimize import minimize\n\ndef obj_function(w,Mi,ai,regcoef1,regcoef2):\n J = -1*np.dot(w.T, ai) + regcoef1*np.dot(np.dot(w.T, Mi), w) + regcoef2*(np.linalg.norm(w, ord=2, keepdims=True))**2\n return J\n\ndef con():\n cons = ({'type': 'eq', 'fun': lambda w:sum(w)-1}, {'type': 'ineq', 'fun': lambda w:w})\n return cons\n\ndef optimize_weights(x0, fun):\n res = minimize(fun, x0, method='SLSQP')\n return res.x\n\ndef hsic_kernel_weights_norm(Kernels_list, adjmat,dim, regcoef1, regcoef2):\n adjmat = np.array(adjmat)\n\n num_kernels = np.size(Kernels_list, 0)\n weight_v = np.zeros((num_kernels, 1))\n y = adjmat\n\n # Graph based kernel\n if dim == 1:\n ideal_kernel = np.dot(y, y.T)\n else:\n ideal_kernel = np.dot(y.T, y)\n\n # ideal_kernel=Knormalized(ideal_kernel)\n # print(type(ideal_kernel))\n N_U = np.size(ideal_kernel, 0)\n l = np.ones((N_U, 1))\n H = np.eye(N_U, dtype=float) - np.dot(l, l.T)/N_U # H:NxN的矩阵\n\n M = np.zeros((num_kernels, num_kernels))\n for i in range(num_kernels):\n for j in range(num_kernels):\n kk1 = np.dot(np.dot(H, Kernels_list[i, :, :]), H)\n kk2 = np.dot(np.dot(H, Kernels_list[j, :, :]), H)\n mm = np.trace(np.dot(kk1.transpose(), kk2))\n m1 = np.trace(np.dot(kk1, kk1.transpose()))\n m2 = np.trace(np.dot(kk2, kk2.transpose()))\n M[i, j] = mm / (np.sqrt(m1) * np.sqrt(m2))\n d_1 = sum(M)\n D_1 = np.diag(d_1)\n LapM = D_1 - M\n\n a = np.zeros((num_kernels, 1))\n for i in range(num_kernels):\n kk = np.dot(np.dot(H, Kernels_list[i, :, :]), H)\n aa = np.trace(np.dot(kk.transpose(), ideal_kernel))\n a[i] = aa*((N_U-1)**-2)\n\n v = np.random.rand(num_kernels, 1)\n falpha = lambda v:obj_function(v, LapM, a, regcoef1, regcoef2)\n x_alpha = optimize_weights(v, falpha)\n weight_v = x_alpha\n return weight_v\n\ndef line_map(X):\n col_X = np.size(X, 1)\n Mapping_X = []\n for i in range(col_X):\n col_v = (X[:, i] - X[:, i].min()) / float(X[:, i].max() - X[:, i].min())\n Mapping_X.append(col_v)\n Mapping_X = np.array(Mapping_X)\n Mapping_X = Mapping_X.T\n return Mapping_X\n\ndef combine_kernels(weights, kernels):\n result = np.zeros(kernels[1, :, :].shape)\n n = len(weights)\n for i in range(n):\n result = result + weights[i] * kernels[i, :, :]\n return result\n\ndef kernel_RBF(X, Y, gamma):\n r2 = np.tile(np.sum(X**2, 1), (np.size(Y, 0),1)).T + np.tile(np.sum(Y**2, 1), (np.size(X, 0), 1)) - 2 * np.dot(X, Y.T)\n k = np.exp(-r2 * gamma)\n return k\n\ndef skl_mk_svm(train_x,feature_id,train_y,test_x,test_y,c,gamma_list):\n predict_y = []\n Scores = []\n kernel_weights = []\n m = int(len(feature_id) / 2)\n num_train_samples = np.size(train_x, 0)\n num_test_samples = np.size(test_x, 0)\n #1.computer training and test kernels (with RBF)\n K_train = []\n K_test = []\n for i in range(m):\n kk_train = kernel_RBF(train_x[:, feature_id[2*i]:feature_id[2*i+1]], train_x[:, feature_id[2*i]:feature_id[2*i+1]], gamma_list[i])\n K_train.append(kk_train)\n\n kk_test = kernel_RBF(test_x[:, feature_id[2*i]:feature_id[2*i+1]], train_x[:, feature_id[2*i]:feature_id[2*i+1]], gamma_list[i])\n K_test.append(kk_test)\n\n K_train = np.array(K_train) #这时K_train是三维矩阵了\n K_test = np.array(K_test) #这时K_test是三维矩阵了\n\n # 2.multiple kernel learning\n kernel_weights = hsic_kernel_weights_norm(K_train, train_y, 1, 0.1, 0.01)\n # kernel_weights = np.ones((m, 1))\n # kernel_weights = kernel_weights / m\n kernel_weights = kernel_weights.reshape(m,).tolist()\n print(kernel_weights)\n\n K_train_com = combine_kernels(kernel_weights, K_train)\n K_test_com = combine_kernels(kernel_weights, K_test)\n\n K_train_com.tolist()\n K_test_com.tolist()\n # 3.train and test model\n # K_train_com = np.insert(K_train_com, 0, [j for j in range(1, num_train_samples+1)], axis=1)\n # cg_str = ['-t 4 -c '+ str(c)+' -b 1 -q']\n train_y = train_y.reshape(len(K_train_com),).tolist()\n clf = svm.SVC(C=c,kernel='precomputed')\n clf.fit(K_train_com, train_y)\n # K_test_com = np.insert(K_test_com, 0, [j for j in range(1, num_test_samples+1)], axis=1)\n y_pred = clf.predict(K_test_com)\n precision = precision_score(test_y, y_pred, average=\"weighted\")\n return y_pred, precision","sub_path":"ml/multi_kernel_svm.py","file_name":"multi_kernel_svm.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"134734442","text":"# weather_rev2.py controller\nfrom flask import Flask, render_template\nimport sqlite3\nfrom weather_crawling_rev2 import total_air_quality, update_time\n\napp = Flask(__name__)\n \n@app.route('/')\n@app.route('/weather')\ndef weather() -> 'html':\n\tplace = \"논현동 air quality information\" \n\tair_pm = total_air_quality()[0]\n\tupdate = update_time()[0]\n\tcom_dict = {update:air_pm}\n\tdef db_connect():\n\t\twith sqlite3.connect(\"naverPM.db\") as connection:\n\t\t\tc = connection.cursor()\n\t\t\tc.execute(\"\"\"INSERT INTO partculate(particulate_matter) values (%s)\"\"\", comdict['05.18 19:00'])\n\treturn render_template('weather.html', place = place, air_pm = air_pm, update_time = update)\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n\n","sub_path":"testFiles/weather_rev2.py","file_name":"weather_rev2.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"161413170","text":"import numpy as np\n\nclass KMeans():\n #Class to compute the kmeans clustering of given dataset.\n\n def __init__(self):\n #Class initialization method\n pass\n def __distance(self,v,w):\n #Method to calculate the distance between two vectors\n #Inputs:\n # v,w -> 2 1D vectors\n #Outputs:\n # d -> euclidean distance between the two vectors v and w\n mag = v - w #Magnitude of distance between data points in each dimension\n dist = np.sum(mag*mag,axis=1)**0.5 #Vectorized implementation of distance calculation\n dist = dist.reshape((len(dist),1))\n return dist\n #Return value is a scalar value that signifies the distance between the two vectors.\n\n def __partitionData(self,data,centroids):\n #Method to partition data into the respective clusters signified by the centroids by computing the distance between\n #the data points and the cluster centroids. A data point belongs to the cluster when the distance between it and the\n #centroid point for that cluster is the least among the distance with all other clusters.\n #Inputs:\n # data -> Input data\n # centroids -> Cluster centroids\n #Outputs:\n # clusters -> computed centroids of the new clusters\n k = len(centroids) #Storing the number of centroids\n (m,n) = data.shape\n clusters = np.empty((m,1))\n c = []\n for i in range(k):\n c.append([]) #Initializing a array datastructure to store cluster data points\n clusters = np.concatenate((clusters,\n self.__distance(data,centroids[i])),axis=1) #Computing the distance wrt each cluster and creating a matrix\n index = clusters[:,1:].argmin(axis=1).transpose() #Determining the cluster with least distance for each data point\n #Rearranging the data points according to the determined clusters\n for i in range(m):\n c[index[i]].append(data[i])\n clusters = np.array([np.array(cluster) for cluster in c]) #Converting the clusters into a numpy array\n return clusters\n\n def __centroids(self,clusters):\n #Methods to compute the centroids from the clusters.\n #Inputs:\n # clusters -> Clustered Data\n #Outputs:\n # centroids -> Cluster centroids\n centroids = []\n for i in range(len(clusters)): #Iterating over each cluster\n centroids.append(np.mean(clusters[i],axis=0)) #Computing the centroids of the cluster\n centroids = np.array(centroids) #Converting the centroids list to a numpy array\n return centroids\n\n def __identical(self,c1,c2):\n #Method to check if two centroids are identical\n #Inputs:\n # c1,c2 -> Centroids which are to be checked for identicalness\n #Outputs:\n # Boolean -> A boolean value indicating whether the centroids are identical or not.\n if sum(c1.flatten() == c2.flatten()) == c1.size: #sum of true values(1) compared with size of centroids\n return True #Centroids are identical if sum of true values is equal to size\n #Implies that all elements are the same in both the centroids\n return False #Return false if the sum is not equivalent to the size.\n #Implies that one or more of the elements are different\n\n def cluster(self,data,number):\n #Method to perform clustering of the given dataset into the mentioned number of clusters\n #Inputs:\n # data -> Input data\n # number -> Number of clusters the data has to be partitioned into\n #Outputs:\n # clusters -> Clustered Data.\n np.random.shuffle(data) #Shuffling data randomly before clustering\n centroids = [] #List to store the centroids\n for i in range(number):\n centroids.append(data[i]) #Initializing the initial cluster centroids\n centroids = np.array(centroids) #Converting the list to a numpy array list\n flag = False #Initializing loop flag to False. flag signifies if two computed\n #centroids are identical\n while not flag: #Iterate till the centroids are not identical\n c = centroids #Making a copy of centroids for later comparision\n clusters = self.__partitionData(data,centroids) #Parititioning data into clusters\n centroids = self.__centroids(clusters) #Computing the centroids of the clusters\n flag = self.__identical(c,centroids) #Updating the flag about the identicalness of the two centroids\n return [clusters,centroids] #Returning the clusters and centroids obtained by K-Means Clustering\n","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"271433526","text":"from cmd import Cmd\nfrom prettytable import PrettyTable\nfrom termcolor import colored\nfrom pygments import highlight\nfrom pygments.lexers import JsonLexer, PythonLexer\nfrom pygments.formatters import TerminalFormatter\n\nfrom process import formatResponse, formatValue, getConfig, requestInput, filterData\nfrom schema import Schema\n\nimport json, enum\n\nclass DisplayType(enum.Enum):\n TABLE = 1\n JSON = 2\n\ndef searchProcess(schema, inp, displayType):\n p = inp.split(':') if inp != '' else []\n if len(p) == 0:\n table = requestInput(\"Enter table: \", [\"Unsupported table\", \"List table: \\n {}\".format(schema.tables)], schema.tables)\n p.append(table)\n table, args = p[0].lower(), p[1].split('=') if len(p) > 1 else []\n if table not in schema.tables:\n print(\"Unsupported table!\")\n return\n result = []\n if len(args) < 2:\n if len(args) == 1:\n print(\"Search filter is invalid: (Format searchfield=searchvalue)\")\n args = []\n field = requestInput(\"Enter search field: \", [\"Unsupport search field\", \"List {}'s search field: \\n {}\".format(table, schema.searchField[table])], schema.searchField[table])\n args.append(field)\n value = requestInput(\"Enter search value: \")\n args.append(value)\n else:\n if args[0] not in schema.searchField[table]:\n args = []\n print(\"Unsupport search field!\")\n field = requestInput(\"Enter search field: \", [\"Unsupport search field\", \"List {}'s search field: \\n {}\".format(table, schema.searchField[table])], schema.searchField[table])\n args.append(field)\n value = requestInput(\"Enter search value: \")\n args.append(value)\n elif len(args) == 1:\n value = requestInput(\"Enter search value: \")\n args.append(value)\n schemaMap = schema.dataMap[table]\n result = filterData(schemaMap, args[0], args[1])\n if len(result) == 0:\n print(\"No result found\")\n else:\n if displayType == DisplayType.TABLE:\n displayConfig = globalConfig['display']\n t = PrettyTable(map(lambda x: colored(x['label'].upper(), 'green'), displayConfig[table]))\n for r in result:\n t.add_row([\"\" if key not in r else formatValue(r[key], 15) if type(r[key]) != list else formatValue(', '.join(r[key]), 15) for key in map(lambda x: x['key'], displayConfig[table])])\n print(t)\n else:\n jsonRaw = json.dumps(formatResponse(result), indent=4, sort_keys=True)\n print(highlight(jsonRaw, JsonLexer(), TerminalFormatter()))\n\nclass MyPrompt(Cmd):\n prompt = '> '\n intro = \"Welcome! Type ? to list commands\"\n schema = Schema()\n\n def do_exit(self, inp):\n print(\"Bye\")\n return True\n def help_exit(self):\n print('exit the application. Shorthand: x q Ctrl-D.')\n def do_describe(self, inp):\n if inp not in self.schema.tables:\n print(colored(\"Unsupported table\", \"red\"))\n print(colored(\"List table: \\n\", 'yellow'))\n for t in self.schema.tables:\n print(colored(t, 'green'))\n print('\\n')\n return\n print(colored(\"List search fields: \\n\", \"yellow\"))\n for t in self.schema.searchField[inp]:\n print(colored(t, 'green'))\n print('\\n')\n def help_describe(self):\n print('list [table] searchable field, command: describe [table-name]')\n def do_search(self, inp):\n searchProcess(self.schema, inp, DisplayType.JSON)\n def help_search(self):\n print('search [table] record by filter, return by JSON. command: search [table-name]:[filter-field]=[filter-value]')\n def do_table(self, inp):\n searchProcess(self.schema, inp, DisplayType.TABLE)\n def help_table(self):\n print('search [table] record by filter, return tabular view. command: table [table-name]:[filter-field]=[filter-value]')\n def default(self, inp):\n if inp == 'x' or inp == 'q':\n return self.do_exit(inp)\n \n print(\"Command {} not found\".format(inp))\n \n do_EOF = do_exit\n help_EOF = help_exit\n \nif __name__ == '__main__':\n global globalConfig\n globalConfig = getConfig()\n app = MyPrompt()\n app.cmdloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"538471924","text":"\"\"\"\r\nfile: spirograph.py\r\nlanguage: python3\r\nauthor: mal3941@g.rit.edu Moisés Lora Pérez\r\nclass: CSCI 141-03\r\ndescription: This program draws a spirograph iteratively given a p which equates to the value of the offset of the pen\r\npoint in the moving circle\".\r\n\"\"\"\r\nfrom math import *\r\nfrom turtle import *\r\n\r\ndef drawSpirograph(p,t,r,R):\r\n \"\"\"\r\n In this function, the turtle is assigned to a position (x,y) which coordinates correspond to the values of x and y\r\n obtained with the formula denoted below.\r\n :param p: The offset of the pen point in the moving circle\r\n :param t: The iteration between 2*PI and 0, in intervals of -0.01\r\n :param r: The radius of the moving circle\r\n :param R: The radius of the fixed circle\r\n \"\"\"\r\n #The formulas below determine the equation of the curve\r\n x= (R-r)*cos(t) - (r+p)*cos((R-r)/r*t)\r\n y= (R-r)*sin(t) - (r+p)*sin((R-r)/r*t)\r\n #Moves the turtle to the position of x and y at the current point of iteration.\r\n goto(x,y)\r\n\r\ndef main():\r\n \"\"\"\r\n In this function the values of R,r and t are assigned, while p is inputed by the user. The function then proceeds\r\n to iterate the values of t at intervals of -0.01 until they are less than 0 while at the same times drawing the\r\n curves that form the spirograph.\r\n Pre-Condition: The drawing starts at the turtle's initial position.\r\n Post-Condition: The turtle then draws curves until it reaches back to it's initial position.\r\n \"\"\"\r\n p = int(input(\"Enter an integer value for p:\"))\r\n if 10 <= p <= 100:\r\n R = 100\r\n r=4\r\n t =2*pi\r\n up()\r\n drawSpirograph(p,t,r,R)\r\n down()\r\n while t>0:\r\n drawSpirograph(p,t, r, R)\r\n t-=0.01\r\n\r\n else:\r\n print(\"Incorrect value for p!\")\r\n\r\n#this executes the program\r\nmain()\r\n#this asks the user for termination\r\ninput(\"Hit enter to close...\")\r\n","sub_path":"Computer Science 1/Homeworks/hw2/spirograph.py","file_name":"spirograph.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"31570380","text":"import torch\nfrom functions import gen_data, preprocessing, get_params\nfrom net import Net\n\nfrom matplotlib import pyplot as plt\n\nnet = Net()\nprint(\"Net ready, creating training set\")\n\nepochs = 5000\ntrain_size = 5000\nval_size = 50\n\n#VALEURS\nparams = get_params()\narange,brange,pop,n,T = params\n\n#TRAINING SET\ntrain_data,train_labels = gen_data(arange,brange,pop,n,T,train_size) #data,labels = infected curve(array), (a,b)\np_train_data, p_train_labels = preprocessing(train_data,train_labels,params) #p_data, p_labels = preprocesed data/labels : (max,max position,max delta,average) and normalized a and b\ntrain_inputs, train_targets = torch.tensor(p_train_data).float(), torch.tensor(p_train_labels).float() #inputs, labels = pytroch tensors for p_data and p_labels\nprint(\"Train set ready\")\n\n#VALIDATION SET\nval_data,val_labels = gen_data(arange,brange,pop,n,T,val_size)\np_val_data, p_val_labels = preprocessing(val_data,val_labels,params)\nval_inputs, val_targets = torch.tensor(p_val_data).float(), torch.tensor(p_val_labels).float()\nprint(\"Validation set ready.\")\n\ncriterion = torch.nn.MSELoss() #Loss function\n\nlr = 0.2\nopt = torch.optim.SGD(net.parameters(), lr=lr)\nprint(\"Starting training\")\nfor i in range(epochs):\n opt.zero_grad()\n outputs=net(train_inputs)\n loss = criterion(outputs,train_targets)\n loss.backward()\n opt.step()\n if (i+1)%10 == 0:\n loss = criterion(net(val_inputs),val_targets).item()\n print(\"{}/{} : {}\".format(i+1,epochs,loss))\nprint(\"Training finished.\")\ntorch.save(net.state_dict(), \"model\")\nprint(\"Model saved.\")","sub_path":"pytorch/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70632375","text":"from PIL import Image, ImageDraw, ImageFilter, ImageEnhance, ImageFont, ImageDraw, ImageOps\n\n\ndef suggar_num_to_str(suggar):\n if suggar < 18:\n suggar_str = 'sausas'\n elif suggar < 31.5:\n suggar_str = 'pusiau sausas'\n elif suggar < 45:\n suggar_str = 'pusiau saldus'\n else:\n suggar_str = 'saldus'\n\n return suggar_str\n\n\ndef suggar_num_to_str_en(suggar):\n if suggar < 18:\n suggar_str = 'dry '\n elif suggar < 31.5:\n suggar_str = 'off-dry '\n elif suggar < 45:\n suggar_str = 'semi-sweet'\n else:\n suggar_str = 'sweet'\n\n return suggar_str\n\n\ndef find_middle(im, text, font):\n draw = ImageDraw.Draw(im)\n w, h = draw.textsize(text, font=font)\n return int(w/2)\n\n\ndef generate_label(title1, title2, number_alcohol, number_years, number_sweetness, color_var, color_val2):\n number_alcohol = \"alc. \" + str(round(number_alcohol, 1)) + \" % by Vol.\"\n number_sweetness = str(number_sweetness)\n number_years = str(number_years)\n\n font_size = 25 * 2 + 10\n font_offset = 20\n font_color = color_val2\n # print(font_color)\n # font_color = 'rgb(0, 0, 0)'\n font = ImageFont.truetype('fonts/Montserrat-Bold.otf', size=font_size)\n font_regular = ImageFont.truetype('fonts/Montserrat-Regular.otf', size=int(font_size / 1.2))\n font_italic = ImageFont.truetype('fonts/Montserrat-Italic.otf', size=int(font_size / 1.5))\n\n # img = Image.new(mode=\"RGB\", size=(int(1240/5-12), int(1754/5-12)), color=(227, 194, 127))\n\n # img = Image.new(mode=\"RGB\", size=(int(1240 / 5 - 12), int(1754 / 5 - 12)), color=(255, 255, 255))\n\n img = Image.new(mode=\"RGB\", size=(int(2480 / 5 - 12), int(3508 / 5 - 12)), color=color_var)\n\n basewidth = 150\n img_temp = Image.open(\"static/img/bird2.png\")\n wpercent = (basewidth / float(img_temp.size[0]))\n hsize = int((float(img_temp.size[1]) * float(wpercent)))\n img_temp = img_temp.resize((basewidth, hsize), Image.ANTIALIAS)\n img.paste(img_temp, (int(2480 / 5 - 170), int(3508 / 5 - 300)))\n\n\n\n\n x, y = img.size\n\n draw = ImageDraw.Draw(img)\n\n if find_middle(img, title1, font) * 2 < x - 10:\n draw.text((x / 2 - find_middle(img, title1, font), 2 / 6 * y - 1 * font_size), title1, fill=font_color, font=font)\n else:\n w = find_middle(img, title1, font) * 2\n font_temp = ImageFont.truetype('fonts/Montserrat-Bold.otf', size=int(font_size * (x - 10) / w))\n draw.text((x / 2 - find_middle(img, title1, font_temp), 2 / 6 * y - 1 * font_size), title1, fill=font_color,\n font=font_temp)\n\n if find_middle(img, title2, font_regular) * 2 < x - 10:\n draw.text((x / 2 - find_middle(img, title2, font_regular), 3 / 6 * y - 0.5 * font_size),\n title2, fill=font_color, font=font_regular)\n else:\n w = find_middle(img, title2, font_regular) * 2\n font_regular_temp = ImageFont.truetype('fonts/Montserrat-Regular.otf', size=int(((font_size * (x - 10) / w)) / 1.2))\n draw.text((x / 2 - find_middle(img, title2, font_regular_temp), 3 / 6 * y - 0.5 * font_size),\n title2, fill=font_color, font=font_regular_temp)\n\n\n\n\n draw.text((x / 2 - find_middle(img, number_years, font_regular), 4 / 6 * y - 0.5 * font_size),\n number_years, fill=font_color, font=font_regular)\n draw.text((x / 2 - find_middle(img, number_sweetness, font_italic), 5 / 6 * y - 0.5 * font_size),\n number_sweetness, fill=font_color, font=font_italic)\n draw.text((x / 2 - find_middle(img, number_alcohol, font_italic), 5 / 6 * y + 0.5 * font_size),\n number_alcohol, fill=font_color, font=font_italic)\n\n img = ImageOps.expand(img, border=6, fill='black')\n # img = ImageOps.expand(img, border=3, fill='white')\n\n if 1==1:\n img_multy = Image.new(\"RGB\", (2480, 3508))\n for i in range(0, 5):\n for j in range(0, 5):\n img_multy.paste(img, (i * int(2480 / 5), j * int(3508 / 5)))\n img_multy.paste(img, (i * int(2480 / 5), j * int(3508 / 5)))\n img_multy.paste(img, (i * int(2480 / 5), j * int(3508 / 5)))\n img_multy.paste(img, (i * int(2480 / 5), j * int(3508 / 5)))\n img_multy.paste(img, (i * int(2480 / 5), j * int(3508 / 5)))\n\n return img_multy\n # return img\n","sub_path":"label_pil_2.py","file_name":"label_pil_2.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"456088078","text":"num = int(input(\"Enter the number of students: \"))\r\nx = {}\r\n\r\nfor i in range(num):\r\n name = input(\"Enter name: \")\r\n score = int(input(\"Enter {0}'s score: \".format(name)))\r\n x[score] = name\r\n\r\nprint(x[max(x)], \"has a highest score of\", max(x))\r\nx.pop(max(x))\r\nprint(x[max(x)], \"has a second highest score of\", max(x))\r\n\r\n\r\n","sub_path":"practical2/q08_top2_scores.py","file_name":"q08_top2_scores.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"190344091","text":"# Python | Remove leading zeros from an IP address\n# Given an IP address, remove leading zeros from the IP address.\n\ndef RemoveLeadingZeros(s1):\n\n lst=s1.split('.')\n\n fnl_lst=[]\n tmp_lst=[]\n for l in lst:\n\n tmp=list(l)\n tmp_lst=[]\n flg=True\n for k in tmp:\n\n if flg==True and k=='0':\n continue\n else:\n tmp_lst.append(k)\n flg=False\n fnl_lst.append(''.join(tmp_lst))\n\n return '.'.join(fnl_lst)\n\ndef main():\n\n s1='100.020.003.400'\n print(RemoveLeadingZeros(s1))\n\n s1 = '001.200.001.004'\n print(RemoveLeadingZeros(s1))\n\n\nif __name__=='__main__':\n main()","sub_path":"python/CodingExercises/RemoveLeadingZeros.py","file_name":"RemoveLeadingZeros.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279527846","text":"#Reformat the coach info\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\nnum = 'test'\r\ncoach = pd.read_csv(\"coaches.csv\", low_memory=False)\r\ncoach['Year'] = coach['Year'].fillna(method='ffill')\r\ncoach = coach.loc[coach['Year'] >= 2012]\r\ncoach = coach.iloc[::-1]\r\ncoach.to_csv('coaches3.csv') \r\ncoach['Week'] = 0\r\ncoach2 = pd.DataFrame()\r\nsYear = []\r\ni = 0\r\nweeks=0\r\n#coach = coach.groupby(coach.columns.tolist(),as_index=False).size()\r\nfor index, season in coach.iterrows():\r\n sYear.append(season)\r\n #weeks = 0\r\n #print(\"!\")\r\n \r\n while i < len(sYear):\r\n #print(sYear[i])\r\n weeks+=sYear[i]['G']\r\n #print(weeks)\r\n i+=1\r\n #print(weeks)\r\n if weeks == 16:\r\n game = 0\r\n i = 0\r\n while i < len(sYear):\r\n for week in range(sYear[i]['G']):\r\n game = game +1\r\n if(game == 12):\r\n d = {}\r\n d['Year'] = sYear[i]['Year']\r\n d['Coach'] = sYear[i]['Coach']\r\n d['Offense'] = sYear[i]['Offense']\r\n d['Defense'] = sYear[i]['Defense']\r\n d['Team'] = sYear[i]['Team']\r\n d['Week'] = game\r\n coach2 = coach2.append(pd.Series(d, index=['Year', 'Coach', 'Offense', 'Defense', 'Team', 'Week']), ignore_index=True)\r\n game+=1\r\n #print(season)\r\n d = {}\r\n #print(i)\r\n d['Year'] = sYear[i]['Year']\r\n d['Coach'] = sYear[i]['Coach']\r\n d['Offense'] = sYear[i]['Offense']\r\n d['Defense'] = sYear[i]['Defense']\r\n d['Team'] = sYear[i]['Team']\r\n d['Week'] = game\r\n coach2 = coach2.append(pd.Series(d, index=['Year', 'Coach', 'Offense', 'Defense', 'Team', 'Week']), ignore_index=True)\r\n i+=1\r\n i = 0\r\n sYear = []\r\n weeks = 0\r\n\r\n \r\ncoach2.to_csv('coaches2.csv') \r\n \r\n ","sub_path":"addCoaches.py","file_name":"addCoaches.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53499088","text":"# -*- coding: utf-8 -*-\n# KMP 串匹配算法\n\n\ndef genPnext(p):\n \"\"\" 生成针对 p 中个位置 i 的下一检查位置表,用于 KMP 算法 \"\"\"\n\n i, k, m = 0, -1, len(p)\n pnext = [-1] * m # 初始数组元素全为 -1\n while i < m-1: # 生成下一个(即:i+1) pnext 元素值\n if k == -1 or p[i] == p[k]:\n i, k = i+1, k+1\n pnext[i] = k # 设置 pnext 元素\n else:\n k = pnext[k] # 退到更短的前缀\n return pnext\n\n\ndef genPnextEnhancement(p):\n \"\"\" 生成针对 p 中个位置 i 的下一检查位置表,用于 KMP 算法 \"\"\"\n\n i, k, m = 0, -1, len(p)\n pnext = [-1] * m\n while i < m-1: # 生成下一个(即:i+1) pnext 元素值\n if k == -1 or p[i] == p[k]:\n i, k = i+1, k+1\n if p[i] == p[k]:\n pnext[i] = pnext[k]\n else:\n pnext[i] = k\n else:\n k = pnext[k] # 退到更短的前缀\n return pnext\n\n\ndef KMPMatching(t, p, pnext):\n \"\"\" KMP 串匹配算法主函数 \"\"\"\n\n i, j = 0, 0\n m, n = len(p), len(t)\n while i 'Atom':\n return self._Residues[resid][name]\n\n def GetAtomIdx(self, atom):\n for k, v in self._Atoms.items():\n if atom == v:\n return k\n\n def ReadFromPdb(self, fname):\n self._Residues = dict()\n self._Atoms = dict()\n\n with open(fname, \"r\") as file:\n for line in file.readlines():\n data_type = line[0:6].strip()\n if data_type not in ['ATOM', 'HETATM']:\n continue\n atom = Atom()\n atom.DataType = line[0:6].strip()\n atom.Name = line[12:16].strip()\n atom.AltLoc = line[16].strip()\n atom.ResName = line[17:20].strip()\n atom.ChainId = line[21].strip()\n atom.ResSeq = int(line[22:26])\n atom.ResCode = line[26].strip()\n atom.Coordinate = np.array(list(map(float, [line[30:38], line[38:46], line[46:54]])))\n atom.Occup = 0.0 # float(line[54:60])\n atom.Tempfac = 0.0 # float(line[60:66])\n atom.Element = atom.Name[0] # line[76:78].strip()\n num = int(line[6:11])\n\n if atom.ResSeq not in self._Residues:\n self._Residues[atom.ResSeq] = dict()\n\n self._Residues[atom.ResSeq][atom.Name] = atom\n self._Atoms[num] = atom\n\n def SaveToPdb(self, fname):\n with open(fname, \"w\") as f:\n for (idx, atom) in self._Atoms.items():\n line = '{a0:<6}{a1:>5}{s}{a2:>4}{a3:>1}{a4:>3}{s}{a5:>1}' \\\n '{a6:>4}{a7:<1}{s:>3}{a8[0]:>8.3f}{a8[1]:>8.3f}{a8[2]:>8.3f}' \\\n '{a9:>6.2f}{a10:>6.2f}{s:>11}{a11:<2}\\n'.format(\n a0=atom.DataType, a1=idx, a2=atom.Name, a3=atom.AltLoc,\n a4=atom.ResName, a5=atom.ChainId, a6=atom.ResSeq,\n a7=atom.ResCode, a8=atom.Coordinate, a9=atom.Occup,\n a10=atom.TempFac, a11=atom.Element, s=' '\n )\n f.write(line)\n\n def GetChargePosition(self, resid):\n position: np.ndarray\n charge: str\n\n residue = self._Residues[resid]\n resname = residue['C'].ResName\n\n if resname == \"ARG\":\n charge = \"+\"\n position = residue[\"NH1\"].Coordinate\n elif resname == \"HIS\":\n charge = \"+\"\n position = residue[\"ND1\"].Coordinate\n elif resname == \"LYS\":\n charge = \"+\"\n position = residue[\"NZ\"].Coordinate\n elif resname == \"ASP\":\n charge = \"-\"\n position = 0.5 * (residue[\"OD1\"].Coordinate + residue[\"OD2\"].Coordinate)\n elif resname == \"GLU\":\n charge = \"-\"\n position = 0.5 * (residue[\"OE1\"].Coordinate + residue[\"OE2\"].Coordinate)\n else:\n assert False, f\"{resname} not charged\"\n\n return charge, position\n\n def GetDipolePosition(self, resid):\n positive_charge: str\n negative_charge: str\n\n residue = self._Residues[resid]\n resname = residue['C'].ResName\n\n if resname == \"SER\":\n positive_charge = \"HG1\"\n negative_charge = \"OG\"\n elif resname == \"THR\":\n positive_charge = \"HG1\"\n negative_charge = \"OG1\"\n elif resname == \"ASN\":\n positive_charge = \"CG\"\n negative_charge = \"OD1\"\n elif resname == \"GLN\":\n positive_charge = \"CD\"\n negative_charge = \"OE1\"\n elif resname == \"CYS\":\n positive_charge = \"HG\"\n negative_charge = \"SG\"\n elif resname == \"TYR\":\n positive_charge = \"HH\"\n negative_charge = \"OH\"\n elif resname == \"TRP\":\n positive_charge = \"HE1\"\n negative_charge = \"NE1\"\n elif resname == \"PRO\":\n positive_charge = \"NH\"\n negative_charge = \"N\"\n elif resname == \"GLH\":\n positive_charge = \"HE2\"\n negative_charge = \"OE2\"\n elif resname == \"ASH\":\n positive_charge = \"HD2\"\n negative_charge = \"OD2\"\n else:\n assert False, f\"Logical error\"\n\n positive_charge_pos = residue[positive_charge].Coordinate\n negative_charge_pos = residue[negative_charge].Coordinate\n\n dipole_vec = positive_charge_pos - negative_charge_pos\n dipole_pos = 0.5 * (positive_charge_pos + negative_charge_pos)\n\n return dipole_pos, dipole_vec, negative_charge_pos, positive_charge_pos\n\n def GetAminoacidType(self, resid):\n resname = self._Residues[resid]['C'].ResName\n if resname in self.POLAR_AMINOACIDS:\n return \"P\" # Polar\n elif resname in self.CHARGED_AMINOACIDS:\n return \"C\" # Charged\n else:\n return \"O\" # Other\n","sub_path":"molecule.py","file_name":"molecule.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519791109","text":"# -*- coding: utf-8 -*-\n# @Time : 2019-08-21 16:00\n# @Author : Kai Zhang\n# @Email : kai.zhang@lizhiweike.com\n# @File : ex2-isVaildSudoku.py\n# @Software: PyCharm\n\n\n\"\"\"\nhttps://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode/\n\"\"\"\n\n\nclass Solution:\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n # init data\n rows = [{} for i in range(9)]\n columns = [{} for i in range(9)]\n boxes = [{} for i in range(9)]\n\n # validate a board\n for i in range(9):\n for j in range(9):\n num = board[i][j]\n if num != '.':\n num = int(num)\n box_index = (i // 3) * 3 + j // 3\n\n # keep the current cell value\n rows[i][num] = rows[i].get(num, 0) + 1\n columns[j][num] = columns[j].get(num, 0) + 1\n boxes[box_index][num] = boxes[box_index].get(num, 0) + 1\n\n # check if this value has been already seen before\n if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:\n return False\n return True\n\n def isValidSudoku_2(self, board: list) -> bool:\n row = [[x for x in y if x != '.'] for y in board]\n col = [[x for x in y if x != '.'] for y in zip(*board)]\n pal = [[board[i + m][j + n] for m in range(3) for n in range(3) if board[i + m][j + n] != '.'] for i in\n (0, 3, 6) for j in (0, 3, 6)]\n return all(len(set(x)) == len(x) for x in (*row, *col, *pal))\n","sub_path":"task6/ex2-isVaildSudoku.py","file_name":"ex2-isVaildSudoku.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605909066","text":"import xlrd\n\nfrom app.util.base import base_dao\n\nexcel_file = 'static/stock1-3.xls'\n\n\ndef clean_data():\n dao = base_dao.BaseDao()\n dao.execute(\"truncate table db_ads.kc_rg_product_can_be_send_amount\")\n dao.execute(\"truncate table db_ads.kc_rg_valid_loading_detail\")\n dao.execute(\"truncate table db_model.t_load_task\")\n dao.execute(\"truncate table db_model.t_load_task_item\")\n print('数据清理完毕')\n\n\ndef import_data(excel_list):\n sql_temp = \"INSERT INTO db_ads.kc_rg_product_can_be_send_amount %KEYS% VALUES %VALUES%\"\n for elem in excel_list:\n keys = ''\n for key in elem.keys():\n keys += str(key) + ','\n keys = '(' + keys[0:len(keys)-1] + ')'\n values = ''\n for value in elem.values():\n if value:\n values += '\\'' + str(value) + '\\'' + ','\n else:\n values += 'null' + ','\n values = '(' + values[0:len(values)-1] + ')'\n sql = sql_temp.replace('%KEYS%', keys).replace('%VALUES%', values)\n print(sql)\n dao = base_dao.BaseDao()\n dao.execute(sql)\n\n\ndef read_excel():\n # 打开excel表,填写路径\n book = xlrd.open_workbook(excel_file)\n # 找到sheet页\n table = book.sheet_by_name(\"Sheet1\")\n # 获取总行数总列数\n row_Num = table.nrows\n col_Num = table.ncols\n list = []\n key = table.row_values(0) # 这是第一行数据,作为字典的key值\n\n if row_Num <= 1:\n print(\"没数据\")\n return list\n for i in range(1, row_Num):\n row_dict = {}\n values = table.row_values(i)\n for x in range(col_Num):\n # 把key值对应的value赋值给key,每行循环\n row_dict[key[x]] = values[x]\n # 把字典加到列表中\n list.append(row_dict)\n return list\n\n\nif __name__ == '__main__':\n # excel_list = read_excel()\n # import_data(excel_list)\n clean_data()","sub_path":"app/test/test_single_dispatch.py","file_name":"test_single_dispatch.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"624260186","text":"'''\nAuthor: Jan Bernhard\nPurpose: Module to control the Princeton Minitaur robot research unit.\n'''\n# standard imports\nimport serial\nimport time\nimport logging\nimport __future__\n\nclass Robot(object):\n\t\"\"\"\n\tObject to control Minitaur Robot that reacts to 8 byte integer \n\tmove.\n\t\"\"\"\n\t\n\tdef __init__(self,reaction_time = 0.5):\n\t\tself.current_command = None # stores most recent command\n\t\tself.forward = 0.0\n\t\tself.turn = 0.0\n\t\tself.height = 0.0\n\t\tself.last_cmd = time.time()\n\t\tself.reaction_time = reaction_time\n\t\tself.step_size = 0.1\n\t\tpass\n\n\tdef connect(self, usb_port_address, bauderate, time_out = 1):\n\t\t\"\"\"\n\t\tSets up the initial serial communication connection\n\t\t\"\"\"\n\n\t\tlogging.info(\"robot.py: Starts to connect components.\")\n\n\t\t# connect components\n\t\ttry:\n\t\t\tself.ser = serial.Serial(usb_port_address,\n\t\t\t\t\t\t\t\t\tbauderate, \n\t\t\t\t\t\t\t\t\ttimeout = time_out)\n\t\t\tself.connect_body = True # stores which components are connected.\n\t\t\tlogging.info(\"robot.py: Body component connected\")\n\t\texcept:\n\t\t\tself.connect_body = False\n\t\t\tlogging.warning(\"robot.py: Body component could not be connected.\")\n\n\t\tlogging.info(\"robot.py: Body = {}\".format(self.connect_body))\n\n\t\treturn\n\t\n\tdef disconnect(self):\n\t\t\"\"\"\n\t\tDisconnects the serial communication.\n\t\t\"\"\"\n\t\tif self.connect_body:\n\t\t\tself.ser.close()\n\n\t\tlogging.info(\"robot.py: Disconected body component successfully.\")\n\t\treturn\n\n#--------------------------------------------------------------------\n# Body Control\n#--------------------------------------------------------------------\n\tdef __rampUp(self,key, value):\n\t\t\"\"\"\n\t\tRamps up command inputs steadily to prevent erradic movements\n\t\t\"\"\"\n\t\tcmd = getattr(self,key)\n\t\tcmd = round(cmd,1)\n\t\tvalue = round(value,1)\n\t\tif cmd < value:\n\t\t\tcmd = cmd + self.step_size\n\t\telif cmd > value:\n\t\t\tcmd = cmd - self.step_size\n\t\telse:\n\t\t\tpass\n\t\tsetattr(self,key,cmd)\n\t\t# self.last_cmd = time.time()\n\t\treturn cmd\n\n\tdef __convertToMove(self, float_in):\n\t\t\"\"\"\n\t\tTakes in move in float form and encodes move as two digit string.\n\t\t\"\"\"\n\t\t# logging.info(\"Converts move command to 8byte string\")\n\t\tint_in = int(float_in * 10)\n\t\tfirst_digit = 0 if int_in < 0 else 1 #encodes negative\n\t\tsecond_digit = abs(int_in) #only consider magnitude\n\t\treturn (first_digit, second_digit)\n\n\tdef move(self, **kwargs):\n\t\t\"\"\"\n\t\tControls main body translation.\n\t\tConverts command move input to 8 byte integer.\n\n\t\tTakes arguments as follows:\n\t\t\tbehavior [int] 0 to 9,\n\t\t\tforward [m/s] -0.9 to 0.9,\n\t\t\tturn [rad/s] -0.9 to 0.9,\n\t\t\theight [% relative to normal] -0.9 to 0.9\n\t\t\n\t\tReturns:\n\t\t\tBool that signifies if command was correctly received by Minitaur.\n\t\t\"\"\"\n\t\tif not self.connect_body:\n\t\t\tlogging.warning(\"robot.py: Method move(): Cannot execute command. Body disconneted.\")\n\t\t\treturn\n\n\t\tnew_move = list(\"90000000\")\n\n\t\tfor key in kwargs:\n\t\t\tif key == 'forward':\n\t\t\t\tfwd = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[2:4] = self.__convertToMove(fwd)\n\t\t\telif key == 'turn':\n\t\t\t\ttrn = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[4:6] = self.__convertToMove(trn)\n\t\t\telif key == 'height':\n\t\t\t\thght = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[6:8] = self.__convertToMove(hght)\n\t\t\telif key == 'behavior':\n\t\t\t\tnew_move[1] = int(kwargs[key])\n\t\t\telif key == 'step_size':\n\t\t\t\tself.step_size = kwargs[key]\n\n\t\tnew_move = map(unicode,new_move) # converting int to char\n\t\tnew_move = ''.join(new_move) # joining char to str\n\n\t\t# Waiting for Signal that Minitaur is ready to receive move input\n\t\tread = None # Stores messages from Minitaur\n\t\treceived = False # True iff the correct message was received\n\t\twhile not received:\n\t\t\t# print(read)\n\t\t\tread = self.ser.readline()\n\t\t\ttry:\n\t\t\t\t\t# converts bites to unicode str\n\t\t\t\tif read == b'next\\n':\n\t\t\t\t\t# Sending new move string\n\t\t\t\t\tself.ser.write(str.encode(str(new_move)))\n\t\t\t\t\t# print(\"Send:\",new_move)\n\t\t\t\tif unicode(new_move) in unicode(read,\"utf-8\"):\n\t\t\t\t\treceived = True\n\t\t\t\t\tbreak\n\t\t\t\t# Logs warning when battery voltage is too low or motor temp to high\n\t\t\t\tif 'WARNING' in unicode(read,\"utf-8\"):\n\t\t\t\t\twarning_str = unicode(read,\"utf-8\")[8:len(unicode(read,\"utf-8\"))]\n\t\t\t\t\tif 'voltage' in unicode(read,\"utf-8\"):\n\t\t\t\t\t\tlogging.warning(\"robot.py: Battery Voltage too low\")\n\t\t\t\t\t\tlogging.info(\"robot.py: \" + warning_str)\n\t\t\t\t\tif 'temperature' in unicode(read,\"utf-8\"):\n\t\t\t\t\t\t# Won't currently work because .getTemperature() \n\t\t\t\t\t\t# isn't implemented on Minitaur SDK\n\t\t\t\t\t\tlogging.warning(\"robot.py: \" + warning_str)\n\n\n\n\t\t\texcept UnicodeDecodeError:\n\t\t\t\tlogging.warning(\"robot.py: Communication couldn't be decoded\")\n\n\t\t# Through warning if move command wasn't correctly received by Minitaur\n\t\tif not received:\n\t\t\tlogging.warning(\"robot.py: Last Move command {} was not received by Minitaur.\"\\\n\t\t\t\t\t\t\t.format(self.current_command))\n\t\telse:\n\t\t\tlogging.info(\"robot.py: Command received\")\n\t\t\t# Update current move command and log command\n\t\tif self.current_command != new_move:\n\t\t\tself.current_command = new_move\n\t\t\tlogging.info(\"robot.py: Move command sent: {}\".format(new_move))\n\t\t\n\t\treturn received\n\n\n\tdef testMove(self, **kwargs):\n\t\t\"\"\"\n\t\tSame as move but does not need connection/prints dummy responses\n\t\tTakes arguments as follows:\n\t\t\tbehavior [int] 0 to 9,\n\t\t\tforward [m/s] -0.9 to 0.9,\n\t\t\tturn [rad/s] -0.9 to 0.9,\n\t\t\theight [% relative to normal] -0.9 to 0.9\n\t\t\"\"\"\n\n\t\tnew_move = list(\"90000000\")\n\n\t\tfor key in kwargs:\n\t\t\tif key == 'forward':\n\t\t\t\tfwd = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[2:4] = self.__convertToMove(fwd)\n\t\t\telif key == 'turn':\n\t\t\t\ttrn = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[4:6] = self.__convertToMove(trn)\n\t\t\telif key == 'height':\n\t\t\t\thght = self.__rampUp(key,kwargs[key])\n\t\t\t\tnew_move[6:8] = self.__convertToMove(hght)\n\t\t\telif key == 'behavior':\n\t\t\t\tnew_move[1] = int(kwargs[key])\n\t\t\tprint(key)\n\n\t\tnew_move = map(str,new_move) # converting int to char\n\t\tnew_move = ''.join(new_move) # joining char to str\n\n\t\tprint(\"Move command sent: {}\".format(new_move))\n\n\t\nif __name__ == '__main__':\n\t\"\"\"\n\tOffline Test routine: \n\t - walk forward 3sec and rotate head slightly up and right, \n\t - walk at higher standing height normal height 2sec \n\t\t\tand turn head to starting position, \n\t - sit 2 sec,\n\t - return to starting position\n\t\"\"\"\n\tobj = Robot()\n\ttry:\n\t\tprint(\" >>> START TEST SEQUENCE <<<\")\n\t\tprint(\">>> Stand <<<\")\n\t\tfor _ in range(30):\n\t\t\tobj.testMove()\n\t\t\ttime.sleep(0.1)\n\t\tprint(\">>> WALK <<<\")\n\t\tfor _ in range(30):\n\t\t\tobj.testMove(forward=0.3,height = .1)\n\t\t\ttime.sleep(0.1)\n\t\tprint(\">>> Turn right<<<\")\n\t\tfor _ in range(20):\n\t\t\tobj.testMove(forward=0.1,turn =.6, height=.1)\n\t\t\ttime.sleep(0.1)\n\t\tprint(\">>> Turn left <<<\")\n\t\tfor _ in range (20):\n\t\t\tobj.testMove(forward=0.1,turn=-.6,height=.1)\n\t\t\ttime.sleep(0.1)\n\t\tprint(\">>> STAND <<<\")\n\t\tfor _ in range (20):\n\t\t\tobj.testMove()\n\t\t\ttime.sleep(0.1)\n\t\t\n\texcept KeyboardInterrupt: \n\t\tprint(\"Test ended prematurely and has been disconnected\")\n","sub_path":"main/robot_control/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"56537351","text":"\"\"\"Proyecto1 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.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 , include\nfrom . import views\n\nurlpatterns = [\n path('', views.login),\n path('operaciones/',views.operaciones,name='ope'),\n path('transCP/',views.trcuentapropia),\n path('transCT/',views.trcuentaterceros),\n path('preautorizacion/',views.preautorizacion),\n path('pagoplanillayproveedor/',views.pagoplanilla),\n path('pagoservicios/', views.servicios),\n path('solicitarprestamo/', views.solicitarprestamo),\n path('agregarterceros/', views.agregarterceros),\n path('suspendercuenta/', views.suspendercuenta),\n path('activarcuenta/', views.activarcuenta),\n path('estadodecuenta/', views.estadodecuenta),\n path('estadotarjeta/', views.estadotarjeta),\n]\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"361731141","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 1 13:04:12 2021\n\n@author: Binny\n\"\"\"\n\nimport numpy as np\nimport time\nfrom matplotlib import pyplot as plt\n\nX = [0.75, 3.24]\nY = [0.11, 0.83]\nw_list = []\nb_list =[]\nstep_size_w_list = []\nstep_size_b_list = []\n\ndef f(w, b, x):\n return 1.0/(1.0 + np.exp(-(w*x + b)))\n\ndef error(w, b):\n err = 0.0\n for x,y in zip(X,Y):\n fx = f(w,b,x)\n err += (fx - y) ** 2\n err = err / 2\n return err\n \ndef grad_b(w, b, x, y):\n fx = f(w, b, x)\n return (fx - y) * fx * (1 - fx)\n\ndef grad_w(w, b, x, y):\n fx = f(w, b, x)\n return (fx - y) * fx * (1 - fx) * x\n\ndef do_momentum_gradient_descent():\n w, b, lr, max_epochs = 0, 0, 0.1, 84\n prev_w, prev_b, gamma = 0, 0, 0.9\n \n for i in range(max_epochs):\n dw, db = 0, 0\n \n print(\"error= \", error(w, b))\n \n for x,y in zip(X,Y):\n dw += grad_w(w, b, x, y)\n db += grad_b(w, b, x, y)\n step_size_w = gamma * prev_w + lr * dw\n step_size_b = gamma * prev_b + lr * db\n\n step_size_w_list.append(step_size_w)\n step_size_b_list.append(step_size_b)\n \n w = w - step_size_w\n b = b - step_size_b\n\n w_list.append(w)\n b_list.append(b)\n\n prev_w = step_size_w\n prev_b = step_size_b \n \n print(\"weight w1 = \",w)\n print(\"bias b = \", b)\n print(\"step_size_w = \", step_size_w)\n print(\"step_size_b = \", step_size_b)\n \n print()\n \nstart = time.time() \ndo_momentum_gradient_descent()\nend = time.time()\n\nprint(\"total time by momentum based = \", end-start)\n\nplt.xlabel(\"weights\")\nplt.ylabel(\"bias\")\nplt.plot(w_list,b_list)\nplt.show()\n\nplt.xlabel(\"step size of weight\")\nplt.ylabel(\"weights\")\nplt.plot(step_size_w_list, w_list)\nplt.show()\n\nplt.xlabel(\"step size of bias\")\nplt.ylabel(\"bias\")\nplt.plot(step_size_b_list, b_list)\nplt.show()\n","sub_path":"Batch, Momentum-based, and Nesterov Accelerated Gradient Descent/python scripts/momentum_based GD.py","file_name":"momentum_based GD.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"468353670","text":"# speeding.py\n# This program indicates the amount of a speeding ticket fine given mph.\n\ndef main():\n print(\"This program calculates a speeding ticket fine.\")\n while True:\n try:\n speedLim = int(input(\"Please enter the speed limit: \"))\n speed = int(input(\"Please enter the recorded speed: \"))\n if speed > speedLim:\n fine = 50\n over = speed % speedLim\n fine += over * 5\n if speed > 90:\n fine += 200\n print(\"\\nA recorded speed of {0} mph is illegal, the speeding ticket fine totals to ${1}.\\n\".format(speed, fine))\n else:\n print(\"\\nA recorded speed of {0} mph is legal.\\n\".format(speed))\n except ValueError:\n print(\"\\nYou have not entered a whole numeric figure.\\n\")\n\nmain()\n","sub_path":"python/python-programming-zelle/speeding.py","file_name":"speeding.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78578495","text":"#!/usr/bin/env python3\n\nfrom enum import Enum\n\nclass Direction(Enum):\n from_bottom = 0\n from_left = 1\n from_top = 2\n from_right = 3\n idle = 4\n\ndef isValid (new_x, new_y, steps, grid):\n x_max = len(grid)\n y_max = len(grid[0])\n return ((new_x >= 0 and new_x < x_max and new_y >= 0 and new_y < y_max)\n and (grid[new_x][new_y] == '.'\n or (grid[new_x][new_y] != 'X' and grid[new_x][new_y] > steps)))\n\ndef move_castle(x, y, dx, dy, last_d, last_steps, grid, queue):\n if dx == 1:\n new_direction = Direction.from_top\n elif dx == -1:\n new_direction = Direction.from_bottom\n elif dy == 1:\n new_direction = Direction.from_left\n elif dy == -1:\n new_direction = Direction.from_right\n\n while isValid(x+dx, y+dy, last_steps, grid):\n queue.append((x+dx, y+dy, new_direction))\n grid[x+dx][y+dy] = last_steps + (last_d != new_direction)\n x += dx\n y += dy\n\ndef enqueue (x, y, last_d, grid, queue):\n current_steps = grid[x][y]\n move_castle(x, y, 1, 0, last_d, current_steps, grid, queue)\n move_castle(x, y, -1, 0, last_d, current_steps, grid, queue)\n move_castle(x, y, 0, 1, last_d, current_steps, grid, queue)\n move_castle(x, y, 0, -1, last_d, current_steps, grid, queue)\n\ndef castle_on_the_grid():\n n = int(input())\n grid = [[x for x in input().strip()] for i in range(n)]\n a, b, c, d = map(int, input().strip().split(' '))\n grid[a][b] = 0\n\n queue = []\n enqueue(a, b, Direction.idle, grid, queue)\n \n while queue:\n x, y, delta = queue.pop(0)\n enqueue(x, y, delta, grid, queue)\n\n return grid[c][d]\n\nprint(castle_on_the_grid())","sub_path":"data_structures/queues/castle_on_the_grid.py","file_name":"castle_on_the_grid.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205557495","text":"# https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps\n\nimport unittest\nfrom collections import Counter\n\nclass Solution:\n\n def ransom_note(self, magazine, note):\n magazine_counter = Counter(magazine)\n note_counter = Counter(note)\n\n for k, v in note_counter.items():\n if k in magazine_counter:\n if magazine_counter[k] < v:\n return 'No'\n else:\n return 'No'\n return 'Yes'\n\n\n# test\n\ns = Solution()\n\n# test_cases = [['give me one grand today night','give one grand today'],\n# ['two times three is not four','two times two is four'],\n# ['ive got a lovely bunch of coconuts','ive got some coconuts'],\n# ['attack at dawn','Attack at dawn']]\n#\n# test_cases = [[x.rstrip().split(), y.rstrip().split()] for x,y in test_cases]\n#\n# for t1 in test_cases:\n# print(t1, s.count_triplets(t1[0], t1[1]))\n\n\nclass TestInt(unittest.TestCase):\n\n def test_integer(self):\n s = Solution()\n\n test_cases = [['give me one grand today night','give one grand today'],\n ['two times three is not four','two times two is four'],\n ['ive got a lovely bunch of coconuts','ive got some coconuts'],\n ['attack at dawn','Attack at dawn']]\n test_results = ['Yes', 'No', 'No','No']\n\n for i, test_case in enumerate(test_cases):\n self.assertEqual(s.ransom_note(test_case[0], test_case[1]), test_results[i])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"hackerrank/hash_maps/ransom_note.py","file_name":"ransom_note.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328975954","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom django.conf import settings\nfrom . import views\n\nurlpatterns = [\n\tpath('', views.index, name='index'),\n\tpath('index/', views.index, name='game'),\n\tpath('post/new', views.post_new, name='post_new'),\n\tpath('post//edit/', views.post_edit, name='post_edit'),\n\turl(r'^drafts/$', views.post_draft_list, name='post_draft_list'),\n\turl(r'^dailyposts/$', views.post_list, name='post_list'),\n\turl(r'^post/(?P\\d+)/publish/$', views.post_publish, name='post_publish'),\n\turl(r'^post/(?P\\d+)/remove/$', views.post_remove, name='post_remove'),\n\turl(r'^post/(?P\\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),\n\turl(r'^comment/(?P\\d+)/approve/$', views.comment_approve, name='comment_approve'),\n\turl(r'^comment/(?P\\d+)/remove/$', views.comment_remove, name='comment_remove'),\t\n\turl(r'^gamenotice/$', views.notice_list, name='notice_list'),\n\turl(r'^fashionnotice/$', views.notice2_list, name='notice2_list'),\n] ","sub_path":"kako_fashion/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609187773","text":"# -*- coding: utf-8 -*-\n\"\"\"Writer for GIFT PPA script files.\"\"\"\n\nimport io\nimport os\n\nfrom l2tdevtools.dependency_writers import interface\n\n\nclass GIFTPPAInstallScriptWriter(interface.DependencyFileWriter):\n \"\"\"GIFT PPA installation script file writer.\"\"\"\n\n _TEMPLATE_FILE = os.path.join('data', 'templates', 'gift_ppa_install.sh')\n\n # Path to GIFT PPA installation script.\n PATH = os.path.join('config', 'linux', 'gift_ppa_install_py3.sh')\n\n def _FormatDPKGDebugDependencies(self, debug_dependencies):\n \"\"\"Formats DPKG debug dependencies for the template.\n\n Args:\n debug_dependencies (list[str]): DPKG package names of debug dependencies.\n\n Returns:\n str: formatted DPKG debug dependencies.\n \"\"\"\n formatted_debug_dependencies = []\n if debug_dependencies:\n for index, dependency in enumerate(sorted(debug_dependencies)):\n if index == 0:\n line = 'DEBUG_DEPENDENCIES=\"{0:s}'.format(dependency)\n else:\n line = ' {0:s}'.format(dependency)\n\n if index + 1 == len(debug_dependencies):\n line = '{0:s}\";'.format(line)\n\n formatted_debug_dependencies.append(line)\n\n return '\\n'.join(formatted_debug_dependencies)\n\n def _FormatDPKGDevelopmentDependencies(self, development_dependencies):\n \"\"\"Formats DPKG development dependencies for the template.\n\n Args:\n development_dependencies (list[str]): DPKG package names of development\n dependencies.\n\n Returns:\n str: formatted DPKG development dependencies.\n \"\"\"\n formatted_development_dependencies = []\n if development_dependencies:\n for index, dependency in enumerate(sorted(development_dependencies)):\n if index == 0:\n line = 'DEVELOPMENT_DEPENDENCIES=\"{0:s}'.format(dependency)\n else:\n line = ' {0:s}'.format(dependency)\n\n if index + 1 == len(development_dependencies):\n line = '{0:s}\";'.format(line)\n\n formatted_development_dependencies.append(line)\n\n return '\\n'.join(formatted_development_dependencies)\n\n def _FormatDPKGPythonDependencies(self, python_dependencies):\n \"\"\"Formats DPKG Python dependencies for the template.\n\n Args:\n python_dependencies (list[str]): DPKG package names of Python\n dependencies.\n\n Returns:\n str: formatted DPKG Python dependencies.\n \"\"\"\n formatted_python_dependencies = []\n\n for index, dependency in enumerate(sorted(python_dependencies)):\n if index == 0:\n line = 'PYTHON_DEPENDENCIES=\"{0:s}'.format(dependency)\n else:\n line = ' {0:s}'.format(dependency)\n\n if index + 1 == len(python_dependencies):\n line = '{0:s}\";'.format(line)\n\n formatted_python_dependencies.append(line)\n\n return '\\n'.join(formatted_python_dependencies)\n\n def _FormatDPKGTestDependencies(self, test_dependencies):\n \"\"\"Formats DPKG test dependencies for the template.\n\n Args:\n test_dependencies (list[str]): DPKG package names of test dependencies.\n\n Returns:\n str: formatted DPKG test dependencies.\n \"\"\"\n formatted_test_dependencies = []\n if test_dependencies:\n for index, dependency in enumerate(sorted(test_dependencies)):\n if index == 0:\n line = 'TEST_DEPENDENCIES=\"{0:s}'.format(dependency)\n else:\n line = ' {0:s}'.format(dependency)\n\n if index + 1 == len(test_dependencies):\n line = '{0:s}\";'.format(line)\n\n formatted_test_dependencies.append(line)\n\n return '\\n'.join(formatted_test_dependencies)\n\n def _GetDPKGDebugDependencies(self, python_dependencies):\n \"\"\"Retrieves DPKG debug dependencies.\n\n Args:\n python_dependencies (list[str]): DPKG package names of Python\n dependencies.\n\n Returns:\n list[str]: DPKG package names of Python debug dependencies.\n \"\"\"\n debug_dependencies = []\n for dependency in sorted(python_dependencies):\n if dependency.startswith('lib') and dependency.endswith('python3'):\n dependency, _, _ = dependency.partition('-')\n debug_dependencies.extend([\n '{0:s}-dbg'.format(dependency),\n '{0:s}-python3-dbg'.format(dependency)])\n\n return debug_dependencies\n\n def _Write(self):\n \"\"\"Writes a gift_ppa_install.sh file.\"\"\"\n python_dependencies = self._GetDPKGPythonDependencies()\n test_dependencies = self._GetDPKGTestDependencies(python_dependencies)\n\n # TODO: replace by dev_dependencies.ini or equiv.\n development_dependencies = ['pylint']\n\n if self._project_definition.name == 'plaso':\n development_dependencies.append('python-sphinx')\n\n debug_dependencies = self._GetDPKGDebugDependencies(python_dependencies)\n\n formatted_python_dependencies = self._FormatDPKGPythonDependencies(\n python_dependencies)\n\n formatted_test_dependencies = self._FormatDPKGTestDependencies(\n test_dependencies)\n\n formatted_development_dependencies = (\n self._FormatDPKGDevelopmentDependencies(development_dependencies))\n\n formatted_debug_dependencies = self._FormatDPKGDebugDependencies(\n debug_dependencies)\n\n template_mappings = {\n 'debug_dependencies': formatted_debug_dependencies,\n 'development_dependencies': formatted_development_dependencies,\n 'project_name': self._project_definition.name,\n 'python_dependencies': formatted_python_dependencies,\n 'test_dependencies': formatted_test_dependencies}\n\n template_file = os.path.join(self._l2tdevtools_path, self._TEMPLATE_FILE)\n file_content = self._GenerateFromTemplate(template_file, template_mappings)\n\n with io.open(self.PATH, 'w', encoding='utf-8') as file_object:\n file_object.write(file_content)\n\n def Write(self):\n \"\"\"Writes a gift_ppa_install.sh file.\"\"\"\n self._Write()\n","sub_path":"l2tdevtools/dependency_writers/gift_ppa.py","file_name":"gift_ppa.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418265708","text":"import os,re,fnmatch\nfrom shutil import copy,copytree\nfrom igf_data.illumina.samplesheet import SampleSheet\nfrom igf_data.illumina.runinfo_xml import RunInfo_xml\nfrom igf_data.utils.fileutils import copy_local_file\n\nclass moveBclFilesForDemultiplexing:\n def __init__(\n self, input_dir, output_dir, samplesheet,\n run_info_xml, platform_model=None):\n self.input_dir = input_dir\n self.output_dir = output_dir\n self.samplesheet = samplesheet\n self.run_info_xml = run_info_xml\n self.platform_model = platform_model\n\n\n def copy_bcl_files(self):\n '''\n Function for copying BCL files to the output directory\n '''\n try:\n input_dir = self.input_dir\n output_dir = self.output_dir\n bcl_files_list = self._generate_platform_specific_list()\n if len(bcl_files_list) == 0:\n raise ValueError(\n 'No file list found for samplesheet {0}'.\\\n format(self.input_dir))\n for bcl_entity in bcl_files_list:\n input_target = os.path.join(input_dir, bcl_entity)\n output_target = output_target = \\\n os.path.join(output_dir, bcl_entity)\n copy_local_file(input_target, output_target)\n except Exception as e:\n raise ValueError(\n 'Failed to copy bcl file, error: {0}'\\\n .format(e))\n\n def _generate_platform_specific_list(self, lane_list=()):\n '''\n An internal function for getting list of files and directories specific for each platform\n\n :param lane_list: A list of lanes to check\n :returns: A list of files\n '''\n try:\n lane_list = list(lane_list)\n #platform_model = self.platform_model\n samplesheet_data = SampleSheet(infile=self.samplesheet)\n if self.platform_model is None:\n # set pattern for HiSeq platforms\n hiseq_pattern = re.compile('^HISEQ', re.IGNORECASE)\n nextseq_pattern = re.compile('^NEXTSEQ', re.IGNORECASE)\n miseq_pattern = re.compile('^FASTQ Only', re.IGNORECASE)\n novaseq_pattern = re.compile('^NOVASEQ', re.IGNORECASE)\n # read the samplesheet info\n platform_name = samplesheet_data.get_platform_name()\n runinfo_data = RunInfo_xml(xml_file=self.run_info_xml)\n platform_series = runinfo_data.get_platform_number()\n if (re.search(hiseq_pattern, platform_name)):\n if platform_series.startswith('K'):\n self.platform_model = 'HISEQ4000' # assign platform model for HISEQ4000\n else:\n self.platform_model = 'HISEQ2500' # or may be its HISEQ2500\n raise ValueError('no method of for hiseq 2500')\n elif(re.search(nextseq_pattern, platform_name)):\n self.platform_model = 'NEXTSEQ' # assign platform model for 'NEXTSEQ'\n elif(re.search(novaseq_pattern, platform_name)):\n self.platform_model = 'NOVASEQ6000'\n elif(re.search(miseq_pattern, platform_name)):\n if platform_series.startswith('M'):\n self.platform_model = 'MISEQ'\n else:\n raise ValueError(\n 'Platform series {0} is not MiSeq'.\\\n format(platform_series))\n else:\n raise ValueError(\n 'Platform {0} not recognised'.\\\n format(platform_name))\n bcl_files_list = list()\n if self.platform_model == 'HISEQ4000':\n bcl_files_list = [\n 'Data/Intensities/s.locs',\n 'InterOp',\n 'RunInfo.xml',\n 'runParameters.xml']\n if len(lane_list):\n # need to change the following lines if there are more than 9 lanes\n for lane in lane_list:\n bcl_files_list.\\\n append(\n 'Data/Intensities/BaseCalls/L00{0}'.format(lane))\n else:\n for lane in samplesheet_data.get_lane_count():\n bcl_files_list.\\\n append(\n 'Data/Intensities/BaseCalls/L00{0}'.format(lane))\n elif self.platform_model == 'NOVASEQ6000':\n bcl_files_list = [\n 'Data/Intensities/s.locs',\n 'InterOp',\n 'RunInfo.xml',\n 'RunParameters.xml']\n if len(lane_list):\n # need to change the following lines if there are more than 9 lanes\n for lane in lane_list:\n bcl_files_list.\\\n append(\n 'Data/Intensities/BaseCalls/L00{0}'.format(lane))\n else:\n for lane in samplesheet_data.get_lane_count():\n bcl_files_list.\\\n append(\n 'Data/Intensities/BaseCalls/L00{0}'.format(lane))\n elif self.platform_model == 'NEXTSEQ':\n bcl_files_list = [\n 'Data',\n 'InterOp',\n 'RunInfo.xml',\n 'RunParameters.xml']\n elif self.platform_model == 'MISEQ':\n bcl_files_list = [\n 'Data',\n 'InterOp',\n 'RunInfo.xml',\n 'runParameters.xml']\n return bcl_files_list\n except Exception as e:\n raise ValueError(\n 'Failed to get a platform specific bcl file list, error: {0}'.\\\n format(e))\n\n\nclass moveBclTilesForDemultiplexing(moveBclFilesForDemultiplexing):\n \"\"\"\n A class for copying BCL files for a list of tiles to a specific dir\n\n :param input_dir: Input run dir\n :param output_dir: Target output dir\n :param samplesheet: Samplesheet filepath\n :param run_info_xml: RunInfo.xml file path\n :param platform_model: Platform model, default None\n :param force: Force copy existing file, default False\n :param tiles_list: List of times to copy, default (1101,)\n\n obj = moveBclTilesForDemultiplexing(**kwargs)\n obj.copy_bcl_files()\n\n \"\"\"\n def __init__(self, input_dir, output_dir, samplesheet, run_info_xml,\n force=False, platform_model=None, tiles_list=(1101,)):\n self.tiles_list = list(tiles_list)\n self.force = force\n super().__init__(\n input_dir,\n output_dir,\n samplesheet,\n run_info_xml,\n platform_model)\n\n def copy_bcl_files(self):\n \"\"\"\n A function for transferring bcl files for selected tiles to a target dir\n \"\"\"\n try:\n input_dir = self.input_dir\n output_dir = self.output_dir\n bcl_files_list, final_tiles_list = \\\n self._generate_platform_specific_list()\n if len(bcl_files_list)==0:\n raise ValueError(\n 'No file list found for run path {0}'.\\\n format(self.input_dir))\n bcl_files_list = list(set(bcl_files_list)) # make the list unique\n for bcl_entity in bcl_files_list:\n bcl_entity = bcl_entity.lstrip('/')\n input_target = os.path.join(input_dir, bcl_entity)\n output_target = os.path.join(output_dir, bcl_entity)\n if not os.path.exists(output_target) or \\\n input_target.endswith('*.csv') or \\\n (os.path.exists(output_target) and\n os.path.getsize(input_target) != os.path.getsize(output_target)):\n copy_local_file(input_target, output_target, force=self.force) # skip existing cbcl file\n return final_tiles_list\n except Exception as e:\n raise ValueError(\n 'Failed to copy bcl files for tiles, error: {0}'.\\\n format(e))\n\n\n def _generate_platform_specific_list(self):\n \"\"\"\n An internal method for generating platform specific file list\n \"\"\"\n try:\n bcl_files_list = \\\n super()._generate_platform_specific_list()\n if self.platform_model is None:\n self.platform_model = super().platform_model\n final_bcl_list = list()\n final_tiles_list = list()\n for entry in bcl_files_list:\n if entry.startswith('Data/Intensities/BaseCalls/L00'):\n lookup_path = os.path.join(self.input_dir, entry)\n lane = os.path.basename(entry).replace('L00', '')\n for tile in self.tiles_list:\n tile_id = 's_{0}_{1}'.format(lane, tile)\n final_tiles_list.append(tile_id)\n if self.platform_model == 'HISEQ4000':\n for root, _, files in os.walk(lookup_path):\n for f in files:\n if fnmatch.fnmatch(f, '{0}*'.format(tile_id)):\n path = os.path.join(root, f)\n path = path.replace(self.input_dir, '')\n final_bcl_list.append(path)\n elif self.platform_model == 'NOVASEQ6000':\n temp_list = list()\n for root, _, files in os.walk(lookup_path):\n for f in files:\n if f.endswith('.filter'):\n if fnmatch.fnmatch(f, '{0}.filter'.format(tile_id)):\n temp_list.append(os.path.join(root, f))\n if f.endswith('.cbcl'):\n temp_list.append(os.path.join(root, f))\n for path in temp_list:\n path = path.replace(self.input_dir, '')\n final_bcl_list.append(path)\n else:\n final_bcl_list.append(entry)\n return final_bcl_list, final_tiles_list\n except Exception as e:\n raise ValueError(\n 'Failed to generate platform specific list got bcl tile, error: {0}'.\\\n format(e))","sub_path":"igf_data/process/moveBclFilesForDemultiplexing.py","file_name":"moveBclFilesForDemultiplexing.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"338364050","text":"#!/usr/bin/env python\n\nimport pd\nimport csv\nimport json\nimport os\n\napp_base_url = os.environ.get('APP_BASE_URL', 'https://event-sender.herokuapp.com')\nwith open('domains.csv') as csvfile:\n readCSV = csv.DictReader(csvfile)\n domains_processed = set()\n for row in readCSV:\n if row['domain'] in domains_processed:\n print(f\"-- Already processed {row['domain']}\\n\")\n continue\n try:\n extensions = pd.fetch(token=row['token'], endpoint=\"extensions\")\n subs = pd.get_subs(row['token'])\n except:\n print(f\"-- Oops, couldn't get extensions for {row['domain']}\\n\")\n continue\n domains_processed.add(row['domain'])\n print(f\"Processing domain {row['domain']}\")\n webhook_v2_extensions = [extension for extension in extensions if extension['extension_schema']['id'] == 'PJFWPEP']\n crux_extensions = [extension for extension in webhook_v2_extensions if extension['endpoint_url'] == f\"{app_base_url}/respond\"]\n v2_by_service = {}\n for extension in crux_extensions:\n if len(extension['extension_objects']) > 1:\n print(f\"== Extension {extension['id']} has {len(extension['extension_objects'])} objects?!\")\n for extension_object in extension['extension_objects']:\n if not extension_object['id'] in v2_by_service:\n v2_by_service[extension_object['id']] = []\n v2_by_service[extension_object['id']].append(extension)\n\n v3_subs = [sub for sub in subs if 'delivery_method' in sub and 'url' in sub['delivery_method'] and sub['delivery_method']['url'] == f\"{app_base_url}/respond\"]\n v3_by_service = {}\n for sub in v3_subs:\n if not sub['filter']['id'] in v3_by_service:\n v3_by_service[sub['filter']['id']] = []\n v3_by_service[sub['filter']['id']].append(sub)\n \n print(f\" Services with v2 webhooks: {', '.join(v2_by_service.keys())}\")\n print(f\" Services with v3 webhooks: {', '.join(v3_by_service.keys())}\")\n\n v2_set = set(v2_by_service.keys())\n v3_set = set(v3_by_service.keys())\n both_set = v2_set.intersection(v3_set)\n v2_only_set = v2_set - v3_set\n v3_only_set = v3_set - v2_set\n print(f\" Services with both v2 and v3 webhooks: {', '.join(both_set)}\")\n print(f\" Services with only v2 webhooks: {', '.join(v2_only_set)}\")\n print(f\" Services with only v3 webhooks: {', '.join(v3_only_set)}\")\n\n for service_id in v2_only_set:\n print(f\" Add v3 webhook on service {service_id}\")\n # pd.add_sub(row['token'], service_id)\n print('')","sub_path":"add_v3.py","file_name":"add_v3.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104587123","text":"#\n# @lc app=leetcode id=46 lang=python3\n#\n# [46] Permutations\n#\n\n# @lc code=start\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n lst = [[i] for i in nums]\n for i in range(len(nums)-1):\n new_lst = []\n for j in lst:\n for k in nums:\n if k not in j:\n new_lst.append(j + [k])\n lst = new_lst\n return lst\n# @lc code=end\n","sub_path":"python3/46.permutations.py","file_name":"46.permutations.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"76261512","text":"from .types import ArtifactType\nfrom fact.exceptions import (\n TaskExistsError,\n TaskNotFoundError,\n TaskInvalidUUID,\n ArtifactExistsError,\n ArtifactNotFoundError,\n ArtifactInvalidName,\n ArtifactInvalidType,\n)\n\nfrom pathlib import Path\nfrom uuid import UUID\nfrom typing import BinaryIO, List, Union\nimport logging\n\nlog = logging.getLogger(__name__)\n\n# TODO: Rewrite the storage API to always produce writestreams, for\n# compatibility with S3 buckets\n\n\nclass Artifact:\n \"\"\"\n Stores information about an artifact\n \"\"\"\n\n def __init__(self, artifact_name: str = \"\", artifact_type: str = \"\") -> None:\n \"\"\"Initialises an Artifact object\n\n :param artifact_name: Name of artifact\n :param artifact_type: Type of artifact\n :raises:\n ArtifactInvalidName: Invalid name. Cannot be empty.\n ArtifactInvalidType: Invalid artifact type, needs to be found in ArtifactType\n \"\"\"\n if not artifact_name:\n raise ArtifactInvalidName(\"Invalid empty name\", artifact_name)\n\n if not artifact_type:\n artifact_type = ArtifactType.unknown.name\n elif not Artifact.is_valid_artifact_type(artifact_type):\n valid_types = \"{\" + \", \".join(ArtifactType.__members__.keys()) + \"}\"\n err_msg = f\"Invalid artifact type. Select from: {valid_types}\"\n raise ArtifactInvalidType(err_msg, artifact_type)\n\n self.artifact_name = artifact_name\n self.artifact_type = ArtifactType[artifact_type]\n\n def get_artifact_type(self) -> str:\n \"\"\"Gets artifact type of instance\n :return: Artifact type\n \"\"\"\n return self.artifact_type.name\n\n def get_artifact_path(self) -> tuple[Path, Path]:\n \"\"\"Gets artifact path of instance\n :return: (Artifact path, Artifact name) ->\n ( {artifact_type}, {artifact_name} )\n \"\"\"\n artifact_type = self.get_artifact_type()\n artifact_path = Path(artifact_type)\n return artifact_path, Path(self.artifact_name)\n\n def get_artifact_info(self) -> dict[str, str]:\n \"\"\"Gets artifact info of instance\n :return: Artifact info (Attributes of instance)\n \"\"\"\n artifact_type: str = self.get_artifact_type()\n return {\"artifact_name\": self.artifact_name, \"artifact_type\": artifact_type}\n\n @staticmethod\n def is_valid_artifact_name(artifact_name: str) -> bool:\n \"\"\"Checks if artifact name is not empty\n :param artifact_name: Name of artifact\n :return: Validation result\n \"\"\"\n return bool(artifact_name)\n\n @staticmethod\n def is_valid_artifact_type(artifact_type: str) -> bool:\n \"\"\"Checks if artifact type exists in ArtifactType\n :param artifact_type: Type of artifact\n :return: Validation result\n \"\"\"\n return artifact_type in ArtifactType.__members__\n\n\nclass Task:\n \"\"\"\n Stores information about a task\n \"\"\"\n\n def __init__(self, task_uuid_str: str = \"\") -> None:\n \"\"\"Initialises a Task object\n\n :param task_uuid_str: UUID string of task\n :raises:\n TaskInvalidUUID: Invalid task UUID\n \"\"\"\n if not Task.is_valid_uuid(task_uuid_str):\n raise TaskInvalidUUID(\"Invalid Task UUID\", task_uuid_str)\n self.task_uuid = UUID(task_uuid_str)\n self.artifacts: list[Artifact] = []\n\n def get_artifact(self, artifact_info: dict) -> Union[Artifact, None]:\n \"\"\"Gets artifact matching the artifact info in instance\n\n :param artifact_info: Artifact info\n :return: The artifact matched or None\n \"\"\"\n for a in self.artifacts:\n if a.get_artifact_info() == artifact_info:\n return a\n return None\n\n def is_artifact_exists(self, artifact_info: dict) -> bool:\n \"\"\"Checks if artifact exists in instance based on artifact info\n\n :param artifact_info: Artifact info\n :return: Whether the artifact exists\n \"\"\"\n artifact: Union[Artifact, None] = self.get_artifact(artifact_info)\n if artifact is not None:\n return True\n return False\n\n def add_artifact(self, artifact: Artifact) -> None:\n \"\"\"Adds artifact to instance if it is does not exist already\n\n :param artifact: The artifact to add to instance\n :raises:\n ArtifactExistsError: Artifact exists already\n \"\"\"\n artifact_info: dict = artifact.get_artifact_info()\n if self.is_artifact_exists(artifact_info):\n raise ArtifactExistsError(\"Artifact exists already\", artifact_info)\n self.artifacts.append(artifact)\n\n def get_task_uuid(self) -> str:\n \"\"\"Gets task UUID of instance\n\n :returns: Task UUID\n \"\"\"\n return str(self.task_uuid)\n\n def get_task_path(self) -> Path:\n \"\"\"Gets task path of instance\n\n :returns: Task path\n \"\"\"\n task_uuid: str = self.get_task_uuid()\n return Path(task_uuid)\n\n def _get_artifacts(self) -> list[dict]:\n \"\"\"Gets list of artifact info in task instance\n\n :returns: List of artifact info\n \"\"\"\n artifacts: list[dict] = []\n for artifact in self.artifacts:\n artifacts.append(artifact.get_artifact_info())\n return artifacts\n\n def get_task_info(self) -> dict:\n \"\"\"Gets task info of instance\n\n :returns: Task info (Attributes of instance)\n \"\"\"\n task_uuid = self.get_task_uuid()\n artifacts = self._get_artifacts()\n return {\"task_uuid\": task_uuid, \"artifacts\": artifacts}\n\n @staticmethod\n def is_valid_uuid(uuid_str: str) -> bool:\n \"\"\"Checks if UUID string is valid\n :param uuid_str: UUID of task\n :return: Validation result\n \"\"\"\n try:\n UUID(uuid_str)\n except ValueError:\n return False\n else:\n return True\n\n\nclass Storage:\n \"\"\"\n Manages the file system and maintains a structure with\n Task and Artifact objects\n\n Structure:\n Storage\n |__ Task\n |__ Artifact\n |__ Artifact\n |__ Task\n \"\"\"\n\n def __init__(self, data_dir: Path) -> None:\n \"\"\"Initialises a Storage object\n\n :param data_dir: Data directory for storage\n :raises:\n DirectoryExistsError: Directory exists already\n PermissionError: Insufficient permission to create directory\n \"\"\"\n self.data_dir = data_dir\n self.tasks: List[Task] = []\n\n if self.data_dir.exists():\n log.info(\"Existing directory found. Attempting to restore Storage.\")\n self._restore_storage()\n else:\n try:\n self.data_dir.mkdir(parents=True, exist_ok=True)\n except PermissionError as e:\n raise e\n\n def get_task(self, task_uuid: str) -> Union[Task, None]:\n \"\"\"Gets task of instance matching the task UUID\n\n :param task_uuid: Task UUID\n :return: The task matched or None\n \"\"\"\n for t in self.tasks:\n if t.get_task_uuid() == task_uuid:\n return t\n return None\n\n def is_task_uuid_exists(self, task_uuid: str) -> bool:\n \"\"\"Checks if task exists in instance based on task UUID\n\n :param task_uuid: Task UUID\n :return: Whether the task exists\n \"\"\"\n task: Union[Task, None] = self.get_task(task_uuid)\n if task is not None:\n return True\n return False\n\n def add_task(self, task: Task) -> None:\n \"\"\"Adds task to instance if it is does not exist already\n\n :param task: The task to add to instance\n :raises:\n TaskExistsError: Task exists already\n \"\"\"\n task_uuid: str = task.get_task_uuid()\n if self.is_task_uuid_exists(task_uuid):\n raise TaskExistsError(\"Task exists already\", task.get_task_uuid())\n self.tasks.append(task)\n\n def add_task_artifact(self, task_uuid: str, artifact: Artifact) -> Path:\n \"\"\"Adds artifact to a task that exists in instance already\n and provides path to store in file system\n\n :param task_uuid: UUID of task to add to instance\n :param artifact: Artifact to store in instance\n :returns: Artifact path to store in file system\n :raises:\n TaskNotFoundError: Task does not exist in instance\n PermissionError: Insufficient permission to create directory\n \"\"\"\n task: Union[Task, None] = self.get_task(task_uuid)\n if task is None:\n storage_path = str(self.get_storage_path())\n raise TaskNotFoundError(\n f\"Task does not exists in {storage_path}\", task_uuid\n )\n task.add_artifact(artifact)\n\n artifact_type_path, artifact_name = artifact.get_artifact_path()\n artifact_path: Path = (\n self.get_storage_path() / task.get_task_path() / artifact_type_path\n )\n if not artifact_path.exists():\n try:\n artifact_path.mkdir(parents=True, exist_ok=True)\n except PermissionError as e:\n raise e\n\n artifact_full_path: Path = artifact_path / artifact_name\n return artifact_full_path\n\n def get_task_artifact_path(self, task_uuid: str, artifact: Artifact) -> Path:\n \"\"\"Gets path to where artifact of task in instance is stored on file system\n\n :param task_uuid: UUID of task to add to instance\n :param artifact: Artifact to store in instance\n :returns: Artifact path where it is store on file system\n :raises:\n TaskNotFoundError: Task does not exist in instance\n ArtifactNotFoundError: Artifact does not exist in instance\n \"\"\"\n task: Union[Task, None] = self.get_task(task_uuid)\n if task is None:\n storage_path = str(self.get_storage_path())\n raise TaskNotFoundError(\n f\"Task does not exists in {storage_path}\", task_uuid\n )\n artifact_info = artifact.get_artifact_info()\n task_artifact: Union[Artifact, None] = task.get_artifact(artifact_info)\n if task_artifact is None:\n raise ArtifactNotFoundError(\n f\"Artifact does not exist in {task_uuid}\", artifact_info\n )\n\n artifact_type_path, artifact_name = task_artifact.get_artifact_path()\n artifact_path: Path = (\n self.get_storage_path()\n / task.get_task_path()\n / artifact_type_path\n / artifact_name\n )\n return artifact_path\n\n def get_storage_path(self) -> Path:\n \"\"\"Gets path of instance in file system\n\n :return: The data directory of instance\n \"\"\"\n return self.data_dir\n\n def get_storage_info(self) -> dict:\n \"\"\"Gets storage info of instance\n\n :returns: Storage info (Attributes of instance)\n \"\"\"\n data_dir: str = str(self.get_storage_path())\n tasks = [task.get_task_info() for task in self.tasks]\n return {\"data_dir\": data_dir, \"tasks\": tasks}\n\n def _restore_storage(self) -> None:\n \"\"\"Restores instance from files and folders in self.data_dir\"\"\"\n file_paths = self.data_dir.rglob(\"*\")\n for fpath in file_paths:\n pruned_fpath = fpath.relative_to(self.data_dir)\n fpath_parts = pruned_fpath.parts\n\n num_of_parts = len(fpath_parts)\n if num_of_parts > 3:\n log.warning(\n f\"Unknown folder structure. Skipping reconstruction of {pruned_fpath}.\"\n )\n continue\n\n try:\n task_uuid_str = fpath_parts[0]\n task = Task(task_uuid_str)\n self.add_task(task)\n except TaskInvalidUUID:\n log.warning(\n f\"Invalid task UUID: {task_uuid_str}. \"\n + f\"Skipping reconstruction of {pruned_fpath}.\"\n )\n continue\n except TaskExistsError:\n pass\n\n if num_of_parts == 3:\n _, artifact_type, artifact_name = fpath_parts\n try:\n artifact = Artifact(artifact_name, artifact_type)\n except ArtifactInvalidName:\n log.warning(\n f\"Invalid artifact name: {artifact_name}. \"\n + f\"Skipping reconstruction of {pruned_fpath}.\"\n )\n continue\n except ArtifactInvalidType:\n log.warning(\n f\"Invalid artifact type: {artifact_type}. \"\n + f\"Skipping reconstruction of {pruned_fpath}.\"\n )\n continue\n else:\n self.add_task_artifact(task_uuid_str, artifact)\n\n\nclass Session:\n \"\"\"Provides a session to interact with storage and manage the file system\"\"\"\n\n def __init__(self, storage: Storage, task: Task, artifact: Artifact):\n self.storage = storage\n self.task = task\n self.artifact = artifact\n self.file_io: BinaryIO\n\n def __enter__(self):\n self.setup()\n return self\n\n def __exit__(self, *exc):\n self.close()\n\n def setup(self):\n \"\"\"Add self.task to self.storage and self.artifact to that task\n and open Binary IO to that artifact path.\"\"\"\n try:\n self.storage.add_task(self.task)\n except TaskExistsError:\n pass\n task_uuid = self.task.get_task_uuid()\n artifact_path = self.storage.add_task_artifact(task_uuid, self.artifact)\n self.file_io = open(artifact_path, \"wb\")\n\n def write(self, data: bytes):\n \"\"\"Write data to self.file_io\n :param data: Data to be written to artifact\"\"\"\n try:\n self.file_io.write(data)\n except AttributeError:\n raise\n\n def close(self):\n \"\"\"Close self.file_io\"\"\"\n try:\n self.file_io.close()\n except AttributeError:\n raise\n","sub_path":"fact/storage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"220582932","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\nngf = 32\n\nclass Dis_z(nn.Module):\n def __init__(self, latent_dim):\n super(Dis_z, self).__init__()\n # self.ngpu = ngpu\n self.z_dim = latent_dim\n self.net = nn.Sequential(\n nn.Linear(self.z_dim, 128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.5),\n nn.Linear(128, 1),\n nn.Sigmoid()\n )\n\n def forward(self, z):\n output = self.net(z)\n return output\n\nclass Decoder(nn.Module):\n def __init__(self, latent_dim):\n super(Decoder, self).__init__()\n # self.ngpu = ngpu\n self.z_dim = latent_dim\n self.net = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(self.z_dim, ngf * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d(ngf * 2, 1, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. 1 x 32 x 32\n )\n\n def forward(self, z):\n z_ = z.view(z.shape[0], z.shape[1], 1, 1)\n output = self.net(z_)\n return output\n\nclass Encoder(nn.Module):\n def __init__(self, latent_dim):\n super(Encoder, self).__init__()\n self.latent_dim = latent_dim\n self.net = nn.Sequential(\n nn.Conv2d(1, ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # ngf x 16 x 16\n\n nn.Conv2d(ngf, 2 * ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(2 * ngf),\n nn.ReLU(True),\n # 2*ngf x 8 x 8\n\n nn.Conv2d(2 * ngf, 4 * ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(4 * ngf),\n nn.ReLU(True),\n # 4*ngf x 4 x 4\n nn.Conv2d(4 * ngf, 8 * ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(8 * ngf),\n nn.ReLU(True),\n # 8*ngf x 2 x 2\n\n nn.Conv2d(8 * ngf, self.latent_dim, padding = 1, kernel_size = 4, stride=2),\n # latent_dim x 1 x 1\n )\n def forward(self, x):\n return torch.squeeze(self.net(x))\n\nclass Discriminator(nn.Module):\n def __init__(self, color_channel = 1, pretrained = False):\n super(Discriminator, self).__init__()\n self.x_net = nn.Sequential(\n nn.Conv2d(color_channel, ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # ngf * 16 * 16\n\n nn.Conv2d(ngf, ngf, padding = 1, kernel_size = 4, stride=2),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # ngf * 8 * 8\n )\n\n self.net = nn.Sequential(\n nn.Linear(ngf * 8 * 8, 128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Dropout(0.5),\n nn.Linear(128, 1),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n # print (\"z dim:\", z.shape)\n x_ = torch.flatten(self.x_net(x), start_dim = 1)\n logits = self.net(x_)\n return logits\n","sub_path":"IRAD/mnist_utils.py","file_name":"mnist_utils.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498494681","text":"import sys, pygame #import pygame, the main library used for graphics\r\n\r\npygame.init() #initialise all of the pygame modules for later use\r\n\r\n#Variables for window size\r\nscreen_width = 1200\r\nscreen_height = 900\r\n\r\nwhite = (255, 255, 255)\r\n\r\nscreen = pygame.display.set_mode([screen_width, screen_height]) #Creates the screen itself\r\nscreen.fill((145, 194, 255)) #Set the background color of the window\r\npygame.display.set_caption(\"Photoelectric Effect Simulator V-Alpha\") #Set the title of the window\r\n\r\ndef button_clicked(button, width, height, mouse, click):\r\n #Defines the bounds of the button\r\n if (button.topleft[0] < mouse[0] < button.topleft[0] + width) and (button.topleft[1] < mouse[1] < button.topleft[1] + height):\r\n\r\n #Draws a new rect of different colour to give the appearance of interaction.\r\n ##Consider different method; this covers the text\r\n pygame.draw.rect(screen, (170, 255, 236), button)\r\n\r\n #Button is pressed so return true\r\n if click[0] == 1:\r\n return True\r\n\r\n#Create a function that will handle the main menu\r\ndef main_menu(mouse, click):\r\n titlefont = pygame.font.SysFont(\"consolas\", 55) #Create a font for the visual title\r\n buttonfont = pygame.font.SysFont(\"consolas\", 45) #Create a font for the text on the buttons\r\n\r\n title = titlefont.render(\"The Photoelectric Effect Simulator\", True, white) #Set the text of the title, and give the colour white\r\n #Create the text for the buttons, and color them black\r\n start_text = buttonfont.render(\"Start\", True, (0,0,0))\r\n quiz_text = buttonfont.render(\"Quiz\", True, (0,0,0))\r\n exit_text = buttonfont.render(\"Exit\", True, (0,0,0))\r\n\r\n #Some variables for the buttons, so if I decide to change anything later it will be easy to do\r\n button_width = 250\r\n button_height = 100\r\n button_color = white\r\n\r\n #Draw the rect objects themselves on the screen, with necessary properties\r\n start_button = pygame.draw.rect(screen, button_color, ((screen_width/6) - button_width/2, 650, button_width, button_height)) #Start Simulation\r\n quiz_button = pygame.draw.rect(screen, button_color, ((screen_width/2) - button_width/2, 650, button_width, button_height)) #Quiz\r\n exit_button = pygame.draw.rect(screen, button_color, (5*(screen_width/6) - button_width/2, 650, button_width, button_height)) #Exit\r\n\r\n #Blit the text objects to the screen in the necessary positions\r\n screen.blit(title, ((screen_width/2)-(title.get_width()/2), screen_height/5))\r\n screen.blit(start_text, (start_button.center[0] - start_text.get_width()/2, start_button.center[1] - start_text.get_height()/2))\r\n screen.blit(quiz_text, (quiz_button.center[0] - quiz_text.get_width()/2, quiz_button.center[1] - quiz_text.get_height()/2))\r\n screen.blit(exit_text, (exit_button.center[0] - exit_text.get_width()/2, exit_button.center[1] - exit_text.get_height()/2))\r\n\r\n #Call the button_clicked method, once for each button, so the program can continue as necessary when a button is pressed\r\n b1 = button_clicked(start_button, button_width, button_height, mouse, click)\r\n b2 = button_clicked(quiz_button, button_width, button_height, mouse, click)\r\n b3 = button_clicked(exit_button, button_width, button_height, mouse, click)\r\n\r\n #Exit button pressed, so end the program\r\n if b3:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\nwhile True:\r\n\r\n #Get the current mouse position and state of the mouse buttons\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n main_menu(mouse, click) #For testing purposes, just call the menu here\r\n\r\n #Main loop\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n","sub_path":"v0.0.2.py","file_name":"v0.0.2.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"460405213","text":"from PIL import Image\r\ndef encode():\r\n def decrypt(text,s): \r\n result = \"\" \r\n \r\n # traverse text \r\n for i in range(len(text)): \r\n char = text[i] \r\n \r\n # Encrypt uppercase characters \r\n if (char.isupper()): \r\n result += chr((ord(char) - s))\r\n \r\n # Encrypt lowercase characters \r\n else: \r\n result += chr((ord(char) - s)) \r\n \r\n \r\n return result \r\n name=input(\"enter img name with ext:\")\r\n img=Image.open(name)\r\n img.show()\r\n imgcpy=img.copy()\r\n tname = input(\"enter the file name to be encrypted\")\r\n with open(tname,'r') as file:\r\n text = file.read()\r\n s = 4\r\n fname =input(\"enter fname\")\r\n with open (fname,'w') as file1:\r\n file1.write(decrypt(text,s))\r\n with open (fname,'r') as file2:\r\n \r\n message=file2.read()\r\n if len(message)==0:\r\n raise Exception(\"Data is empty\")\r\n message+=\" stp \"\r\n mess8bit=To8bitBin(message)\r\n #print mess8bit\r\n getPix(mess8bit,imgcpy,name)\r\n print (\"Encryption Complete\")\r\n img=Image.open(\"new\"+name[0:len(name)-3]+\"bmp\")\r\n img.show()\r\ndef To8bitBin(mess):\r\n binmess = [] \r\n for i in mess: \r\n binmess.append(format(ord(i), '08b'))\r\n return binmess\r\n\r\ndef getPix(mess8bit,img,name):\r\n pixelmap=img.load()\r\n i=j=0\r\n rgb=0\r\n for k in mess8bit:\r\n l=0\r\n while l<8:\r\n pixel=pixelmap[i,j]\r\n #print \"pixelmap1:\",pixelmap[i,j]\r\n #print \"pixel:\",pixel\r\n p=str(format(int(pixel[rgb]),'08b'))\r\n #print \"p:\",p\r\n newpix=p[0:6]+k[l:l+2]\r\n #print \"newpix1:\", newpix\r\n l+=2\r\n newpix=int(newpix,2)\r\n #print \"newpix2:\",newpix\r\n if rgb==0:\r\n pixelmap[i,j]=(newpix,int(pixel[1]),int(pixel[2]))\r\n elif rgb==1:\r\n pixelmap[i,j]=(int(pixel[0]),newpix,int(pixel[2]))\r\n else:\r\n pixelmap[i,j]=(int(pixel[0]),int(pixel[1]),newpix)\r\n #print \"pixelmap2:\",pixelmap[i,j]\r\n if rgb==2:\r\n rgb=0\r\n else:\r\n rgb+=1\r\n j+=1\r\n if j==img.size[1]:\r\n j=0\r\n i+=1\r\n \r\n img.save(\"new\"+name[0:len(name)-3]+\"bmp\")\r\nencode()\r\n\r\n\r\n\r\n \r\n \r\n \r\n","sub_path":"encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"651934889","text":"import logging\nimport mysql.connector\nimport sys\nimport config as cfg\nfrom logging.handlers import TimedRotatingFileHandler\n\"\"\"\n Se encarga de llamar a un servicio que separa la palabra en silabas\n\"\"\"\nclass Auditor:\n\n def __init__(self, telegram_message):\n self.message = telegram_message.message\n self.user_id = telegram_message.user_id\n self.user_alias = telegram_message.user_alias\n self.user_name = telegram_message.user_name\n self.converted_message = telegram_message.convertedMessage\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n self.logger = logging.getLogger(__name__)\n flogging = TimedRotatingFileHandler('log/jeringoso_bot.log', when=\"d\", interval=1, backupCount=7)\n flogging.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n self.logger.addHandler(flogging)\n self.logger = logging.getLogger(__name__)\n self.logger.info('payload a enviar: \"%s\"', self.message)\n\n def auditar(self):\n self.logger.info('palabra a guardar: \"%s\"', self.message)\n\n \n try:\n connection = mysql.connector.connect(host=cfg.dbdata['host'], # your host, usually localhost\n user=cfg.dbdata['user'], # your username\n passwd=cfg.dbdata['passwd']) # your password\n\n cursor = connection.cursor()\n # Create a new record\n sql = \"INSERT INTO dsc.telegram_message (user_id, user_alias, user_name, message, request_timestamp) VALUES (%s, %s, %s, %s, NOW())\"\n cursor.execute(sql, (self.user_id, self.user_alias, self.user_name, self.message))\n\n # connection is not autocommit by default. So you must commit to save\n # your changes.\n connection.commit()\n self.logger.debug('registración realizada en la base de datos. Palabra ingresada %s', self.message, self.converted_message)\n except Exception as e:\n logging.error(\"Error al guardar mensaje {0}\".format(e))\n finally:\n connection.close()","sub_path":"Auditor.py","file_name":"Auditor.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"191161700","text":"\nimport cv2 as cv\nfrom Useful_Tools.MATLAB_Importing import loadmat\nfrom RF_Voltages import Calc_RF_Voltage\nfrom Useful_Tools.General_Data_Vis import Save_Figs\nimport numpy as np\nimport numpy.ma as ma\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.patches as patches\nimport cvxpy as cp\nimport sys\nimport skimage.color\nimport skimage.filters\nimport skimage.io\nimport skimage.viewer\n\n\n#****************************\n#params used on day\n\n# ROI_xCOL_range_low=13\n# ROI_xCOL_range_high=23\n#\n# ROI_yROW_range_low=25\n# ROI_yROW_range_high=35\n#\n# ROI_z_slice=20\n\nROI_xCOL_range_low=13\nROI_xCOL_range_high=23\n\nROI_yROW_range_low=25\nROI_yROW_range_high=35\n\nROI_z_slice=20\n\n\n\n#if cube...\n# ROI_z_range_low = 35\n# ROI_z_range_high = 45\n\n#constraint params\nSAR_Limit = 5\n\n#generate realistic RF pulse\npulseDuration = 4 * (10 ** -3) # s\nsliceThickness = 42 * (10 ** -3) # m\nBWT = 8\nEmp = 0.8\nV_max = 114.265 #114.265 # V\nTR = 7.36 * (10 ** -3) # s\n#*********************************************************************\n#load in MATLAB files\nAdj_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/AdjDataUser.mat')\nSys_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/SysDataUser.mat')\nSar_dictionary = loadmat('/Users/lizgabriel/PycharmProjects/PTx/Data/menieres_2021_02_19/SarDataUser.mat')\n\nS = np.array(Adj_dictionary['Adj']['S'])\ntxScaleFactor = np.array(Sys_dictionary['txScaleFactor'])\nadjtra = float(Sys_dictionary['adjtra'])\nZZ = Sar_dictionary['ZZ']\nZZtype = Sar_dictionary['ZZtype']\numax = np.array(Sys_dictionary['umax'])\n\n# get dimensions\nmatrixsize = int(math.sqrt(S.shape[0])) #assuming square array replace with rows and columns, rename as N_ etc\ncoils = int((S.shape[1]))\nslices = int((S.shape[2]))\n\n#*********************************************************************\n#get sar vops\nSAR_VOP_Index = (np.where(ZZtype == 6))[0][:] #find indicies of where in ZZ type the code = 6\nSAR_VOP = np.take(ZZ, SAR_VOP_Index, axis=2) #find corresponding VOP matrices\n\n#*********************************************************************\n#correct S which is [2809,8,52]\nS_Corrected = S #* txScaleFactor[None,:,None]\nS_Corrected_Summed = np.sum(S_Corrected, axis=1)\n\n\n#Cic pol, NOT for optimisation, only for plotting\nS_Corrected_CP = S * txScaleFactor[None,:,None]\nS_Corrected_Summed_CP = np.sum(S_Corrected_CP, axis=1)\n\n\n# #*********************************************\n#run this to figure out ROI params\nS_Corrected_Image = S_Corrected_Summed.reshape((matrixsize,matrixsize,slices), order = 'C')\n# #plot out before and after on same plot\n# fig=plt.figure(figsize=(30, 30))\n# columns = 10\n# rows = 10\n#\n# ax=[]\n# for i in range(0,slices):\n# ax.append(fig.add_subplot(rows, columns, i+1))\n# ax[-1].axis('off')\n# plt.imshow(np.abs(S_Corrected_Image[:,:,i]),vmin=0,vmax=0.025)\n# ax[ROI_z_slice].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n# plt.show()\n\n\n\n# #test to check tx scale factor being applied correctly\n# S_Corrected_loop=np.zeros((2809,8,80), dtype='complex')\n# for i in range(0,coils):\n# S_Corrected_loop[:,i,:]= S[:,i,:] * txScaleFactor[i]\n\n# # test to show applying txscale factor messes up phase info\n# a = (S[1000,1,40] * txScaleFactor[1]) + (S[1000,2,40] * txScaleFactor[2]) + (S[1000,3,40] * txScaleFactor[3]) + (S[1000,4,40] * txScaleFactor[4]) + (S[1000,5,40] * txScaleFactor[5]) + (S[1000,6,40] * txScaleFactor[6]) +(S[1000,7,40] * txScaleFactor[7]) + (S[1000,0,40] * txScaleFactor[0])\n# phase_a = np.angle(a)\n\n# #test summing being done as expected\n# Sum_Loop=np.zeros((matrixsize*matrixsize,slices), dtype = complex)\n# for j in range(0,(matrixsize*matrixsize)):\n# for i in range(0,slices):\n# Sum_Loop[j,i] = S_Corrected[j,0,i] + S_Corrected[j,1,i] + S_Corrected[j,2,i] + S_Corrected[j,3,i] + S_Corrected[j,4,i] + S_Corrected[j,5,i] +S_Corrected[j,6,i] +S_Corrected[j,7,i]\n# diff = Sum_Loop - S_Corrected_Summed\n\n\n#*********************************************************************\n#CREATE ROI AROUND IAMS\n# #limit S to an ROI around inner ear\n\n#create blank arrays\nimage_coil=[]\nROI_Square=[]\n\n\n#also get a test square ROI for each coil\nfor i in range(0,coils):\n #image for each coil\n image_coil.append((S_Corrected[:,i,:]).reshape((matrixsize,matrixsize,slices), order ='C'))\n #ROI square, for each coil\n ROI_Square.append((image_coil[i])[ROI_yROW_range_low:ROI_yROW_range_high,ROI_xCOL_range_low:ROI_xCOL_range_high,ROI_z_slice])\n\n\nROI_Square=np.array(ROI_Square)\nROI_Square_Stacked = ROI_Square.reshape((8,-1), order='F')\nROI_Square_Stacked = ROI_Square_Stacked.transpose()\n\n# #to check ROI position\n# image_coil = np.array(image_coil)\n# for i in range(0,coils):\n# fig, axs = plt.subplots(1, 2, figsize=(10, 10))\n# axs[0].imshow(np.abs(image_coil[i,:,:,ROI_z_slice]), vmin=0, vmax=0.1)\n# axs[1].imshow(np.abs(ROI_Square[i,:,:]), vmin=0, vmax=0.1)\n# plt.show()\n\n\n\n# #•••••••••••••••••••••••••••••••••••••\n# #ROI tests\n# #sanity check to see is ROI Coil and STacked ROI coil have same S maps for each coil\n# should_be_zeros =[]\n# for i in range(0,coils):\n# diff = np.amax(ROI_Square[i,:,:]) - np.amax(ROI_Square_Stacked[i,:])\n# should_be_zeros.append(diff)\n# should_be_zero = np.amax(should_be_zeros)\n# #seems all good!\n\n#•••••••••••••••••••••••••••••••••••••\n# optimisation!\n\n# AIM - value of 11.7/adjtra (target T/V) for that data set is the aim in the ROI\n# b = is target T/V in ROI\n# minimise this ||Sw - b||^2 subject to for each vop: w^H * VOP * w < SAR local limit and subject to for each wi: abs(wi) < umax\n# https://www.cvxpy.org one step at a time!\n\nV_sq_av, AmpIntAv = Calc_RF_Voltage(pulseDuration, sliceThickness, BWT, Emp, V_max, TR)\n\n\nw = cp.Variable(8, complex=True)\n\nVOP = cp.Constant(SAR_VOP[:,:,0])\nVOP1 = cp.Constant(SAR_VOP[:,:,1])\nVOP2 = cp.Constant(SAR_VOP[:,:,2])\nVOP3 = cp.Constant(SAR_VOP[:,:,3])\nVOP4 = cp.Constant(SAR_VOP[:,:,4])\nVOP5 = cp.Constant(SAR_VOP[:,:,5])\nVOP6 = cp.Constant(SAR_VOP[:,:,6])\nVOP7 = cp.Constant(SAR_VOP[:,:,7])\n\n\n\nb = np.full((ROI_Square_Stacked[:,1]).shape, 11.7/adjtra)\nobjective = cp.Minimize(cp.sum_squares(((ROI_Square_Stacked @ w) - b)))\nconstraints = [(V_sq_av * cp.quad_form(w,VOP)) <= SAR_Limit , (V_sq_av * cp.quad_form(w,VOP1)) <= SAR_Limit , (V_sq_av * cp.quad_form(w,VOP2)) <=SAR_Limit, (V_sq_av * cp.quad_form(w,VOP3)) <= SAR_Limit, (V_sq_av * cp.quad_form(w,VOP4)) <= SAR_Limit, (V_sq_av * cp.quad_form(w,VOP5)) <= SAR_Limit, (V_sq_av * cp.quad_form(w,VOP6)) <= SAR_Limit, (V_sq_av * cp.quad_form(w,VOP7)) <= SAR_Limit]\n# constraints = [(cp.quad_form(w,VOP)) <= SAR_Limit , (cp.quad_form(w,VOP1)) <= SAR_Limit , (cp.quad_form(w,VOP2)) <=SAR_Limit, (cp.quad_form(w,VOP3)) <= SAR_Limit, (cp.quad_form(w,VOP4)) <= SAR_Limit, (cp.quad_form(w,VOP5)) <= SAR_Limit, (cp.quad_form(w,VOP6)) <= SAR_Limit, (cp.quad_form(w,VOP7)) <= SAR_Limit]\nprob = cp.Problem(objective, constraints)\nresult = prob.solve()\nprint(w.value)\nw_opt = w.value\n\n#get w_opt angle and phase\nw_opt_abs = np.abs(w_opt)\nw_opt_ph = (np.angle(w_opt) * 180) / np.pi\n\n#before and after average values in Square ROI\nROI_summed_after = np.matmul(ROI_Square_Stacked, w_opt)\n# ROI_summed_before = np.sum(ROI_Square_Stacked, axis =1)\nROI_summed_before = np.matmul(ROI_Square_Stacked, txScaleFactor)\n\nBefore_Av_CP = np.average(np.abs(ROI_summed_before))\nAfter_Av = np.average(np.abs(ROI_summed_after))\nBefore_Min_CP = np.min(np.abs(ROI_summed_before))\nAfter_Min = np.min(np.abs(ROI_summed_after))\nBefore_CoV = Before_Av_CP/((np.std(np.abs(ROI_summed_before))))\nAfter_CoV = After_Av/((np.std(np.abs(ROI_summed_after))))\n\nShimCalcSAR=[]\n#voltage check\nfor i in range(1,8):\n ShimCalcSAR.append((V_sq_av * (np.matmul(np.matmul((w_opt.conj().T) , SAR_VOP[:,:,i]) , w_opt))))\nprint(ShimCalcSAR)\n\n\n\n\n\n#Get before image\nS_Corrected_Image = S_Corrected_Summed.reshape((matrixsize,matrixsize,slices), order = 'C')\nS_Corrected_Image_CP = S_Corrected_Summed_CP.reshape((matrixsize,matrixsize,slices), order = 'C')\n\n#Get optimised total image\nS_Opt_Sum = np.sum((S_Corrected * w_opt[None,:,None]), axis=1)\nImageOpt = S_Opt_Sum.reshape((matrixsize,matrixsize,slices), order = 'C') #2D images slice by slice\n\n#get optimised ROI image\nROI_Image_Opt = np.sum((ROI_Square * w_opt[:,None,None]), axis=0)\n\n\n# same plot for both, quad, target, solution, line profiles through, argand diagram of drives (see paper)\n#\n# plot it out\n# https://stackoverflow.com/questions/46615554/how-to-display-multiple-images-in-one-figure-correctly/46616645\n\n\n#plot out before and after\n# fig=plt.figure(figsize=(30, 30))\n# columns = 10\n# rows = 10\n# ax=[]\n#\n# for i in range(0,slices):\n# ax.append(fig.add_subplot(rows, columns, i+1))\n# ax[-1].axis('off')\n# plt.imshow(np.abs(S_Corrected_Image_CP[:,:,i]),vmin=0,vmax=0.1)\n# plt.figtext(0.5,0.98,\"original\", ha=\"center\", va=\"top\", fontsize=40, color=\"r\")\n# ax[ROI_z_slice].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n# plt.show()\n#\n# fig=plt.figure(figsize=(30, 30))\n# columns = 10\n# rows = 10\n# ax=[]\n# for j in range(0, slices):\n# ax.append(fig.add_subplot(rows, columns, j+1))\n# ax[-1].axis('off')\n# plt.imshow(np.abs(ImageOpt[:,:,j]),vmin=0,vmax=0.1)\n# plt.figtext(0.5,0.98,\"optimised\", ha=\"center\", va=\"top\", fontsize=40, color=\"r\")\n# ax[ROI_z_slice].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n# plt.show()\n\n\n#zoom in before, target, after on one slice\nfig, axs = plt.subplots(2, 3, figsize=(10, 10))\naxs[0,0].imshow(np.abs(S_Corrected_Image_CP[:,:,ROI_z_slice]),vmin=0,vmax=0.1)\naxs[0,1].imshow(np.full((S_Corrected_Image[:,:,ROI_z_slice]).shape, 11.7/adjtra),vmin=0,vmax=0.1)\naxs[0,2].imshow(np.abs(ImageOpt[:,:,ROI_z_slice]),vmin=0,vmax=0.1)\n\naxs[0,0].set_title(\"pre opt\")\naxs[0,1].set_title(\"target value\")\naxs[0,2].set_title(\"post opt\")\n\n\naxs[0,0].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\naxs[0,1].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\naxs[0,2].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n\n#line profile through slice\nrow = int((ROI_yROW_range_high + ROI_yROW_range_low)/2)\nrow_Image = np.abs(S_Corrected_Image[row,:,ROI_z_slice]) #checked it was this way round using distinctive row 52\nrow_ImageOpt = np.abs(ImageOpt[row,:,ROI_z_slice])\nrow_Image_CP = np.abs(S_Corrected_Image_CP[row,:,ROI_z_slice])\nrow_target = np.full(row_Image.shape, 11.7/adjtra)\n\n\naxs[0,0].axhline(y=row,color='red')\naxs[0,2].axhline(y=row,color='red')\n\naxs[1,2].plot(row_ImageOpt, 'm', label='optimised image')\naxs[1,0].plot(row_Image_CP, 'k', label='pre optimised image')\naxs[1,1].plot(row_ImageOpt, 'm', label='optimised image')\naxs[1,1].plot(row_Image_CP, 'k', label='before')\naxs[1,1].plot(row_target, label='target')\n\naxs[1,0].legend(loc='upper right')\naxs[1,1].legend()\naxs[1,2].legend(loc='upper right')\n\naxs[1,0].set_xlabel('Pixel')\naxs[1,1].set_xlabel('Pixel')\naxs[1,2].set_xlabel('Pixel')\n\naxs[1,0].set_ylabel('B1+ (uT/V)')\naxs[1,1].set_ylabel('B1+ (uT/V)')\naxs[1,2].set_ylabel('B1+ (uT/V)')\n\n\naxs[1,1].axvline(x=ROI_xCOL_range_low, color='red',ls='--')\naxs[1,1].axvline(x=ROI_xCOL_range_high, color='red', ls='--')\nplt.show()\n\n\n\n\n#NOW PHASE INFO\n#zoom in before, target, after on one slice\nfig, axs = plt.subplots(1, 2, figsize=(10, 10))\naxs[0].imshow(np.angle(S_Corrected_Image[:,:,ROI_z_slice]), vmin=-3.14159, vmax=3.14159)\naxs[1].imshow(np.angle(ImageOpt[:,:,ROI_z_slice]), vmin=-3.14159, vmax=3.14159)\n\naxs[0].set_title(\"pre opt phase\")\naxs[1].set_title(\"post opt phase\")\n\naxs[0].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\naxs[1].add_patch(patches.Rectangle((ROI_xCOL_range_low,ROI_yROW_range_low), (ROI_xCOL_range_high-ROI_xCOL_range_low), (ROI_yROW_range_high-ROI_yROW_range_low), edgecolor=\"red\", facecolor='none'))\n\na=np.angle(S_Corrected_Image[:,:,ROI_z_slice])\n\nplt.show()\n\n\n#argand diagram.....\nfor x in w_opt:\n plt.polar([np.angle(w_opt)], [np.abs(w_opt)], marker='o')\nplt.show()\n\n\n\n# post op - units?\n# fig, axs = plt.subplots(1, 2, figsize=(10, 10))\n# ImageOptANGLE = (ImageOpt * 2.675 * (10**8) * (10**-6) * 184.8 * (10**-3)) * (180/np.pi)\n# rowImageOptANGLE = np.abs(ImageOptANGLE[25,:,ROI_z_slice])\n# axs[0].imshow(np.abs(ImageOptANGLE[:,:,ROI_z_slice]))\n# axs[1].plot(rowImageOptANGLE)\n# plt.show()\n\n\n# # VOPS\n# fig=plt.figure(figsize=(30, 30))\n# columns = 4\n# rows = 2\n# ax=[]\n#\n# for i in range(0,7):\n# ax.append(fig.add_subplot(rows, columns, i+1))\n# ax[-1].axis('off')\n# plt.imshow(np.abs(SAR_VOP[:,:,i]))\n# plt.show()\n#\n","sub_path":"PTx_19_02_21_SquareFIXED.py","file_name":"PTx_19_02_21_SquareFIXED.py","file_ext":"py","file_size_in_byte":13562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"330139873","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 30 13:22:16 2019\n\n@author: lgozasht\n\"\"\"\nimport os\nfrom pathlib import Path\nfrom sequenceAnalyzer import FastAreader\nfrom Bio.Seq import Seq\nimport random\nimport copy\n\n\n\nclass RetrieveIntroners():\n \"\"\"\n retrieve putative introners for each species \n \"\"\"\n \n def __init__(self, intronerFile, exintFile):\n \n self.intronerFile = intronerFile\n self.ieList = []\n self.exintFile = exintFile\n self.finalList = []\n \n def retrieveIEs(self):\n myReaderIE = FastAreader(self.intronerFile)\n for header, seq in myReaderIE.readFasta():\n headList = header.split('_')\n #print(headList)\n fam = headList[0]\n\n #print(fam)\n #print(scaff)\n scaff = headList[1]\n #scaff = head[1:len(head):1]\n #print(scaff)\n coord = headList[2]\n coordList = coord.split(\"-\")\n start = int(coordList[0])\n #print(start)\n stop = int(coordList[1])\n #print(stop)\n ieDic = {'fam':fam, 'scaff':scaff,'start':start,'stop':stop, 'seq': seq}\n self.ieList.append(ieDic)\n \n def retrieveAll(self):\n \"\"\"\n extract from scott's script output file\n \"\"\"\n allList = []\n myReaderAll = FastAreader(self.exintFile)\n for header, seq in myReaderAll.readFasta():\n #seq.upper()\n data = header + ';' + seq\n allList.append(data)\n \n for data in allList:\n # print(data)\n intron = data.split(';')[-1]\n # print(data)\n header = data.split(';')[0]\n # print(header)\n for ieDic in self.ieList:\n ieSeq = ieDic['seq']\n #intronList = intron.split() \n #intronUpper = intronList.join('').upper()\n intronUpper = copy.deepcopy(intron)\n intronUpper = intronUpper.upper()\n if ieSeq in intronUpper:\n # print(intron)\n del ieDic['seq']\n \n ieDic['seq'] = intron\n ieDic['header'] = header\n self.finalList.append(ieDic)\n #break\n sequence = Seq(ieDic['seq']) \n revComp = sequence.reverse_complement()\n strrevComp = str(revComp)\n if strrevComp in intronUpper:\n \n #print(intron)\n del ieDic['seq']\n ieDic['header'] = header\n\n ieDic['seq'] = intron\n self.finalList.append(ieDic)\n #break\n #print(self.finalList)\n\n return self.finalList\n\n \n\n \n \n\n \nclass csvReader():\n \"\"\"\n Read NCBI eukaryotes.csv file and extract the assembky reference, fasta link, and annotation link for each species in the eukaryotes file.\n \n Return a dictionary containing the assembky reference, fasta link, and annotation link for each species in the eukaryotes file.\n \"\"\"\n\n\n def __init__(self, dataFile = ''):\n\n self.dataFile = dataFile\n\n def csv(self):\n assemblies = []\n with open(self.dataFile,'r') as f:\n for line in f:\n line = line.rstrip()\n sp = line.split(',')\n if '#' in sp[0]:\n continue\n \n \n\n\n elif len(sp) == 16:\n #print('what')\n refLink = sp[15]\n refLink = refLink.strip('\\\"')\n refLink = refLink.strip('\\\"')\n genLink = sp[14]\n genLink = genLink.strip('\\\"')\n genLink = genLink.strip('\\\"')\n\n try:\n #print(link)\n refPreAssembly = refLink.split(\"/\")[-1]\n # print(preAssembly)\n # preList = preAssembly.split(\"_\")\n # print(preList[0])\n # print(preList[1])\n\n refAssembly = refPreAssembly.split(\"_\")[0] + \"_\" + refPreAssembly.split(\"_\")[1]\n # print(Assembly)\n refFasta = refLink + '/*_genomic.fna.gz'\n refAnnotation = refLink + '/*_genomic.gbff.gz'\n genPreAssembly = genLink.split(\"/\")[-1]\n # print(preAssembly)\n # preList = preAssembly.split(\"_\")\n # print(preList[0])\n # print(preList[1])\n\n genAssembly = genPreAssembly.split(\"_\")[0] + \"_\" + genPreAssembly.split(\"_\")[1]\n # print(Assembly)\n genFasta = genLink + '/*_genomic.fna.gz'\n genAnnotation = genLink + '/*_genomic.gbff.gz'\n\n assemblyDic = {'Species': sp[0],'RefSeq' : refAssembly, 'refFasta' :refFasta , 'refAnnotation' : refAnnotation, 'GenBank' : genAssembly, 'genFasta' :genFasta , 'genAnnotation' : genAnnotation}\n assemblies.append(assemblyDic)\n except IndexError:\n \n link = sp[14]\n link = link.strip('\\\"')\n link = link.strip('\\\"')\n try:\n #print(link)\n preAssembly = link.split(\"/\")[-1]\n # print(preAssembly)\n # preList = preAssembly.split(\"_\")\n # print(preList[0])\n # print(preList[1])\n \n Assembly = preAssembly.split(\"_\")[0] + \"_\" + preAssembly.split(\"_\")[1]\n # print(Assembly)\n \n fasta = link + '/*_genomic.fna.gz'\n annotation = link + '/*_genomic.gbff.gz'\n \n assemblyDic = {'Species': sp[0],'GenBank' : Assembly, 'genFasta' : fasta, 'genAnnotation' : annotation}\n assemblies.append(assemblyDic)\n except IndexError:\n pass\n\n return assemblies\n \nclass Compare():\n \n \"\"\"\n Run scott's script to compare intron positions for all putative introners\n \"\"\"\n \n def __init__(self, eukFile, NAME):\n self.eukFile = eukFile\n self.NAME = NAME\n self.dataDic = {}\n self.relevantClade = ''\n self.relatedSpecies = []\n\n def dataGen(self):\n with open(self.eukFile,'r') as f:\n for line in f:\n line = line.rstrip()\n sp = line.split(',')\n if '#' in sp[0]:\n continue\n else:\n try:\n clade = sp[1].split(';')[-1]\n \n genLink = sp[14]\n genLink = genLink.strip('\\\"')\n genLink = genLink.strip('\\\"')\n \n refPreAssembly = genLink.split(\"/\")[-1]\n refAssembly = refPreAssembly.split(\"_\")[0] + \"_\" + refPreAssembly.split(\"_\")[1]\n if self.NAME == refAssembly:\n self.relevantClade = clade\n if clade not in self.dataDic.keys():\n self.dataDic[clade] = [refAssembly]\n else:\n self.dataDic[clade].append(refAssembly)\n except IndexError:\n pass\n def randomSelect(self):\n relevantList = self.dataDic[self.relevantClade]\n i = 0\n while i < 5:\n randomSpecies = random.choice(relevantList)\n config = Path('../ieFind*/Data_{0}/my{0}.exons-introns'.format(randomSpecies))\n if config.is_file():\n self.relatedSpecies.append(random.choice(relevantList))\n i += 1\n \n def runScottScript(self):\n for species in self.relatedSpecies:\n os.system('cp ../ieFind*/Data_{0}/my{0}.exons-introns .'.format(species))\n \n \n os.system('perl ./HOMOLOGOUS_INTRON_FILTER.PL -filter Data_{0}/putativeIEs.exons-introns Data_{0}/my{1}.exons-introns Data_{0}/my{2}.exons-introns Data_{0}/my{3}.exons-introns Data_{0}/my{4}.exons-introns Data_{0}/my{5}.exons-introns > Data_{0}/HOMO.out'.format(self.NAME, self.relatedSpecies[0], self.relatedSpecies[1], self.relatedSpecies[2], self.relatedSpecies[3], self.relatedSpecies[4]))\n \n \n \n \n \n \n\ndef main():\n myData = csvReader('test.csv')\n genomeData = myData.csv()\n \"\"\"STEP 1\"\"\"\n for assembly in genomeData:\n try:\n NAME = assembly['GenBank']\n print(NAME)\n ieFile = Path(\"Data_{0}/postProteinAlignmentIEs.fa\".format(NAME))\n \n # print(\"please\")\n if ieFile.is_file():\n \n \n print('Processing {0}'.format(NAME))\n \n os.system('wget {0}'.format(assembly['genAnnotation']))\n # os.system('wget {0}'.format(assembly['genFasta']))\n\n os.system('gunzip {0}*'.format(NAME))\n os.system('cp {0}* ./Data_{0}'.format(NAME))\n os.system('gunzip ./Data_{0}/*'.format(NAME))\n os.system('rm -r {0}*'.format(NAME))\n# fastaList = assembly['Fasta'].split(\"/\")\n# fastaGz = fastaList[-2]\n# fasta = fastaGz + '_genomic.fna'\n annotationList = assembly['genAnnotation'].split(\"/\")\n annotationGz = annotationList[-2]\n annotation = annotationGz + '_genomic.gbff'\n print(annotation)\n# print(fasta)\n print(NAME)\n \"\"\"\n Make exint files for each species\n \"\"\"\n os.system('perl ./exint-gb.pl Data_{0}/{1} > ./Data_{0}/my{0}.exons-introns'.format(NAME, annotation))\n \n \n myPutativeIntroners = RetrieveIntroners(\"Data_{0}/postProteinAlignmentIEs.fa\".format(NAME),'./Data_{0}/my{0}.exons-introns'.format(NAME))\n myPutativeIntroners.retrieveIEs()\n finalList = myPutativeIntroners.retrieveAll()\n print(finalList)\n with open('Data_{0}/putativeIEs.exons-introns'.format(NAME), 'w') as exintFile:\n for ieDic in finalList:\n header = ieDic['header']\n seq = ieDic['seq']\n exintFile.write('>{0}\\n'.format(header))\n exintFile.write('{0}\\n'.format(seq))\n\n \n \n \n \"\"\"\n compare introns (Scott's script)\n \n What about the fasta. Does it just need to be in the same direction? or what?\n \"\"\"\n os.system('rm -r Data_{0}/GCA*'.format(NAME))\n os.system('rm -r Data_{0}/GCF*'.format(NAME))\n os.system('cp my* Data_{0}'.format(NAME))\n os.system('cp putative* Data_{0}'.format(NAME))\n\n #myComparison = Compare(ieList)\n \n \n \n \n else:\n print(\"no IEs\")\n continue\n except KeyError:\n print('No Genbank Assembly')\n \n \n \n \"\"\"Step 2\"\"\"\n \n for assembly in genomeData:\n try:\n NAME = assembly['GenBank']\n print(NAME)\n ieFile = Path(\"Data_{0}/postProteinAlignmentIEs.fa\".format(NAME))\n if ieFile.is_file():\n\n myComparison = Compare('test.csv', NAME)\n myComparison.dataGen()\n myComparison.randomSelect()\n myComparison.runScottScript()\n os.system('cp my* Data_{0}'.format(NAME))\n os.system('cp putative* Data_{0}'.format(NAME))\n os.system('rm -r my*')\n os.system('rm -r putative*')\n\n else:\n print(\"no IEs\")\n continue\n except KeyError:\n print('No Genbank Assembly')\n \n \n \n \n \n \n \nif __name__ == \"__main__\":\n main() ","sub_path":"comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":12880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149384246","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.8.5 (default, Jan 27 2021, 15:41:15) \n# [GCC 9.3.0]\n# Embedded file name: /home/docker/CSN/bin/gpu_ccsn.py\n# Compiled at: 2021-03-31 16:15:26\n# Size of source mod 2**32: 19699 bytes\n\"\"\"\npython version of csn algorithm\nhttps://github.com/wys8c764/CSN\n\"\"\"\nimport os, argparse, logging, pandas as pd, numpy as np\nfrom scipy import sparse\nfrom scipy import stats\nimport sys\nsys.path.append('.')\nimport useful_functions as uf\n\ndef condition_g(adjmc, kk=50, dlimit=5):\n \"\"\"return the degree >5 and top kk ρ统计量的gene index, 可优化参数 > degree limit\"\"\"\n a = np.sum(adjmc, axis=1)\n id1 = np.argwhere(a >= dlimit)\n INDEX = np.argsort(a[id1.flatten()])[::-1]\n id2 = INDEX[0:kk]\n return id2.tolist()\n\n\ndef get_data(csv):\n if str(csv).endswith('csv'):\n df = pd.read_csv(csv, index_col=0, header=0)\n else:\n df = pd.read_csv(csv, index_col=0, header=0, sep='\\t')\n return df\n\n\nclass SSN:\n \"\"\"Construction of cell-specific networks\n 模型构建过程用所有的样品数据,后续预测用整合有的大表做dm转化但仅输出少量样品(cells.list)的network和degree matrix\n 在dblur features水平做矩阵融合\n The function performs the transformation from gene expression matrix to cell-specific network (csn).\n This is a groups style docs.\n \n Parameters: \n `data` Gene expression matrix, rows = genes, columns = cells\n Returns: None\n Raises: KeyError - raises an exception\n \"\"\"\n\n def __init__(self, data, outdir='./', log=None):\n \"\"\"\n default values when initialize. set log file\n \"\"\"\n self.outdir = outdir\n self.tablename = data\n uf.create_dir(self.outdir)\n self.log = os.path.join(self.outdir, log) if log else os.path.join(self.outdir, '{}_{}.log'.format(os.path.basename(data), uf.now()))\n self.logger = uf.create_logger(self.log)\n self.logger.info('start reading data from {}, log file is {}'.format(data, self.log))\n df = get_data(data)\n self.data = df.loc[(df.sum(axis=1) != 0, df.sum(axis=0) != 0)]\n self.csn = None\n self.logger.info('finish reading data from {}'.format(data))\n\n @uf.robust\n def get_cells(self, cells=None):\n \"\"\"\n Get cells in list format\n \n Parameters:\n file cells.list\n Returns: \n cells in list format\n Raises: \n KeyError - raises an exception\n \"\"\"\n if not cells:\n cells = list(self.data.columns)\n else:\n if isinstance(cells, list):\n cells = cells\n else:\n if os.access(cells, os.R_OK):\n cells = [cell.strip() for cell in open(cells).readlines()]\n else:\n print('cells must be list or file with one column')\n return cells\n\n @uf.robust\n def csnet(self, cells=None, alpha=0.01, boxsize=0.1, edgeW=0, kk=0, dlimit=5, to_csv=0, average=1, *args, **kwargs):\n \"\"\"\n fcndm = cndm(data, 0.1, 0.1, 1) for test\n Construct the CSN for sepecified cells\n \n Parameters: \n `cells` Construct the CSNs for all cells, set cells = None (Default) otherwise input cells.list\n `alpha` Significant level (eg. 0.001, 0.01, 0.05 ...)\n larger alpha leads to more edges, Default = 0.01\n `boxsize` Size of neighborhood, the value between 1 to 2 is recommended, Default = 0.1, \n `edgeW` 1 edge is weighted (statistic pxy(x))\n 0 edge is not weighted (Default)\n `nodeW` 1 node is weighted (gene or otu abundance)\n 0 node is not wieghted (Default)\n `csn` Cell-specific network, the kth CSN is in csn{k}\n rows = genes, columns = genes\n `kk` the number of conditional gene. when kk=0, the method is CSN\n `dlimit` the min degree limitation of conditional genes.\n `average` whether use the average(adjmc + adjmc1) network or intersection(adjmc.*adjmc1) network.\n\n Returns: \n csnet dict \n Raises: \n KeyError - raises an exception \n Notes:\n Too many cells or genes may lead to out of memory.\n\n 学习 dataframe 和array python的矩阵运算。\n np index start from 0 \n 每个new cell都要和原来所有的细胞一起计算lower upper边界矩阵,都要排序每个基因来计算。\n 如果数据库足够大,可以就用原来的边界矩阵,重新换算出upper和lower矩阵。带入new cell的基因表达数据就可以。\n \"\"\"\n self.logger.info('start construction cell-specific network ')\n nr, nc = self.data.shape\n data = self.data\n upper = pd.DataFrame(np.zeros((nr, nc)), columns=data.columns, index=data.index)\n lower = pd.DataFrame(np.zeros((nr, nc)), columns=data.columns, index=data.index)\n for i in range(nr):\n sort_gi = data.iloc[i, :].sort_values(axis=0, ascending=True)\n s1 = sort_gi.values\n s2 = sort_gi.index\n n1 = sum(np.sign(s1))\n n0 = nc - n1\n h = round(boxsize * np.sqrt(n1))\n k = 0\n while k < nc:\n s = 0\n while k + s + 1 < nc and s1[(k + s + 1)] == s1[k]:\n s = s + 1\n\n if s >= h:\n upper.loc[(data.index[i], s2[range(k, k + s + 1)])] = data.loc[(data.index[i], s2[k])]\n lower.loc[(data.index[i], s2[range(k, k + s + 1)])] = data.loc[(data.index[i], s2[k])]\n else:\n upper.loc[(data.index[i], s2[range(k, k + s + 1)])] = data.loc[(data.index[i], s2[int(min(nc - 1, k + s + h))])]\n lower.loc[(data.index[i], s2[range(k, k + s + 1)])] = data.loc[(data.index[i], s2[int(max(n0 * (n0 > h), k - h))])]\n k = k + s + 1\n\n # %If gene expression matrix is sparse, use the sparse matrix will accelerate\n # %the calculation and reduce memory footprint\n # %data = sparse(data); upper = sparse(upper); lower = sparse(lower);\n\n self.logger.info('finish caculate the neighborhood of each gene for each cell')\n cells = self.get_cells(cells=cells)\n\n\n csn = dict()\n B = pd.DataFrame(np.zeros((nr, nc)), columns=data.columns, index=data.index)\n p = -stats.norm.ppf(q=alpha, loc=0, scale=1)\n \n for k in cells:\n for j in B.columns:\n if average:\n B.loc[:, j] = (data.loc[:, j] <= upper.loc[:, k]) & (data.loc[:, j] >= lower.loc[:, k]) & (data.loc[:, k] > 0)\n else:\n B.loc[:, j] = (data.loc[:, j] <= upper.loc[:, k]) & (data.loc[:, j] >= lower.loc[:, k])\n\n B = B * 1\n a = np.matrix(B.sum(axis=1))\n csnk = (B.dot(B.T) * nc - a.T * a) / np.sqrt(np.multiply(a.T * a, (nc - a).T * (nc - a)) / (nc - 1) + np.spacing(1))\n csnlink = (csnk > p) * 1\n if csnlink.sum().sum() == 0:\n self.logger.info('no genes in Cell {} has a link'.format(k))\n continue\n if kk != 0:\n id = condition_g(csnlink, kk=kk, dlimit=dlimit)\n csnlink = pd.DataFrame(np.zeros([nr, nr])) if average else pd.DataFrame(np.ones([nr, nr]))\n for m in range(kk):\n B_z = B.iloc[id[m], :] * B\n idc = np.argwhere(B.iloc[id[m], :] != 0).flatten()\n B_z = B_z.iloc[:, idc]\n r = B_z.shape[1]\n a_z = np.mat(B_z.sum(axis=1))\n c_z = B_z @ B_z.T\n csnk1 = (c_z * r - a_z.T * a_z) / np.sqrt(np.multiply(a_z.T * a_z, (r - a_z).T * (r - a_z)) / (r - 1) + np.spacing(1))\n csnlink1 = (csnk1 > p) * 1\n csnlink = csnlink + csnlink1 if average else csnlink * csnlink1\n\n else:\n kk = 1\n csnlink = csnlink / kk if average else csnlink\n csn[k] = csnlink\n if to_csv:\n filename = os.path.join(self.outdir, 'cellnws', '{}.nw.csv'.format(k))\n uf.create_dir(self.outdir + '/cellnws')\n csn[k].to_csv(path_or_buf=filename)\n self.logger.info('Cell {} specific network is completed'.format(k))\n\n self.logger.info('Finished constructing all {} cell specific networks'.format(len(cells)))\n self.upper = upper\n self.lower = lower\n self.csn = csn\n\n @uf.robust\n def csndm(self, cells=None, normalize=1, to_csv=1, nodeW=0, *args, **kwargs):\n \"\"\"Construction of network degree matrix\n The function performs the transformation from gene expression matrix to network degree matrix (ndm).\n \n Parameters: \n `data` Gene expression matrix (TPM/RPKM/FPKM/count), rows = genes, columns = cells. otu_even.table \n `alpha` Significant level (eg. 0.001, 0.01, 0.05 ...), Default = 0.01\n `boxsize` Size of neighborhood, Default = 0.1 (nx(k) = ny(k) = 0.1*n)\n `normalize`1 result is normalized (Default); \n 0 result is not normalized\n Note:\n If gene expression matrix is sparse, use the sparse matrix will accelerate the calculation and reduce memory footprint\n data = sparse(data); upper = sparse(upper); lower = sparse(lower);\n 可用于机器学习,样品分类预测等\n 只输出指定 cells 的degree matrix ,不指定就输出所有cell的全部gene's dm\n \"\"\"\n data = self.data\n self.logger.info('Constructing network degree matrix ...')\n cells = self.get_cells(cells=cells)\n nr, nc = self.data.shape\n ndm = pd.DataFrame(np.zeros((nr, nc)), columns=data.columns, index=data.index)\n csn = self.csn\n celln = 0\n for k in cells:\n if k not in csn:\n self.logger.info('Cell {} has no network'.format(k))\n continue\n if nodeW:\n ndm.loc[:, k] = csn[k].sum(axis=1) * data.loc[:, k]\n else:\n ndm.loc[:, k] = csn[k].sum(axis=1)\n celln += 1\n self.logger.info('Network degree vector of cell {} is complete'.format(k))\n\n if normalize:\n self.logger.info('Normalizing network degree matrix ...')\n a = ndm.mean(axis=0)\n ndm = ndm.div(a + np.spacing(1), axis=1)\n ndm = np.log(1 + ndm)\n self.ndm = ndm\n if to_csv:\n filename = os.path.join(self.outdir, '{}.{}cells.nwdm.csv'.format(os.path.basename(self.tablename), celln))\n ndm.to_csv(path_or_buf=filename)\n self.logger.info('Finished network degree matrix, file: {}'.format(filename))\n\n @uf.robust\n def nfe(self, cells=None, to_csv=1, *args, **kwargs):\n data = self.data\n csn = self.csn\n self.logger.info('caculate network_flow_entropy ...')\n cells = self.get_cells(cells=cells)\n nr, nc = data.shape\n NFE = pd.DataFrame(np.zeros((nc, 1)), columns=['network_flow_entropy'], index=data.columns)\n celln = 0\n for k in cells:\n if k not in csn:\n self.logger.info('Cell {} has no network'.format(k))\n NFE.loc[k] = None\n continue\n datak = np.mat(data.loc[:, k])\n P = np.multiply(datak.T * datak, np.mat(csn[k]))\n cc = P.sum(axis=1) != 0\n idc = np.array(cc)[:, 0]\n id = data.index[idc]\n x = data.loc[(id, k)]\n x_n = x / x.sum()\n P1 = P[[id]][:, id]\n P_n = P1 / P1.sum(axis=1)\n x_p = pd.DataFrame(P_n) * np.array(x_n).reshape(-1, 1)\n x_p[x_p == 0] = 1\n NFE.loc[k] = -np.sum(np.sum(x_p * np.log(x_p)))\n NFE.loc[k]\n celln += 1\n self.logger.info('network_flow_entropy of cell {} is {}'.format(k, NFE.loc[k][0]))\n\n self.NFE = NFE\n if to_csv:\n filename = os.path.join(self.outdir, '{}.{}cells.NFE.csv'.format(os.path.basename(self.tablename), celln))\n NFE.to_csv(path_or_buf=filename)\n self.logger.info('Finished network_flow_entropy, output file: {}'.format(filename))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Cell-specific Network Constructed by Single-cell RNA Sequencing Data', usage='%(prog)s --help or -h for detailed help', epilog='\\n Example:\\n python %(prog)s --data Otu_table.xls --netcells cells.list --dmcells cells.list\\n --outdir ./ --logfile ntwk.log --dm2csv --net2csv\\n --normalize\\n ', formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('--data', '-i', required=True, help='OTU table file (required)')\n parser.add_argument('--outdir', '-o', default='./', help=\"a path to store analysis results, default='./'\")\n parser.add_argument('--logfile', default=None, help='the output log file name')\n parser.add_argument('--netcells', default=None, help='one column list of cell_names or caculate network for all cells [default]')\n parser.add_argument('--dmcells', default=None, help='one column list of cell_names or caculate degree matrix for all cells [default]')\n parser.add_argument('--edgeW', action='store_true', default=False, help='weight the network links with link strength [default:no weight]')\n parser.add_argument('--nodeW', action='store_true', default=False, help='weight the network nodes with abundance [default: no weight]')\n parser.add_argument('--net2csv', action='store_true', default=False, help='print out the net file for each cell [default: no print]')\n parser.add_argument('--dm2csv', action='store_true', default=False, help='print out the degree matrix file of the selected cells [default: print]')\n parser.add_argument('--kk', '-k', default=50, type=int, help='the number of top conditional gene')\n parser.add_argument('--alpha', '-a', default=0.01, type=float, help='alpha value cutoff')\n parser.add_argument('--boxsize', '-b', default=0.1, type=float, help='boxsize for nework construction')\n parser.add_argument('--normalize', action='store_true', default=False, help='normalize the matrix')\n args = parser.parse_args()\n t_s = uf.datetime.now()\n csn = SSN(args.data, outdir=args.outdir, log=args.logfile)\n csnet = csn.csnet(cells=args.netcells, kk=args.kk, alpha=args.alpha, boxsize=args.boxsize, edgeW=args.edgeW, to_csv=args.net2csv)\n csndm = csn.csndm(cells=args.dmcells, normalize=args.normalize, to_csv=args.dm2csv, nodeW=args.nodeW)\n t_e = uf.datetime.now()\n usedtime = t_e - t_s\n csn.logger.info('Finish constructing network degree matrix, time used: {}'.format(usedtime))\n# okay decompiling __pycache__/gpu_ccsn.cpython-35.pyc\n","sub_path":"bin/gpu_numba_ccsn.py","file_name":"gpu_numba_ccsn.py","file_ext":"py","file_size_in_byte":15302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"139933020","text":"\"\"\"The model uses two conv layers+batch norm followed by two fully connected. Converges very fast with high accuracy\"\"\"\n\nimport tensorflow as tf\nimport time\nimport sys\nfrom tensorflow.python import debug as tf_debug\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n# Parameters\n\ntraining_epochs = 10\ndisplay_step = 1\nbatch_size = 100\nwidth = 28\nheight = 28\n#number of classes\nnClass = 10\n\n# Constants describing the training process.\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\nNUM_EPOCHS_PER_DECAY = 1 # Epochs after which learning rate decays.\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.0001 # Initial learning rate.\n\n#MODEL\n\n# Architecture\n\ndef conv2d(input, weight_shape, bias_shape):\n incoming = weight_shape[0] * weight_shape[1] * weight_shape[2]\n weight_init = tf.random_normal_initializer(stddev=(2.0/incoming)**0.5)\n W = tf.get_variable(\"W\", weight_shape, initializer=weight_init)\n bias_init = tf.constant_initializer(value=0)\n b = tf.get_variable(\"b\", bias_shape, initializer=bias_init)\n return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(input, W, strides=[1, 1, 1, 1], padding='SAME'), b))\n\ndef max_pool(input, k=2):\n return tf.nn.max_pool(input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')\n\ndef layer(input, weight_shape, bias_shape):\n weight_init = tf.random_normal_initializer(stddev=(2.0/weight_shape[0])**0.5)\n bias_init = tf.constant_initializer(value=0)\n W = tf.get_variable(\"W\", weight_shape,\n initializer=weight_init)\n b = tf.get_variable(\"b\", bias_shape,\n initializer=bias_init)\n return tf.nn.relu(tf.matmul(input, W) + b, name='last_layer')\n\n\ndef inference(x, keep_prob):\n\n x = tf.reshape(x, shape=[-1, height, width, 1])\n with tf.variable_scope(\"conv_1\"):\n conv_1 = conv2d(x, [5, 5, 1, 32], [32])\n\n with tf.variable_scope('batch_norm'):\n norm1 = tf.nn.lrn(conv_1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm1')\n with tf.variable_scope('max_pool1'):\n pool_1 = max_pool(norm1)\n\n\n\n with tf.variable_scope(\"conv_2\"):\n conv_2 = conv2d(pool_1, [5, 5, 32, 64], [64])\n\n with tf.variable_scope('batch_norm'):\n norm2 = tf.nn.lrn(conv_2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm2')\n\n with tf.variable_scope('max_pool2'):\n pool_2 = max_pool(norm2)\n\n with tf.variable_scope(\"conv_3\"):\n conv_3 = conv2d(pool_2, [5, 5, 64, 32], [32])\n\n # with tf.variable_scope('max_pool3'):\n # pool_3 = max_pool(conv_3)\n\n with tf.variable_scope(\"fc1\"):\n pool_2_flat = tf.reshape(conv_3, [-1, 7 * 7 * 32])\n fc_1 = layer(pool_2_flat, [7*7*32, 384], [384])\n with tf.variable_scope(\"fc2\"):\n fc_2 = layer(fc_1, [384, 192], [192])\n # apply dropout\n fc_1_drop = tf.nn.dropout(fc_2, keep_prob)\n\n with tf.variable_scope(\"output\"):\n output = layer(fc_1_drop, [192, nClass], [nClass])\n\n return output\n\n\ndef loss(output, y):\n xentropy = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=y)\n loss = tf.reduce_mean(xentropy)\n return loss\n\n\ndef training(cost, global_step):\n tf.summary.scalar(\"cost\", cost)\n learning_rate = tf.train.exponential_decay(INITIAL_LEARNING_RATE, global_step,\n 100, 0.96, staircase=True)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(cost, global_step=global_step)\n return train_op\n\n\n\ndef evaluate(output, y):\n logits = tf.nn.softmax(output)\n correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar(\"validation error\", (1.0 - accuracy))\n return accuracy\n\nx = tf.placeholder(\"float\", [None, height* width*1], name='placehold_x')\ny = tf.placeholder('float', [None, nClass], name='placehold_y')\n\nkeep_prob = tf.placeholder(tf.float32, name='keep_prob') # dropout probability\n\noutput = inference(x, keep_prob)\ncost = loss(output, y)\n\nglobal_step = tf.Variable(0, name='global_step', trainable=False)\n\n# Passing global_step to minimize() will increment it at each step.\n\ntrain_op = training(cost, global_step)\neval_op = evaluate(output, y)\nsummary_op = tf.summary.merge_all()\nsaver = tf.train.Saver()\n\nsess = tf.Session() # config=tf.ConfigProto(log_device_placement=True)\nsummary_writer = tf.summary.FileWriter(\"summary_logs/\", graph_def=sess.graph_def)\ninit_op = tf.global_variables_initializer()\nsess.run(init_op)\n\nwith tf.device('/gpu:0'):\n with sess.as_default():\n # Training cycle\n for epoch in range(training_epochs):\n avg_cost = 0.\n total_batch_train = int(mnist.train.num_examples / batch_size)\n\n # Loop over all batches\n for i in range(total_batch_train):\n minibatch_x, minibatch_y = mnist.train.next_batch(batch_size)\n #print (minibatch_x, 'n/', minibatch_y)\n # Fit training using batch data\n sess.run(train_op, feed_dict={x: minibatch_x, y: minibatch_y, keep_prob: 0.5})\n train_precision = sess.run(eval_op, feed_dict={x: minibatch_x, y: minibatch_y, keep_prob: 1})\n # Compute average loss\n avg_cost += sess.run(cost, feed_dict={x: minibatch_x, y: minibatch_y, keep_prob: 0.5})/batch_size\n if not i % 10:\n print('Epoch #: ', epoch, ' Batch #: ', i, 'loss: ', avg_cost, 'train error: ', (1-train_precision))\n\n # Display logs per epoch step\n if epoch % display_step == 0:\n minibatch_x_val, minibatch_y_val = mnist.validation.next_batch(batch_size)\n accuracy = sess.run(eval_op,\n feed_dict={x: minibatch_x_val, y: minibatch_y_val, keep_prob: 1})\n print(\"Validation Error:\", (1 - accuracy))\n\n summary_str = sess.run(summary_op, feed_dict={x: minibatch_x, y: minibatch_y, keep_prob: 1})\n summary_writer.add_summary(summary_str, sess.run(global_step))\n\n saver.save(sess, \"model_logs/model-checkpoint\", global_step=global_step)\n\n temp1 = sess.run(output, feed_dict={x: minibatch_x_val, keep_prob: 1})\n prediction = sess.run(tf.nn.softmax(temp1))\n print(minibatch_x_val[0:10],'\\n',minibatch_y_val[0:10],'\\n',prediction[0:10])\n\n print (\"Optimization Finished!\")\n\n\n # total_batch_eval=N_OF_SAMPL_VAL/batch_size\n #\n # for i in range(total_batch_eval):\n # vbatch_xs, vbatch_ys = sess.run([vimageBatch, vlabelBatch])\n # accuracy = sess.run(eval_op, feed_dict={x: vimageBatch, y: vlabelBatch, keep_prob: 1})\n #\n # print (\"Test Accuracy:\", accuracy)\n\n # finalise\n # coord.request_stop()\n # coord.join(threads)\n\n### Predict\n#\n# img_addr = '/home/pavelkrolevets/Working/TF_facenet/data/VALIDATION_DIR/dog/dog.155.jpg'\n# with tf.gfile.FastGFile(img_addr, 'rb') as f:\n# image_data = f.read()\n# image = tf.image.decode_jpeg(image_data, channels=3)\n# image = tf.image.convert_image_dtype(image=image, dtype=tf.float32)\n# image = tf.reshape(image, [-1, width, height, 3])\n# pred_im = sess.run(image)\n#\n# prediction = sess.run(inference, feed_dict={x: pred_im, keep_prob: 1})\n# print(prediction)\n\n\n","sub_path":"Model_test_on_MNIST.py","file_name":"Model_test_on_MNIST.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"35753787","text":"import os, re, time, os\n\nclass MyMarkdown(object):\n\n def __init__(self):\n self.items = []\n self.filename = ''\n\n def Parser(self, filename):\n index = 0\n if os.path.exists(filename):\n self.filename = filename\n for block in self.Blocks():\n if \"####\" in block:\n index = index + 1\n fromTime, toTime = self.TimeParser(block)\n self.items.append({\"fromTime\": fromTime, \"toTime\": toTime})\n else:\n self.items[index-1]['content'] = block\n else:\n raise FileNotExists\n\n def AddItem(self, fromTime, toTime, content):\n item = {\"fromTime\": fromTime, \"toTime\": toTime, \"content\": content}\n fromTimeList = [time.strptime(item['fromTime'], \"%H:%M\").tm_hour*60 + time.strptime(item['fromTime'], \"%H:%M\").tm_min for item in self.items]\n fromTimeFloat = time.strptime(fromTime, \"%H:%M\").tm_hour*60 + time.strptime(fromTime, \"%H:%M\").tm_min\n if len(self.items) == 0:\n self.items.append(item)\n elif len(self.items) == 1:\n if (fromTimeFloat - fromTimeList[0]) <= 0:\n self.items.insert(0, item)\n else:\n self.items.append(item)\n else:\n for iTime in range(0, len(fromTimeList)-1):\n if (fromTimeFloat - fromTimeList[iTime])*(fromTimeFloat - fromTimeList[iTime+1]) <= 0: \n self.items.insert(iTime+1, item)\n break\n else:\n self.items.append(item)\n\n def Log(self):\n print(\"{0}:\".format(self.filename.split('/')[-1].split('.')[-2]))\n index = 0\n for item in self.items:\n index = index + 1\n print(\"[{0}] {1} \\n {2}\".format(str(index), self.TimeStr(item[\"fromTime\"], item[\"toTime\"]), item['content']))\n\n def Open(self, app):\n try:\n os.system(\"open -a {} {}\".format(app, self.filename))\n except Exception as e:\n raise OpenError\n\n def FinishItem(self, index):\n if index < len(self.items)+1:\n self.items[index - 1][\"content\"] = self.items[index - 1][\"content\"] + \" 🍺\"\n else:\n raise IndexOutofRange\n\n def DeleteItem(self, index):\n if len(self.items) > 0: \n del self.items[index-1]\n else:\n print(\"There is no items in {0} to delete.\".format(self.filename))\n\n def Write(self):\n if not self.filename == '':\n with open(self.filename, 'w') as f:\n for item in self.items:\n f.write(\"#### {0}\\n\\n\".format(self.TimeStr(item[\"fromTime\"], item[\"toTime\"])))\n f.write(\" {0}\\n\\n\".format(item[\"content\"]))\n else:\n raise InvalidFilename\n\n def TimeStr(self, fromTimeStr, toTimeStr):\n if toTimeStr:\n return \"{}~{}\".format(fromTimeStr, toTimeStr)\n else:\n return \"{}\".format(fromTimeStr)\n\n def TimeParser(self, block):\n res = re.findall(\"(\\d+:\\d+)\", block)\n if len(res) == 1:\n return res[0], None\n if len(res) == 2:\n return res[0], res[1]\n else:\n raise TimeParseError\n\n def Blocks(self):\n \"\"\"\n Generate blocks\n \"\"\"\n blocks = []\n for line in self.Lines():\n if line.strip():\n blocks.append(line)\n elif blocks:\n yield ''.join(blocks).strip()\n blocks = [] \n\n def Lines(self):\n contents = ''\n with open(self.filename, 'r') as f:\n contents = f.readlines()\n for line in contents: yield line\n yield '\\n'\n","sub_path":"MyMarkdown.py","file_name":"MyMarkdown.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"591489104","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpi4py import MPI\nimport imageio\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\nnp.random.seed(12)\nn_iter = 1000\nN = 50\nm = 200\n\ndef Gosper(pos):\n j = 1\n pos[6+j, 2+j] = pos[6+j, 3+j] = pos[7+j, 2+j] = pos[7+j, 3+j] = 1\n pos[4+j, 36+j] = pos[4+j, 37+j] = pos[5+j, 36+j] = pos[5+j, 37+j] = 1\n \n pos[6+j, 12+j] = pos[7+j, 12+j] = pos[8+j, 12+j] = 1\n pos[5+j, 13+j] = pos[4+j, 14+j] = pos[9+j, 13+j] = pos[10+j, 14+j] = 1\n pos[4+j, 15+j] = pos[10+j, 15+j] = 1\n pos[7+j, 16+j] = pos[5+j, 17+j] = pos[9+j, 17+j] = 1\n pos[7+j, 18+j] = pos[6+j, 18+j] = pos[8+j, 18+j] = pos[7+j, 19+j] = 1\n \n pos[6+j, 22+j] = pos[5+j, 22+j] = pos[4+j, 22+j] = 1\n pos[6+j, 23+j] = pos[5+j, 23+j] = pos[4+j, 23+j] = 1\n pos[7+j, 24+j] = pos[3+j, 24+j] = 1\n pos[7+j, 26+j] = pos[3+j, 26+j] = pos[8+j, 26+j] = pos[2+j, 26+j] = 1\n return pos\n\nA = np.zeros((N, N))\nA = Gosper(A)\n\ndef shift(B):\n B = np.roll(np.array(B), 1, axis = 1)\n return B[:, 1:]\n\nif rank == 0:\n frames_path = \"./pics_for_shift/{i}.jpg\"\n #im = plt.imshow(A, cmap='binary')\n #plt.savefig(frames_path.format(i=0))\n #plt.close()\n gif_path = \"./shift.gif\"\n\nN_ = int(np.floor(N/size))\nif N >= size:\n if rank != size - 1:\n N_start = N_*rank\n N_end = N_*(rank + 1) - 1\n else:\n N_start = N_*rank\n N_end = N_start + int(N - N_*(size - 1)) - 1\nelse:\n if rank < disc:\n N_start = rank\n N_end = rank\n else:\n N_start = 0\n N_end = 0\n\nfor j in range(n_iter):\n \n start = MPI.Wtime()\n A_shifted = shift(A[:, [N_start - 1 % N] + list(range(N_start, N_end + 1))])\n\n comm.Barrier()\n\n A_shifted = comm.gather(A_shifted, 0)\n\n if rank == 0:\n # print(\"Matrix A is:\\n\", A)\n B = np.hstack([A_shifted[i] for i in range(len(A_shifted))])\n # print(\"Shifted matrix B is:\\n\", B)\n #im = plt.imshow(B, cmap='binary')\n #plt.savefig(frames_path.format(i=j + 1))\n #plt.close()\n A = B.copy()\n end = MPI.Wtime()\n comm.Barrier()\n comm.Bcast(A, root=0)\n \nif rank == 0:\n print(end - start)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Tasks 7-9/Task8_original.py","file_name":"Task8_original.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"49910092","text":"class Solution:\n def smallestRange(self, A):\n import functools\n A = [row[::-1] for row in A]\n ans = -1e9, 1e9\n for left in sorted(functools.reduce(set.union, map(set, A))):\n right = -1e9\n for B in A:\n while B and B[-1] < left:\n B.pop()\n if not B:\n return ans\n right = max(right, B[-1])\n if right - left < ans[1] - ans[0]:\n ans = left, right\n return ans\n","sub_path":"632/632.smallest-range-covering-elements-from-k-lists.302560656.Accepted.leetcode.python3.py","file_name":"632.smallest-range-covering-elements-from-k-lists.302560656.Accepted.leetcode.python3.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"458579025","text":"####################################\n# Author: Ronald Cardenas\n# Date: July 2017\n# Project: Document Modeling with External Attention for Sentence Extraction\n\n####################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nsys.path.append('../../common')\n\n\nimport math\nimport os\nimport random\nimport sys\nimport time\nimport pdb\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport subprocess as sp\n#from tensorflow.python import debug as tf_debug\n\nfrom data_utils import DataProcessor, BatchData\nfrom my_flags import FLAGS\nfrom my_model import MY_Model\nfrom model_docsum import accuracy_qas_top, mrr_metric\nfrom train_test_utils import batch_predict_with_a_model, batch_load_data\nfrom sklearn.model_selection import ParameterSampler, ParameterGrid\nfrom scipy.stats.distributions import expon\nfrom scipy.stats import lognorm, uniform\n\nseed = 42\n\nnp.random.seed(seed)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Rutine for sweeping through hyper-parameters setups for the original sidenet')\n parser.add_argument('gpu',help='gpu id',type=str,default=\"0\")\n parser.add_argument('dataset',help='Dataset to use / mode of FLAGS setup',type=str,default=\"newsqa\")\n parser.add_argument('file_suffix',help='Suffix for exp name',type=str,default=\"\")\n args = parser.parse_args()\n \n FLAGS.data_mode = args.dataset\n FLAGS.gpu_id = args.gpu\n FLAGS.train_dir = os.path.abspath(\"./train_dir_\" + args.dataset+\"_subs\")\n FLAGS.train_epoch_crossentropy = 50\n\n if args.dataset=='wikiqa':\n FLAGS.use_subsampled_dataset = False\n FLAGS.max_sent_length =100 \n FLAGS.max_doc_length = 30\n elif args.dataset=='newsqa':\n FLAGS.use_subsampled_dataset = True\n FLAGS.max_sent_length = 50\n FLAGS.max_doc_length = 64\n elif args.dataset=='squad':\n FLAGS.use_subsampled_dataset = True\n FLAGS.max_sent_length = 80\n FLAGS.max_doc_length = 16\n\n FLAGS.pretrained_wordembedding_orgdata = os.path.expanduser(\"../datasets/word_emb/1-billion-word-language-modeling-benchmark-r13output.word2vec.vec\")\n FLAGS.preprocessed_data_directory = os.path.expanduser(\"../datasets/preprocessed_data\")\n\n FLAGS.force_reading = False\n \n FLAGS.max_filter_length = 8 \n FLAGS.min_filter_length = 5 \n FLAGS.norm_extra_feats = True\n FLAGS.max_gradient_norm = -1\n FLAGS.decorrelate_extra_feats = False\n\n # set sentence, doc length to maximum\n sp.Popen([\"mkdir\",\"-p\",\"tunning_\"+FLAGS.data_mode])\n output = open(\"tunning_\"+FLAGS.data_mode+\"/\"+FLAGS.data_mode + \"_hp_grid_tuning_%s.txt\" % args.file_suffix,'w')\n\n print(\"Reading vocabulary...\")\n vocab_dict, word_embedding_array = DataProcessor().prepare_vocab_embeddingdict()\n print(\"Reading training set...\")\n train_data = DataProcessor().prepare_news_data(vocab_dict, data_type=\"training\") # subsampled\n # data in whole batch with padded matrixes\n print(\"Reading validation set...\")\n val_batch = batch_load_data(DataProcessor().prepare_news_data(vocab_dict,\n data_type=\"validation\",\n normalizer=train_data.normalizer,\n pca_model=train_data.pca_model))\n setup_by_id = {}\n results_by_id = {}\n results_by_id_mrr = {}\n setup_id = 0\n best_global_acc = -1\n best_global_mrr = -1\n best_setup_id = -1\n best_setup_id_mrr = -1\n\n parameter_grid = {\n \"batch_size\" : [20],\n \"learning_rate\" : [math.exp(-4.605170185988091)],\n \"size\":[1833],\n \"sentembed_size\":[211],\n \"use_dropout\":[True],\n \"dropout\": [0.65,0.8,1.0]\n }\n\n ## loop for hyperparams\n param_gen = ParameterGrid(parameter_grid)\n for setup in param_gen:\n setup_time = time.time()\n setup_by_id[setup_id] = setup\n \n FLAGS.batch_size = setup[\"batch_size\"]\n FLAGS.learning_rate = setup[\"learning_rate\"]\n FLAGS.size = setup[\"size\"]\n FLAGS.sentembed_size = setup[\"sentembed_size\"]\n FLAGS.use_dropout = setup[\"use_dropout\"]\n FLAGS.dropout = setup[\"dropout\"]\n\n prev_drpt = FLAGS.use_dropout\n \n # check if concat, then adjust sentemb size\n fil_lens_to_test = FLAGS.max_filter_length - FLAGS.min_filter_length + 1\n if FLAGS.handle_filter_output == \"concat\" and FLAGS.sentembed_size%fil_lens_to_test != 0:\n q = int(FLAGS.sentembed_size // fil_lens_to_test)\n FLAGS.sentembed_size = q * fil_lens_to_test\n\n print(\"Setup \",setup_id,\": \",setup)\n output.write(\"Setup %d: %s\\n\" % (setup_id,str(setup)))\n\n best_acc = -1\n best_mrr = -1\n best_ep = 0\n best_ep_mrr = 0\n with tf.Graph().as_default() and tf.device('/gpu:'+FLAGS.gpu_id):\n config = tf.ConfigProto(allow_soft_placement = True)\n tf.set_random_seed(seed)\n with tf.Session(config = config) as sess:\n model = MY_Model(sess, len(v4ocab_dict)-2)\n init_epoch = 1\n sess.run(model.vocab_embed_variable.assign(word_embedding_array))\n \n for epoch in range(init_epoch, FLAGS.train_epoch_crossentropy+1):\n ep_time = time.time() # to check duration\n\n train_data.shuffle_fileindices()\n total_loss = 0\n # Start Batch Training\n step = 1\n while (step * FLAGS.batch_size) <= len(train_data.fileindices):\n # Get batch data as Numpy Arrays\n batch = train_data.get_batch(((step-1)*FLAGS.batch_size), (step * FLAGS.batch_size))\n\n # Run optimizer: optimize policy and reward estimator\n _,ce_loss = sess.run([model.train_op_policynet_withgold,\n model.cross_entropy_loss],\n feed_dict={model.document_placeholder: batch.docs,\n model.label_placeholder: batch.labels,\n model.weight_placeholder: batch.weights,\n model.isf_score_placeholder: batch.isf_score,\n model.idf_score_placeholder: batch.idf_score,\n model.locisf_score_placeholder: batch.locisf_score})\n total_loss += ce_loss\n # Increase step\n if step%500==0:\n print (\"\\tStep: \",step)\n step += 1\n #END-WHILE-TRAINING\n total_loss /= step\n FLAGS.authorise_gold_label = False\n FLAGS.use_dropout = False\n # retrieve batch with updated logits in it\n val_batch = batch_predict_with_a_model(val_batch, \"validation\", model, session=sess)\n FLAGS.authorise_gold_label = True\n FLAGS.use_dropout = prev_drpt\n probs = sess.run(model.predictions,feed_dict={model.logits_placeholder: val_batch.logits})\n validation_acc = accuracy_qas_top(probs, val_batch.labels, val_batch.weights, val_batch.isf_score_ids)\n val_mrr = mrr_metric(probs, val_batch.labels, val_batch.weights, val_batch.isf_score_ids,\"validation\")\n \n print(\"\\tEpoch %2d || Train ce_loss: %4.3f || Val acc: %.4f || Val mrr: %.4f || duration: %3.2f\" % \n (epoch,total_loss,validation_acc,val_mrr,time.time()-ep_time))\n output.write(\"\\tEpoch %2d || Train ce_loss: %4.3f || Val acc: %.4f || Val mrr: %.4f || duration: %3.2f\\n\" % \n (epoch,total_loss,validation_acc,val_mrr,time.time()-ep_time))\n\n if validation_acc > best_acc:\n best_acc = validation_acc\n best_ep = epoch\n if val_mrr > best_mrr:\n best_mrr = val_mrr\n best_ep_mrr = epoch\n #break # for time testing\n #END-FOR-EPOCH\n results_by_id[setup_id] = (best_acc,best_ep)\n results_by_id_mrr[setup_id] = (best_mrr,best_ep_mrr)\n if best_acc > best_global_acc:\n best_global_acc = best_acc\n best_setup_id = setup_id\n if best_mrr > best_global_mrr:\n best_global_mrr = best_mrr\n best_setup_id_mrr = setup_id\n # clear graph\n tf.reset_default_graph()\n #END-GRAPH\n \n print(\"Best ACC result in this setup:\",results_by_id[setup_id])\n print(\"Best MRR result in this setup:\",results_by_id_mrr[setup_id])\n print(\"Duration: %.4fsec\" % (time.time()-setup_time))\n output.write(\"Best acc result in this setup: %.6f,%d\\n\" % (best_acc,best_ep))\n output.write(\"Best mrr result in this setup: %.6f,%d\\n\" % (best_mrr,best_ep_mrr))\n output.write(\"Duration: %.4fsec\\n\" % (time.time()-setup_time))\n setup_id += 1\n #END-FOR-PARAMS\n \n print(\"Best acc setup: \",setup_by_id[best_setup_id])\n print(\" Acc: %.4f | Epoch: %d\" % results_by_id[best_setup_id])\n print(\"Best mrr setup: \",setup_by_id_mrr[best_setup_id_mrr])\n print(\" MRR: %.4f | Epoch: %d\" % results_by_id_mrr[best_setup_id_mrr])\n output.write(\"Best acc setup: \" + str(setup_by_id[best_setup_id]) + \"\\n\")\n output.write(\" Acc: %.4f | Epoch: %d\\n\" % results_by_id[best_setup_id])\n output.write(\"Best mrr setup: \" + str(setup_by_id[best_setup_id_mrr]) + \"\\n\")\n output.write(\" MRR: %.4f | Epoch: %d\\n\" % results_by_id_mrr[best_setup_id_mrr])\n output.close()\n \n","sub_path":"answer_selection/xnet_plus/hyperparam_grid_search.py","file_name":"hyperparam_grid_search.py","file_ext":"py","file_size_in_byte":9194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"43770816","text":"__author__ = 'basilbeirouti'\n\nimport datetime, csv, os\nfrom DBConnect import sr_psum, query_profile\nfrom BM25.BM25Okapi import QueryMaster, DocMatrix, JDQueryMaster\nfrom BM25.TextCleaning import cleanStringAndLemmatize, wordslist2string\nimport pickle, glob, bisect, time\n\ndef shift_filter(datetime_obj):\n def is_on_date(shift):\n start = datetime.datetime.strptime(shift[2], \"%Y-%m-%d %H:%M:%S\")\n end = start + datetime.timedelta(minutes = int(shift[3]))\n if start <= datetime_obj <= end:\n return True\n return False\n return is_on_date\n\ndef on_at_time(shifts, datetime_obj):\n ondate = shift_filter(datetime_obj)\n return [shift for shift in shifts if ondate(shift)]\n\ndef pids_at_time(shifts, datetime_obj):\n out = on_at_time(shifts, datetime_obj)\n return [el[1] for el in out]\n\nclass FormatPredictions:\n\n def __init__(self, toppredictions, fullname):\n self.fullname = fullname\n self.names, self.scores = zip(*toppredictions)\n self.names, self.scores = list(self.names), list(self.scores)\n self.actual = fullname\n print(\"num predictions: \", len(self.names))\n print(\"top prediction and score: \", self.names[0], self.scores[0])\n if self.actual in self.names:\n self.rank = self.names.index(self.actual)\n self.score = self.scores[self.rank]\n print(\"actual assignee and score and rank: \", self.names[self.rank], self.score, self.rank)\n print(\"mean score: \", sum(self.scores)/len(self.scores))\n self.recognized = True\n else:\n print(\"does not recognize \", self.actual)\n self.recognized = False\n\n #SRnum, numpredictions, meanscore, topprediction, topscore, actualassignee, actualassigneescore, actualassigneerank\n def statistics(self):\n return len(self.names), sum(self.scores)/len(self.scores), self.names[0], self.scores[0], self.fullname, self.score, self.rank\n\n\nclass Evaluator:\n\n def __init__(self, corpuspath):\n self._textcorpuspath = corpuspath\n\n def fit(self, pids_context):\n \"\"\"\n :type pids_context: sequence or set\n :param pids_context: sequence or set of string person_ids who are on shift and found in TextCorpus folder\n :return:\n \"\"\"\n self.pids_context = set(pids_context)\n self.documents = [(pid,self.get_pid_document(pid)) for pid in pids_context]\n self.dm = DocMatrix(self.documents, bm25 = True)\n self.qm = QueryMaster(self.dm)\n\n def transform(self, cleaned_psum):\n self.cleanedpsum = cleaned_psum\n self.pids_predictions = self.qm.queryalgorithm(self.cleanedpsum)\n return self.pids_predictions\n\n def get_pid_document(self, pid):\n with open(os.path.join(self._textcorpuspath, pid) + \".txt\", 'r') as file:\n document = file.read()\n return document\n\nclass CorpusManager:\n\n def __init__(self, pathtocorpus, pids):\n\n self._textcorpuspath = pathtocorpus\n self.allpids = set(pids)\n self.knownpids = set()\n self.load_corpus_names()\n self.load_pids_dict()\n self.pids_names = dict()\n self.names_pids = dict()\n for pid in self.knownpids:\n self.pids_names[pid] = self.pidsdict[pid][\"full_name\"]\n self.names_pids[self.pidsdict[pid][\"full_name\"]] = pid\n\n def get_name(self, pid):\n if pid in self.pids_names:\n return self.pids_names[pid]\n profile = query_profile(pid)\n newname = profile[pid][\"full_name\"]\n self.pids_names[pid] = newname\n self.names_pids[newname] = pid\n pickle.dump(self.pids_names, open(\"pids_names.p\", \"wb\"))\n pickle.dump(self.names_pids, open(\"names_pids.p\", \"wb\"))\n return self.pids_names[pid]\n\n def load_corpus_names(self):\n filenames = glob.glob(self._textcorpuspath + \"/*.txt\")\n for filename in filenames:\n path, name = os.path.split(filename)\n name = name.replace(\".txt\", \"\")\n self.knownpids.add(name)\n\n def load_pids_dict(self):\n self.pidsdictpath = os.path.join(os.getcwd(), \"TextCorpus\", \"pidsdict27.p\")\n if os.path.exists(self.pidsdictpath):\n if os.path.getsize(self.pidsdictpath) > 0:\n self.pidsdict = pickle.load(open(self.pidsdictpath, 'rb'))\n else:\n print(\"PID Dictionary is empty\")\n self.pidsdict = dict()\n\n def to_name(self, pid):\n name = self.pids_names[pid]\n return name\n\nclass ScheduleManager:\n\n def __init__(self, shifts, **kwargs):\n self.shifts = shifts\n self.shifts.sort(key = lambda x: datetime.datetime.strptime(x[2],\"%Y-%m-%d %H:%M:%S\"))\n self.precomputedkeys = [datetime.datetime.strptime(el[2], \"%Y-%m-%d %H:%M:%S\") for el in self.shifts]\n\n def shift_context(self, datetime_obj):\n r = find_lt(self.precomputedkeys, datetime_obj)\n l = find_gt(self.precomputedkeys, datetime_obj-datetime.timedelta(hours = 12))\n self._shifts = self.shifts[l:r+1]\n return on_at_time(self._shifts, datetime_obj)\n\n def pids_context(self, datetime_obj):\n temp = self.shift_context(datetime_obj)\n return [el[1] for el in temp]\n\n# corp_manager = CorpusManager(os.path.join(os.getcwd(), \"TextCorpus\"), shifts)\n# corp_manager.updatecorpus()\n# corp_manager.make_pids_dict()\n\ndef find_lt(a, x):\n 'Find rightmost value less than x'\n i = bisect.bisect_left(a, x)\n if i:\n return i-1\n raise ValueError\n\ndef find_gt(a, x):\n 'Find leftmost value greater than x'\n i = bisect.bisect_right(a, x)\n if i != len(a):\n return i\n raise ValueError\n\nclass JDEvaluator(Evaluator):\n\n def prepare_docmatrix(self, knownpids):\n self.full_dm = DocMatrix([(pid, self.get_pid_document(pid)) for pid in list(knownpids)], bm25 = False)\n self.qm = JDQueryMaster(self.full_dm)\n\n def fit(self, pids_context):\n \"\"\"\n :type pids_context: sequence or set\n :param pids_context: sequence or set of string person_ids who are on shift and found in TextCorpus folder\n :return:\n \"\"\"\n self.pids_context = list(pids_context)\n self.rows = [self.full_dm.tse_dict[pid] for pid in self.pids_context]\n self.partial_dm = self.full_dm._docmatrix[self.rows].tocsr()\n self.bm25_partial_dm = self.full_dm.okapi_weights(self.partial_dm)\n\n def transform(self, cleaned_psum):\n self.cleanedpsum = cleaned_psum\n self.pids_predictions = self.qm.jdqueryalgorithm(cleaned_psum, self.bm25_partial_dm, self.pids_context)\n return self.pids_predictions\n\n def get_pid_document(self, pid):\n with open(os.path.join(self._textcorpuspath, pid) + \".txt\", 'r') as file:\n document = file.read()\n return document\n\nclass JDRequestManager:\n\n def __init__(self, eval_obj, sched_obj, corp_obj):\n\n \"\"\"\n :param eval_obj:\n :type eval_obj: JDEvaluator\n :param sched_obj:\n :type sched_obj: ScheduleManager\n :param corp_obj:\n :type corp_obj: CorpusManager\n :return:\n \"\"\"\n\n self.eval_obj = eval_obj\n self.eval_obj.prepare_docmatrix(corp_obj.knownpids)\n print(\"finished loading entire corpus into main memory\")\n self.sched_obj = sched_obj\n self.corp_obj = corp_obj\n\n def query_algorithm(self, psum, pids_context):\n self.eval_obj.fit(set(pids_context))\n self._last_cleaned_psum = wordslist2string(cleanStringAndLemmatize(psum))\n self._last_pidspredictions = self.eval_obj.transform(self._last_cleaned_psum)\n pids, scores = zip(*self._last_pidspredictions)\n pids, scores = list(pids), list(scores)\n names = [str(self.corp_obj.to_name(pid)) for pid in pids]\n self._last_namespredictions = list(zip(names, scores))\n return self._last_namespredictions\n\n","sub_path":"AppMain.py","file_name":"AppMain.py","file_ext":"py","file_size_in_byte":7913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"196592159","text":"t = int(input())\nfor i in range(t):\n a = 0\n b = 0\n n = int(input())\n arr = [int(j) for j in input().split()]\n for j in arr:\n if j%2 == 0 :\n a = 1\n else :\n b = 1\n if a == 1 and b == 1 :\n print(\"YES\")\n elif b == 1 and n%2 == 1 :\n print(\"YES\")\n else :\n print(\"NO\")\n","sub_path":"1296a.py","file_name":"1296a.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"474290471","text":"from rest_framework import serializers\nfrom .models import NewsConten,NewsTag,NewsPub,NewsHotAddModle,NewsBanner\nfrom apps.authPro.serailizer import NewsUserSerailizer\n\nclass NewsContentSerailizer(serializers.ModelSerializer):\n auth = NewsUserSerailizer()\n class Meta:\n model = NewsConten\n fields = ('id','content','create_time','auth')\n\n\nclass NewsTagSerailizer(serializers.ModelSerializer):\n\n class Meta:\n model = NewsTag\n fields = ('id','name','create_time',)\n\nclass NewsPubSerailizer(serializers.ModelSerializer):\n auth = NewsUserSerailizer()\n tag = NewsTagSerailizer()\n\n class Meta:\n model = NewsPub\n fields = ('id','title','desc','pub_time','thumbnail','auth','tag')\n\nclass NewsHotSerailizer(serializers.ModelSerializer):\n news = NewsPubSerailizer()\n\n class Meta:\n model = NewsHotAddModle\n fields = ('id','news','priority','create_time')\n\nclass NewsBannerSerializer(serializers.ModelSerializer):\n class Meta:\n model = NewsBanner\n fields = '__all__'","sub_path":"apps/news/serailizer.py","file_name":"serailizer.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605914129","text":"from django.conf import settings\nfrom django.db import models, transaction\nfrom django.db.models.query_utils import Q\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom issues.models import ProposalStatus, IssueStatus\nfrom meetings.models import MeetingParticipant\nfrom ocd.base_models import HTMLField, UIDMixin\nfrom ocd.email import send_mails\nfrom users.default_roles import DefaultGroups\nfrom users.models import OCUser, Membership\nimport issues.models as issues_models\nimport logging\nimport meetings.models as meetings_models\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SendToOption(object):\n\n ONLY_ME = 1\n ONLY_ATTENDEES = 2\n BOARD_ONLY = 3\n ALL_MEMBERS = 4\n\n choices = (\n (ONLY_ME, _(\"Only Me (review)\")),\n (ONLY_ATTENDEES, _(\"Only attendees\")),\n (BOARD_ONLY, _(\"The Board\")),\n (ALL_MEMBERS, _(\"All Members\")),\n )\n\n publish_choices = (\n (ONLY_ME, _(\"Only Me (review)\")),\n (BOARD_ONLY, _(\"The Board\")),\n (ALL_MEMBERS, _(\"All Members\")),\n )\n\n\nclass Community(UIDMixin):\n\n name = models.CharField(max_length=200, verbose_name=_(\"Name\"))\n is_public = models.BooleanField(_(\"Public Community\"), default=False,\n db_index=True)\n logo = models.ImageField(upload_to='community_logo', verbose_name=_(\"Community Logo\"), blank=True, null=True)\n official_identifier = models.CharField(max_length=300, verbose_name=_(\"Community Identifier\"), blank=True, null=True)\n\n upcoming_meeting_started = models.BooleanField(\n _(\"Meeting started\"),\n default=False)\n upcoming_meeting_title = models.CharField(\n _(\"Upcoming meeting title\"),\n max_length=300, null=True,\n blank=True)\n upcoming_meeting_scheduled_at = models.DateTimeField(\n _(\"Upcoming meeting scheduled at\"),\n blank=True, null=True)\n upcoming_meeting_location = models.CharField(\n _(\"Upcoming meeting location\"),\n max_length=300, null=True,\n blank=True)\n upcoming_meeting_comments = HTMLField(_(\"Upcoming meeting background\"),\n null=True, blank=True)\n\n upcoming_meeting_participants = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n blank=True,\n related_name=\"+\",\n verbose_name=_(\n \"Participants in upcoming meeting\"))\n\n upcoming_meeting_guests = models.TextField(_(\"Guests in upcoming meeting\"),\n null=True, blank=True,\n help_text=_(\"Enter each guest in a separate line\"))\n\n upcoming_meeting_version = models.IntegerField(\n _(\"Upcoming meeting version\"), default=0)\n\n upcoming_meeting_is_published = models.BooleanField(\n _(\"Upcoming meeting is published\"),\n default=False)\n upcoming_meeting_published_at = models.DateTimeField(\n _(\"Upcoming meeting published at\"),\n blank=True, null=True)\n\n upcoming_meeting_summary = HTMLField(_(\"Upcoming meeting summary\"),\n null=True, blank=True)\n board_name = models.CharField(_(\"Board Name\"), max_length=200,\n null=True, blank=True)\n \n class Meta:\n verbose_name = _(\"Community\")\n verbose_name_plural = _(\"Communities\")\n\n def __unicode__(self):\n return self.name\n\n @models.permalink\n def get_absolute_url(self):\n return \"community\", (str(self.pk),)\n\n @models.permalink\n def get_upcoming_absolute_url(self):\n return \"community\", (str(self.pk),)\n\n def upcoming_issues(self, upcoming=True):\n l = issues_models.IssueStatus.IS_UPCOMING if upcoming else \\\n issues_models.IssueStatus.NOT_IS_UPCOMING\n return self.issues.filter(active=True, status__in=(l)\n ).order_by('order_in_upcoming_meeting')\n\n def available_issues(self):\n return self.issues.filter(active=True, status=issues_models.IssueStatus.OPEN\n ).order_by('created_at')\n def issues_ready_to_close(self):\n return self.upcoming_issues().filter(\n proposals__active=True,\n proposals__decided_at_meeting=None,\n proposals__status__in=[\n ProposalStatus.ACCEPTED,\n ProposalStatus.REJECTED\n ]\n )\n\n def get_board_name(self):\n return self.board_name or _('Board')\n\n def get_members(self):\n return OCUser.objects.filter(memberships__community=self)\n\n def get_guest_list(self):\n if not self.upcoming_meeting_guests:\n return []\n return filter(None, [s.strip() for s in self.upcoming_meeting_guests.splitlines()])\n\n def send_mail(self, template, sender, send_to, data=None, base_url=None):\n\n if not base_url:\n base_url = settings.HOST_URL\n\n d = data.copy() if data else {}\n\n d.update({\n 'base_url': base_url,\n 'community': self,\n 'LANGUAGE_CODE': settings.LANGUAGE_CODE,\n 'MEDIA_URL': settings.MEDIA_URL,\n 'STATIC_URL': settings.STATIC_URL,\n })\n\n subject = render_to_string(\"emails/%s_title.txt\" % template, d).strip()\n\n message = render_to_string(\"emails/%s.txt\" % template, d)\n html_message = render_to_string(\"emails/%s.html\" % template, d)\n from_email = \"%s <%s>\" % (self.name, settings.FROM_EMAIL)\n\n recipient_list = set([sender.email])\n\n if send_to == SendToOption.ALL_MEMBERS:\n recipient_list.update(list(\n self.memberships.values_list('user__email', flat=True)))\n elif send_to == SendToOption.BOARD_ONLY:\n recipient_list.update(list(\n self.memberships.board().values_list('user__email', flat=True)))\n elif send_to == SendToOption.ONLY_ATTENDEES:\n recipient_list.update(list(\n self.upcoming_meeting_participants.values_list(\n 'email', flat=True)))\n\n logger.info(\"Sending agenda to %d users\" % len(recipient_list))\n\n send_mails(from_email, recipient_list, subject, message, html_message)\n\n return len(recipient_list)\n\n def close_meeting(self, m, user):\n\n with transaction.commit_on_success():\n m.community = self\n m.created_by = user\n m.title = self.upcoming_meeting_title\n m.scheduled_at = (self.upcoming_meeting_scheduled_at\n or timezone.now())\n m.location = self.upcoming_meeting_location\n m.comments = self.upcoming_meeting_comments\n m.guests = self.upcoming_meeting_guests\n m.summary = self.upcoming_meeting_summary\n\n m.save()\n\n self.upcoming_meeting_started = False\n self.upcoming_meeting_title = None\n self.upcoming_meeting_scheduled_at = None\n self.upcoming_meeting_location = None\n self.upcoming_meeting_comments = None\n self.upcoming_meeting_summary = None\n self.upcoming_meeting_version = 0\n self.upcoming_meeting_is_published = False\n self.upcoming_meeting_published_at = None\n self.upcoming_meeting_guests = None\n self.save()\n\n for i, issue in enumerate(self.upcoming_issues()):\n\n proposals = issue.proposals.filter(\n active=True,\n decided_at_meeting=None\n ).exclude(\n status=ProposalStatus.IN_DISCUSSION\n )\n for p in proposals:\n p.decided_at_meeting = m\n p.save()\n\n for c in issue.comments.filter(active=True, meeting=None):\n c.meeting = m\n c.save()\n\n meetings_models.AgendaItem.objects.create(\n meeting=m, issue=issue, order=i,\n closed=issue.completed)\n\n issue.is_published = True\n\n if issue.completed:\n issue.status = issue.statuses.ARCHIVED\n issue.order_in_upcoming_meeting = None\n\n issue.save()\n\n for i, p in enumerate(self.upcoming_meeting_participants.all()):\n\n try:\n mm = p.memberships.get(community=self)\n except Membership.DoesNotExist:\n mm = None\n\n MeetingParticipant.objects.create(meeting=m, ordinal=i, user=p,\n display_name=p.display_name,\n default_group_name=mm.default_group_name if mm else None)\n\n self.upcoming_meeting_participants = []\n\n return m\n\n def draft_agenda(self):\n \"\"\" prepares a fake agenda item list for 'protocol_draft' template. \"\"\"\n\n def as_agenda_item(issue):\n return {\n 'issue': issue,\n\n 'proposals':\n issue.proposals.filter(decided_at_meeting=None,\n active=True)\n .exclude(status=ProposalStatus.IN_DISCUSSION),\n \n 'accepted_proposals':\n issue.proposals.filter(decided_at_meeting=None,\n active=True,\n status=ProposalStatus.ACCEPTED),\n \n 'rejected_proposals':\n issue.proposals.filter(decided_at_meeting=None,\n active=True,\n status=ProposalStatus.REJECTED),\n \n 'comments':\n issue.comments.filter(meeting=None, active=True),\n }\n\n return [as_agenda_item(x) for x in\n self.issues.filter(status__in=IssueStatus.IS_UPCOMING)]\n","sub_path":"src/communities/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119869833","text":"import torch\nimport torch.nn.functional as F\nimport argparse\n\nfrom deep_model.data_utils import build_tokenizer, build_embedding_matrix\nfrom deep_model.models.cnn import CNN\nfrom configs.config import config\n\n\n\nclass Inferer:\n \"\"\"A simple inference example\"\"\"\n def __init__(self, opt, use_retrain_parameter:bool=False):\n self.opt = opt\n self.tokenizer = build_tokenizer(\n fnames=[opt.dataset_file['train'], opt.dataset_file['test']],\n max_seq_len=opt.max_seq_len,\n # dat_fname='{0}_tokenizer.dat'.format(opt.dataset))\n dat_fname= config.deep_model_dir / f'{opt.dataset}_tokenizer.dat')\n embedding_matrix = build_embedding_matrix(\n word2idx=self.tokenizer.word2idx,\n embed_dim=opt.embed_dim,\n dat_fname=config.deep_model_dir / '{0}_{1}_embedding_matrix.dat'.format(str(opt.embed_dim), opt.dataset))\n self.model = opt.model_class(embedding_matrix, opt)\n print('loading model {0} ...'.format(opt.model_name))\n state_dict_path = model_state_dict_paths[\"retrain\"] if use_retrain_parameter else model_state_dict_paths[\"best\"]\n print(f\"use parameter {state_dict_path.absolute()}\")\n if not torch.cuda.is_available():\n self.model.load_state_dict(torch.load(state_dict_path, map_location = torch.device('cpu')))\n else:\n self.model.load_state_dict(torch.load(state_dict_path))\n self.model = self.model.to(opt.device)\n # switch model to evaluation mode\n self.model.eval()\n torch.autograd.set_grad_enabled(False)\n\n def evaluate(self, raw_text):\n #context_seqs = [self.tokenizer.text_to_sequence(raw_text.lower().strip()) for raw_text in raw_texts]\n context_seqs = [self.tokenizer.text_to_sequence(raw_text.lower().strip())]\n context_indices = torch.tensor(context_seqs, dtype=torch.int64).to(self.opt.device)\n\n t_inputs = [context_indices]\n t_outputs = self.model(t_inputs)\n t_outputs[t_outputs >= 0.5] =1\n t_outputs[t_outputs < 0.5] = 0\n return t_outputs\n\n #t_probs = F.softmax(t_outputs, dim=-1).cpu().numpy()\n #return t_probs\n\n\n\nmodel_classes = {\n 'cnn': CNN,\n}\n# set your trained models here\nmodel_state_dict_paths = {\n 'retrain': config.deep_model_dir / 'state_dict/cnn_PM',\n \"best\": config.deep_model_dir / 'state_dict_best/cnn_PM',\n}\nclass Option(object): pass\nopt = Option()\nopt.model_name = 'cnn'\nopt.model_class = model_classes[opt.model_name]\nopt.dataset = 'PM'\nopt.dataset_file = {\n 'train': config.deep_model_dir / 'dataset/description2017.txt',\n 'test': config.deep_model_dir / 'dataset/description2018.txt',\n}\n# opt.state_dict_path = model_state_dict_paths[opt.model_name]\nopt.embed_dim = 300\nopt.hidden_dim = 300\nopt.max_seq_len = 100\nopt.polarities_dim = 1\nopt.max_kernel_size = 3\nopt.n_filters = 100\nopt.dropout = 0.5\n# opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nopt.device = torch.device('cpu')\n\n\n","sub_path":"deep_model/infer_example.py","file_name":"infer_example.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"610908126","text":"import discord\nfrom random import choice\nimport os\nimport datetime\nimport bdbf\nimport datetime\nimport database\nimport json\nimport asyncio\nimport requests\n\ntoken = os.environ.get('TOKEN', None)\n\n\n\n\nclient = bdbf.Client(commandPrefix = \"-\", embedFooter = {\"text\": \"Powered by wertousek\",\"icon_url\":\"https://cdn.discordapp.com/avatars/436131686640648195/d72e4885e1d21bca46bd245bb00c4687.png\"})\nguild = client.get_guild(825802518805086278)\n\nwith open (\"sprostySlovnik.json\",\"r\") as sprostySlovnik:\n sprostaSlova = json.loads(sprostySlovnik.read())\n\nclass GetOutOfLoop(Exception):\n pass\n\n@client.event # event decorator/wrapper\nasync def on_ready():\n print(f\"We have logged in as {client.user}\")\n\n@client.event\nasync def on_message(message):\n print(f\"{message.channel}: {message.author}: {message.author.name}: {message.content}\")\n \n try:\n if message.channel.guild.id not in (436132782725660672,):\n if \"guild\" in dir(message.channel):\n msgLog = [datetime.datetime.utcnow().isoformat(), str(message.author), str(message.author.id),str(message.channel.guild), str(message.channel.guild.id), str(message.channel), str(message.channel.id), message.content, str(message.id)]\n else:\n msgLog = [datetime.datetime.utcnow().isoformat(), str(message.author), str(message.author.id),\"\", \"\", str(message.channel), str(message.channel.id), message.content, str(message.id)]\n\n try:\n database.messageLog.append_row(msgLog)\n except:\n pass\n except:\n pass\n \n if message.channel.id in [717434872733368531,717456125259153488,773470209503526932,774214326277505044,775706385190617089,800459924164968529,765588311829381141,784788638566711316,798501918972313601,798833045867331584,798856483008806912,798856778728079401,789127499639816212,788087884933890098,775065672782577714,775768221151526974,717440779903172640,717440779903172640]:\n return {\"command\":False}\n \"\"\"await spamProtection(message, choice([f\"{message.author.mention} nespamuj!\",f\"{message.author.mention} Mohli bys psát trochu méně. nikoho to tu nezajímá, jak spamuješ\",f\"{message.author.mention}už nic nepiš! bolí mě z toho hlava!\"]), 5)\"\"\"\n\n \"\"\"if \"kedy\" in message.content.lower() and \"aktualizacia\" in message.content.lower():\n await message.channel.send(\"Nauč sa písať diakritiku ty bezcitné hovado\")\n\n for i in [[\"kdy\",\"bude\",\"aktualizace\"],[\"kdy\",\"vyjde\",\"aktualizace\"],[\"kdy\",\"update\"],[\"jak\",\"je\",\"na\",\"tom\",\"aktualizace\"]]:\n b = 0\n for j in i:\n if j in message.content.lower():\n b += 1\n if b == len(i):\n await message.channel.send(choice([\"Kdo ví\",\"Nikdo neví\",\"Bude až bude\",\"Někdy vyjde, neboj\"]))\n\n for i in [[\"kedy\",\"vyjde\",\"aktualizácia\"],[\"kedy\",\"bude\",\"aktualizácia\"],[\"kedy\",\"update\"],[\"kedy\",\"updatu\"]]:\n b = 0\n for j in i:\n if j in message.content.lower():\n b += 1\n if b == len(i):\n await message.channel.send(choice([\"Ani boh nevie\",\"Neboj bude\",\"Zistíš až vyjde\"]))\"\"\"\n\n if type(message.channel) == discord.DMChannel:\n if message.author.id == 436131686640648195:\n try:\n msgTextSplit = message.content.split(\" \",1)\n channel = await client.fetch_channel(int(msgTextSplit[0]))\n await channel.send(msgTextSplit[1])\n except Exception as e:\n await message.channel.send(e)\n raise e\n\n #print(sprostaSlova)\n b = False\n for slovo in message.content.lower().split(\" \"):\n for sSlovo in sprostaSlova[\"sprostaSlova\"]:\n if sSlovo in slovo:\n try:\n for nSslovo in sprostaSlova[\"neSprostaSlova\"]:\n if nSslovo in slovo:\n b = False\n print(slovo, nSslovo, sSlovo)\n raise GetOutOfLoop\n b = True\n except GetOutOfLoop:\n pass\n if b and \"Soukupe mlč\" not in message.content:\n await message.channel.send(choice([f\"{message.author.mention} Zklidni slovník kamaráde\",f\"Hej! {message.author.mention} Tohle slovo bys měl co nejdříve odstranit ze svého slovníku!\",f\"Hej! Hej! Hej! {message.author.mention} Nikdo tady na ty tvoje sprosťárny neni zvědavej!\" ]),delete_after=20)\n\n if message.author.id != 436131686640648195 and message.channel.guild.id == 436132782725660672 and message.content == \"!rank\":\n await asyncio.sleep(1)\n await message.channel.send(\"Amatér\")\n \n if str(message.channel.id) not in database.commandStates.col_values(1):\n database.commandStates.append_row([str(message.channel.id), \"off\"])\n \n channelIndexInCommandStates = database.commandStates.col_values(1).index(str(message.channel.id))\n \n if database.commandStates.col_values(2)[channelIndexInCommandStates] == \"off\" and not message.author.guild_permissions.administrator:\n return {\"command\": False}\n \n@client.command(\"randomKlub\")\nasync def randomKlub(message):\n \"\"\"napíše náhodný klub z aktualizace Jaro20 do hry [CSM](https://www.csmweb.net/)\"\"\"\n with open(\"teams20.txt\",\"r\") as teams:\n team = choice(teams.read().split(\"\\n\"))\n await message.channel.send(team)\n \n@client.command(\"randomKlub18\")\nasync def randomKlub18(message):\n \"\"\"napíše náhodný klub z aktualizace Podzim18 do hry [CSM](https://www.csmweb.net/)\"\"\"\n with open(\"teams.txt\",\"r\") as teams:\n team = choice(teams.read().split(\"\\n\"))\n await message.channel.send(team)\n \n@client.command(\"randomklub\")\nasync def randomKlub(message):\n \"\"\"randomklub\"\"\"\n with open(\"teams20.txt\",\"r\") as teams:\n team = choice(teams.read().split(\"\\n\"))\n await message.channel.send(team)\n \n@client.command(\"randomklub18\")\nasync def randomKlub18(message):\n \"\"\"randomklub18\"\"\"\n with open(\"teams.txt\",\"r\") as teams:\n team = choice(teams.read().split(\"\\n\"))\n await message.channel.send(team)\n\n@client.command(\"trh\")\nasync def trh(message):\n \"\"\"napíše, po kterých kolech se aktualizuje trh\"\"\"\n await message.channel.send(\"Trh se aktualizuje po odehrání těchto kol:\\nDomácí: 3, 8, 13, 18, 23, 28, 33, 38, 43\\nSvětový: 5, 10, 15, 20, 25, 30, 35, 40, 45\")\n \n@client.command(\"prodej\")\nasync def prodej(message, *attributes):\n \"\"\"**Použití**: `-prodej ` napíše, za kolik procent ceny hráč prodávat\"\"\"\n if len(attributes) == 0:\n await message.channel.send(\"Hráče se doporučuje prodávat za 80 až 90% jeho ceny\")\n else:\n attributes = attributes[0]\n await message.channel.send(f\"Hráče prodej za {int(int(attributes)*0.85)}€, {int(int(attributes)*0.8)}€ až {int(int(attributes)*0.9)}€\")\n \n@client.command(\"nejslabsi\")\nasync def nejslabsi(message):\n \"\"\"napíše tabulku nejslabších týmů z každé ligy\"\"\"\n await message.channel.send(\"Hledáš nejslabší kluby? tak snad tohle pomůže https://media.discordapp.net/attachments/695395367092486144/721144888862703666/Nejvetsi_lemplove.PNG (tabulku vytvořil FluffyHero)\")\n \n@client.command(\"kodyJaro20\")\nasync def kodyJaro20(message):\n \"\"\"Pošle odkaz na tabulku kódů týmů pro scénáře\"\"\"\n await message.channel.send(\"Děláš scénář a nevíš kód týmu? Nevadí, tady máš tabulku (hlavně se nezapomeň o scénář pak podělit :slight_smile:) http://bit.ly/KodyJaro20\")\n\n@client.command(\"hostovani\")\nasync def hostovani(message, *attributes):\n \"\"\"**Použití**: `-hostovani ` např `-hostovani 300000 30 16`\\n Napíše, kolik peněz si říct za hostování\"\"\"\n try:\n attributes = attributes[0]\n attributes = [i for i in map(int,attributes.split(\" \"))]\n await message.channel.send(f\"Hráče posílej na hostování za {int(attributes[0]/3/attributes[1]*attributes[2])} €.\")\n except:\n await message.channel.send(\"Tento příkaz se používá způsobem `-hostovani ` např `-hostovani 300000 30 16` popřípadě to samé akorát místo hostování napsat host\")\n\n@client.command(\"host\")\nasync def host(message, *attributes):\n \"\"\"host\"\"\"\n try:\n attributes = attributes[0]\n attributes = [i for i in map(int,attributes.split(\" \"))]\n await message.channel.send(f\"Hráče posílej na hostování za {int(attributes[0]/3/attributes[1]*attributes[2])} €.\")\n except:\n await message.channel.send(\"Tento příkaz se používá způsobem `-hostovani ` např `-hostovani 300000 30 16` popřípadě to samé akorát místo hostování napsat host\")\n\n@client.command(\"search\")\nasync def search(msg, *args):\n \"\"\"Searches the web\"\"\"\n print(args)\n if args == ():\n return\n r = requests.get(f\"https://api.duckduckgo.com/?q={args[0]}&format=json&kl=cz-cs\").json()\n print(msg.content)\n await msg.channel.send(\"Ty to nevíš? No tak já ti pomůžu\", embed=client.embed(r[\"Heading\"], description=r[\"AbstractText\"], fields=[]))\n \n@client.command(\"command\")\nasync def commandToggeling(msg, *args):\n \"\"\"Přepínání commandů\"\"\"\n if str(msg.channel.id) not in database.commandStates.col_values(1):\n database.commandStates.append_row([str(msg.channel.id), \"off\"])\n \n channelIndexInCommandStates = database.commandStates.col_values(1).index(str(msg.channel.id))\n args = args[0]\n if args == None:\n await msg.channel.send(f\"Commandy jsou aktuálně ***{database.commandStates.col_values(2)[channelIndexInCommandStates]}***\")\n elif args == \"on\":\n database.commandStates.update_cell(channelIndexInCommandStates,2, \"on\")\n await msg.channel.send(\"Commandy zapnuty\")\n elif args == \"off\":\n database.commandStates.update_cell(channelIndexInCommandStates,2, \"off\")\n await msg.channel.send(\"Commandy vypnuty\")\n else:\n await msg.channel.send(f\"Neznámý stav {args}, použij *off*, nebo *on*\")\n \nclient.run(token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"532410793","text":"import twitter\nimport pandas as pd\nimport csv\n\naccounts = []\naccess_token = \"2772719962-Q1haRjy5TtepL0xxg6uTpPvSLxYqgt1wngMPVb6\"\naccess_token_secret = \"s9cBS22Ty1odbv1T2NOlrhAtfLADUfkBqbIXABnc7fJDW\"\napi_key = \"84dHSReoui2rHa8XkSgGRBneD\"\napi_key_secret = \"JsyLTccaGCZ0lLID4aI0lW35wYjeZbqaBc1WspENpdMz5tXWZS\"\n\napi = twitter.Api(consumer_key=api_key,\n consumer_secret=api_key_secret,\n access_token_key=access_token,\n access_token_secret= access_token_secret)\n\nprint(api.VerifyCredentials())\n\n\ndef block_user(list_user):\n for user in list_user:\n print(user)\n try:\n api.CreateBlock(screen_name=user)\n except:\n pass\n\nwith open(\"accounts.csv\", newline='') as csvfile:\n accountreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for account in accountreader:\n accounts.append(str(account)[22:-2])\n\nprint(accounts[0])\nprint(len(accounts))\n\nblock_user(accounts)","sub_path":"Block_users.py","file_name":"Block_users.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"154486087","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n@version: 1.0\n@author: kevin\n@license: Apache Licence \n@contact: liujiezhang@bupt.edu.cn\n@site: \n@software: PyCharm Community Edition\n@file: detail.py\n@time: 16/11/25 上午10:57\n\"\"\"\n\nfrom spiders.myfunc import *\nfrom scrapy.http import HtmlResponse\nfrom collections import defaultdict\nimport itertools\nimport time\n\n\ndef goodsUrlList(home_url):\n '''\n 根据三级目录商品首页获取所有详情页url\n :param home_url: http://www.vipmro.com/search/?&categoryId=501110\n :return:url列表\n '''\n # 所有条件下的列表\n all_group_list = parseOptional(home_url)\n # 保存所有goods的详情页url\n url_list = []\n for url in all_group_list:\n # url = 'http://www.vipmro.com/search/?ram=0.9551325197768372&categoryId=501110&attrValueIds=509805,509801,509806,509807'\n # 解析html\n home_page = getHtmlFromJs(url)['content'].encode('utf-8')\n html = HtmlResponse(url=url,body=str(home_page))\n urls = html.selector.xpath('/html/body/div[7]/div[1]/ul/li/div[2]/a/@href').extract()\n url_list.extend(urls)\n # print(len(urls))\n # print(urls)\n # exit()\n # print(len(url_list))\n # print(url_list)\n return url_list\n\ndef goodsDetail(detail_url):\n '''\n 利用xpath解析关键字段\n :param detail_url: 详情页url\n :return: 各个字段信息 dict\n '''\n goods_data = defaultdict()\n # 详情页链接\n goods_data['source_url'] = detail_url\n # 解析html body必须是str类型\n body = getHtmlFromJs(detail_url)['content'].encode('utf-8')\n html = HtmlResponse(url=detail_url,body=str(body))\n # 名称\n goods_data['name'] = html.xpath('/html/body/div[7]/div[2]/h1/text()').extract()[0]\n # 价格\n goods_data['price'] = html.selector.xpath('/html/body/div[7]/div[2]/div[2]/ul/li[1]/label[1]/text()').extract()[0]\n # 型号\n goods_data['type'] = html.selector.xpath('/html/body/div[7]/div[2]/div[2]/ul/li[3]/label/text()').extract()[0]\n # 详情\n goods_data['detail'] = html.selector.xpath('/html/body/div[9]/div[2]/div[2]/table').extract()[0]\n # 图片\n pics = []\n for pic in html.selector.xpath('/html/body/div[7]/div[1]/div[2]/div[2]/ul/li/img'):\n # 去除图片尺寸,方法图片\n pics.append(pic.xpath('@src').extract()[0].replace('!240240',''))\n goods_data['pics'] = '|'.join(pics)\n goods_data['storage'] = ''\n goods_data['lack_period'] = ''\n goods_data['created'] = int(time.time())\n goods_data['updated'] = int(time.time())\n\n # print(goods_data['detail'])\n return goods_data\n\ndef parseOptional(url):\n '''\n 解析url下页面各种选择项组合的url\n :param url: http://www.vipmro.com/search/?&categoryId=501110\n :return:['http://www.vipmro.com/search/?categoryId=501110&attrValueIds=509801,512680,509807,509823']\n '''\n # 解析html\n home_page = getHtmlFromJs(url)['content'].encode('utf-8')\n html = HtmlResponse(url=url,body=str(home_page))\n # 系列参数\n xi_lie = html.selector.xpath('/html/body/div[5]/div[6]/ul/li/a/@href').re(r'ValueIds=(\\d+)')\n # 额定极限分断能力\n fen_duan = html.selector.xpath('/html/body/div[5]/div[10]/ul/li/a/@href').re(r'ValueIds=(\\d+)')\n # 脱扣器形式\n tuo_kou_qi = html.selector.xpath('/html/body/div[5]/div[14]/ul/li/a/@href').re(r'ValueIds=(\\d+)')\n # 安装方式\n an_zhuang = html.selector.xpath('/html/body/div[5]/div[12]/ul/li/a/@href').re(r'ValueIds=(\\d+)')\n # 获取所有参数组合\n all_group = list(itertools.product(xi_lie,fen_duan,tuo_kou_qi,an_zhuang))\n _url = url + '&attrValueIds='\n url_list = map(lambda x:_url+','.join(list(x)),all_group)\n\n return url_list\n\nif __name__ == '__main__':\n # url = 'http://www.vipmro.com/product/587879'\n url = 'http://www.vipmro.com/search/?&categoryId=501110'\n goodsUrlList(url)\n print(\"it works\")\n\n","sub_path":"spiders/vipmro/detail.py","file_name":"detail.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"175868567","text":"import logging\nimport logging.config\nimport othermod as om\nfrom othermod import add\nfrom othermod import mult\n\n# logging.config.fileConfig('logging.conf')\nlogging.config.fileConfig(disable_existing_loggers=False, fname='resources/logging.conf')\n# logging.config.fileConfig(disable_existing_loggers=False, fname='resources/fileh.conf')\n# logging.config.fileConfig(disable_existing_loggers=False, fname='/Users/arunangsusahunarayan7/LogConfiguration/logging.conf')\n# D:\\Python_Projects\\LogBestPracticesPython\\resources\\fileh.conf\n# create logger\nlogger = logging.getLogger(__name__)\n\n\ndef do_calculation() -> object:\n \"\"\"\n The main entry point of the application\n :rtype: object\n \"\"\"\n # logging.basicConfig(filename=\"mySnake21.log\", level=logging.INFO)\n logger.info(\"Program started\")\n result = add(7, 8)\n logger.info(\"**********Done!********** {}\".format(result))\n result1 = mult(7, 8)\n logger.info(\"Done! {}\".format(result1))\n logger.debug(\"**********Done!********** {}\".format(result1))\n result2 = om.sub(9, 3)\n logger.debug(\"*********Done!*********** {}\".format(result2))\n\n\ndo_calculation()\n\n# 'application' code\n# logger.debug('debug message')\n# logger.info('info message')\n# logger.warn('warn message')\n# logger.error('error message')\n# logger.critical('critical message')\n\n","sub_path":"test_logging_conf.py","file_name":"test_logging_conf.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138773944","text":"import exceptions\n\ndef toInt(n):\n # Convert string to int if valid, otherwise return None\n n = n.strip()\n return int(n) if n else None\n\ndef validTimeBounds(start, end, length):\n # Ensure time bounds are valid for given file length\n if start != None != end:\n if (start < end) and (start >= 0) and (end <= length):\n return True\n elif start == end == None:\n return True\n return False\n\ndef parseFileName(filename, delimiter, categories):\n # Split filename into user-defined categories.\n # Error raised if category length does not match extracted filename segments.\n segs = filename.split(delimiter)\n if len(segs) != len(categories):\n raise exceptions.FilenameParseError(filename)\n else:\n filename_info = {}\n for c, s in zip(categories, segs):\n # Trim file extensions\n if '.' in s:\n s = s.split('.')[0]\n filename_info[c] = s\n return filename_info","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"391691472","text":"import os\nimport matplotlib.pyplot as pl\nimport numpy as np\nfrom lmfit import minimize, Parameters\nimport glob\n\n# pipeline files\nfrom auxiliaries import *\nfrom scipy.ndimage import filters\nfrom scipy.stats.stats import pearsonr\nfrom scipy.integrate import quad\nfrom scipy.interpolate import LSQUnivariateSpline as spline\nfrom scipy.interpolate import UnivariateSpline\nfrom scipy import signal\nfrom scipy.ndimage import filters\nimport os\n\ndef moving_average(series, sigma=3.0):\n b = signal.gaussian(24, sigma)\n average = filters.convolve1d(series, b/b.sum())\n var = filters.convolve1d(np.power(series-average,2), b/b.sum())\n return average, var\n\n\ndef chunks(l, n):\n \"\"\" Yield successive n-sized chunks from l.\n \"\"\"\n for i in range(0, len(l), n):\n yield list(l[i:i+n])\n\ndef median_filter(time,data,binsize=30):\n # do a running median filter dividing all data points by the median of their immediate surroundings\n i = 0\n data_filtered = []\n while i < len(time):\n\t bin_begin = int(max(0, (i - binsize/2)))\n\t bin_end = int(min(len(time),(i+binsize/2)))\n\t the_bin = data[bin_begin:bin_end]\n\t the_bin = sorted(the_bin)\n\t median = np.median(the_bin) #[len(the_bin)/2]\n\t data_filtered.append(data[i]/median)\n\t i = i + 1\n return data_filtered\n\n\ndef NewMedianFilter(time,flux, binsize=24):\n\n # do a running median filter dividing all data points by the median of their immediate surroundings\n N = int(len(time)/binsize)\n MedianArray = []\n for i in range(N+1):\n median = np.median(flux[i*binsize:(i+1)*binsize])\n if inp.std(Perp2):\n X_Transformed = Perp1\n Y_Transformed = Perp2\n else:\n X_Transformed = Perp2\n Y_Transformed = Perp1\n\n #FIT A FIFTH ORDER POLYNOMIAL\n TempXTransformed = np.copy(X_Transformed)\n TempYTransformed = np.copy(Y_Transformed)\n\n params = np.polyfit(TempXTransformed, TempYTransformed,5)\n XXX = np.linspace(min(TempXTransformed),max(TempXTransformed),1000)\n YYY = np.polyval(params, XXX)\n\n\n\n #Calculate Arc Length\n Mult = np.arange(len(params)-1,0,-1)\n NewParams = params[:-1]*Mult\n\n #This helps you evaluate the integrand\n def Integrand(x,params):\n return np.sqrt(1+(np.polyval(params,x))**2)\n\n\n TempArcLength = []\n #Calculate Arclength for every coordinates\n for XVal in X_Transformed:\n tempArc,_ = quad(Integrand,0,XVal,args=(NewParams),epsabs=1e-8)\n TempArcLength.append(tempArc)\n\n TempArcLength = np.array(TempArcLength).astype(np.float32)\n ArcLength.extend(TempArcLength)\n\n\n ArcLength = np.array(ArcLength)*3.98\n params = np.polyfit(ArcLength,TimeDetrendedFlux,5)\n FluxPred = np.polyval(params, ArcLength)\n\n XXX = np.linspace(min(ArcLength), max(ArcLength), 1000)\n YYY = np.polyval(params, XXX)\n\n pl.figure()\n pl.plot(ArcLength, TimeDetrendedFlux, \"ko\")\n pl.plot(XXX,YYY,\"r-\",lw=2)\n pl.xlabel(\"Arclength (Arcseconds)\")\n pl.ylabel(\"Relative Flux\")\n pl.savefig(outputfolder+\"/RelativeFlux_Self_ArcLength.png\")\n\n StartStd = np.std(TimeDetrendedFlux-FluxPred)\n SelectedFile = \"Self\"\n for FileName in PointingFiles:\n ReadFile = np.loadtxt(FileName,delimiter=',',skiprows=1)\n t_pointing = ReadFile[:,0].astype(np.float32)\n Arc_pointing = ReadFile[:,2]*3.98 #convert into arc seconds\n\n #Need to interpolate because the read time does not match exactly\n TargetArc = np.interp(time, t_pointing, Arc_pointing)\n params = np.polyfit(TargetArc,TimeDetrendedFlux,5)\n FluxPred = np.polyval(params, TargetArc)\n StdCurrent = np.std(TimeDetrendedFlux-FluxPred)\n\n if StartStd>StdCurrent:\n SelectedFile = FileName\n StartStd = StdCurrent\n TargetArc = np.interp(time, t_pointing, Arc_pointing)\n XXX = np.linspace(min(TargetArc), max(TargetArc), 1000)\n YYY = np.polyval(params, XXX)\n pl.figure()\n pl.plot(TargetArc, TimeDetrendedFlux, \"ko\")\n pl.plot(XXX,YYY,\"r-\",lw=2)\n pl.xlabel(\"Arclength (Arcseconds)\")\n pl.ylabel(\"Relative Flux\")\n pl.savefig(outputfolder+\"/RelativeFlux_ArcLength.png\")\n pl.close('all')\n\n\n print (\"The Selected file is \", SelectedFile)\n\n if SelectedFile==\"Self\":\n TargetArc = np.copy(ArcLength)\n\n ds = np.diff(TargetArc)\n dt = np.diff(time)\n dV = ds/dt + 50.0\n\n\n TempTime = np.copy(time[1:])\n TempdV = np.copy(dV)\n\n\n\n\n\n ChunkSize = 72 #chunk every day or so\n for k in range(3):\n N = int(len(TempTime)/ChunkSize)\n Location = [int((i+0.5)*ChunkSize) for i in range(N)]\n knots = [TempTime[i] for i in Location]\n spl_dv = spline(TempTime, TempdV, knots, k=2)\n Detrended_dV = spl_dv(TempTime)\n Residual = np.abs(TempdV -Detrended_dV)\n Indices = Residual<3.0*np.std(Residual)\n TempTime = TempTime[Indices]\n TempdV = TempdV[Indices]\n\n #There is a time trend in dV. Remove it\n Detrended_dV = spl_dv(time[1:])\n dV = np.abs(dV/Detrended_dV) -1.0\n Std = np.std(dV)\n ThrusterIndices = np.abs(dV)>2.0*Std\n ThrusterIndices = np.concatenate([np.array([False]),ThrusterIndices])\n Locations = np.where(ThrusterIndices)[0]\n\n fig, (ax1, ax2, ax3) = pl.subplots(3, figsize=(15, 7), dpi=80, facecolor='w', edgecolor='k', sharex=True)\n ax1.plot(time,Xc,\"bo\")\n ax2.plot(time,Yc,\"go\")\n ax3.plot(time,TimeDetrendedFlux,\"ko\")\n for Location in Locations:\n ax1.axvline(x=time[Location],c=\"red\",ymin=-10.0,ymax=10.0, clip_on=True)\n ax2.axvline(x=time[Location],c=\"red\",ymin=-10.0,ymax=10.0, clip_on = True)\n ax3.axvline(x=time[Location],c=\"red\",ymin=-10.0,ymax=10.0, clip_on = True)\n ax1.set_ylabel(\"Xc\")\n ax2.set_ylabel(\"Yc\")\n ax3.set_ylabel(\"Time Detrended Flux\")\n ax3.set_xlabel(\"BJD (Days)\")\n pl.tight_layout()\n pl.savefig(outputfolder+\"/ThrusterEvent.png\")\n pl.close('all')\n\n #Remove the thruster events\n time = time[~ThrusterIndices]\n flux = flux[~ThrusterIndices]\n TimeDetrendedFlux = TimeDetrendedFlux[~ThrusterIndices]\n TargetArc = TargetArc[~ThrusterIndices]\n\n #Divide the data into different chunks\n time_chunks = list(chunks(time,chunksize))\n flux_chunks = list(chunks(flux,chunksize))\n detrendedflux_chunks = list(chunks(TimeDetrendedFlux,chunksize))\n Arc_chunks = list(chunks(TargetArc,chunksize))\n\n #if the last chunk is really small\n if len(time_chunks[-1]) 0:\n sol1 = ((-b) + (discriminante ** 0.5))/(2 * a)\n sol2 = ((-b) - (discriminante ** 0.5))/(2 * a)\nelse:\n sol1 = '''({} + {}i)/{}'''.format(-b, ((-discriminante) ** 0.5), 2*a)\n sol2 = '''({} - {}i)/{}'''.format(-b, ((-discriminante) ** 0.5), 2*a)\n \nprint('''Las soluciones para la ecuación son:\n{} y {}'''.format(sol1, sol2))","sub_path":"practica_3/7_ecuacion_cuadratica.py","file_name":"7_ecuacion_cuadratica.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"295213309","text":"from PIL import Image, ImageOps\nimport numpy as np\nimport itertools as iter\nfrom importlib import reload\nfrom sklearn.neighbors import NearestNeighbors\nimport diffPairs as dp\nreload(dp)\n\nimg_fname = 'colorbend.png'\nother_imgs_fnames = ['selfie2.jpg', 'selfie3.jpg', 'selfie4.jpg']\noutput_fname = 'output.png'\nsquare_size = 40\nstretch_amt = 1\ndwnspl_others = 0.5\ndiffusion_amt = 0\n\n\ndef avg_color(img):\n arr = [j[:3] for sub in np.array(img) for j in sub]\n sum_pix = np.sum(arr, 0)\n sum_pix = sum_pix / len(arr)\n return sum_pix\n\n\ndef downsample_difference(img, size=3):\n down = np.array(img.resize((size,size), Image.BILINEAR))\n return down.ravel()\n\n\nclass CropImg(object):\n __slots__ = ['img', 'orig_box', 'val', 'paired']\n def __init__(self, crop_img, box):\n self.img = crop_img\n self.orig_box = box\n self.val = downsample_difference(crop_img)\n # self.val = avg_color(crop_img)\n self.paired = False\n\n\ndef get_squares_from_img(img_in, square_size=square_size):\n grid_size_x = (img_in.size[0] // square_size)\n grid_size_y = (img_in.size[1] // square_size)\n\n squares = [[0 for j in range(grid_size_y)] for i in range(grid_size_x)]\n for i in range(grid_size_x):\n for j in range(grid_size_y):\n box = (i * square_size, j * square_size, (i + 1)*square_size, (j + 1)*square_size)\n region = img_in.crop(box)\n squares[i][j] = CropImg(region, box)\n return squares\n\n\ndef closest_square_match(match, sq_list):\n points = [x.val for x in sq_list]\n neigh = NearestNeighbors(1)\n neigh.fit(points)\n best_ind = neigh.kneighbors([match.val], 1, return_distance=False)[0][0]\n best_square = sq_list[best_ind]\n\n # best_diff = 10e10\n # best_square = 0\n # best_ind = 0\n # for i, x in enumerate(sq_list):\n # diff = np.sum(np.abs(x.val - match.val)**2)\n # if diff < best_diff:\n # best_diff = diff\n # best_square = x\n # best_ind = i\n return best_square, (match.val - best_square.val), best_ind\n\n\ndef get_neighboring_squares(center, main_squares):\n x_size = len(main_squares[0])\n y_size = len(main_squares)\n free_squares = []\n for shift in list(iter.product([-1, 0, 1], [-1, 0, 1])):\n idxs = (center[0] + shift[0], center[1] + shift[1])\n try:\n sq = main_squares[idxs[0]][idxs[1]]\n except IndexError:\n continue\n if not sq.paired:\n free_squares.append(idxs)\n return free_squares\n\nmain_img = Image.open(img_fname).convert('RGB')\nnew_size = (int(main_img.size[0] * stretch_amt), int(main_img.size[1] * stretch_amt))\nmatch_img = main_img.resize(new_size)\n\nother_imgs = [Image.open(fname) for fname in other_imgs_fnames]\n\nprint('slicing images into squares...')\nmain_squares = get_squares_from_img(match_img)\nother_squares = np.array([get_squares_from_img(x) for x in other_imgs]).ravel()\n\ncoordinates = list(iter.product(range(len(main_squares)), range(len(main_squares[0]))))\n# np.random.shuffle(coordinates)\n\nprint('matching images...')\npairs = []\nX = []\nfor c in coordinates:\n X.append(main_squares[c[0]][c[1]].val)\nY = np.array([sq.val for sq in other_squares])\nind_map = dp.min_diff_pair_mapping(X, Y, finish_early_factor=0.1)\n\n# for i, coord in enumerate(coordinates):\n#\n# if not i % 500:\n# print(' {} of {}...'.format(i, len(coordinates)))\n#\n# cx, cy = coord\n# square_to_match = main_squares[cx][cy]\n# match, diff, best_ind = closest_square_match(square_to_match, other_squares)\n# square_to_match.paired = True\n# pairs.append((square_to_match, match))\n# other_squares = np.delete(other_squares, best_ind)\n#\n# # diffuse error to neighboring cells\n# if not diffusion_amt:\n# continue\n# free_squares = get_neighboring_squares((cx, cy), main_squares)\n# if not free_squares:\n# continue\n# for s in free_squares:\n# edit_val = main_squares[s[0]][s[1]].val\n# main_squares[s[0]][s[1]].val = edit_val + (diff * diffusion_amt / len(free_squares))\n\n# reassemble image from scraps\nfor x, y in enumerate(ind_map):\n cx, cy = coordinates[x]\n matched_square = other_squares[y]\n orig_square = main_squares[cx][cy]\n match_img.paste(matched_square.img, orig_square.orig_box)\n\nmatch_img.save(f'stitched_{output_fname}')\n","sub_path":"neighborsMosaic.py","file_name":"neighborsMosaic.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"401847804","text":"\"\"\"empty message\n\nRevision ID: 8f428eb63e12\nRevises: \nCreate Date: 2018-06-11 15:17:38.110714\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '8f428eb63e12'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('Request_type',\n sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('name', sa.String(length=40), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('Role',\n sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('User',\n sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('name', sa.String(length=50), nullable=False),\n sa.Column('email', sa.String(length=250), nullable=True),\n sa.Column('password', sa.String(), nullable=False),\n sa.Column('role_id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.ForeignKeyConstraint(['role_id'], ['Role.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('name')\n )\n op.create_table('Request',\n sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('status', sa.Integer(), nullable=False),\n sa.Column('request_id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('owner_id', postgresql.UUID(as_uuid=True), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['owner_id'], ['User.id'], ),\n sa.ForeignKeyConstraint(['request_id'], ['Request_type.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('Request')\n op.drop_table('User')\n op.drop_table('Role')\n op.drop_table('Request_type')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/8f428eb63e12_.py","file_name":"8f428eb63e12_.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"198614903","text":"from enum import Enum, auto\n\nimport logging\nimport selectors\nimport socket\n\nfrom network.proto_message import ProtoMessage\nfrom network.proto_reader import ProtoReader\nfrom network.proto_writer import ProtoWriter\nfrom network.fsm import FiniteStateMachine, FSMTransition\n\n\nclass ClientState(Enum):\n DISCONNECTED = auto()\n CONNECTED = auto()\n READY = auto()\n PLAYING = auto()\n\n\nclass ClientInput(Enum):\n INIT = \"INIT\"\n START = \"START\"\n UPDATE = \"UPDATE\"\n STOP = \"STOP\"\n\n\nclass Client():\n \"\"\"Multiplayer client.\"\"\"\n\n def __init__(self, address):\n self.__address = address\n self.__selector = selectors.DefaultSelector()\n self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__socket.setblocking(False)\n self.__proto_message = None\n self.__processed_count = 0\n self.__reader = ProtoReader(self.__socket)\n self.__writer = ProtoWriter(self.__socket)\n self.__fsm = FiniteStateMachine(ClientState.DISCONNECTED, {\n ClientState.DISCONNECTED: {\n ClientInput.INIT: FSMTransition(ClientState.CONNECTED, self.command_init)\n },\n ClientState.CONNECTED: {\n ClientInput.START: FSMTransition(ClientState.PLAYING)\n },\n ClientState.PLAYING: {\n ClientInput.UPDATE: FSMTransition(ClientState.PLAYING, self.command_update),\n ClientInput.STOP: FSMTransition(ClientState.DISCONNECTED, self.command_stop)\n }\n })\n\n def connect(self, player_name):\n \"\"\"Connects to the server.\"\"\"\n logging.debug(\"Connecting to {0}:{1}\".format(self.__address[0], self.__address[1]))\n self.__socket.connect_ex(self.__address)\n self.__proto_message = ProtoMessage.connect_message(player_name)\n self.__selector.register(self.__socket, selectors.EVENT_WRITE)\n\n def tick(self):\n \"\"\"Does client work.\"\"\"\n if not self.__selector.get_map():\n logging.error(\"Client ticking but not connected to server\")\n return\n\n events = self.__selector.select(timeout=-1)\n for _, mask in events:\n try:\n self.__process_events(mask)\n except (RuntimeError, ConnectionRefusedError, ConnectionResetError) as e:\n logging.debug(f\"Client disconnected: {e}\")\n self.stop()\n\n def stop(self):\n \"\"\"Stops the client.\"\"\"\n logging.debug(\"Stop client\")\n try:\n self.__selector.unregister(self.__socket)\n except Exception as e:\n logging.debug(f\"__selector.unregister() exception for {self.__address}: {repr(e)}\")\n\n try:\n self.__socket.close()\n except OSError as e:\n logging.debug(f\"__socket.close() exception for {self.__address}: {repr(e)}\")\n finally:\n self.__socket = None\n self.__selector.close()\n\n @property\n def state(self):\n \"\"\"Returns the current state of the client.\"\"\"\n return self.__fsm.state\n\n def command_init(self, from_state, to_state):\n \"\"\"Executes the INIT command from the Server. Returns True if the state transition is successful.\"\"\"\n logging.debug(f\"command_init(): {from_state} -> {to_state}\")\n self.__proto_message = ProtoMessage.ready_message()\n return True\n\n def command_update(self, from_state, to_state):\n \"\"\"Executes the START command from the Server. Returns True if the state transition is successful.\"\"\"\n logging.debug(f\"command_update(): {from_state} -> {to_state}\")\n self.__proto_message = ProtoMessage.input_message([\"FORWARD\", \"LEFT\", \"FIRE\"])\n return True\n\n def command_stop(self, from_state, to_state):\n \"\"\"Executes the STOP command from the Server. Returns True if the state transition is successful.\"\"\"\n logging.debug(f\"command_stop(): {from_state} -> {to_state}\")\n self.stop()\n return True\n\n def __process_events(self, mask):\n \"\"\"Processes events.\"\"\"\n if mask & selectors.EVENT_READ:\n done_reading = self.__reader.read()\n if done_reading:\n self.__process_response(self.__reader.obj)\n self.__reader.reset()\n self.__set_write_mode()\n\n if mask & selectors.EVENT_WRITE:\n assert self.__proto_message.buffer\n self.__writer.set_buffer(self.__proto_message.buffer)\n done_writing = self.__writer.write()\n logging.debug(f\"Sent {self.__proto_message.payload}\")\n\n if done_writing:\n self.__proto_message.reset()\n self.__set_read_mode()\n\n def __process_response(self, dictionary):\n logging.debug(f\"Received response: {dictionary}\")\n try:\n self.__fsm.transition(ClientInput(dictionary[\"message\"]))\n except KeyError as e:\n logging.error(f\"Bad FSM transition data. {repr(e)}\")\n self.__processed_count += 1\n\n def __set_read_mode(self):\n \"\"\"Sets __selector to look for read events.\"\"\"\n self.__selector.modify(self.__socket, selectors.EVENT_READ)\n\n def __set_write_mode(self):\n \"\"\"Sets __selector to look for write events.\"\"\"\n self.__selector.modify(self.__socket, selectors.EVENT_WRITE)\n\n\nif __name__ == \"__main__\":\n import time\n logging.basicConfig(level=logging.DEBUG, format=\"%(levelname)s: %(filename)s:%(lineno)d: %(message)s\")\n\n client = Client((\"localhost\", 54879))\n client.connect(\"Player2\")\n\n done = False\n while not done:\n try:\n client.tick()\n time.sleep(0.02)\n\n if client.state == ClientState.PLAYING:\n client.command_update(ClientState.PLAYING, ClientState.PLAYING)\n\n except (AssertionError, KeyboardInterrupt):\n client.stop()\n done = True\n\n except ValueError:\n done = True\n","sub_path":"src/pygamengn/network/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"159118689","text":"#!/usr/bin/python\n# cdp.py - gather cdp information, change interface descriptions\n#\n# Written by: Brian Franklin (brian.franklin@emc.com)\n#\n# Version 0.1 - Initial Release\n# Version 0.2 - Added error checking, summary_cdp_found list,\n# minor bugs fixed, added error logging\n# Version 0.3 - Don't change if description already present \n#\n################################################################\n\n\nimport paramiko\nimport sys\nimport time\nimport os\nimport os.path\n#import pprint\nimport argparse\nimport logging\nfrom inspect import currentframe, getframeinfo\nfrom colorlog import ColoredFormatter\nfrom contextlib import contextmanager\n@contextmanager\n\n\nclass color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n\n\ndef nonblank_lines(f):\n for l in f:\n line = l.rstrip()\n if line:\n yield line\n\n\ndef write_file(data,path,filename,mode):\n logger = logging.getLogger('CDP')\n try:\n outputFilename = path + \"/\"+ filename\n outfile = open(outputFilename, mode)\n outfile.write(data)\n outfile.close()\n except:\n logger.error(create_logger_message (\"Error writing file: \"+outputFilename))\n\n return\n\n\ndef create_logger_message (error):\n '''\n ### Creates a formatted error message\n '''\n\n# error_msg = \"*** \"+str(error) +\" ***\"\n \n# return error_msg\n return str(error)\n\ndef multi_command(remote_conn, commands, waitHowLong, waitForString):\n \n ### Only errors are returned\n logger = logging.getLogger('CDP')\n logger.debug(create_logger_message (\"Multi_command: \"))\n \n for command in commands:\n (error,output)=send_command(remote_conn,command,waitHowLong,waitForString)\n if error:\n return (True,output)\n return (False,\"\")\n\n\ndef send_command(remote_conn, command, waitHowLong, waitForString):\n '''\n Send command to device\n\n waitHowLong (in seconds)\n\n '''\n logger = logging.getLogger('CDP')\n\n remote_conn.send(command)\n\n command = command.strip(\"\\n\")\n logger.debug(create_logger_message (\"Running (\"+str(command)+\")\"+\"; Waiting for (\"+waitForString+\"); Will wait for (\"+str(waitHowLong)+\") seconds\"))\n\n ### Wait for the command to complete\n timeout = time.time()+waitHowLong\n \n time.sleep(1)\n \n output = \" \"\n remote_conn.settimeout(15)\n\n while waitForString not in output: \n\n try:\n logger.debug(create_logger_message (\"Inside try\"))\n output = remote_conn.recv(50000)\n \n except:\n logger.debug(create_logger_message (\"(\"+waitForString+\") not found\"))\n return (True,\"(\"+waitForString+\") not found\")\n\n logger.debug(create_logger_message (\"Output: \"+str(output)))\n\n\n if \"AAA_AUTHOR_STATUS_METHOD\" in output or \"Permission denied\" in output:\n logger.error(create_logger_message (\"Permissions: Not allowed to execute that command (\"+command+\")\"))\n return (True,\"Permissions: Not allowed to execute that command (\"+command+\")\")\n elif \"Invalid command at\" in output:\n logger.error(create_logger_message (\"Invalid: Not allowed to execute that command (\"+command+\")\"))\n return (True,\"Invalid: Not allowed to execute that command (\"+command+\")\")\n elif time.time() < timeout:\n logger.debug(create_logger_message (\"Checking for timeout \"))\n time.sleep(1)\n else:\n logger.warning(create_logger_message (\"Command timed out waiting for \"+waitForString))\n return (True,\"Command timed out waiting for \"+waitForString)\n logger.debug(create_logger_message (\"Still looking for (\"+waitForString+\")\")) \n\n logger.debug(create_logger_message (\"Command complete. (\"+command+\")\"))\n\n return (False,output)\n\n\ndef establish_connection(ip, username='', password=''):\n '''\n Use Paramiko to establish an SSH channel to the device\n Must return both return_conn_pre and return_conn so that the SSH\n connection is not garbage collected\n '''\n try:\n remote_conn_pre = paramiko.SSHClient()\n remote_conn_pre.set_missing_host_key_policy(\n paramiko.AutoAddPolicy())\n\n try:\n remote_conn_pre.connect(ip, username=username, password=password,\n look_for_keys=False, allow_agent=False)\n except:\n logger.error(create_logger_message (\"SSH Connection failed for \"+ip))\n return (0,0) \n\n remote_conn = remote_conn_pre.invoke_shell()\n except paramiko.AuthenticationException:\n return (0,0)\n\n ### Clear banner and prompt\n output = remote_conn.recv(65535)\n\n return (remote_conn_pre, remote_conn)\n\n\n\ndef main():\n\n\n ### Set all available CLI arguments\n\n parser = argparse.ArgumentParser(description=color.RED+color.BOLD + '*** This is a script to gather CDP information per host and change the interface description (if requested) based on this information ***** Script by Brian Franklin ***'+color.END)\n\n parser.add_argument(\n '-change', \n default=False,\n dest='change',\n action='store_true', \n help='Change descriptions ' + color.BOLD + '(default: %(default)s)' + color.END)\n \n parser.add_argument(\n '-overwrite', \n default=False,\n dest='overwrite',\n action='store_true', \n help='Overwrite descriptions even if they already exist ' + color.BOLD + '(default: %(default)s)' + color.END)\n \n parser.add_argument(\n '-cdpSuffix', \n default='cdpDetailOutput.txt',\n dest='cdpSuffix',\n help='Suffix on \"show cdp neighbor detail\" output file ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-hosts', \n default='hosts.csv',\n dest='hostsFile',\n help='Hosts file name ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-bad', \n default='bad.hosts.csv',\n dest='badHostsFile',\n help='Hosts that have login issues ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-done', \n default='done.hosts.csv',\n dest='doneHostsFile',\n help='Hosts that have finished ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-cdpFound', \n dest='cdpFound',\n help='Filename for parsed list of cdp neighbors found ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-cdpCSV', \n dest='cdpCSV',\n help='Filename for parsed list of cdp neighbors with details ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-outputPath', \n default='/tmp/cdp_output',\n dest='outputPath',\n help='Output path for files ' + color.BOLD + '(default: %(default)s)' + color.END)\n\n parser.add_argument(\n '-l', \n default='INFO', \n dest='logLevel', \n choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], \n help=\"Set the logging level ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL') \" + color.BOLD + \"(default: %(default)s)\" + color.END)\n\n parser.add_argument(\n '-log', \n default='logfile.log', \n dest='logFile', \n help=\"Set the logfile name. Location will be output path.\" + color.BOLD + \"(default: %(default)s)\" + color.END)\n\n\n args = parser.parse_args()\n\n\n #######################################################################################\n ### Create logging setup\n #######################################################################################\n\n ### create logger\n logger = logging.getLogger('CDP')\n\n numLogLevel = getattr(logging,args.logLevel.upper())\n\n if not isinstance(numLogLevel, int):\n raise ValueError(create_logger_message('Invalid log level: '+args.logLevel))\n\n logger.setLevel(numLogLevel)\n\n ### create console handler and set level to debug\n ch = logging.StreamHandler()\n ch.setLevel(numLogLevel)\n\n fl = logging.FileHandler(args.outputPath + \"/\" + args.logFile,\"w\")\n\n ### create formatter\n formatter = ColoredFormatter(\n \" %(log_color)s%(asctime)-22s%(levelname)-8s%(reset)s %(funcName)-15s %(log_color)s%(message)s%(reset)s\",\n datefmt='%m/%d/%Y %H:%M:%S',\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red,bg_white',\n },\n secondary_log_colors={},\n style='%'\n )\n\n ### add formatter to ch\n ch.setFormatter(formatter)\n\n ### add ch to logger\n logger.addHandler(ch)\n\n ### add fl to logger\n logger.addHandler(fl)\n\n logger.debug(create_logger_message(\"Supplied arguments: \"+str(args)))\n\n #######################################################################################\n ### Pull devices and login information from file\n #######################################################################################\n ### Check if hosts file exists and is readable\n if not (os.path.isfile(args.hostsFile) and os.access(args.hostsFile, os.R_OK)):\n \n logger.critical(create_logger_message(\"hostsFile \"+args.hostsFile + \" NOT FOUND!\"))\n exit(1)\n\n credentials = {}\n\n\n #######################################################################################\n ### :START: Loop through hostsFile and gather credentials\n #######################################################################################\n\n logger.info(create_logger_message(\"Reading \"+args.hostsFile))\n with open(args.hostsFile) as f:\n for line in nonblank_lines(f):\n line=line.strip()\n host=line.split(\",\")[0]\n username=line.split(\",\")[1]\n password=line.split(\",\")[2]\n try:\n credentials[host]['username']\n logger.warning(create_logger_message(\"Duplicate host found (\"+host+\") skipping\"))\n continue\n except KeyError:\n logger.debug(create_logger_message(\"Host not duplicate (\"+host+\")\"))\n logger.info(create_logger_message(\"\\tAdding \"+host+\" to credentials list\"))\n pass\n\n credentials[host]={}\n credentials[host]['username'] = username\n credentials[host]['password'] = password\n #######################################################################################\n ### :END: Loop through hostsFile and gather credentials\n #######################################################################################\n\n #######################################################################################\n ### If cdp parsed CSV, add header\n #######################################################################################\n\n if args.cdpCSV:\n\n logger.debug(create_logger_message(\"\\tAdding header to cdpCSV\"))\n write_file(\"localHost,localPort,remoteName,remotePort,remoteMgmt\\n\",args.outputPath + \"/\",args.cdpCSV,'w')\n\n #######################################################################################\n ### List of found cdp neighbors for summary file; Create list \n #######################################################################################\n if args.cdpFound:\n summary_found_cdp = {}\n\n #######################################################################################\n ### :START Loop 1: Loop through all hosts in credentials file\n #######################################################################################\n for hosts in credentials:\n error_msg='' \n \n logger.debug(create_logger_message(\"### :START Loop 1: Loop through all hosts in credentials file\"))\n logger.info(create_logger_message(\"Connecting to \" + hosts))\n\n (remote_conn_pre, remote_conn) = establish_connection(hosts, \n credentials[hosts]['username'], credentials[hosts]['password'])\n\n try: \n\n #######################################################################################\n ### :START: Try section:\n #######################################################################################\n logger.debug(create_logger_message(\"### :START: Try Section:\"))\n #######################################################################################\n ### :START: If remote connection open \n #######################################################################################\n if remote_conn_pre != 0:\n logger.debug(create_logger_message(\"### :START: If remote connection open \"))\n\n ### Get switch name\n logger.debug(create_logger_message(\"Getting switch hostname from \" + hosts)) \n\n (error,output)=send_command(remote_conn,\"sh run | inc hostname|switchname\\n\",10,\"hostname \")\n if error:\n logger.error(create_logger_message(\"sh run | inc hostname|switchname\"))\n error_msg = output\n raise \n\n sp=output.split(\"\\n\")\n\n\n for i in range(len(sp)):\n sp[i] = sp[i].strip()\n if 'hostname ' in sp[i]:\n switchname = sp[i].lstrip('hostname ').rstrip()\n if 'switchname ' in sp[i]:\n switchname = sp[i].lstrip('switchname ').rstrip()\n\n if switchname == '':\n logger.error(create_logger_message(\"hostname/switchname not found\"))\n error_msg = \"hostname/switchname not found\"\n raise\n\n ### Turn off --- MORE --- \n logger.debug(create_logger_message(\"Turn off --- MORE ---\")) \n\n (trash1,trash2) = send_command(remote_conn,\"\\n\",5,switchname)\n\n (error,output) = send_command(remote_conn,\"terminal length 0\\n\",5,switchname)\n if error:\n logger.error(create_logger_message(\"terminal length 0\"))\n error_msg = output \n raise\n \n logger.info(create_logger_message(\"\\tCollecting 'show cdp neighbor detail' output....\")) \n\n (trash1,trash2) = send_command(remote_conn,\"\\n\",5,switchname)\n\n\n (error,output) = send_command(remote_conn,\"show cdp neighbor detail\\n\",180,switchname+\"#\")\n if error:\n logger.error(create_logger_message(\"show cdp neighbor detail\"))\n error_msg = output\n raise \n \n logger.debug(create_logger_message(\"Writing show cdp neighbor detail (\"+hosts+\")\"))\n\n write_file(output,args.outputPath + \"/\",hosts + \"-\" + args.cdpSuffix,'w')\n\n\n #######################################################################################\n ### :START: Parse SHOW CDP NEIGHBOR DETAIL \n #######################################################################################\n if args.change or args.cdpCSV or args.cdpFound:\n logger.info(create_logger_message(\"\\tParsing 'show cdp neighbor detail' output....\")) \n\n logger.debug(create_logger_message(\"### :START: Parse SHOW CDP NEIGHBOR DETAIL \"))\n sp = output.split(\"\\n\")\n\n remoteName = ''\n localPort = ''\n network_devices = {}\n commandList = []\n\n #######################################################################################\n ### :START: Parse through cdp output \n #######################################################################################\n logger.debug(create_logger_message(\"### :START: Parse through cdp output \"))\n for i in range(len(sp)):\n\n sp[i] = sp[i].strip()\n \n logger.debug(create_logger_message(\"\\tparse line = \" + sp[i]))\n\n ### Reset at divider \n if '----------------' in sp[i]:\n if remoteName and localPort:\n\n logger.debug(create_logger_message(\"Creating CDP list\"))\n\n network_devices[localPort] = {}\n network_devices[localPort]['localPort'] = localPort\n network_devices[localPort]['remoteName'] = remoteName\n network_devices[localPort]['remotePort'] = remotePort\n network_devices[localPort]['remoteMgmt'] = remoteMgmt\n \n ### If wanting list of all cdp found devices\n if args.cdpFound:\n summary_found_cdp[remoteName]['mgmt'] = remoteMgmt\n\n\n ### If cdp parsed CSV \n if args.cdpCSV:\n \n logger.debug(create_logger_message(\"\\tAdding \" +hosts+\",\"+localPort+\",\"+remoteName+\",\"+remotePort+\",\"+remoteMgmt+\" to \"+args.cdpCSV))\n\n write_file(hosts+\",\"+localPort+\",\"+remoteName+\",\"+remotePort+\",\"+remoteMgmt+\"\\n\",args.outputPath + \"/\",args.cdpCSV,'a')\n\n ### If change descriptions\n if args.change:\n (error,desc) = send_command(remote_conn,\"sh run interface \"+ network_devices[localPort]['localPort'] +\" | inc description\\n\",5,switchname)\n\n logger.debug(create_logger_message(str(error)+\" \"+desc))\n\n if error or args.overwrite:\n ### Previous description not found\n logger.info(create_logger_message(\"\\tAdding description for \"+hosts+\" interface \"+network_devices[localPort]['localPort'] + \" to command list\"))\n logger.debug(create_logger_message(\"Creating command list\"))\n \n\n description = network_devices[localPort]['localPort'] + \" <-> \" + network_devices[localPort]['remoteName'] + \" \" + network_devices[localPort]['remotePort']\n\n logger.debug(create_logger_message(\"interface \" + network_devices[localPort]['localPort'] + \"\\n\" +\n \"description \" + description + \"\\n\"))\n\n commandList.append(\"interface \" + network_devices[localPort]['localPort'] + \"\\n\")\n commandList.append(\"description \" + description + \"\\n\")\n else:\n logger.info(create_logger_message(\"\\tDescription for \"+hosts+\" interface \"+network_devices[localPort]['localPort'] + \" will not be modified\"))\n\n \n ### Reset cdp variables\n localPort = ''\n remoteName = ''\n remotePort = ''\n remotePlatform = ''\n remoteMgmt = ''\n\n ### Process remote hostname \n elif 'Device ID:' in sp[i]:\n\n remoteName = sp[i].split('Device ID:')[1]\n remoteName = remoteName.split('(')[0]\n \n if args.cdpFound:\n try:\n summary_found_cdp[remoteName]['mgmt']\n logger.debug(create_logger_message(\"checking if \"+remoteName+\" already in summary list\"))\n continue\n except KeyError:\n logger.debug(create_logger_message(remoteName+\" NOT already in summary list. Adding\"))\n summary_found_cdp[remoteName] = {}\n pass\n\n logger.debug(create_logger_message(\"remoteName = \" + remoteName))\n\n\n ### Process in/out ports\n elif 'Interface: ' in sp[i]:\n localPort = sp[i].lstrip('Interface: ').split(',')[0]\n remotePort = sp[i].split('port): ')[1] \n \n logger.debug(create_logger_message(\"localPort = \" + localPort + \"; remotePort = \" + remotePort))\n\n\n ### Process MGMT address\n elif 'Mgmt' in sp[i]:\n \n remoteMgmt = sp[i+1].lstrip('IPv4 Address: ').rstrip()\n\n logger.debug(create_logger_message(\"mgmt ip = \" + remoteMgmt))\n\n logger.debug(create_logger_message(\"### :END: Parse through cdp output\"))\n #######################################################################################\n ### :END: Parse through cdp output \n #######################################################################################\n\n #######################################################################################\n ### :START: Grab last entry if there\n #######################################################################################\n\n if remoteName and localPort:\n logger.debug(create_logger_message(\"### :START: Grab last entry if there\"))\n\n logger.debug(create_logger_message(\"\\tAdding last entry \" + remoteName + \" \" +localPort))\n\n network_devices[localPort] = {}\n network_devices[localPort]['remoteName'] = remoteName\n network_devices[localPort]['localPort'] = localPort\n network_devices[localPort]['remotePort'] = remotePort\n network_devices[localPort]['remoteMgmt'] = remoteMgmt\n\n ### If wanting list of all cdp found devices\n if args.cdpFound:\n summary_found_cdp[remoteName]['mgmt'] = remoteMgmt\n\n ### If cdp parsed CSV\n if args.cdpCSV:\n\n logger.debug(create_logger_message(\"Adding \" +hosts+\",\"+localPort+\",\"+remoteName+\",\"+remotePort+\",\"+remoteMgmt+\" to cdpCSV\"))\n write_file(hosts+\",\"+localPort+\",\"+remoteName+\",\"+remotePort+\",\"+remoteMgmt+\"\\n\",args.outputPath + \"/\",args.cdpCSV,'a')\n\n ### If change descriptions\n if args.change:\n\n (error,desc) = send_command(remote_conn,\"sh run interface \"+ network_devices[localPort]['localPort'] +\" | inc description\\n\",5,\"description \")\n\n logger.debug(create_logger_message(str(error)+desc))\n\n if error or args.overwrite:\n ### Previous description not found\n logger.info(create_logger_message(\"\\tAdding description for \"+hosts+\" interface \"+network_devices[localPort]['localPort'] + \" to command list\"))\n logger.debug(create_logger_message(\"Creating command list\"))\n \n\n description = network_devices[localPort]['localPort'] + \" <-> \" + network_devices[localPort]['remoteName'] + \" \" + network_devices[localPort]['remotePort']\n\n logger.debug(create_logger_message(\"interface \" + network_devices[localPort]['localPort'] + \"\\n\" +\n \"description \" + description + \"\\n\"))\n\n commandList.append(\"interface \" + network_devices[localPort]['localPort'] + \"\\n\")\n commandList.append(\"description \" + description + \"\\n\")\n\n else:\n logger.info(create_logger_message(\"\\tDescription for \"+hosts+\" interface \"+network_devices[localPort]['localPort'] + \" will not be modified\"))\n logger.debug(create_logger_message(\"### :END: Grab last entry if there\"))\n\n #######################################################################################\n ### :END: Grab last entry if there\n #######################################################################################\n logger.debug(create_logger_message(\"### :END: Parse SHOW CDP NEIGHBOR DETAIL\"))\n #######################################################################################\n ### :END: Parse SHOW CDP NEIGHBOR DETAIL \n #######################################################################################\n\n\n logger.debug(create_logger_message(commandList))\n\n if args.change and commandList:\n ### Make changes and save\n\n commandList.insert(0,\"configure terminal\\n\")\n commandList.append(\"end\\n\")\n\n logger.info(create_logger_message(\"\\tChanging configuration... PLEASE WAIT...\"))\n\n (error,output) = multi_command(remote_conn,commandList,10,switchname)\n if error:\n logger.error(create_logger_message(\"Error: \"+commandList))\n error_msg = output\n raise \n\n logger.info(create_logger_message(\"\\tSaving configuration... PLEASE WAIT...\"))\n logger.debug(create_logger_message(\"Saving config on \"+hosts))\n\n (error,output) = send_command(remote_conn,\"copy run start\\n\",180,switchname)\n if error:\n logger.error(create_logger_message(\"copy run start\"))\n error_msg = output\n raise\n \n logger.debug(create_logger_message(\"FINISHED changing descriptions on \"+hosts))\n logger.debug(create_logger_message(\"### :END: Grab last entry if there\"))\n\n ### Save done hosts\n logger.info(create_logger_message(\"\\t\"+hosts+\" completed.\"))\n write_file(hosts+\",\"+credentials[hosts]['username']+\",\"+credentials[hosts]['password']+\"\\n\",args.outputPath,args.doneHostsFile,'a')\n \n logger.debug(create_logger_message(\"### :END: If remote connection open\"))\n #######################################################################################\n ### :END: If remote connection open \n #######################################################################################\n\n else:\n logger.error(create_logger_message(\"end of try section for remote_conn_pre != 0. Should I be here?\"))\n error_msg = \"end of try section for remote_conn_pre != 0. Should I be here?\" \n raise \n\n logger.debug(create_logger_message(\"### :END: Try Section:\"))\n\n except:\n #######################################################################################\n ### :START: EXCEPT Try section:\n #######################################################################################\n\n ### Can't login to host\n logger.error(create_logger_message(\"### :Except Section:\"))\n logger.error(create_logger_message(\"### \"+ str(sys.exc_info())))\n logger.info(create_logger_message(\"Error on \"+hosts+\". Adding to \"+args.badHostsFile))\n write_file(hosts+\",\"+credentials[hosts]['username']+\",\"+credentials[hosts]['password']+\",\"+error_msg,args.outputPath,args.badHostsFile,\"a\")\n error_msg='' \n\n finally:\n ### Close ssh connection\n logger.debug(create_logger_message(\"### :Finally Section:\"))\n if remote_conn_pre != 0:\n logger.info(create_logger_message(\"\\tClosing ssh connection\"))\n remote_conn_pre.close()\n\n logger.debug(create_logger_message(\"### :END Loop 1: Loop through all hosts in credentials file\"))\n #######################################################################################\n ### :END Loop 1: Loop through all hosts in credentials file\n #######################################################################################\n \n\n if args.cdpFound:\n logger.debug(create_logger_message(\"Creating \"+args.cdpFound))\n logger.debug(create_logger_message(\"List contains: \"+str(summary_found_cdp)))\n\n ### Write cdp found file\n for found in summary_found_cdp:\n logger.debug(create_logger_message(\"Adding to \"+args.cdpFound+\" \"+found))\n write_file(found+\",\"+summary_found_cdp[found]['mgmt']+\"\\n\",args.outputPath,args.cdpFound,'a') \n\n logger.info(create_logger_message(\"DONE with all hosts!\"))\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"cdp.py","file_name":"cdp.py","file_ext":"py","file_size_in_byte":30143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"553657415","text":"#!/usr/bin/env python\n\nfrom copy import deepcopy \nfrom get import Get\nfrom lxml import etree\nfrom post import Post\nimport multiprocessing as mp\nimport os\nimport re\nimport sys\nimport xml.dom.minidom\n\n\nplatform = etree.XPath(\"//Resource[@typeId='1']\")\nservers = etree.XPath(\"//*/Resource[@typeId='2']\")\nservices = etree.XPath(\"//*/Resource[@typeId='3']\")\nresources = etree.XPath(\"//*/Resource\")\nalertdefs = etree.XPath(\"//*/AlertDefinition/Resource[@id=$resourceId]\")\nfindAlertByName = etree.XPath(\"//*/AlertDefinition[@name=$name]\")\nfindResourcebyNameTypeId = etree.XPath(\"//*/Resource[@name=$name][@typeId=$typeId]\")\nfindResourcebyNameContainsTypeId = etree.XPath(\"//*/Resource[contains(@name,$name)][@typeId=$typeId]\")\n#findResourcebyPrototypeTypeId = etree.XPath(\"//*/Resource[@typeId=$typeId]/ResourcePrototype[@prototype=$prototype]\")\n\n\ndef all_alertdefs(resourceroot, alertroot):\n\t\"\"\"docstring for all_alertdefs\"\"\"\n\tfor resource in resources(resourceroot):\n\t\tfor alertdef in alertdefs(alertroot, resourceId = resource.attrib['id']):\n\t\t\tyield alertdef.getparent()\n\t\n\ndef server_alertdefs(resourceroot, alertroot):\n\t\"\"\"docstring for resourceroot\"\"\"\n\tfor server in servers(resourceroot):\n\t\tfor alertdef in alertdefs(alertroot, resourceId = server.attrib['id']):\n\t\t\tyield alertdef.getparent()\n\ndef platform_alertdefs(resourceroot, alertroot):\n\t\"\"\"docstring for platform_alertdefs\"\"\"\n\tfor p in platform(resourceroot):\n\t\tfor alertdef in alertdefs(alertroot, resourceId = p.attrib['id']):\n\t\t\tyield alertdef.getparent()\n\n\ndef service_alertdefs(resourceroot, alertroot):\n\t\"\"\"docstring for resource_and_alerts\"\"\"\n\tfor service in services(resourceroot):\n\t\tfor alertdef in alertdefs(alertroot, resourceId = service.attrib['id']):\n\t\t\tyield alertdef.getparent()\n\ndef foundAlertDef(alertdef, alertroot, sourceplat, targetplat):\n\t\"\"\"docstring for foundAlertDef\"\"\"\n\tif len(findAlertByName(alertroot, \\\n\t\t\tname = alertdef.attrib['name'].replace(sourceplat, targetplat))) >=1 :\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef foundResource(resource, resourceroot, sourceplat, targetplat):\n\t\"\"\"docstring for foundResource\"\"\"\n\tif len(findResourcebyNameTypeId(resourceroot, \\\n\t\t\tname = resource.attrib['name'].replace(sourceplat, targetplat), \\\n\t\t\ttypeId = resource.attrib['typeId'])) >=1 :\n\t\treturn True\n\telse:\n\t\treturn False\n\n'''\n# SOME USE CASES AS SHOWN BELOW\nif __name__ == '__main__':\n\t(sourceplat, targetplat) = ('lnx20776.csxt.csx.com', 'lnx20777.csxt.csx.com')\n\n\twith open(sys.argv[1]) as f:\n\t\tsource_resource = etree.fromstring(f.read())\n\n\twith open(sys.argv[2]) as f:\n\t\tsource_alertdef = etree.fromstring(f.read())\n\t\n\twith open(sys.argv[3]) as f:\n\t\ttarget_resource = etree.fromstring(f.read())\n\n\twith open(sys.argv[4]) as f:\n\t\ttargetalertdef = etree.fromstring(f.read())\n\t\n\tprint \n\tprint \"ALL RESOURCES .. \" \n\tfor r in resources(source_resource):\n\t\tif foundResource(r, source_resource, sourceplat, targetplat):\n\t\t\tprint \"Skipping resource %s .. \" % r.attrib['name']\n\t\telse:\n\t\t\tprint \"Adding resource %s ..\" % r.attrib['name']\n\n\tprint \"ALL ALERTS .. \" \n\tfor a in all_alertdefs(source_resource, source_alertdef):\n\t\tif foundAlertDef(a, targetalertdef, sourceplat, targetplat):\n\t\t\tprint \"Skipping source_alertdef %s ..\" % a.attrib['name']\n\tsys.exit(0)\n\n\tprint \"Printing RESOURCE AND ITS CORRESPONDING ALERTS!!\"\n\tfor p in platform(source_resource):\n\t\tprint p.attrib['name']\n\t\tfor a in alertdefs(source_alertdef, source_resourceId=p.attrib['id']):\n\t\t\tprint \"\\t\", a.getparent().attrib['name']\n\t\tprint \n\n\tfor sr in servers(source_resource):\n\t\tprint sr.attrib['name']\n\t\tfor a in alertdefs(source_alertdef, source_resourceId=sr.attrib['id']):\n\t\t\tprint a.getparent().attrib['name']\n\t\tprint \n\t\n\tfor a in all_alertdefs(source_resource, source_alertdef):\n\t\tprint a\n\t\tif foundAlertDef(a, source_alertdef, sourceplat, targetplat):\n\t\t\tprint \"YES!\"\n\tsys.exit(0)\n\n\tprint \n\tprint \"PLATFORM LEVEL ALERTS .. \" \n\tfor a in platform_alertdefs(source_resource, source_alertdef):\n\t\tprint a.attrib['name']\n\tsys.exit(0)\n\t\n\tprint \"SERVER LEVEL ALERTS .. \" \n\tfor a in server_alertdefs(source_resource, source_alertdef):\n\t\tprint a\n\n\tprint \"SERVICE LEVEL ALERTS .. \" \n\tfor a in service_alertdefs(source_resource, source_alertdef):\n\t\tprint a\n\tsys.exit(0)\n'''\n","sub_path":"webapps/hyperic_GUI/rtputils/alertmigrator/libxml.py","file_name":"libxml.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"572665868","text":"from collections import deque\ndef solution(tickets):\n tickets.sort(key = lambda x:x[1])\n #print(tickets)\n start = [i for i in range(len(tickets)) if tickets[i][0] == \"ICN\"]\n #print(start)\n answer = []\n for s in start:\n q = deque([])\n q.append([s])\n if not answer:\n while q:\n #path 는 숫자로 구성\n path = q.popleft()\n if len(path) == len(tickets):\n answer = [tickets[x][0] for x in path] + [tickets[path[-1]][1]]\n break\n for i in range(len(tickets)):\n if i not in path and tickets[path[-1]][1] == tickets[i][0]:\n # print(i)\n q.append(path+[i])\n # answer = []\n return answer","sub_path":"Programmers/DFS_BFS/43164.py","file_name":"43164.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"622650775","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nRungekutta = np.loadtxt('Rungekutta.dat')\n\nplt.figure(figsize=(12,4))\n\ntime = Rungekutta[:,0]\nx = Rungekutta[:,1]\nv = Rungekutta[:,2]\n\nplt.subplot(1,2,1)\nplt.plot(time,x,c='g')\nplt.grid()\nplt.xlabel('time(s)')\nplt.ylabel('x(m)')\nplt.title(\"Harmonic oscillator, Position\")\n\nplt.subplot(1,2,2)\nplt.plot(x,v,c='g')\nplt.grid()\nplt.xlabel('x(m)')\nplt.ylabel('v(m/s)')\nplt.title(\"Harmonic oscillator, Velocity\")\n\nplt.savefig(\"Rungekutta.png\")","sub_path":"Rungekutta.py","file_name":"Rungekutta.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"407591125","text":"# Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\n# A shift on s consists of moving the leftmost character of s to the rightmost position.\n\n# For instance, if s = 'abcde', then it will be 'bcdea' after one shift.\n\nclass rotate_string:\n def sub_string_position(self, s1, s2):\n if len(s1) != len(s2):\n return len(s1)\n for i in range(len(s1)):\n if s1[i:] in s2:\n print(s1[i:])\n return i\n return i\n\n def is_rotate_string(self, s1, s2):\n p = self.sub_string_position(s1, s2)\n if p == len(s1):\n return False\n rss1 = s1[0:p]\n rss2 = s1[p:]\n s3 =rss1[::-1] + rss2[::-1]\n print(s3[::-1], s2)\n if s3[::-1] == s2:\n return True\n return False\n\ns = 'abcde'\ngoal = 'bcdea'\nrs = rotate_string()\nprint(rs.is_rotate_string(s, goal))","sub_path":"2021/796_Rotate_String.py","file_name":"796_Rotate_String.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"356236144","text":"from flask import *\nimport json\nimport jwt\nimport datetime\nfrom flaskext.mysql import MySQL\n\nADMIN_ROLE = 1\nUSER_ROLE = 0\nFAIL_MESSAGE = \"NO\"\n\nsetrole = ['user','admin']\n\napp = Flask(__name__)\nmysql = MySQL()\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_PASSWORD'] = 'root'\napp.config['MYSQL_DATABASE_DB'] = 'funbid'\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\nmysql.init_app(app)\n\ndbconn = mysql.connect()\ndb = dbconn.cursor()\n\nJWT_SECRET = '99'\n\ndefault_bidcount = 10\n\ndef encode(account):\n\tiat = datetime.datetime.utcnow()\n\treturn jwt.encode({\n\t\t#'sub': account['id'],\n\t\t'id': str(account['id']),\n\t\t'role': str(account['role']),\n\t\t'iat': iat,\n\t\t'exp': iat + datetime.timedelta(days=365)\n\t\t}, JWT_SECRET).decode('utf-8')\n\ndef decode(access_token):\n\ttry:\n\t\ttoken = jwt.decode(access_token, JWT_SECRET, leeway=10)\n\texcept jwt.InvalidTokenError:\n\t\treturn None\n\treturn token\n\ndef token_valid():\n\tif request.headers.get('Authorization'):\n\t\tjwt_token = decode(request.headers.get('Authorization'))\n\t\tif jwt_token == None:\n\t\t\treturn None\n\t\t'''\n\t\tt = datetime.datetime.utcnow()\n\t\tiat = datetime.datetime.fromtimestamp(jwt_token.get('iat'))\n\t\texp = datetime.datetime.fromtimestamp(jwt_token.get('exp'))\n\t\tif (t < iat) or (t > exp):\n\t\t\treturn None\n\t\t'''\n\t\treturn jwt_token\n\treturn None\n\ndef login():\n\tif (request.values.get('loginusername')) and (request.values.get('loginpassword')):\n\t\tusername = request.values.get('loginusername')\n\t\tpassword = request.values.get('loginpassword')\n\t\tdb.execute(\"SELECT id,role FROM funbid.user WHERE username='\"+username+\"' AND password='\"+password+\"' AND active=1\")\n\t\tdata = db.fetchone()\n\t\tif data == None:\n\t\t\treturn None\n\t\ttoken = encode({'id':data[0],'role':data[1]})\n\t\treturn token\n\treturn None\n\ndef authorcheck():\n\tt = token_valid()\n\tif t != None:\n\t\treturn t\n\tt = login()\n\tif t != None:\n\t\treturn decode(t)\n\treturn None\n\ndef checkrole(user):\n\t# return the role of userid in db: admin, tutor or student\n\tif user == None:\n\t\treturn None\n\tif 'role' in user.keys():\n\t\troleid = int(user['role'])\n\t\treturn setrole[roleid]\n\tif 'id' in user.keys():\n\t\tuserid = str(user['id'])\n\t\tdb.execute('SELECT role FROM aloha.account WHERE id = '+userid)\n\t\tdata = db.fetchone()\n\t\tif data == None:\n\t\t\treturn None\n\t\treturn setrole[data[0]]\n\treturn None\n\ndef valid_name(name):\n\tif name == None:\n\t\treturn None\n\tif (\"'\" in name) or ('\"' in name) or ('\\\\' in name):\n\t\treturn None\n\tif (len(name) < 3) or (len(name) > 50):\n\t\treturn None\n\treturn name\n\ndef valid_email(email):\n\tif email == None:\n\t\treturn None\n\tif (\"'\" in email) or ('\"' in email) or ('\\\\' in email):\n\t\treturn None\n\tif (len(email) < 3) or (len(email) > 255):\n\t\treturn None\n\t# check for duplicate email\n\tcmd = \"SELECT DISTINCT email FROM aloha.account\"\n\tdb.execute(cmd)\n\twhile (99):\n\t\temailcheck = db.fetchone()\n\t\tif emailcheck == None:\n\t\t\tbreak\n\t\tif emailcheck[0] == email:\n\t\t\treturn None\n\treturn email\n\ndef valid_limit(limit):\n\tif limit == None:\n\t\treturn None\n\tfor c in limit:\n\t\tif (ord(c) < ord('0')) or (ord(c) > ord('9')):\n\t\t\treturn None\n\tif (int(c) <= 0) or (int(c) > 15):\n\t\treturn None\n\treturn limit\n\ndef valid_id(id_):\n\tif id_ == None:\n\t\treturn None\n\tfor c in id_:\n\t\tif (ord(c) < ord('0')) or (ord(c) > ord('9')):\n\t\t\treturn None\n\treturn id_\n\ndef valid_number(number_):\n\tif number_ == None:\n\t\treturn None\n\tfor c in number_:\n\t\tif (ord(c) < ord('0')) or (ord(c) > ord('9')):\n\t\t\treturn None\n\treturn number_\n\ndef valid_password(password):\n\tif password == None:\n\t\treturn None\n\tif (\"'\" in password) or ('\"' in password) or ('\\\\' in password):\n\t\treturn None\n\tif (len(password) < 5) or (len(password) > 10):\n\t\treturn None\n\tif ' ' in password:\n\t\treturn None\n\tcheck = 0\n\tfor c in password:\n\t\tif (ord(c) >= ord('0')) and (ord(c) <= ord('9')):\n\t\t\tcheck = 1\n\t\t\tbreak\n\tif check:\n\t\treturn password\n\treturn None\n\n@app.route('/user-login', methods=['POST'])\ndef user_login():\n\ttoken = login()\n\tif token != None:\n\t\tuser = decode(token)\n\t\tif user == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tif 'role' in user.keys():\n\t\t\troleid = int(user['role'])\n\t\t\treturn token\n\treturn FAIL_MESSAGE\n\n@app.route('/admin-login', methods=['POST'])\ndef admin_login():\n\ttoken = login()\n\tif token != None:\n\t\tuser = decode(t)\n\t\tif user == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tif 'role' in user.keys():\n\t\t\troleid = int(user['role'])\n\t\t\tif setrole[roleid] == 'admin':\n\t\t\t\treturn token\n\treturn FAIL_MESSAGE\n\n@app.route('/upload-new-item', methods=['POST'])\ndef upload_new_item():\n\tauthor = authorcheck()\n\tuserid = str(author['id'])\n\trole = checkrole(author)\n\tif (role == 'admin') or (role == 'user'):\n\t\t#Name, image, category, init-price, create-date, start-date, end-date\n\t\tname = request.values.get('name')\n\t\timage = request.values.get('image')\n\t\tcategory = request.values.get('category')\n\t\tinitprice = request.values.get('initprice')\n\t\tcreatedate = str(datetime.datetime.now())\n\t\tstartdate = request.values.get('startdate')\n\t\tenddate = request.values.get('enddate')\n\t\tif (True):\n\t\t\t# add to db\n\t\t\tcmd = \"INSERT INTO funbid.item (name,sellerid,image,category,initprice,createdate,startdate,enddate,iswinner,currentprice,currentwinner,active) VALUES ('\"+name+\"',\"+userid+\",'\"+image+\"','\"+category+\"',\"+initprice+\",'\"+createdate+\"','\"+startdate+\"','\"+enddate+\"',0,\"+initprice+\",-1,1)\"\n\t\t\tprint(cmd)\n\t\t\tdb.execute(cmd)\n\t\t\tdbconn.commit()\n\t\t\titem_id = dbconn.insert_id()\n\t\t\treturn str(item_id)\n\treturn FAIL_MESSAGE\n\n@app.route('/register', methods=['POST'])\ndef register():\n\tusername = request.values.get('username')\n\tpassword = request.values.get('password')\n\tcreatedate = str(datetime.datetime.now())\n\tfullname = request.values.get('fullname')\n\tif (fullname == None):\n\t\tfullname = \"\"\n\taddress = request.values.get('address')\n\tif (address == None):\n\t\taddress = \"\"\n\timage = request.values.get('image')\n\tif (image == None):\n\t\timage = \"\"\n\trole = request.values.get('role')\n\tcmd = \"SELECT id FROM funbid.user WHERE username='\"+username+\"'\"\n\tdb.execute(cmd)\n\ttemp = db.fetchone()\n\tif (temp == None):\n\t\t# add to db\n\t\tcmd = \"INSERT INTO funbid.user (username,password,createdate,fullname,address,image,bidcount,active,role) values ('\"+username+\"','\"+password+\"','\"+createdate+\"','\"+fullname+\"','\"+address+\"','\"+image+\"',\"+str(default_bidcount)+\",1,\"+str(role)+\")\"\n\t\tdb.execute(cmd)\n\t\tdbconn.commit()\n\t\tuser_id = dbconn.insert_id()\n\t\treturn str(user_id)\n\treturn FAIL_MESSAGE\n\n@app.route('/get-item-list-id', methods=['GET','POST'])\ndef get_item_list_id():\n\tif (True):\n\t\tcmd = \"SELECT id FROM funbid.item ORDER BY createdate DESC LIMIT 20\"\n\t\tdb.execute(cmd)\n\t\tres = []\n\t\twhile (99):\n\t\t\ttemp = db.fetchone()\n\t\t\tif temp == None:\n\t\t\t\tbreak\n\t\t\tres.append(temp[0])\n\t\treturn json.dumps(res)\n\treturn FAIL_MESSAGE\n\n@app.route('/get-item-detail', methods=['POST'])\ndef get_item_detail():\n\titemid = request.values.get('itemid')\n\tif (valid_id(itemid)):\n\t\tcmd = \"SELECT name,sellerid,image,category,initprice,createdate,startdate,enddate,iswinner,currentprice,currentwinner FROM funbid.item WHERE id = \"+itemid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tres = {'name':temp[0],'sellerid':temp[1],'image':temp[2],'category':temp[3],'initprice':temp[4],'createdate':str(temp[5]),'startdate':str(temp[6]),'enddate':str(temp[7]),'iswinner':temp[8],'currentprice':temp[9],'currentwinner':temp[10]}\n\t\treturn json.dumps(res)\n\treturn FAIL_MESSAGE\n\n@app.route('/get-user-detail', methods=['POST'])\ndef get_user_detail():\n\tuserid = request.values.get('userid')\n\tif (valid_id(userid)):\n\t\tcmd = \"SELECT username,createdate,fullname,address,image,bidcount,password,role FROM funbid.user WHERE id = \"+userid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tres = {'username':temp[0],'createdate':str(temp[1]),'fullname':temp[2],'address':temp[3],'image':temp[4],'bidcount':temp[5],'password':temp[6],'role':temp[7]}\n\t\treturn json.dumps(res)\n\treturn FAIL_MESSAGE\n\n@app.route('/bid', methods=['POST'])\ndef bid():\n\tauthor = authorcheck()\n\tuserid = str(author['id'])\n\trole = checkrole(author)\n\tif (role == 'admin') or (role == 'user'):\n\t\titemid = request.values.get('itemid')\n\t\tbidprice = request.values.get('bidprice')\n\t\tuserbidcount = 0\n\t\tcmd = \"SELECT bidcount FROM funbid.user WHERE id = \"+userid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tuserbidcount = temp[0]\n\t\tif userbidcount <= 0:\n\t\t\treturn FAIL_MESSAGE\n\t\tcmd = \"SELECT startdate,enddate,currentprice FROM funbid.item WHERE id = \"+itemid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tstartdate = temp[0]\n\t\tenddate = temp[1]\n\t\tcurrentprice = temp[2]\n\t\ttimenow = datetime.datetime.now()\n\t\tif (timenow < startdate) or (timenow > enddate) or (int(bidprice) <= currentprice):\n\t\t\treturn FAIL_MESSAGE\n\t\tcmd = \"INSERT INTO funbid.auction (userid,itemid,bidprice,time) VALUES (\"+userid+\",\"+itemid+\",\"+bidprice+\",'\"+str(timenow)+\"')\"\n\t\tdb.execute(cmd)\n\t\tcmd = \"UPDATE funbid.item SET currentwinner = \"+userid+\", currentprice = \"+bidprice+\" WHERE id = \"+itemid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\tcmd = \"UPDATE funbid.user SET bidcount = \"+str(userbidcount-1)+\" WHERE id = \"+userid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\tdbconn.commit()\n\t\treturn \"OK\"\n\treturn FAIL_MESSAGE\n\n@app.route('/search-item', methods=['POST'])\ndef seach_item():\n\titemname = request.values.get('itemname')\n\tnumber = request.values.get('number')\n\tif (valid_name(itemname)) and (valid_number(number)):\n\t\tcmd = \"SELECT name,sellerid,image,category,initprice,createdate,startdate,enddate,iswinner,currentprice,currentwinner FROM funbid.item WHERE name like '%\"+itemname+\"%' AND active = 1 LIMIT \"+number\n\t\tdb.execute(cmd)\n\t\titem_list = []\n\t\twhile (99):\n\t\t\ttemp = db.fetchone()\n\t\t\tif temp == None:\n\t\t\t\tbreak\n\t\t\titem_list.append({'name':temp[0],'sellerid':temp[1],'image':temp[2],'category':temp[3],'initprice':temp[4],'createdate':str(temp[5]),'startdate':str(temp[6]),'enddate':str(temp[7]),'iswinner':temp[8],'currentprice':temp[9],'currentwinner':temp[10]})\n\t\treturn json.dumps(item_list)\n\treturn FAIL_MESSAGE\n\n@app.route('/search-user', methods=['POST'])\ndef seach_user():\n\tusername = request.values.get('username')\n\tnumber = request.values.get('number')\n\tif (valid_name(username)) and (valid_number(number)):\n\t\tcmd = \"SELECT username,createdate,fullname,address,image,bidcount,role FROM funbid.user WHERE ((username like '%\"+username+\"%') or (fullname like '%\"+username+\"%')) and active=1 LIMIT \"+number\n\t\tdb.execute(cmd)\n\t\titem_list = []\n\t\twhile (99):\n\t\t\ttemp = db.fetchone()\n\t\t\tif temp == None:\n\t\t\t\tbreak\n\t\t\titem_list.append({'username':temp[0],'createdate':str(temp[1]),'fullname':temp[2],'address':temp[3],'image':temp[4],'bidcount':temp[5],'role':temp[6]})\n\t\treturn json.dumps(item_list)\n\treturn FAIL_MESSAGE\n\n@app.route('/delete-user', methods=['POST'])\ndef delete_user():\n\tauthor = authorcheck()\n\tuserid = str(author['id'])\n\trole = checkrole(author)\n\tif (role == 'admin'):\n\t\tuserid = request.values.get('userid')\n\t\tcmd = \"SELECT id FROM funbid.user WHERE id = \"+userid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tcmd = \"UPDATE funbid.user SET active = 0 WHERE id = \"+userid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\tdbconn.commit()\n\t\treturn \"OK\"\n\treturn FAIL_MESSAGE\n\n@app.route('/delete-item', methods=['POST'])\ndef delete_item():\n\tauthor = authorcheck()\n\tuserid = str(author['id'])\n\trole = checkrole(author)\n\tif (role == 'admin'):\n\t\titemid = request.values.get('itemid')\n\t\tcmd = \"SELECT id FROM funbid.item WHERE id = \"+itemid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\ttemp = db.fetchone()\n\t\tif temp == None:\n\t\t\treturn FAIL_MESSAGE\n\t\tcmd = \"UPDATE funbid.item SET active = 0 WHERE id = \"+itemid+\" AND active = 1\"\n\t\tdb.execute(cmd)\n\t\tdbconn.commit()\n\t\treturn \"OK\"\n\treturn FAIL_MESSAGE\n\n#------------------------------------------------------------------------------\n\n@app.route('/', methods=['GET','POST'])\ndef index():\n\treturn \"Yes\"\n\ndef init_db():\n\t#cmd = \"CREATE DATABASE IF NOT EXISTS funbid\"\n\t\n\tcmd = \"CREATE TABLE IF NOT EXISTS user (\\\n\t\tid INT AUTO_INCREMENT PRIMARY KEY,\\\n\t\tusername VARCHAR(60),\\\n\t\tcreatedate DATETIME,\\\n\t\tfullname VARCHAR(60),\\\n\t\taddress VARCHAR(60),\\\n\t\timage VARCHAR(255),\\\n\t\tbidcount INT,\\\n\t\tpassword VARCHAR(60),\\\n\t\trole INT,\\\n\t\tactive INT)\"\n\tdb.execute(cmd)\n\tdbconn.commit()\n\tcmd = \"CREATE TABLE IF NOT EXISTS item (\\\n\t\tid INT AUTO_INCREMENT PRIMARY KEY,\\\n\t\tname VARCHAR(60),\\\n\t\tsellerid INT,\\\n\t\timage VARCHAR(255),\\\n\t\tcategory VARCHAR(60),\\\n\t\tinitprice INT,\\\n\t\tcreatedate DATETIME,\\\n\t\tstartdate DATETIME,\\\n\t\tenddate DATETIME,\\\n\t\tiswinner INT,\\\n\t\tcurrentprice INT,\\\n\t\tcurrentwinner INT,\\\n\t\tactive INT)\"\n\tdb.execute(cmd)\n\tdbconn.commit()\n\tcmd = \"CREATE TABLE IF NOT EXISTS funbid.auction (\\\n\t\tid INT AUTO_INCREMENT PRIMARY KEY,\\\n\t\tuserid INT,\\\n\t\titemid INT,\\\n\t\tbidprice INT,\\\n\t\ttime DATETIME)\"\n\tdb.execute(cmd)\n\tdbconn.commit()\n\nif __name__ == \"__main__\":\n\tinit_db()\n\tapp.run(host='0.0.0.0')\n","sub_path":"funbid/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":12934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498718788","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n# from surprise.model_selection import cross_validate\nfrom surprise import SVD, AlgoBase, Dataset, Reader, accuracy\nfrom surprise.model_selection import train_test_split\n\nfrom models import KNNBasic\n\ndf = pd.read_csv(\"../preprocessing/list_1000a.csv\", delimiter=\";\",\n encoding=\"utf-8\", error_bad_lines=False)\nreader = Reader(rating_scale=(1.0, 5.0))\ndata = Dataset.load_from_df(df[['userId', 'artistId', 'rating']], reader)\ntrain_set, test_set = train_test_split(data, test_size=.25)\n\n\nsim_options_jaccard = {\n 'name': 'jaccard',\n 'user_based': False,\n}\n\nsim_options_pearson = {\n 'name': 'pearson',\n 'user_based': False,\n}\n\nsim_options_cosine = {\n 'name': 'cosine',\n 'user_based': False,\n}\n\ngammas = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n# gammas = [15, 20, 25]\nk_value_jaccard = 20\nt_value_jaccard = 0.4\nk_value_pearson = 35\nt_value_pearson = 0.7\nk_value_mclaughlin_1 = 10\nk_value_mclaughlin_2 = 20\nk_value_mclaughlin_3 = 30\n\njaccard_fcp_values = []\njaccard_max = 1\njaccard_max_index = 0\n\npearson_fcp_values = []\npearson_max = 1\npearson_max_index = 0\n\nmclaughlin_1_fcp_values = []\nmclaughlin_1_max = 1\nmclaughlin_1_max_index = 0\n\nmclaughlin_2_fcp_values = []\nmclaughlin_2_max = 1\nmclaughlin_2_max_index = 0\n\nmclaughlin_3_fcp_values = []\nmclaughlin_3_max = 1\nmclaughlin_3_max_index = 0\n\nindex = 0\n\njaccard_algorithm = KNNBasic(k=k_value_jaccard, threshold=t_value_jaccard, sim_options=sim_options_jaccard)\njaccard_algorithm.fit(train_set)\njaccard_predictions = jaccard_algorithm.test(test_set)\njaccard_fcp = accuracy.fcp(jaccard_predictions)\n\npearson_algorithm = KNNBasic(k=k_value_pearson, threshold=t_value_pearson, sim_options=sim_options_pearson)\npearson_algorithm.fit(train_set)\npearson_predictions = pearson_algorithm.test(test_set)\npearson_fcp = accuracy.fcp(pearson_predictions)\n\nfor gamma in gammas:\n sim_options_mclaughlin = {\n 'name': 'mclaughlin',\n 'user_based': False,\n 'min_support': gamma\n }\n\n mclaughlin_1_algorithm = KNNBasic(k=k_value_mclaughlin_1, sim_options=sim_options_mclaughlin)\n mclaughlin_1_algorithm.fit(train_set)\n mclaughlin_1_predictions = mclaughlin_1_algorithm.test(test_set)\n\n mclaughlin_2_algorithm = KNNBasic(k=k_value_mclaughlin_2, sim_options=sim_options_mclaughlin)\n mclaughlin_2_algorithm.fit(train_set)\n mclaughlin_2_predictions = mclaughlin_2_algorithm.test(test_set)\n\n mclaughlin_3_algorithm = KNNBasic(k=k_value_mclaughlin_3, sim_options=sim_options_mclaughlin)\n mclaughlin_3_algorithm.fit(train_set)\n mclaughlin_3_predictions = mclaughlin_3_algorithm.test(test_set)\n\n if jaccard_fcp > jaccard_max:\n jaccard_max = jaccard_fcp\n jaccard_max_index = index\n jaccard_fcp_values.append(jaccard_fcp)\n\n if pearson_fcp > pearson_max:\n pearson_max = pearson_fcp\n pearson_max_index = index\n pearson_fcp_values.append(pearson_fcp)\n \n mclaughlin_1_fcp = accuracy.fcp(mclaughlin_1_predictions)\n if mclaughlin_1_fcp > mclaughlin_1_max:\n mclaughlin_1_max = mclaughlin_1_fcp\n mclaughlin_1_max_index = index\n mclaughlin_1_fcp_values.append(mclaughlin_1_fcp)\n \n mclaughlin_2_fcp = accuracy.fcp(mclaughlin_2_predictions)\n if mclaughlin_2_fcp > mclaughlin_2_max:\n mclaughlin_2_max = mclaughlin_2_fcp\n mclaughlin_2_max_index = index\n mclaughlin_2_fcp_values.append(mclaughlin_2_fcp)\n\n mclaughlin_3_fcp = accuracy.fcp(mclaughlin_3_predictions)\n if mclaughlin_3_fcp > mclaughlin_3_max:\n mclaughlin_3_max = mclaughlin_3_fcp\n mclaughlin_3_max_index = index\n mclaughlin_3_fcp_values.append(mclaughlin_3_fcp)\n \n index = index + 1\n print(\"We are {}0% done.\".format(index))\n\nplt.plot(gammas, jaccard_fcp_values, 'b', label='Jaccard FCP')\n# plt.plot(gammas[jaccard_max_index], jaccard_fcp_values[jaccard_max_index], 'bo')\n\nplt.plot(gammas, pearson_fcp_values, 'g', label='Pearson FCP')\n# plt.plot(gammas[pearson_max_index], pearson_fcp_values[pearson_max_index], 'go')\n\nplt.plot(gammas, mclaughlin_1_fcp_values, 'y', label='McLaughlin k={} FCP'.format(k_value_mclaughlin_1))\nplt.plot(gammas[mclaughlin_1_max_index], mclaughlin_1_fcp_values[mclaughlin_1_max_index], 'yo')\n\nplt.plot(gammas, mclaughlin_2_fcp_values, 'm', label='McLaughlin k={} FCP'.format(k_value_mclaughlin_2))\nplt.plot(gammas[mclaughlin_2_max_index], mclaughlin_2_fcp_values[mclaughlin_2_max_index], 'mo')\n\nplt.plot(gammas, mclaughlin_3_fcp_values, 'r', label='McLaughlin k={} FCP'.format(k_value_mclaughlin_3))\nplt.plot(gammas[mclaughlin_3_max_index], mclaughlin_3_fcp_values[mclaughlin_3_max_index], 'ro')\n\nplt.ylabel('FCP')\nplt.xlabel('Gama (Y)')\nplt.xticks(np.arange(min(gammas), max(gammas)+1, 10.0))\nplt.legend(loc='best')\nplt.savefig('../results/mclaughlin-fcp-item.png')\nplt.show()\n","sub_path":"experiments/model_creation_mclaughlin_fcp.py","file_name":"model_creation_mclaughlin_fcp.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"453034845","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\n\nfrom utils.videohandler import VideoHandler\n\n\nclass BackgroundExtractor(VideoHandler):\n\n def __init__(self, filename: str, sample: int = 100):\n \"\"\"\n Extract background from video\n :param filename: Video filename\n :param sample: Number of frames\n \"\"\"\n\n super().__init__(filename, self.save_frame)\n\n self.__buffer = []\n\n self.__nframes = int(self._cap.get(cv2.CAP_PROP_FRAME_COUNT))\n self.__step = int(self.__nframes / sample)\n\n self.__iter = 0\n\n def _setup(self):\n \"\"\"\n Change video stream pointer position\n :return: NA\n \"\"\"\n self._cap.set(cv2.CAP_PROP_POS_FRAMES, self.__iter)\n\n def run(self) -> np.ndarray:\n \"\"\"\n Process the video\n :return: NA\n \"\"\"\n\n super().run()\n buffer = np.array(self.__buffer)\n return np.median(buffer, axis=0).astype('uint8')\n\n def save_frame(self, frame: np.ndarray) -> bool:\n \"\"\"\n Save current frame\n :param frame: current frame\n :return: keep processing\n \"\"\"\n\n # gsimg = self.bgr_to_grayscale_improved(frame)\n gsimg = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n self.__buffer.append(gsimg)\n self.__iter += self.__step\n return self.__iter < self.__nframes\n\n def bgr_to_grayscale_improved(self, img: np.ndarray):\n\n # Invert colors\n inv_frame = (255 - img)\n\n # Create a grayscale image multiplying the R, G and B channels\n gsimg = inv_frame.prod(axis=2).astype('float32')\n\n # Get the lowest channel from inverted image and multiply with grayscale imagem\n gsimg *= np.amin(inv_frame, axis=2)\n\n # Normalize values between 0 and 255\n gsimg = ((gsimg * 255) / gsimg.max()).astype('uint8')\n\n return np.intp(255 - gsimg)\n","sub_path":"src/utils/bgextractor.py","file_name":"bgextractor.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289451160","text":"import os.path\nimport logging\n\nfrom pyramid.location import lineage\n\nlog = logging.getLogger(__name__)\n\n\nclass PageFactory(dict):\n def __init__(self, request, name=\"root\", parent=None):\n self.request = request\n\n self.__name__ = ''\n if name != \"root\":\n self.__name__ = name\n self.name = self.__name__\n self.__parent__ = parent\n\n self.tree = self.request.content_tree\n if name != 'root':\n self.tree = parent.tree[name]\n\n def __getitem__(self, item):\n # if the Item appears in self.tree and is a directory: return a new\n # pagefactory\n # if the item appears in self.tree and is a string: return a new page\n try:\n page_or_dir = self.tree[item]\n if isinstance(page_or_dir, dict):\n return PageFactory(self.request, item, self)\n else:\n return Page(item, self, page_or_dir)\n except:\n raise KeyError(\"Page not found\")\n\n def __json__(self, request=None):\n return {'type': 'Directory',\n 'name': self.__name__}\n\n\nclass Page(object):\n def __init__(self, name, parent, source):\n self.__name__ = name\n self.name = name\n self.__parent__ = parent\n self.__source__ = source\n\n self.title = name\n self.contents = self.load_contents()\n\n def load_contents(self):\n contents = \"\"\n try:\n parents = list(lineage(self))[1:][::-1]\n path = os.path.join(*[p.name for p in parents])\n path = os.path.join(self.__parent__.request.content_path,\n path,\n self.__source__)\n with open(path, 'r') as rd:\n contents = rd.read()\n except:\n log.error(\"Woops\", exc_info=True)\n return contents\n\n def __json__(self, request=None):\n return {'type': 'Page',\n 'name': self.__name__}\n","sub_path":"mdwiki/lib/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"337832514","text":"# -*- coding: utf8 -*-\n# Для проекта «Мессенджер» реализовать логирование с использованием модуля logging:\n# 1. В директории проекта создать каталог log, в котором для клиентской и серверной сторон\n# в отдельных модулях формата client_log_config.py и server_log_config.py создать логгеры;\n# 2. В каждом модуле выполнить настройку соответствующего логгера по следующему алгоритму:\n# - Создание именованного логгера;\n# - Сообщения лога должны иметь следующий формат: \"<дата-время> <уровень_важности> <имя_модуля> <сообщение>\";\n# - Журналирование должно производиться в лог-файл;\n# - На стороне сервера необходимо настроить ежедневную ротацию лог-файлов.\n# 3. Реализовать применение созданных логгеров для решения двух задач:\n# - Журналирование обработки исключений try/except. Вместо функции print() использовать журналирование и\n# обеспечить вывод служебных сообщений в лог-файл;\n# - Журналирование функций, исполняемых на серверной и клиентской сторонах при работе мессенджера.\n\nimport logging\nimport logging.handlers\nimport sys\nimport os\n\n# В директории проекта создать каталог log, в него пишем лог сервера\ncurr_dir = os.path.dirname(os.path.realpath(__file__))\nlog_dir = os.path.join(curr_dir, 'log')\nif not os.path.exists(log_dir):\n os.mkdir(log_dir)\nlogging_file = os.path.join(log_dir, 'server.log')\nprint(\"Логировани�� настроено в %s\" % logging_file)\n\n# Создать регистратор верхнего уровня с именем 'server'\nserv_log = logging.getLogger('server')\n# Формат сообщений <дата-время> <уровень_важности> <имя_модуля> <сообщение>\n_format = logging.Formatter(\"%(asctime)s %(levelname)-10s %(module)s: %(message)s\")\n\n# # Создать обработчик, который выводит сообщения с уровнем\n# # CRITICAL в поток stderr\ncrit_hand = logging.StreamHandler(sys.stderr)\ncrit_hand.setLevel(logging.CRITICAL)\ncrit_hand.setFormatter(_format)\n\n# Создать обработчик, который выводит сообщения в файл\n# ротация лога каждые 5 минут для проверки\napplog_hand = logging.handlers.TimedRotatingFileHandler(logging_file, when='m', interval=5, encoding='utf-8',\n backupCount=10)\napplog_hand.setFormatter(_format)\napplog_hand.setLevel(logging.DEBUG)\n\n# Добавить несколько обработчиков в регистратор 'server'\nserv_log.addHandler(applog_hand)\nserv_log.addHandler(crit_hand)\nserv_log.setLevel(logging.DEBUG)\n\nif __name__ == '__main__':\n # Создаем потоковый обработчик логирования (по умолчанию sys.stderr):\n console = logging.StreamHandler(sys.stderr)\n console.setLevel(logging.DEBUG)\n console.setFormatter(_format)\n serv_log.addHandler(console)\n serv_log.info('Тестовый запуск логирования')\n serv_log.critical('critical!')\n serv_log.error('error!')\n serv_log.warning('warning!')\n serv_log.info('info!')\n serv_log.debug('debug!')\n","sub_path":"Lesson_5/server_log_config.py","file_name":"server_log_config.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638689819","text":"import torch\nfrom torch import nn\n\n\nclass ResNet(nn.Module):\n\n def __init__(self):\n super(ResNet, self).__init__()\n\n self.func = nn.Sequential(\n nn.Conv2d(1, 32, 3, 1, 1),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n\n nn.Conv2d(32, 32, 3, 1, 1),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n nn.MaxPool2d(kernel_size=2),\n\n nn.Conv2d(32, 64, 3, 1, 1),\n nn.BatchNorm2d(64),\n nn.ReLU(True),\n\n nn.Conv2d(64, 128, 3, 1, 1),\n nn.BatchNorm2d(128),\n nn.ReLU(True),\n nn.MaxPool2d(kernel_size=2),\n )\n\n self.linear = nn.Sequential(\n nn.Linear(128 * 7 * 7, 512),\n nn.BatchNorm1d(512),\n nn.ReLU(True),\n nn.Dropout(p=0.5),\n\n nn.Linear(512, 128),\n nn.BatchNorm1d(128),\n nn.ReLU(True),\n nn.Dropout(p=0.5),\n\n nn.Linear(128, 10)\n )\n\n def forward(self, x):\n batchsz = x.size(0)\n x = self.func(x)\n x = x.view(batchsz, 128 * 7 * 7)\n logits = self.linear(x)\n\n return logits\n\n\ndef main():\n data = torch.randn(2, 1, 28, 28)\n net = ResNet()\n\n out = net(data)\n print(out.shape)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cnnNet.py","file_name":"cnnNet.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"113775455","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_one_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-voice-connector-group.html\nif __name__ == '__main__':\n \"\"\"\n\tdelete-voice-connector-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/delete-voice-connector-group.html\n\tget-voice-connector-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-voice-connector-group.html\n\tlist-voice-connector-groups : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-voice-connector-groups.html\n\tupdate-voice-connector-group : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-voice-connector-group.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # name : The name of the Amazon Chime Voice Connector group.\n \"\"\"\n add_option_dict = {}\n\n #######################################################################\n # parameter display string\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_one_parameter(\"chime\", \"create-voice-connector-group\", \"name\", add_option_dict)\n\n\n\n\n\n","sub_path":"chime_write_1/voice-connector-group_create.py","file_name":"voice-connector-group_create.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"140622233","text":"# Copy a field from one collection to another. \n# Both collections must be indexed by the same field. \n\nimport sys\nfrom pymongo import MongoClient\nfrom jmAlife.dbManage.parallelMap import parallelMap\n\nDB = MongoClient().patents\n\n# Retrieve the field from the \"from\" collection and \n# return a function which will be passed to parallelMap. \ndef copy_one_field(field, from_coll, from_id, to_id):\n def pmap_func(doc):\n from_doc = from_coll.find_one({from_id: doc[to_id]}, {field:1})\n if from_doc is None: \n return None\n if field in from_doc:\n return {'$set': {field: from_doc[field]}}\n else:\n return None\n return pmap_func\n \nif __name__ == '__main__':\n if len(sys.argv) != 6:\n exit(\"Usage: python {} \")\n field = sys.argv[1] \n from_collection_name = sys.argv[2]\n to_collection_name = sys.argv[3]\n from_id = sys.argv[4]\n to_id = sys.argv[5]\n from_coll = DB[from_collection_name]\n to_coll = DB[to_collection_name]\n pmap_func = copy_one_field(field, from_coll, from_id, to_id)\n parallelMap(pmap_func,\n in_collection = to_coll,\n out_collection = to_coll,\n findArgs = {'spec': {}, 'fields': {}},\n updateFreq = 500,\n bSize = 1000)\n","sub_path":"scripts/dbManage_scripts/copy_field.py","file_name":"copy_field.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"97325475","text":"from basefilter import BaseFilter\nfrom utils import write_classification_to_file, mark_all_in_dict\n\n\nclass NaiveFilter(BaseFilter):\n \"\"\"all emails OK\"\"\"\n\n def test(self, path):\n super().test(path)\n self.mail_dict = mark_all_in_dict(self.mail_dict, \"OK\")\n write_classification_to_file(path + \"/!prediction.txt\", self.mail_dict)\n\n\nclass ParanoidFilter(BaseFilter):\n \"\"\"all emails SPAM\"\"\"\n\n def test(self, path):\n super().test(path)\n self.mail_dict = mark_all_in_dict(self.mail_dict, \"SPAM\")\n write_classification_to_file(path + \"/!prediction.txt\", self.mail_dict)\n\n\nclass RandomFilter(BaseFilter):\n \"\"\"random\"\"\"\n\n def test(self, path):\n super().test(path)\n self.mail_dict = mark_all_in_dict(self.mail_dict)\n write_classification_to_file(path + \"/!prediction.txt\", self.mail_dict)\n\n\nif __name__ == '__main__':\n # nf = NaiveFilter()\n # nf.train(\"emails\")\n # nf.test(\"emails\")\n\n # pf = ParanoidFilter()\n # pf.train(\"emails\")\n # pf.test(\"emails\")\n\n rf = RandomFilter()\n rf.train(\"emails\")\n rf.test(\"emails\")\n","sub_path":"Python/Spam Filter/optional_files/simplefilters.py","file_name":"simplefilters.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20192767","text":"import sys\nfrom cffi import FFI\nimport numpy as np\nsys.path.append('../')\nfrom edges import Edge\n\nif __name__ == '__main__':\n libsimfn = \"./libsim.so\"\n datadir = \"../mkUserlist/data/N80000r0i0/\"\n agentfn = \"%s/agentlist.txt\"%datadir\n graphfn = \"%s/graph.twd\"%datadir\n goalfn = \"%s/goallist.txt\"%datadir\n sim_time = 20000\n interval = 600\n max_step = int( np.ceil( sim_time / interval ))\n num_agents = 80000\n ffi = FFI()\n lib = ffi.dlopen(libsimfn)\n ffi.cdef(\"\"\"\n void init(int argc, char** argv);\n int setStop(int t);\n void iterate();\n void setBombDirect( char *text);\n void setBomb( char *fn);\n int cntOnEdge(int fr, int to);\n void restart();\n void init_restart(int argc, char** argv);\n \"\"\") \n\n # edges = Edge(12)\n # print(\"num_edges\")\n # print(edges.num_edges)\n edges = Edge()\n argv = [sys.argv[0]]\n argv.extend([\n agentfn,\n graphfn,\n goalfn,\n \"-o\",\n \"result2\",\n \"-l\",\n \"99999\",\n \"-e\",\n str(sim_time)\n ])\n print(argv)\n tmp = []\n for a in argv:\n tmp.append(ffi.new(\"char []\", a.encode('ascii')))\n argv = ffi.new(\"char *[]\", tmp)\n # call simulator\n lib.init(len(argv), argv)\n # lib.setBomb(\"./event.txt\".encode('ascii'))\n input()\n res = []\n time = 0\n traveltime = 0\n for step in range(max_step):\n print(\"TIME\", time)\n lib.setStop(time)\n lib.iterate()\n ret = np.zeros(len(edges.observed_edge))\n for e, idx in edges.observed_edge.items():\n fr, to = e\n ret[idx] = lib.cntOnEdge(fr-1, to-1)\n # traveltime += np.sum(ret) * interval / num_agents\n res.append(np.sum(ret) * interval / num_agents)\n time += interval\n print(traveltime)\n print(res)\n print(np.sum(res))\n # with open(\"result/travel_free_time.json\", \"w\") as f:\n # json.dump(res, f)\n","sub_path":"bin/old/run_sim.py","file_name":"run_sim.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"376899748","text":"import requests, time, psycopg2\r\n\r\nconn = psycopg2.connect(\"dbname='**' user='**' host='localhost' password='**'\")\r\ncur = conn.cursor()\r\n\r\nurl = \"https://api.igdb.com/v4/platform_families\"\r\n\r\nlim = 50\r\noffset = 0\r\n\r\nwhile offset < lim:\r\n payload = f\"\"\"\r\n fields id, name;\r\n \\r\\nlimit 50;\\r\\noffset {offset};\r\n \\r\\nsort id; \r\n \"\"\"\r\n headers = {\r\n 'Client-ID': '**',\r\n 'Authorization': 'Bearer **',\r\n 'Content-Type': 'application/javascript',\r\n 'Cookie': '**'\r\n }\r\n\r\n response = requests.request(\"POST\", url, headers=headers, data = payload)\r\n\r\n json_data = response.json()\r\n \r\n cur.executemany(\"\"\"INSERT INTO platform_family(platform_family_id,name) VALUES (%(id)s, %(name)s)\"\"\", json_data)\r\n\r\n offset += 50\r\n time.sleep(0.250)\r\n\r\n \r\nconn.commit()","sub_path":"python files/platform_family.py","file_name":"platform_family.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203433535","text":"import pandas as pd\nimport numpy as np \nfrom scipy.spatial.transform import Rotation as R \nfrom PanoProcessing.rotate_pano import synthesizeRotation \nimport matplotlib.pyplot as plt \nimport cv2\nimport matplotlib.image as mpimg\nimport sys\n\ndef create_data(i): \n data_info = pd.read_csv('./upright_examples.txt') \n depth_dir = './examples/' \n rgb_dir = '/home/paulo/datasets/my3d60/' \n rgb = mpimg.imread(rgb_dir + data_info['input'][i] + '.png') \n random_r = R.from_euler('zyx', [0, data_info['rand_y'][i], data_info['rand_x'][i]], degrees=True) \n correction_r = R.from_euler('zyx', [0, data_info['pred_y'][i], data_info['pred_x'][i]], degrees=True) \n \n rgb_random_rot = synthesizeRotation(rgb, random_r.as_matrix()) \n rgb_upright = synthesizeRotation(rgb_random_rot, correction_r.inv().as_matrix()) \n \n upright_output = np.load(depth_dir + str(i) + '_corrected_output.npy') \n rot_output = np.load(depth_dir + str(i) + '_rot_output.npy')\n input_output = np.load(depth_dir + str(i) + '_input_output.npy')\n \n gt = cv2.imread(rgb_dir + data_info['input'][i].replace('color','depth') + '.exr', cv2.IMREAD_ANYDEPTH) \n gt[gt > 40] = 0 \n\n \n plt.subplot(1,3,1)\n plt.axis('off')\n plt.imshow(rgb)\n plt.subplot(1,3,2)\n plt.axis('off')\n plt.imshow(gt)\n plt.subplot(1,3,3)\n plt.axis('off')\n plt.imshow(input_output)\n plt.savefig('rectified_vs_rotated_depth_1.png', bbox_inches='tight')\n plt.subplot(1,3,1)\n plt.axis('off')\n plt.imshow(rgb_random_rot)\n plt.subplot(1,3,2)\n plt.axis('off')\n plt.imshow(synthesizeRotation(gt, random_r.as_matrix()))\n plt.subplot(1,3,3)\n plt.axis('off')\n plt.imshow(rot_output)\n plt.savefig('rectified_vs_rotated_depth_2.png', bbox_inches='tight')\n\nif __name__ == '__main__':\n create_data(int(sys.argv[1]))\n","sub_path":"vis_rectified_vs_rotated.py","file_name":"vis_rectified_vs_rotated.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53386338","text":"import logging\nfrom typing import Tuple\nimport pickle\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics.pairwise import pairwise_distances\nimport plotly.graph_objs as go\nimport pandas as pd\nimport numpy as np\n\nfrom ..core import ExpMatrix, CellAnnVector\nfrom ..core import CellAnnMatrix\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass ScmapClusterClassifier:\n \"\"\"Class implementing the scmap-cluster method.\"\"\"\n\n PICKLE_PROTOCOL_VERSION = 4 # requires Python 3.4 or higher\n\n def __init__(self, num_genes: int = 500,\n similarity_threshold: float = 0.7) -> None:\n self.num_genes = num_genes\n self.similarity_threshold = similarity_threshold\n \n self.logcount_mean_ = None\n self.frac_zero_ = None\n self.regression_model_ = None\n self.sel_genes_ = None\n self.cluster_medioids_ = None\n\n @property\n def cell_types_(self):\n return self.cell_clusters_.value_counts().index.tolist()\n\n def _select_genes(self, matrix: ExpMatrix) -> pd.Index:\n # we assume matrix is already normalized and log2(x+1)-transformed\n\n mean = matrix.mean(axis=1)\n frac_zero = (matrix == 0).sum(axis=1) / matrix.shape[1]\n \n # only use genes that aren't all zero, and that have some dropout (all)\n sel = (frac_zero > 0) & (frac_zero < 1)\n \n mean = mean.loc[sel]\n frac_zero = frac_zero.loc[sel]\n\n # regress fraction of dropout on mean of log expression using linear regression\n model = LinearRegression()\n model.fit(mean.values.reshape(-1, 1), np.log2(100*frac_zero))\n\n # calculate residuals\n res = np.log2(100*frac_zero) - model.predict(mean.values.reshape(-1,1))\n a = np.argsort(res)[::-1]\n \n sel_genes = matrix.genes.to_series().loc[sel] \\\n .iloc[a[:self.num_genes]].index\n return mean, frac_zero, model, sel_genes\n\n\n def fit(self, matrix, cell_clusters) -> None:\n # we assume matrix is already normalized and log2(x+1)-transformed\n \n #if not count_matrix.cells.equals(logcount_matrix.cells):\n # raise ValueError('\"count_matrix\" and \"logcount_matrix\" must contain identical cells!')\n \n if not cell_clusters.index.to_series().isin(matrix.cells).all():\n raise ValueError('Not all clustered cells are contained in the '\n 'expression matrix!')\n\n # make sure data are aligned\n #count_matrix = count_matrix.loc[:, cell_clusters.index]\n matrix = matrix.loc[:, cell_clusters.index]\n \n # select genes\n mean, frac_zero, model, sel_genes = self._select_genes(matrix)\n \n self.logcount_mean_ = mean\n self.frac_zero_ = frac_zero\n self.regression_model_ = model\n self.sel_genes_ = sel_genes\n self.cell_clusters_ = cell_clusters\n \n # calculate medioids\n vc = cell_clusters.value_counts()\n cluster_labels = vc.index.tolist()\n \n data = np.empty((sel_genes.size, len(cluster_labels)),\n dtype=np.float64)\n med = ExpMatrix(genes=sel_genes, cells=cluster_labels, data=data)\n \n for label in cluster_labels:\n med.loc[:, label] = matrix.loc[sel_genes, cell_clusters == label] \\\n .median(axis=1)\n \n self.cluster_medioids_ = med\n\n\n def plot_gene_selection(self,\n xrange: Tuple[float, float] = None,\n yrange: Tuple[float, float] = None,\n num_genes: int = None, seed: int = 0,\n marker_size: float = 5.0) -> go.Figure:\n #mean, frac_zero, model, res, top=500, xrange=None, yrange=None, num_genes=1000, seed=0) \n \n if self.cluster_medioids_ is None:\n raise RuntimeError('You must train the model first!')\n \n mean = self.logcount_mean_\n frac_zero = self.frac_zero_\n model = self.regression_model_\n sel_genes = self.sel_genes_\n \n if num_genes is None:\n num_genes = mean.size\n\n if xrange is None:\n ptp = np.ptp(mean)\n xmin = (np.amin(mean) - 0.03*ptp)\n xmax = (np.amax(mean) + 0.03*ptp)\n else:\n xmin, xmax = xrange\n\n np.random.seed(seed)\n sel = np.random.choice(mean.size, size=num_genes, replace=False)\n\n trace = go.Scatter(\n x=mean.iloc[sel],\n #y=np.log2((100*frac_zero.loc[sel])),\n y=np.log2(100*frac_zero).iloc[sel],\n mode='markers',\n marker=dict(size=marker_size),\n )\n\n trace2 = go.Scatter(\n x=mean.loc[sel_genes],\n #y=np.log2((100*frac_zero.loc[sel])),\n #y=np.log2(100*frac_zero.loc[sel]).iloc[a[:top]],\n y=np.log2(100*frac_zero.loc[sel_genes]),\n mode='markers',\n marker=dict(color='red', size=marker_size),\n )\n\n y1 = model.intercept_ + xmin*model.coef_[0]\n y2 = model.intercept_ + xmax*model.coef_[0]\n trace3 = go.Scatter(\n x=[xmin, xmax],\n y=[y1, y2],\n mode='lines',\n line=dict(color='black'),\n )\n\n data = [trace, trace2, trace3]\n\n layout = go.Layout(\n xaxis=dict(range=[xmin, xmax], zeroline=False, showline=True,\n ticklen=5, title='Mean log2(Expression)'),\n yaxis=dict(range=yrange, zeroline=False, showline=True,\n ticklen=5, title='log2(% of zero values)'),\n width=800,\n height=800,\n showlegend=False,\n font=dict(size=24),\n )\n\n fig = go.Figure(data=data, layout=layout)\n return fig\n\n \n def predict(self, logcount_matrix):\n \n if self.cluster_medioids_ is None:\n raise RuntimeError('You must train the model first!')\n \n cluster_medioids = self.cluster_medioids_\n \n comb = logcount_matrix.genes & cluster_medioids.genes\n \n if len(comb) == 0:\n raise ValueError('No genes in common!')\n \n sim_cosine = 1 - \\\n pairwise_distances(\n logcount_matrix.loc[comb].T,\n cluster_medioids.loc[comb].T,\n metric='cosine')\n \n sim_pearson = 1 - \\\n pairwise_distances(\n logcount_matrix.loc[comb].T,\n cluster_medioids.loc[comb].T,\n metric='correlation')\n \n # for spearman, transform the genes to ranks\n # and then calculate Pearson correlation\n medioids_ranked = cluster_medioids.loc[comb].rank(axis=0)\n matrix_ranked = logcount_matrix.loc[comb].rank(axis=0)\n \n sim_spearman = 1 - \\\n pairwise_distances(\n matrix_ranked.T,\n medioids_ranked.T,\n metric='correlation')\n \n # return shape: #cells-by-#clusters\n \n n = len(logcount_matrix.cells) # the number of cells\n m = len(cluster_medioids.columns) # the number of classes\n \n data = np.zeros((n, m), dtype=np.int64)\n votes = CellAnnMatrix(\n cells=logcount_matrix.cells,\n columns=cluster_medioids.columns,\n data=data)\n \n for sim in [sim_cosine, sim_pearson, sim_spearman]:\n #for row, col in zip(np.arange(n), sim.idxmax(axis=1)):\n for row, col in zip(np.arange(n), np.argmax(sim, axis=1)):\n votes.iat[row, col] += 1\n \n assert votes.sum().sum() == 3*n\n #num_unassigned = (votes.max(axis=1) < 2).sum()\n \n assigned = pd.Series(index=votes.index, data=np.ones(votes.shape[0],\n dtype=np.bool_))\n assigned.loc[votes.max(axis=1) < 2] = False\n\n num_unassigned = (~assigned).sum()\n _LOGGER.info('Number of cells unassigned after voting: '\n '%d / %d (%.1f %%)',\n num_unassigned, n, 100*(num_unassigned/n))\n \n winner_labels = votes.idxmax(axis=1)\n \n winner = votes.values.argmax(axis=1)\n \n sim_max = np.stack([sim_cosine, sim_pearson, sim_spearman], axis=-1) \\\n .max(axis=-1)\n winner_max_sim = np.float64([sim_max[i, winner[i]] for i in range(n)])\n \n assigned.iloc[winner_max_sim < self.similarity_threshold] = False\n \n num_unassigned = (~assigned).sum()\n _LOGGER.info('Number of cells unassigned after applying similarity '\n 'threshold: %d / %d (%.1f %%)',\n num_unassigned, n, 100*(num_unassigned/n))\n\n winner_labels.loc[~assigned] = 'unassigned'\n winner_labels = CellAnnVector(winner_labels)\n return winner_labels\n\n\n def write_pickle(self, file_path: str) -> None:\n \"\"\"Write classifier to file in pickle format.\"\"\"\n #pred.write_pickle('')\n with open(file_path, 'wb') as ofh:\n pickle.dump(self, ofh, self.PICKLE_PROTOCOL_VERSION)\n _LOGGER.info('Wrote classifier to \"%s\".', file_path)\n \n\n @classmethod\n def read_pickle(cls, file_path: str):\n \"\"\"Read classifier from pickle file.\"\"\"\n with open(file_path, 'rb') as fh:\n clf = pickle.load(fh)\n _LOGGER.info('Loaded classifier from \"%s\".', file_path)\n return clf\n","sub_path":"moana/classify/scmap_cluster.py","file_name":"scmap_cluster.py","file_ext":"py","file_size_in_byte":9567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486400368","text":"from tkinter import *\nwindow = Tk()\nwindow.geometry('200x200') # Создаем окно размером 200х200\nwindow.title('Tkinter') # Задаем название заголовка\n\ndef show_label(event):\n label = Label(window, text='Hello World') # Инициализация Label\n label.place(anchor = CENTER, relx = 0.5, rely = 0.5) # Размещение Label\n button.place_forget() # Убираем кнопку из окна\n\nbutton = Button(window, text = 'Hi!', width = '10', height = '2') # Инициализация кнопки\nbutton.bind('', show_label) # Событие, при нажатии л.кн. мыши вызывает функцую\nbutton.place(anchor = CENTER, relx = 0.5, rely = 0.5) # Размещение кнопки\nwindow.mainloop()","sub_path":"Practic3rdCourse/venv/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"652180382","text":"#!/usr/bin/env python\n'''\nCreated on 2017-21-11\n\n@author: Thien Doan\n'''\n\n\nfrom multiprocessing import Array, Process\nfrom multiprocessing.queues import SimpleQueue\n\nimport os\nimport time\nimport datetime\nimport re\nimport subprocess\nimport sys\nimport traceback\n\nfrom PyQt5 import QtCore, QtGui, uic\nfrom PyQt5 import QtWidgets\nfrom configuration.ateConfig import ateTestIdMap\nfrom ate_settings import *\nfrom tests.scenario import Scenario\nfrom controller.controller import Controller\nfrom utilities.utils import *\n\nform_class = uic.loadUiType(\"/home/pi/misfit/ShineProduction/newATE/view/mainwindow.ui\")[0]\n\nTIMEZONE = 'Asia/Shanghai'\n\nclass MainWindowClass(QtWidgets.QMainWindow, form_class):\n def __init__(self, parent=None):\n QtWidgets.QMainWindow.__init__(self, parent)\n self.setupUi(self)\n self.startButton.clicked.connect(self.start)\n self.startButton.setStyleSheet(\"background-color: green;\")\n\n title = \"ATE Station %s-%s\" % (STATION_ID, STATION_INDEX)\n self.setWindowTitle(title)\n\n self.input2LineEdit.hide()\n self.input2Label.hide()\n self.input1LineEdit.setFocus()\n self.controller = Controller(DEVICE_TYPE, STATION_ID, STATION_INDEX)\n\n if STATION_ID == '1':\n self.input1Label.setText(\"Internal Serial Number (PCB)\")\n\n self.input2Label.show()\n self.input2Label.setText(\"SMT Serial Number\")\n self.input2LineEdit.show()\n self.input2LineEdit.setMaxLength(11)\n\n self.input3Label.hide()\n self.input3LineEdit.hide()\n\n elif STATION_ID == '2':\n self.input1Label.setText(\"Internal Serial Number (PCB)\")\n\n self.input2Label.show()\n self.input2Label.setText(\"E-INK Lot Number\")\n self.input2LineEdit.show()\n self.input2LineEdit.setMaxLength(25)\n\n # Hide the Heart Rate Serial Number\n self.input3Label.hide()\n self.input3LineEdit.hide()\n\n elif STATION_ID == '3':\n # Setup the Internal serial number label and line edit input\n self.input1Label.setText(\"Internal Serial Number (PCB)\")\n self.input1LineEdit.show()\n self.input1LineEdit.setMaxLength(SERIAL_NUMBER_LENGTH)\n\n # Setup the packaging serial number length and line edit input\n self.input2LineEdit.setMaxLength(SERIAL_NUMBER_LENGTH)\n self.input2Label.setText(\"Packaging Serial Number\")\n self.input2Label.show()\n self.input2LineEdit.show()\n\n self.input3Label.setText(\"Heart Rate Serial Number\")\n self.input3Label.show()\n self.input3LineEdit.show()\n # Set focus to the HR SN when the GUI is loaded.\n self.input3LineEdit.setFocus()\n\n def updateGui(self):\n QtWidgets.QApplication.processEvents()\n\n def keyPressEvent(self, event):\n \"\"\"\n This function detects if the Enter or Return key is pressed and calls the\n start() function.\n \"\"\"\n if event.key() == QtCore.Qt.Key_Enter or event.key() == QtCore.Qt.Key_Return:\n self.start()\n\n def start(self):\n\n ateConfig.log.logger.debug('Scenario Attributes ' + str(Scenario.ateTestAttr))\n # Clear all of the Scenario attributes.\n Scenario.clearAteTestAttrs()\n ateConfig.log.logger.debug('Cleared Scenario Attributes ' + str(Scenario.ateTestAttr))\n\n testsFailed = None\n testFailedData = None\n self.__setStatusLabel(4)\n self.updateGui()\n serial_num = ''\n serial_num_internal = ''\n serial_num_smt = ''\n serial_num_hr = ''\n if STATION_ID == '1' or STATION_ID == '2' or STATION_ID == '2.5':\n self.serial_num_internal = self.input1LineEdit.text()\n serial_num_internal = str(self.input1LineEdit.text())\n self.serial_num_smt = self.input2LineEdit.text()\n serial_num_smt = str(self.input2LineEdit.text())\n self.serial_num = None\n serial_num = None\n Scenario.ateTestAttr['SMT_serial_number'] = serial_num_smt\n Scenario.ateTestAttr['internal_serial_number'] = serial_num_internal\n\n if STATION_ID == '2':\n Scenario.ateTestAttr['EInkLotNumber'] = str(self.input2LineEdit.text())\n\n elif STATION_ID == '3':\n # Get the packaging serial number\n self.serial_num_internal = self.input1LineEdit.text()\n serial_num_internal = str(self.input1LineEdit.text())\n # Get the internal serial number.\n self.serial_num = self.input2LineEdit.text() \n serial_num = str(self.input2LineEdit.text())\n # get the heart rate serial number.\n self.heartRateSerialNumber = str(self.input3LineEdit.text())\n self.serial_num_hr = self.heartRateSerialNumber\n serial_num_hr = self.heartRateSerialNumber\n Scenario.ateTestAttr['internal_serial_number'] = serial_num_internal\n Scenario.ateTestAttr['serial_number'] = serial_num\n # Scenario.ateTestAttr['SMT_serial_number'] = serial_num_smt\n Scenario.ateTestAttr['serial_number_heart_rate'] = serial_num_hr\n serial_num_smt = serial_num_hr\n\n #Enable serial number check\n (validSerialNumber, serial_num, serial_num_internal, serial_num_hr) = serialNumberCheck(serial_num, serial_num_internal, serial_num_smt)\n\n # validSerialNumber = True\n if validSerialNumber:\n # Set current local time\n os.environ['TZ'] = TIMEZONE\n time.tzset()\n curr_time = datetime.datetime.now()\n print (\"\\nCurrent local time is %s\\n\" % datetime.datetime.strftime(curr_time,\"%Y-%m-%d %H:%M:%S\"))\n\n for x in range(0, 1):\n (status, testsFailed) = self.controller.executeScenario()\n\n else:\n status = 3\n print('Status: {}'.format(status))\n self.__setStatusLabel(status, testsFailed)\n\n self.input1LineEdit.setText(\"\")\n self.input2LineEdit.setText(\"\")\n self.input3LineEdit.setText(\"\")\n if STATION_ID == '1' or STATION_ID == '2':\n self.input1LineEdit.setFocus()\n elif STATION_ID == '3':\n self.input3LineEdit.setFocus()\n\n def __setStatusLabel(self, success, testsFailed=None):\n\n self.statusTextBrowser.setStyleSheet(\"font-size: 13pt\") \n if success == 0:\n self.statusTextBrowser.setText(\"SUCCESS\")\n self.statusTextBrowser.setStyleSheet(\"background-color: green;\")\n print( \"Success!\")\n elif success == 2:\n self.statusTextBrowser.setText('Tests succeeded, Raspberry Pi not connected to internet')\n self.statusTextBrowser.setStyleSheet(\"background-color: yellow;\")\n print( \"Tests succeeded, Raspberry Pi not connected to internet.\")\n elif success == 3:\n self.statusTextBrowser.setText(\"Invalid serial number! Try rescanning the barcode.\")\n self.statusTextBrowser.setStyleSheet(\"background-color: blue;\")\n print( \"Check errors\")\n elif success == 4:\n self.statusTextBrowser.setText(\"Tests running...\")\n self.statusTextBrowser.setStyleSheet(\"background-color: gray;\")\n elif success == 5:\n self.statusTextBrowser.setText(testsFailed)\n\n self.statusTextBrowser.setStyleSheet(\"background-color: yellow;\") \n self.updateGui()\n time.sleep(1)\n self.statusTextBrowser.setStyleSheet(\"background-color: gray;\")\n self.updateGui()\n time.sleep(1)\n self.statusTextBrowser.setStyleSheet(\"background-color: yellow;\")\n elif success == 6:\n self.statusTextBrowser.setText(testsFailed)\n self.statusTextBrowser.setStyleSheet(\"background-color: red;\")\n print( \"No record for this device in database.\")\n else:\n errorMessage = \"Tests Failed:\\n\"\n\n try:\n # Display the failure code and text for the operator\n for test in testsFailed:\n errorMessage += '==================================================\\n'\n testId = ateConfig.ateTestIdMap[str(test['testClassName'])]\n errorMessage += testId + ': ' + str(test['name']) + '\\n' + str(test['data']) +'\\n'\n\n if 'error' in test:\n errorMessage += '\\n' + 'Error: ' + str(test['error']) + '\\n'\n\n except Exception as exc:\n ateConfig.log.logger.error(sys.exc_info())\n ateConfig.log.logger.error('\\n'.join(traceback.format_stack()))\n\n self.statusTextBrowser.setText(errorMessage)\n self.statusTextBrowser.setStyleSheet(\"background-color: red;\")\n\n print( \"Tests failed\")\n print( \"\\n==============================================================\\n\")\n self.updateGui()\n \n","sub_path":"view/gui_run_tests.py","file_name":"gui_run_tests.py","file_ext":"py","file_size_in_byte":9033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285282229","text":"import requests\nimport tempfile\nfrom pathlib import Path\nfrom operator import itemgetter\nimport subprocess\nfrom typing import List, Set\nfrom Bio import SeqIO\n\nfrom table_generator import create_tab_delimited_table, extract_barcodes\nfrom utilities import fastq_to_fasta\nfrom coveragePlot import coverage_plot\n\ndef coverage_generator(snap_file: Path, rap_file: Path, evalue: str,\n cores: int, top_acc: int, top_coverage_plots: int):\n\n snap = snap_file.read_text().splitlines()\n rap = rap_file.read_text().splitlines()\n\n table = create_tab_delimited_table('SNAP', snap_file)\n\n barcodes = extract_barcodes(table)\n\n for barcode in barcodes:\n\n snap_pattern = '#{}/'.format(barcode)\n rap_pattern = '#{}'.format(barcode)\n\n snap_matches = [line for line in snap if snap_pattern in line]\n rap_matches = [line for line in rap if rap_pattern in line]\n\n barcode_genera = set(line[3] for line in table\n if snap_pattern in line[0])\n\n for genus in barcode_genera:\n\n snap_mixed = [line for line in snap_matches if genus in line]\n\n snap_fastas = ['>{}\\n{}'.format(line[0], line[9])\n for line in snap_mixed]\n\n rap_fastas = ['>{}\\n{}'.format(line[0], line[12])\n for line in rap_matches if genus in line]\n\n snap_rap = snap_fastas + rap_fastas\n\n numreads = len(snap_rap)\n\n accs = [line[2] for line in snap_mixed][:200]\n\n fastas = get_genbank_fasta('fasta', accs)\n\n for acc in accs:\n\n plot_reads_to_acc(snap_rap, acc, genus, workdir, evalue, cores)\n\ndef get_genbank_fasta(rettype, accessions):\n '''Fetches requested accessions and returns them from NCBI'''\n\n acc_string = ' '.join(str(acc) for acc in accessions)\n\n url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?\\\n db=sequences&\\\n id={accs}&\\\n rettype={rettype}&\\\n retmode=text'.replace(' ','').format(accs=acc_string,\n rettype=rettype)\n\n res = requests.get(url)\n\n return res.text\n\ndef extract_accession_from_genbank(fasta_string):\n\n def extract_accession(header: str) -> str:\n\n acc = header.split()[0].lstrip('>')\n\n return acc[:acc.index('.')] if '.' in acc else acc\n\n headers = [line for line in fasta_string.splitlines()\n if line.startswith('>')]\n\n complete_genomes = (header for header in headers\n if 'omplete' in header and 'enome' in header)\n\n accessions = [extract_accession(header) for header in complete_genomes]\n\n if not accessions: # no complete genomes\n\n complete_sequences = (header for header in headers\n if 'omplete' in header and 'equence' in header)\n\n accessions = [extract_accession(header)\n for header in complete_sequences]\n\n if not accessions: # no complete sequences\n\n accessions = [extract_accession(header) for header in headers]\n\ndef extract_to_fast(infile: Path, parent: Path, outfile: Path):\n\n header_file = infile.with_suffix('.headers')\n headers = [line.split()[0] for line in infile.read_text().splitlines()]\n\n header_file.write_text('\\n'.join(headers))\n\n cmd = ('seqtk', 'subseq', str(parent), str(header_file))\n\n output = subprocess.check_output(cmd, universal_newlines=True)\n\n outfile.write_text(output)\n\n header_file.unlink()\n\ndef uniq_blast_results(infile: Path, outfile: Path) -> None:\n\n with infile.open('w') as inf:\n table = [line.split('\\t') for line in inf]\n\n table.sort(key=itemgetter(10))\n table.sort(key=itemgetter(0))\n\n table2 = []\n done = set() # type: Set[str]\n\n for line in table:\n if line[0] not in done:\n table2.append('\\t'.join(line))\n done.add(line[0])\n\n outfile.write_text('\\n'.join(table2))\n\ndef map_perfect_blast_to_genome(blast_out: Path, output: Path, genome_length):\n\n genome = [] # type: List[int]\n\n with blast_out.open('r') as blast, output.open('w') as out:\n for line in blast:\n\n data = line.split()\n\n oStart = int(data[6])\n oEnd = int(data[7])\n oLength = oEnd - oStart + 1\n gStart = min(int(data[8]), int(data[9]))\n gEnd = max(int(data[8]), int(data[9]))\n hitStart = max(0, (gStart - oStart + 1))\n hitEnd = min(genome_length, (gEnd + (oLength - oEnd)))\n\n for hit in range(hitStart, hitEnd + 1):\n genome[hit - 1] += 1\n\n for idx, val in enumerate(genome, 1):\n to_write = '{}\\t{}\\n'.format(idx, val)\n out.write(to_write)\n\n coverage_bp = len(genome) - genome.count(0)\n coverage_pc = coverage_bp / genome_length\n depth = sum(genome) / genome_length\n return coverage_bp, coverage_pc, depth\n\ndef format_report(query, subject, length: int, coverage_bp: int, coverage_pc: float,\n depth: float, num_reads: int, outpath: Path) -> None:\n\n out = '''Mapping: {}\n Against: {}\n Reference sequence length in bp: {}\n Coverage in bp: {}\n % Coverage: {}\n Average depth of coverage: {}\n Number of reads contributing to assembly: {}\n '''.format(query, subject, length, coverage_bp,\n coverage_pc, depth, num_reads)\n\n outpath.write_text(out)\n\ndef plot_reads_to_acc(snap_rap: Path, acc: str, genus: str, workdir: Path, evalue: str, cores: int):\n\n fasta_text = get_genbank_fasta('fasta', acc)\n\n fastafile = (workdir / acc).with_suffix('.fasta')\n blast_out = fastafile.with_suffix('.blastout')\n blast_uniq = blast_out.with_suffix('.uniq.blastout')\n blast_map = blast_out.with_suffix('.map')\n extracted = blast_out.with_suffix('.uniq.ex.fasta')\n\n report_path = snap_rap.parent / '.'.join([snap_rap.stem, acc, genus, 'report'])\n\n fastafile.write_text(fasta_text)\n\n makeblastdb = ['makeblastdb', '-in', str(fastafile), '-dbtype', 'nucl']\n\n blastn = ['blastn', '-task', 'blastn', '-outfmt', '8', '-evalue', evalue,\n '-num_threads', str(cores), '-num_alignments', '1', str(fastafile),\n '-out', str(blast_out)]\n\n subprocess.check_call(makeblastdb)\n subprocess.check_call(blastn)\n\n uniq_blast_results(blast_out, blast_uniq)\n extract_to_fast(blast_uniq, snap_rap, extracted)\n\n with extracted.open('r') as fasta:\n\n record = SeqIO.read(fasta, 'fasta')\n genome_length = len(record.seq)\n\n coverage_bp, coverage_pc, depth = map_perfect_blast_to_genome(blast_out,\n blast_map,\n genome_length)\n\n num_reads = len(blast_uniq.read_text().splitlines())\n\n format_report(snap_rap, acc, genome_length, coverage_bp, coverage_pc,\n depth, num_reads, report_path)\n\n coverage_plot(str(blast_map), '{}_{}'.format(genus, acc))\n","sub_path":"coverage_generator.py","file_name":"coverage_generator.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"562306715","text":"def interface():\n\tprint(\"My Program\")\n\twhile True:\n\t\tprint(\"Options\")\n\t\tprint(\"1 - HDL\")\n\t\tprint(\"2 - LDL\")\n\t\tprint(\"3 - Total Cholesterol\")\n\t\tprint(\"9 - Quit\")\n\t\tchoice = input(\"Enter your choice: \")\n\t\tif choice == '9':\n\t\t\treturn\n\t\telif choice == '1':\n\t\t\tHDL_driver()\n\t\telif choice == '2':\n\t\t\tLDL_driver()\n\t\telif choice == '3':\n\t\t\ttotal_driver()\n\n\ndef HDL_driver():\n\t# Get input\n\tHDL_result = get_test_result_input(\"HDL\")\n\t# Check if HDL is normal\n\tHDL_analysis = analyze_HDL_result(HDL_result)\n\t# Output\n\toutput_test_analysis(\"HDL\", HDL_result, HDL_analysis)\n\ndef get_test_result_input(test_name):\n\ttest_result = input(f\"Enter the {test_name} result: \")\n\treturn int(test_result)\n\ndef output_test_analysis(test_name, test_result, analysis):\n\tprint(\"The {} result is {}\".format(test_name, test_result))\n\tprint(\"That is {}\".format(analysis))\n\n# def get_HDL_input():\n# \tHDL_input = input(\"Enter the HDL test result: \")\n# \treturn int(HDL_input)\n\ndef analyze_HDL_result(HDL_test_value):\n\tif HDL_test_value >= 60:\n\t\treturn \"Normal\"\n\telif 40 <= HDL_test_value < 60:\n\t\treturn \"Borderline Low\"\n\telse:\n\t\treturn \"Low\"\n\n# def output_HDL_analysis(test_result, analysis):\n# \tprint(\"This HDL result is {}\".format(test_result))\n# \tprint(\"That is {}\".format(analysis))\n\t\t\ndef LDL_driver():\n\t# Get input\n\tLDL_result = get_test_result_input(\"LDL\")\n\t# Check if HDL is normal\n\tLDL_analysis = analyze_LDL_result(LDL_result)\n\t# Output\n\toutput_test_analysis(\"LDL\",LDL_result, LDL_analysis)\n\n\n# def get_LDL_input():\n# \tLDL_input = input(\"Enter the LDL test result: \")\n# \treturn int(LDL_input)\n\ndef analyze_LDL_result(LDL_test_value):\n\tif LDL_test_value < 130:\n\t\treturn \"Normal\"\n\telif 130 <= LDL_test_value < 160:\n\t\treturn \"Borderline High\"\n\telif 160 <= LDL_test_value < 190:\n\t\treturn \"High\"\n\telse:\n\t\treturn \"Very High\"\n\n# def output_LDL_analysis(test_result, analysis):\n# \tprint(\"This LDL result is {}\".format(test_result))\n# \tprint(\"That is {}\".format(analysis))\n\n\nif __name__ == \"__main__\":\n\tinterface()\n","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"123776644","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom appgame.views import *\n\nurlpatterns = [\n # Examples:\n # url(r'^$', 'game.views.home', name='home'),\n url(r'^$', say_hello),\n url(r'^status/$', show_versions),\n url(r'^players/$', show_players),\n url(r'^players/(?P[0-9]+)/$', verbose_player_info),\n url(r'^players/([\\w\\-\\.]+@[\\w\\.\\-]+)/$', show_money),\n# url(r'^players/$', get_money),\n url(r'^change_player/([0-9]+)/', change_player),\n url(r'^change_player_django_form/([0-9]+)/', change_player_django_form),\n url(r'^player_changed/([0-9]+)/', player_changed),\n\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"game/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"492086817","text":"# 714. 买卖股票的最佳时机含手续费\nclass Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n # 只交一次手续费,即买入的时候减去股钱和手续费\n dp_0 = 0\n dp_1 = - float('inf')\n for price in prices:\n dp_0 = max(dp_0, dp_1 + price)\n dp_1 = max(dp_1, dp_0 - fee - price)\n return dp_0","sub_path":"Week_04/best-time-to-buy-and-sell-stock-with-transaction-fee.py","file_name":"best-time-to-buy-and-sell-stock-with-transaction-fee.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"477705698","text":"import os\nimport json\nimport time\nimport random\nfrom mininet.topo import Topo\nfrom mininet.cli import CLI\n\nclass Single(Topo):\n def __init__(self):\n Topo.__init__(self)\n \n # Add hosts and switches\n controller = self.addHost('c')\n app = self.addHost('a')\n batcher = self.addHost('b1')\n filter = self.addHost('f1')\n queue = self.addHost('q1')\n maintainer = self.addHost('m1')\n switch = self.addSwitch('s1')\n client = self.addHost('client')\n\n # Add links\n self.addLink(controller, switch)\n self.addLink(app, switch)\n self.addLink(batcher, switch)\n self.addLink(filter, switch)\n self.addLink(queue, switch)\n self.addLink(maintainer, switch)\n self.addLink(client, switch)\n\nclass Simple(Topo):\n def __init__(self):\n Topo.__init__(self)\n\n # Add hosts and switches\n controller = self.addHost('c')\n app = self.addHost('a')\n batcher1 = self.addHost('b1')\n batcher2 = self.addHost('b2')\n batcher3 = self.addHost('b3')\n filter1 = self.addHost('f1')\n queue1 = self.addHost('q1')\n queue2 = self.addHost('q2')\n queue3 = self.addHost('q3')\n maintainer1 = self.addHost('m1')\n switch1 = self.addSwitch('s1')\n client = self.addHost('client')\n\n # Add links\n self.addLink(controller, switch1)\n self.addLink(app, switch1)\n self.addLink(batcher1, switch1)\n self.addLink(batcher2, switch1)\n self.addLink(batcher3, switch1)\n self.addLink(filter1, switch1)\n self.addLink(queue1, switch1)\n self.addLink(queue2, switch1)\n self.addLink(queue3, switch1)\n self.addLink(maintainer1, switch1)\n self.addLink(client, switch1)\n\nclass Double(Topo):\n def __init__(self):\n Topo.__init__(self)\n\n # Cluster 0\n app01 = self.addHost('a01')\n controller01 = self.addHost('c01')\n batcher01 = self.addHost('b01')\n filter01 = self.addHost('f01')\n filter02 = self.addHost('f02')\n queue01 = self.addHost('q01')\n maintainer01 = self.addHost('m01')\n switch0 = self.addSwitch('s0')\n client0 = self.addHost('client0')\n self.addLink(app01, switch0)\n self.addLink(controller01, switch0)\n self.addLink(batcher01, switch0)\n self.addLink(filter01, switch0)\n self.addLink(filter02, switch0)\n self.addLink(queue01, switch0)\n self.addLink(maintainer01, switch0)\n self.addLink(client0, switch0)\n\n # Cluster 1\n app11 = self.addHost('a11')\n controller11 = self.addHost('c11')\n batcher11 = self.addHost('b11')\n filter11 = self.addHost('f11')\n filter12 = self.addHost('f12')\n queue11 = self.addHost('q11')\n maintainer11 = self.addHost('m11')\n switch1 = self.addSwitch('s1')\n client1 = self.addHost('client1')\n self.addLink(app11, switch1)\n self.addLink(controller11, switch1)\n self.addLink(batcher11, switch1)\n self.addLink(filter11, switch1)\n self.addLink(filter12, switch1)\n self.addLink(queue11, switch1)\n self.addLink(maintainer11, switch1)\n self.addLink(client1, switch1)\n\n # Connect the switches\n self.addLink(switch0, switch1, bw=10, delay='100ms', max_queue_size=1000, loss=0, use_htb=True)\n\ndef init(self, args):\n \"init starts a single sinple cluster\"\n args = args.split()\n if len(args) == 0:\n print('Please specify the topology')\n return\n topo = args[0]\n if len(args) < 2:\n gopath = os.path.join(os.getenv('HOME'), 'go')\n else:\n if args[1] == 'vagrant':\n gopath = '/home/vagrant/go'\n else:\n gopath = args[1]\n net = self.mn\n if topo == 'single':\n net.get('c').cmd(os.path.join(gopath, 'bin', 'gochariots-controller') + ' 8081 1 0 > c.log &')\n net.get('a').cmd(os.path.join(gopath, 'bin', 'gochariots-app') + ' 8080 1 0 > a.log &')\n net.get('b1').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9000 1 0 > b.log &')\n net.get('f1').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9010 1 0 > f.log &')\n net.get('q1').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9020 1 0 true > q.log &')\n net.get('m1').cmd(os.path.join(gopath, 'bin', 'gochariots-maintainer') + ' 9030 1 0 > m.log &')\n\n # Wait for controller and app running\n time.sleep(2)\n\n c_ip = net.get('c').IP()\n a_ip = net.get('a').IP()\n b1_ip = net.get('b1').IP()\n f1_ip = net.get('f1').IP()\n q1_ip = net.get('q1').IP()\n m1_ip = net.get('m1').IP()\n print(net.get('client').cmd('curl -XPOST ' + a_ip + ':8080/batcher?host=' + b1_ip + ':9000'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/batcher?host=' + b1_ip + ':9000'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/filter?host=' + f1_ip + ':9010'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/queue?host=' + q1_ip + ':9020'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/maintainer?host=' + m1_ip + ':9030'))\n if topo == 'simple':\n net.get('c').cmd(os.path.join(gopath, 'bin', 'gochariots-controller') + ' 8081 1 0 > c.log &')\n net.get('a').cmd(os.path.join(gopath, 'bin', 'gochariots-app') + ' 8080 1 0 > a.log &')\n net.get('b1').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9000 1 0 > b1.log &')\n net.get('b2').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9001 1 0 > b2.log &')\n net.get('b3').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9002 1 0 > b3.log &')\n net.get('f1').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9010 1 0 > f1.log &')\n net.get('q1').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9020 1 0 true > q1.log &')\n net.get('q2').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9021 1 0 false > q2.log &')\n net.get('q3').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9022 1 0 false > q3.log &')\n net.get('m1').cmd(os.path.join(gopath, 'bin', 'gochariots-maintainer') + ' 9030 1 0 > m1.log &')\n\n # Wait for controller and app running\n time.sleep(2)\n\n c_ip = net.get('c').IP()\n a_ip = net.get('a').IP()\n b1_ip = net.get('b1').IP()\n b2_ip = net.get('b2').IP()\n b3_ip = net.get('b3').IP()\n f1_ip = net.get('f1').IP()\n q1_ip = net.get('q1').IP()\n q2_ip = net.get('q2').IP()\n q3_ip = net.get('q3').IP()\n m1_ip = net.get('m1').IP()\n print(net.get('client').cmd('curl -XPOST ' + a_ip + ':8080/batcher?host=' + b1_ip + ':9000'))\n print(net.get('client').cmd('curl -XPOST ' + a_ip + ':8080/batcher?host=' + b2_ip + ':9001'))\n print(net.get('client').cmd('curl -XPOST ' + a_ip + ':8080/batcher?host=' + b3_ip + ':9002'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/batcher?host=' + b1_ip + ':9000'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/batcher?host=' + b2_ip + ':9001'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/batcher?host=' + b3_ip + ':9002'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/filter?host=' + f1_ip + ':9010'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/queue?host=' + q1_ip + ':9020'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/queue?host=' + q2_ip + ':9021'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/queue?host=' + q3_ip + ':9022'))\n print(net.get('client').cmd('curl -XPOST ' + c_ip + ':8081/maintainer?host=' + m1_ip + ':9030'))\n if topo == 'double':\n net.get('a01').cmd(os.path.join(gopath, 'bin', 'gochariots-app') + ' 8080 2 0 > a01.log &')\n net.get('c01').cmd(os.path.join(gopath, 'bin', 'gochariots-controller') + ' 8081 2 0 > c01.log &')\n net.get('b01').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9000 2 0 > b01.log &')\n net.get('f01').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9010 2 0 > f01.log &')\n net.get('f02').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9011 2 0 > f02.log &')\n net.get('q01').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9020 2 0 true > q01.log &')\n net.get('m01').cmd(os.path.join(gopath, 'bin', 'gochariots-maintainer') + ' 9030 2 0 > m01.log &')\n net.get('a11').cmd(os.path.join(gopath, 'bin', 'gochariots-app') + ' 8080 2 1 > a11.log &')\n net.get('c11').cmd(os.path.join(gopath, 'bin', 'gochariots-controller') + ' 8081 2 1 > c11.log &')\n net.get('b11').cmd(os.path.join(gopath, 'bin', 'gochariots-batcher') + ' 9100 2 1 > b11.log &')\n net.get('f11').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9110 2 1 > f11.log &')\n net.get('f12').cmd(os.path.join(gopath, 'bin', 'gochariots-filter') + ' 9111 2 1 > f12.log &')\n net.get('q11').cmd(os.path.join(gopath, 'bin', 'gochariots-queue') + ' 9120 2 1 true > q11.log &')\n net.get('m11').cmd(os.path.join(gopath, 'bin', 'gochariots-maintainer') + ' 9130 2 1 > m11.log &')\n\n # Wait for controller and app running\n time.sleep(1)\n\n a01_ip = net.get('a01').IP()\n c01_ip = net.get('c01').IP()\n b01_ip = net.get('b01').IP()\n f01_ip = net.get('f01').IP()\n f02_ip = net.get('f02').IP()\n q01_ip = net.get('q01').IP()\n m01_ip = net.get('m01').IP()\n a11_ip = net.get('a11').IP()\n c11_ip = net.get('c11').IP()\n b11_ip = net.get('b11').IP()\n f11_ip = net.get('f11').IP()\n f12_ip = net.get('f12').IP()\n q11_ip = net.get('q11').IP()\n m11_ip = net.get('m11').IP()\n\n print(net.get('client0').cmd('curl -XPOST ' + a01_ip + ':8080/batcher?host=' + b01_ip + ':9000'))\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/batcher?host=' + b01_ip + ':9000'))\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/filter?host=' + f01_ip + ':9010'))\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/filter?host=' + f02_ip + ':9011'))\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/queue?host=' + q01_ip + ':9020'))\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/maintainer?host=' + m01_ip + ':9030'))\n\n print(net.get('client1').cmd('curl -XPOST ' + a11_ip + ':8080/batcher?host=' + b11_ip + ':9100'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/batcher?host=' + b11_ip + ':9100'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/filter?host=' + f11_ip + ':9110'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/filter?host=' + f12_ip + ':9111'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/queue?host=' + q11_ip + ':9120'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/maintainer?host=' + m11_ip + ':9130'))\n\n print(net.get('client0').cmd('curl -XPOST ' + c01_ip + ':8081/remote/batcher?dc=1\\&host=' + b11_ip + ':9100'))\n print(net.get('client1').cmd('curl -XPOST ' + c11_ip + ':8081/remote/batcher?dc=0\\&host=' + b01_ip + ':9000'))\n\n print('If anything wrong, try to restart mininet and run init again with GOPATH specified.')\n print('Example: mininet> init single /home/vagrant/go')\ndef log(self, node):\n \"log shows the log of a node\"\n net = self.mn\n try:\n n = net.get(node)\n except KeyError:\n print('Node ' + node + ' doesn\\'t exist')\n return\n print(n.cmd('cat ' + node + '.log'))\n\ndef post(self, args):\n \"post posts json file to the app\"\n \"post dc_id jsonfile\"\n args = args.split()\n if len(args) == 0:\n print('Please specify json filename')\n return\n jsonfile = args[0]\n net = self.mn\n if len(args) == 2:\n n = net.get('a' + args[1] + '1')\n client = net.get('client' + args[1])\n else:\n n = net.get('a')\n client = net.get('client')\n print(client.cmd('curl -i -XPOST -H \"Content-Type: application/json\" -d \"@' + jsonfile + '\" http://' + n.IP() + ':8080/record'))\n\ndef random_post(self, args):\n \"random_post randomly post records with dependency\"\n \"random_post num_records dependency_prob max_window margin\"\n args = args.split()\n if (len(args) < 4):\n print('random_post num_records dependency_prob max_window margin')\n return\n n = int(args[0])\n dependency_prob = float(args[1])\n max_window = int(args[2])\n margin = int(args[3])\n net = self.mn\n url = [net.get('a01').IP(), net.get('a11').IP()] # Add more app IPs if desired\n for i in range(n):\n value = str(i + 1)\n host_id = random.randint(0, len(url) - 1)\n client = net.get('client' + str(host_id))\n sent = False\n while sent == False:\n if random.random() < dependency_prob:\n key = 'low'\n pretoid = int(max(0, (i - random.randint(1, max_window) - margin) / len(url)))\n else:\n key = 'high'\n pretoid = 0\n payload = json.dumps({'tags': {key: value}, 'prehost': host_id, 'pretoid': pretoid}).replace('\"', '\\\\\"')\n host = 'http://' + str(url[host_id]) + ':8080/record'\n print('curl -i -XPOST -H \"Content-Type: application/json\" -d \"' + payload + '\" ' + host)\n result = client.cmd('curl -i -XPOST -H \"Content-Type: application/json\" -d \"' + payload + '\" ' + host)\n if result.startswith('HTTP/1.1 200 OK'):\n sent = True\n else:\n time.sleep(1)\n\ndef get(self, lid):\n \"get gets the content of record\"\n if lid == '':\n print('Please specify LId')\n return\n net = self.mn\n n = net.get('a')\n client = net.get('client')\n print(client.cmd('curl -XGET -H \"Accept: application/json\" http://' + n.IP() + ':8080/record/' + lid))\n\nCLI.do_init = init\nCLI.do_log = log\nCLI.do_post = post\nCLI.do_random_post = random_post\nCLI.do_get = get\n\ntopos = {\n 'single': (lambda: Single()),\n 'simple': (lambda: Simple()),\n 'double': (lambda: Double())\n }\n","sub_path":"test/mininet/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":14381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"322661844","text":"#coding: UTF-8\nimport random\n\n\nclass NormalPoeat:\n def __init__(self, grammar, vocabulary):\n self.grammar = grammar\n self.vocabulary = vocabulary\n\n def get_random_word(self, wordlist):\n return wordlist[random.randrange(0, len(wordlist))]\n\n def nianshi(self):\n temp = self.get_random_word(self.grammar)\n for i in range(5):\n for word in list(self.vocabulary.keys()):\n temp = temp.replace(word, self.vocabulary[word][random.randrange(\n 0, len(self.vocabulary[word]))], 1)\n print(temp)\n\n\nvocabulary = {}\n\ngrammar = [\"我从TIME的PLAC中VERB\", \"我VERB的ANIMAL的ORGAN令我的心VERB\", \"PERSVERB在那COLO的PLAC\", \"VERB出ADJ的呼喊\",\n \"是那NUMNOUN,NUMNOUN,NUMNOUN\", \"ONOM从NOUN到NOUN\", \"ANIMAL的ORGAN从PLACADJ的VERB\", \"COLOPLAC的故事在时光中VERB\",\n \"ONOM我感谢你,ADJ的ANIMAL神\", \"PERS的COLOORGAN牵动着PERS\"]\nvocabulary[\"TIME\"] = [\"清晨\", \"晌午\", \"黄昏\", \"夜半\"]\nvocabulary[\"VERB\"] = [\"诞生\", \"降生\", \"出生\", \"伊始\", \"坠落\"]\nvocabulary[\"ADJ\"] = [\"光滑\", \"怠惰\", \"筋疲力竭\",\n \"声嘶力竭\", \"七上八下\", \"响彻云霄\", \"滑稽\", \"圣洁\", \"寂寥\"]\nvocabulary[\"ONOM\"] = [\"啊!\", \"呀!\", \"嘿咻!\",\n \"哈呀!\", \"乌拉拉!\", \"玛卡巴卡!\", \"唔西迪西!\", \"依古比古!\"]\nvocabulary[\"PERS\"] = [\"你\", \"我\", \"它\"]\nvocabulary[\"COLO\"] = [\"金黄色\", \"柠檬绿色\", \"玫红色\", \"魅惑蓝\", \"幻影紫\", \"象牙白\"]\nvocabulary[\"PLAC\"] = [\"尼罗河\", \"井冈山\", \"玉琼顶\",\n \"九重天\", \"阿斯加德\", \"约顿海姆\", \"尼福尔海姆和海姆冥界\", \"梵蒂冈\"]\nvocabulary[\"ANIMAL\"] = [\"圣甲虫\",\"地狱双头犬\",\"印度战象\",\"猪人\",\"末影龙\",\"苦力怕\",\"暴风女\"]\nvocabulary[\"ORGAN\"] = [\"十二指肠\", \"左脚小脚趾盖\", \"右脚中脚趾\",\n \"大肠末节\", \"阑尾\", \"左心房\", \"右心室\", \"小脑中叶\", \"骨髓灰质\"]\nvocabulary[\"NOUN\"] = [\"麻布\", \"皮带\", \"月牙\", \"树梢\", \"落叶\", \"卢浮宫\",\n \"埃菲尔铁塔\", \"波音747\", \"狮身人面像\", \"月光宝盒\", \"犹大\", \"以撒\", \"桐人\", \"兔女郎学姐\"]\nvocabulary[\"NUM\"] = [\"一弄\", \"两枝\", \"三朵\", \"六条\", \"十栋\", \"百匹\", \"千张\", \"万卷\"]\n\n\nif __name__ == \"__main__\":\n rocky = NormalPoeat(grammar, vocabulary)\n for i in range(20):\n rocky.nianshi()\n","sub_path":"RTC11#1/VSNQ1/E_Poet.py","file_name":"E_Poet.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20275270","text":"import os\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Assumption: all files that are required are in one directory and he have files for interesting dates\ndef plotBySkill():\n final_job = 'software+engineer'\n all_frames = []\n num_of_all_vacancies = 0\n target_term='Java'\n\n directory = 'd:\\\\Magister\\\\WebScraping\\\\data\\\\'\n\n for filename in os.listdir(directory):\n if filename.endswith(\".json\"):\n frame = pd.read_json(os.path.join(directory, filename), orient='table')\n num_of_all_vacancies = num_of_all_vacancies + frame.NumOfVacancies[0]\n frame = frame.drop('NumOfVacancies', 1)\n all_frames.append(frame)\n\n final_frame = pd.DataFrame(columns=['Term', 'NumPostings'])\n final_dict = {}\n\n for frame in all_frames:\n dicts = frame.to_dict('records')\n for dict in dicts:\n if dict['Term'] == target_term:\n final_dict[dict['Date'].date()] = dict['NumPostings']\n\n final_dict = {\n 'Date': final_dict.keys(),\n 'NumPostings': final_dict.values()\n }\n\n final_frame = final_frame.from_dict(final_dict)\n final_frame.NumPostings = (final_frame.NumPostings) * 100 / num_of_all_vacancies\n final_frame.sort_values(by='Date', ascending=True, inplace=True)\n\n final_plot = final_frame.plot(x='Date', y='NumPostings', kind='bar', legend=None,\n title='Percentage of ' + final_job.replace('+', ' ') + ' Job Ads with a Key Skill, ', rot=0)\n\n final_plot.set_ylabel('Percentage Appearing in Job Ads')\n fig = final_plot.get_figure()\n # plt.show(fig)\n plt.show()\n return fig, final_frame\n","sub_path":"PlotBySkill.py","file_name":"PlotBySkill.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"167819228","text":"\n\"\"\"\nCopyright (c) Microsoft Corporation.\nLicensed under the MIT License.\n\"\"\"\n\nfrom mistune import Markdown\nfrom mechanical_markdown.parsers import RecipeParser, end_token, MarkdownAnnotationError\n\n\nclass Recipe:\n def __init__(self, markdown):\n parser = RecipeParser()\n md = Markdown(parser, extensions=('fenced-code',))\n md(markdown)\n if parser.current_step is not None:\n raise MarkdownAnnotationError('Reached end of input searching for '.format(end_token))\n self.all_steps = parser.all_steps\n\n def exectute_steps(self, manual, default_shell='bash -c'):\n success = True\n report = \"\"\n for step in self.all_steps:\n if not step.run_all_commands(manual, default_shell):\n success = False\n break\n\n for step in self.all_steps:\n if not step.wait_for_all_background_commands():\n success = False\n\n s, r = step.validate_and_report()\n if not s:\n success = False\n report += r\n return success, report\n\n def dryrun(self, default_shell='bash -c'):\n retstr = \"\"\n for step in self.all_steps:\n retstr += step.dryrun(default_shell)\n\n return retstr\n","sub_path":"mechanical_markdown/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"394444407","text":"import os\nfrom app import blueprint\nfrom app.main import create_app, config\n\nenv = config.env\n\napp = create_app(env, config.configFile)\napp.register_blueprint(blueprint)\n\napp.app_context().push()\nprint('DEBUG : ' + str(app.debug))\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8888)\n","sub_path":"openstack-billing/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173431090","text":"from dataclasses import dataclass\nfrom typing import Optional\n\nfrom xsdata.codegen.mixins import ContainerInterface\nfrom xsdata.codegen.mixins import HandlerInterface\nfrom xsdata.codegen.models import Attr\nfrom xsdata.codegen.models import AttrType\nfrom xsdata.codegen.models import Class\nfrom xsdata.codegen.models import Extension\nfrom xsdata.codegen.utils import ClassUtils\nfrom xsdata.logger import logger\nfrom xsdata.models.enums import DataType\nfrom xsdata.models.enums import NamespaceType\nfrom xsdata.models.enums import Tag\nfrom xsdata.models.xsd import ComplexType\nfrom xsdata.models.xsd import SimpleType\n\n\n@dataclass\nclass ClassExtensionHandler(HandlerInterface):\n \"\"\"Reduce class extensions by copying or creating new attributes.\"\"\"\n\n INCLUDES_NONE = 0\n INCLUDES_SOME = 1\n INCLUDES_ALL = 2\n\n container: ContainerInterface\n\n def process(self, target: Class):\n \"\"\"\n Iterate and process the target class's extensions in reverser order.\n\n The reverse order is necessary in order to maintain the correct\n attributes ordering during cloning.\n \"\"\"\n for extension in reversed(target.extensions):\n self.process_extension(target, extension)\n\n def process_extension(self, target: Class, extension: Extension):\n \"\"\"Slit the process of extension into schema data types and user\n defined types.\"\"\"\n if extension.type.native:\n self.process_native_extension(target, extension)\n else:\n self.process_dependency_extension(target, extension)\n\n @classmethod\n def process_native_extension(cls, target: Class, extension: Extension):\n \"\"\"\n Native type flatten handler.\n\n In case of enumerations copy the native data type to all enum\n members, otherwise create a default text value with the\n extension attributes.\n \"\"\"\n if target.is_enumeration:\n cls.copy_extension_type(target, extension)\n else:\n cls.create_default_attribute(target, extension)\n\n def process_dependency_extension(self, target: Class, extension: Extension):\n \"\"\"User defined type flatten handler.\"\"\"\n source = self.find_dependency(extension.type)\n if not source:\n logger.warning(\"Missing extension type: %s\", extension.type.name)\n target.extensions.remove(extension)\n elif not source.is_complex or source.is_enumeration:\n self.process_simple_extension(source, target, extension)\n else:\n self.process_complex_extension(source, target, extension)\n\n @classmethod\n def process_simple_extension(cls, source: Class, target: Class, ext: Extension):\n \"\"\"\n Simple flatten extension handler for common classes eg SimpleType,\n Restriction.\n\n Steps:\n 1. If target is source: drop the extension.\n 2. If source is enumeration and target isn't create default value attribute.\n 3. If both source and target are enumerations copy all attributes.\n 4. If both source and target are not enumerations copy all attributes.\n 5. If target is enumeration: drop the extension.\n \"\"\"\n if source is target:\n target.extensions.remove(ext)\n elif source.is_enumeration and not target.is_enumeration:\n cls.create_default_attribute(target, ext)\n elif source.is_enumeration == target.is_enumeration:\n ClassUtils.copy_attributes(source, target, ext)\n else: # this is an enumeration\n target.extensions.remove(ext)\n\n @classmethod\n def process_complex_extension(cls, source: Class, target: Class, ext: Extension):\n \"\"\"\n Complex flatten extension handler for primary classes eg ComplexType,\n Element.\n\n Drop extension when:\n - source includes all target attributes\n Copy all attributes when:\n - source includes some of the target attributes\n - source has suffix attribute and target has at least one attribute\n - target has at least one suffix attribute\n - source is marked as strict type\n \"\"\"\n res = cls.compare_attributes(source, target)\n if res == cls.INCLUDES_ALL:\n target.extensions.remove(ext)\n elif (\n res == cls.INCLUDES_SOME\n or source.strict_type\n or (source.has_suffix_attr and len(target.attrs) > 0)\n or target.has_suffix_attr\n ):\n ClassUtils.copy_attributes(source, target, ext)\n\n def find_dependency(self, attr_type: AttrType) -> Optional[Class]:\n \"\"\"\n Find dependency for the given extension type with priority.\n\n Search priority: xs:SimpleType > xs:ComplexType\n \"\"\"\n\n conditions = (\n lambda x: x.type is SimpleType,\n lambda x: x.type is ComplexType,\n )\n\n for condition in conditions:\n result = self.container.find(attr_type.qname, condition=condition)\n if result:\n return result\n\n return None\n\n @classmethod\n def compare_attributes(cls, source: Class, target: Class) -> int:\n \"\"\"Compare the attributes of the two classes and return whether the\n source includes all, some or none of the target attributes.\"\"\"\n if source is target:\n return cls.INCLUDES_ALL\n\n if not target.attrs or not source.attrs:\n return cls.INCLUDES_NONE\n\n source_attrs = {attr.name for attr in source.attrs}\n target_attrs = {attr.name for attr in target.attrs}\n difference = source_attrs - target_attrs\n\n if not difference:\n return cls.INCLUDES_ALL\n if len(difference) != len(source_attrs):\n return cls.INCLUDES_SOME\n\n return cls.INCLUDES_NONE\n\n @classmethod\n def copy_extension_type(cls, target: Class, extension: Extension):\n \"\"\"Add the given extension type to all target attributes types and\n remove it from the target class extensions.\"\"\"\n\n for attr in target.attrs:\n attr.types.append(extension.type.clone())\n target.extensions.remove(extension)\n\n @classmethod\n def create_default_attribute(cls, item: Class, extension: Extension):\n \"\"\"Add a default value field to the given class based on the extension\n type.\"\"\"\n if extension.type.native_code == DataType.ANY_TYPE.code:\n attr = Attr(\n name=\"any_element\",\n local_name=\"any_element\",\n index=0,\n default=list if extension.restrictions.is_list else None,\n types=[extension.type.clone()],\n tag=Tag.ANY,\n namespace=NamespaceType.ANY.value,\n restrictions=extension.restrictions.clone(),\n )\n else:\n attr = Attr(\n name=\"value\",\n local_name=\"value\",\n index=0,\n default=None,\n types=[extension.type.clone()],\n tag=Tag.EXTENSION,\n restrictions=extension.restrictions.clone(),\n )\n\n item.attrs.insert(0, attr)\n item.extensions.remove(extension)\n","sub_path":"xsdata/codegen/handlers/class_extension.py","file_name":"class_extension.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"489898666","text":"import transaction\nfrom webserver.db import DB\nfrom os import path\nimport sys\n\n\nsys.path.append('./apps')\nurl = 'sqlite:///%s/datas/test.sqlite' % path.abspath('.')\nsettings = { 'sqlalchemy.url': url}\ndb = DB(settings)\n\nwith transaction.manager:\n session = db.create_session(transaction.manager)\n\n from origin.models.server_datas import ServerData\n model = ServerData(name='one', value='F.Q.')\n session.add(model)\n\n from other.models.other_datas import OtherData\n model = OtherData(name='test 1', value='value 1')\n session.add(model)\n model = OtherData(name='test 2', value='value 2')\n session.add(model)\n model = OtherData(name='test 3', value='value 3')\n session.add(model)\n","sub_path":"Python/webserver_Pyramid-based/webserver/__tmpl__/init_test_data.py","file_name":"init_test_data.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"443451272","text":"## @file AthenaPoolExample_AppendJobOptions.py\n## @brief Example job options file to illustrate how to append event data to an existing Pool file.\n## @author Peter van Gemmeren \n## $Id: AthenaPoolExample_AppendJobOptions.py,v 1.16 2008-09-29 15:25:22 gemmeren Exp $\n###############################################################\n#\n# This Job option:\n# ----------------\n# 1. Updates (appends to) SimplePoolFile2.root file with EventInfo and EventStreamInfo MetaData.\n# ------------------------------------------------------------\n# Expected output file (20 + 20 events):\n# -rw-r--r-- 1 gemmeren zp 31305 Aug 5 17:23 SimplePoolFile2.root\n# ------------------------------------------------------------\n# File:SimplePoolFile2.root\n# Size: 30.571 kb\n# Nbr Events: 40\n# \n# ================================================================================\n# Mem Size Disk Size Size/Evt MissZip/Mem items (X) Container Name (X=Tree|Branch)\n# ================================================================================\n# 17.616 kb 2.791 kb 0.070 kb 0.000 40 (T) DataHeader\n# --------------------------------------------------------------------------------\n# 6.089 kb 0.601 kb 0.015 kb 0.182 40 (B) EventInfo_p3_McEventInfo\n# 3.454 kb 0.854 kb 0.021 kb 0.465 2 (T) MetaDataHdrDataHeaderForm\n# 18.440 kb 1.188 kb 0.030 kb 0.383 1 (B) EventStreamInfo_p2_Stream2\n# 18.440 kb 1.188 kb 0.030 kb 0.383 1 (B) EventStreamInfo_p2_Stream1\n# 14.169 kb 1.290 kb 0.032 kb 0.113 40 (T) POOLContainer_DataHeaderForm\n# 11.495 kb 1.808 kb 0.045 kb 0.349 2 (T) MetaDataHdrDataHeader\n# ================================================================================\n# 89.704 kb 9.719 kb 0.243 kb 0.000 40 TOTAL (POOL containers)\n# ================================================================================\n#\n#==============================================================\n\n## basic (generator) job configuration\nimport AthenaCommon.AtlasUnixGeneratorJob\n\n## get a handle on the default top-level algorithm sequence\nfrom AthenaCommon.AlgSequence import AlgSequence\ntopSequence = AlgSequence()\n\n## get a handle on the ServiceManager\nfrom AthenaCommon.AppMgr import ServiceMgr as svcMgr\n\n#--------------------------------------------------------------\n# Event related parameters\n#--------------------------------------------------------------\nfrom AthenaCommon.AppMgr import theApp\ntheApp.EvtMax = 20\n\n#--------------------------------------------------------------\n# Load POOL support\n#--------------------------------------------------------------\nimport AthenaPoolCnvSvc.WriteAthenaPool\n\nsvcMgr.EventSelector.RunNumber = 2\n#Set first event number to 20 (to continue previous production)\nsvcMgr.EventSelector.FirstEvent = 20;\n\n#Explicitly specify the output file catalog\nsvcMgr.PoolSvc.WriteCatalog = \"xmlcatalog_file:Catalog1.xml\"\n\n#Open file in \"update\" mode\nsvcMgr.PoolSvc.FileOpen = \"update\";\n\n#--------------------------------------------------------------\n# Private Application Configuration options\n#--------------------------------------------------------------\n# Load \"user algorithm\" top algorithms to be run, and the libraries that house them\nfrom AthenaPoolExampleAlgorithms.AthenaPoolExampleAlgorithmsConf import AthPoolEx__WriteData\ntopSequence += AthPoolEx__WriteData(\"WriteData\")\n\nfrom AthenaPoolExampleAlgorithms.AthenaPoolExampleAlgorithmsConf import AthPoolEx__WriteTag\nWriteTag = AthPoolEx__WriteTag( \"WriteTag\" )\nWriteTag.Magic = 1\ntopSequence += WriteTag\n\nfrom AthenaPoolCnvSvc.WriteAthenaPool import AthenaPoolOutputStream\nStream1 = AthenaPoolOutputStream ( \"Stream1\" , \"SimplePoolFile2.root\" )\nStream1.WritingTool.AttributeListKey = \"RunEventTag\"\n\n#--------------------------------------------------------------\n# Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL)\n#--------------------------------------------------------------\nsvcMgr.MessageSvc.OutputLevel = 3\nsvcMgr.PoolSvc.OutputLevel = 2\nsvcMgr.AthenaPoolCnvSvc.OutputLevel = 2\ntopSequence.WriteData.OutputLevel = 2\nStream1.OutputLevel = 2\nStream1.WritingTool.OutputLevel = 3\nStream1.HelperTools[0].OutputLevel = 3\n\n#\n# End of job options file\n#\n###############################################################\n","sub_path":"Database/AthenaPOOL/AthenaPoolExample/AthenaPoolExampleAlgorithms/share/AthenaPoolExample_AppendJobOptions.py","file_name":"AthenaPoolExample_AppendJobOptions.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"604772196","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# Imports\nimport urllib\nfrom io import BytesIO\nfrom zipfile import ZipFile\nimport pandas as pd\nimport requests\nfrom sqlalchemy import create_engine\nimport pyodbc\n\n# In[ ]:\n\n\n# In[ ]:\n\n# Load BEA CAINC5N_NC data\nresponse = requests.get(\"https://apps.bea.gov/regional/zip/CAINC5N.zip\")\nzip_file = ZipFile(BytesIO(response.content))\nfiles = zip_file.namelist()\nwith zip_file.open(files[34]) as csvfile:\n df = pd.read_csv(csvfile, encoding=\"ISO-8859-1\", sep=\",\")\n\n\n# In[ ]:\n\n\n# Check for unused fields\ndf.tail(10)\n\n\n# In[ ]:\n\n\n# Remove unused fields\ndf.drop(df.tail(4).index, inplace=True)\n\n\n# In[ ]:\n\n\n# Clean GeoFIPS\ndf[\"GeoFIPS\"] = df[\"GeoFIPS\"].str.replace('\"', \"\")\n\n\n# In[ ]:\n\n\n# Set GeoFIPS as Index\ndf.set_index(df[\"GeoFIPS\"], inplace=True)\n\n\n# In[ ]:\n\n\n# Drop GeoFIPS column\ndf.drop(\"GeoFIPS\", axis=1, inplace=True)\n\n\n# # Personal Income\n# In[ ]:\nprint(\"Updating Personal Income..\")\n\ndf_per_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Personal_Income.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_per_backup.to_csv(\"./Backups/STG_BEA_CA5N_Personal_Income_BACKUP.txt\")\n\nfilter1 = df[\"LineCode\"] == 10\ndf_per = df[filter1]\n\ndf_per.to_csv(\"./Updates/STG_BEA_CA5N_Personal_Income.txt\", sep=\"\\t\")\n\n# # Population\n\n# In[ ]:\nprint(\"Done. Updating Population..\")\n\ndf_pop_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Population.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_pop_backup.to_csv(\"./Backups/STG_BEA_CA5N_Population_BACKUP.txt\")\n\nfilter1 = df[\"LineCode\"] == 20\ndf_pop = df[filter1]\n\ndf_pop.to_csv(\"./Updates/STG_BEA_CA5N_Population.txt\", sep=\"\\t\")\n\n# # Per capita Personal Income\n\n# In[ ]:\n\nprint(\"Done. Updating Per Capita Personal Income..\")\n\ndf_pi_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Per_Capita_Personal_Income.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_pi_backup.to_csv(\"./Backups/STG_BEA_CA5N_Per_Capita_Personal_Income.txt\")\n\nfilter1 = df[\"LineCode\"] == 30\ndf_pi = df[filter1]\n\ndf_pi.to_csv(\"./Updates/STG_BEA_CA5N_Per_Capita_Personal_Income.txt\", sep=\"\\t\")\n\n# # Wages and Salaries\n\n# In[ ]:\n\n\nprint(\"Done. Updating Wages and Salaries..\")\n\n\n# In[ ]:\n\n\n# Create Backups\ndf_w_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Wages_and_Salaries.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_w_backup.to_csv(\"./Backups/STG_BEA_CA5N_Wages_and_Salaries_BACKUP.txt\")\n\n\n# In[ ]:\n\n\n# Create a new dataframe for wages and salaries\nfilter1 = df[\"LineCode\"] == 50\ndf_wages = df[filter1]\n\n\n# In[ ]:\n\n\n# Save as tab-delimited txt file for export to SSMS\ndf_wages.to_csv(\"./Updates/STG_BEA_CA5N_Wages_and_Salaries.txt\", sep=\"\\t\")\n\n\n# # Health Care and Social Assistance\n\n# In[ ]:\n\n\nprint(\"Done. Updating Health Care and Social Assistance..\")\n\n\n# In[ ]:\n\n\n# Create Backups\ndf_h_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Health_Care_and_Social_Assistance.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_h_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Health_Care_and_Social_Assistance_BACKUP.txt\"\n)\n\n\n# In[ ]:\n\n\n# Create a new dataframe for Health_Care_and_Social_Assistance\nfilter1 = df[\"LineCode\"] == 1600\ndf_health = df[filter1]\n\n\n# In[ ]:\n\n\n# Save as tab-delimited txt file for export to SSMS\ndf_health.to_csv(\n \"./Updates/STG_BEA_CA5N_Health_Care_and_Social_Assistance.txt\", sep=\"\\t\"\n)\n\n# # Information\n\n# In[ ]:\n\n\nprint(\"Done. Updating Information..\")\n\n\n# In[ ]:\n\n\n# Create Backups\ndf_i_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Information.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_i_backup.to_csv(\"./Backups/STG_BEA_CA5N_Information_BACKUP.txt\")\n\n\n# In[ ]:\n\n\n# Create new dataframe for Information\nfilter1 = df[\"LineCode\"] == 900\ndf_info = df[filter1]\n\n\n# In[ ]:\n\n\n# Save as tab-delimited txt file for export to SSMS\ndf_info.to_csv(\"./Updates/STG_BEA_CA5N_Information.txt\", sep=\"\\t\")\n\n\n# # Management of Companies and Enterprises\n\n# In[ ]:\n\n\nprint(\"Done. Updating Management of Companies and Enterprises..\")\n\n# Create Backups\ndf_mang_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Management_of_Companies_and_Enterprises.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_mang_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Management_of_Companies_and_Enterprises_BACKUP.txt\"\n)\n\n# Create new dataframe for Information\nfilter1 = df[\"LineCode\"] == 1300\ndf_management = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_management.to_csv(\n \"./Updates/STG_BEA_CA5N_Management_of_Companies_and_Enterprises.txt\", sep=\"\\t\"\n)\n\n# # Manufacturing\n\n# In[ ]:\n\n\nprint(\"Done. Updating Manufacturing..\")\n\n# Create Backups\ndf_manu_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Manufacturing.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_manu_backup.to_csv(\"./Backups/STG_BEA_CA5N_Manufacturing_BACKUP.txt\")\n\n# Create new dataframe for Manufacturing\nfilter1 = df[\"LineCode\"] == 500\ndf_manufacturing = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_manufacturing.to_csv(\"./Updates/STG_BEA_CA5N_Manufacturing.txt\", sep=\"\\t\")\n\n\n# # Mining, Quarrying, and Oil and Gas Production\n\n# In[ ]:\n\n\nprint(\"Done. Updating Mining, Quarrying, and Oil and Gas Production..\")\n\n# Create Backups\ndf_min_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Mining_Quarrying_and_Oil_and_Gas_Extraction.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_min_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Mining_Quarrying_and_Oil_and_Gas_Extraction_BACKUP.txt\"\n)\n\n# Create new dataframe for Mining_Quarrying_and_Oil_and_Gas_Extraction\nfilter1 = df[\"LineCode\"] == 200\ndf_mining = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_mining.to_csv(\n \"./Updates/STG_BEA_CA5N_Mining_Quarrying_and_Oil_and_Gas_Extraction.txt\", sep=\"\\t\"\n)\n\n\n# # Other Services\n\n# In[ ]:\n\n\nprint(\"Done. Updating Other Services..\")\n\n# Create Backups\ndf_ser_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Other_Services.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_ser_backup.to_csv(\"./Backups/STG_BEA_CA5N_Other_Services_BACKUP.txt\")\n\n# Create new dataframe for Other_Services\nfilter1 = df[\"LineCode\"] == 1900\ndf_services = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_services.to_csv(\"./Updates/STG_BEA_CA5N_Other_Services.txt\", sep=\"\\t\")\n\n\n# # Professional, Scientific, and Technical Services\n\n# In[ ]:\n\n\nprint(\"Done. Updating Professional Scientific and Technical Services..\")\n\n# Create Backups\ndf_pst_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Professional_Scientific_and_Technical_Services.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_pst_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Professional_Scientific_and_Technical_Services_BACKUP.txt\"\n)\n\n# Create new dataframe for Professional_Scientific_and_Technical_Services\nfilter1 = df[\"LineCode\"] == 1200\ndf_professional = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_professional.to_csv(\n \"./Updates/STG_BEA_CA5N_Professional_Scientific_and_Technical_Services.txt\",\n sep=\"\\t\",\n)\n\n# # Real Estate and Rental Housing\n\n# In[ ]:\n\n\nprint(\"Done. Updating Real Estate and Rental Housing..\")\n\n# Create Backups\ndf_hou_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Real_Estate_and_Rental_and_Leasing.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_hou_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Real_Estate_and_Rental_and_Leasing_BACKUP.txt\"\n)\n\n# Create new dataframe for Real_Estate_and_Rental_and_Leasing\nfilter1 = df[\"LineCode\"] == 1100\ndf_realestate = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_realestate.to_csv(\n \"./Updates/STG_BEA_CA5N_Real_Estate_and_Rental_and_Leasing.txt\", sep=\"\\t\"\n)\n\n\n# # Retail Trade\n\n# In[ ]:\n\n\nprint(\"Done. Updating Retail Trade..\")\n\n# Create Backups\ndf_r_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Retail_Trade.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_r_backup.to_csv(\"./Backups/STG_BEA_CA5N_Retail_Trade_BACKUP.txt\")\n\n# Create new dataframe for Retail_Trade\nfilter1 = df[\"LineCode\"] == 700\ndf_retail = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_retail.to_csv(\"./Updates/STG_BEA_CA5N_Retail_Trade.txt\", sep=\"\\t\")\n\n\n# # Transportation and Warehousing\n\n# In[ ]:\n\n\nprint(\"Done. Updating Transportation and Warehousing..\")\n\n# Create Backups\ndf_t_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Transportation_and_Warehousing.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_t_backup.to_csv(\"./Backups/STG_BEA_CA5N_Transportation_and_Warehousing_BACKUP.txt\")\n\n# Create new dataframe for Transportation_and_Warehousing\nfilter1 = df[\"LineCode\"] == 800\ndf_transportation = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_transportation.to_csv(\n \"./Updates/STG_BEA_CA5N_Transportation_and_Warehousing.txt\", sep=\"\\t\"\n)\n\n\n# # Utilities\n\n# In[ ]:\n\n\nprint(\"Done. Updating Utilities..\")\n\n# Create Backups\ndf_u_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Utilities.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_u_backup.to_csv(\"./Backups/STG_BEA_CA5N_Utilities_BACKUP.txt\")\n\n# Create new dataframe for Utilities\nfilter1 = df[\"LineCode\"] == 300\ndf_utilities = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_utilities.to_csv(\"./Updates/STG_BEA_CA5N_Utilities.txt\", sep=\"\\t\")\n\n# # Wholesale Trade\n\n# In[ ]:\n\n\nprint(\"Done. Updating Wholesale Trade..\")\n\n# Create Backups\ndf_wt_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Wholesale_Trade.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_wt_backup.to_csv(\"./Backups/STG_BEA_CA5N_Wholesale_Trade_BACKUP.txt\")\n\n# Create new dataframe for Wholesale_Trade\nfilter1 = df[\"LineCode\"] == 600\ndf_wholesale = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_wholesale.to_csv(\"./Updates/STG_BEA_CA5N_Wholesale_Trade.txt\", sep=\"\\t\")\n\n# # Proprietors' Income\n\n# In[ ]:\n\n\nprint(\"Done. Updating Proprietors Income..\")\n\n# Create Backups\ndf_pi_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Proprietors_Income.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_pi_backup.to_csv(\"./Backups/STG_BEA_CA5N_Proprietors_Income_BACKUP.txt\")\n\n# Create new dataframe for Proprietors_Income\nfilter1 = df[\"LineCode\"] == 70\ndf_propinc = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_propinc.to_csv(\"./Updates/STG_BEA_CA5N_Proprietors_Income.txt\", sep=\"\\t\")\n\n# # Government and Government Enterprises\n\n# In[ ]:\n\n\nprint(\"Done. Updating Government and Government Enterprises..\")\n\n# Create Backups\ndf_g_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Government_and_Government_Enterprises.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_g_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Government_and_Government_Enterprises_BACKUP.txt\"\n)\n\n# Create new dataframe for Government_and_Government_Enterprises\nfilter1 = df[\"LineCode\"] == 2000\ndf_gov = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_gov.to_csv(\n \"./Updates/STG_BEA_CA5N_Government_and_Government_Enterprises.txt\", sep=\"\\t\"\n)\n\n# # Private Nonfarm Compensation\n\n# In[ ]:\n\n\nprint(\"Done. Updating Private Nonfarm Compensation..\")\n\n# Create Backups\ndf_pnc_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Private_Nonfarm_Compensation.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_pnc_backup.to_csv(\"./Backups/STG_BEA_CA5N_Private_Nonfarm_Compensation_BACKUP.txt\")\n\n# Create new dataframe for Private_Nonfarm_Compensation\nfilter1 = df[\"LineCode\"] == 90\ndf_private = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_private.to_csv(\"./Updates/STG_BEA_CA5N_Private_Nonfarm_Compensation.txt\", sep=\"\\t\")\n\n# # Farm Compensation\n\n# In[ ]:\n\n\nprint(\"Done. Updating Farm Compensation..\")\n\n# Create Backups\ndf_fc_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Farm_Compensation.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_fc_backup.to_csv(\"./Backups/STG_BEA_CA5N_Farm_Compensation_BACKUP.txt\")\n\n# Create new dataframe for Farm_Compensation\nfilter1 = df[\"LineCode\"] == 81\ndf_farm = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_farm.to_csv(\"./Updates/STG_BEA_CA5N_Farm_Compensation.txt\", sep=\"\\t\")\n\n\n# # Nonfarm Compensation\n\n# In[ ]:\n\n\nprint(\"Done. Updating Nonfarm Compensation..\")\n\n# Create Backups\ndf_nf_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Nonfarm_Compensation.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_nf_backup.to_csv(\"./Backups/STG_BEA_CA5N_Nonfarm_Compensation_BACKUP.txt\")\n\n# Create new dataframe for Nonfarm_Compensation\nfilter1 = df[\"LineCode\"] == 82\ndf_nonfarm = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_nonfarm.to_csv(\"./Updates/STG_BEA_CA5N_Nonfarm_Compensation.txt\", sep=\"\\t\")\n\n\n# # Supplements to Wages and Salaries\n\n# In[ ]:\n\n\nprint(\"Done. Updating Supplements to Wages and Salaries..\")\n\n# Create Backups\ndf_supp_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Supplements_to_Wages_and_Salaries.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_supp_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Supplements_to_Wages_and_Salaries_BACKUP.txt\"\n)\n\n# Create new dataframe for Supplements_to_Wages_and_Salaries\nfilter1 = df[\"LineCode\"] == 60\ndf_supplement = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_supplement.to_csv(\n \"./Updates/STG_BEA_CA5N_Supplements_to_Wages_and_Salaries.txt\", sep=\"\\t\"\n)\n\n\n# # Federal, Civilian\n\n# In[ ]:\n\n\nprint(\"Done. Updating Govt Type Federal Civilian..\")\n\n# Create Backups\ndf_fcgov_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Federal_Civilian_Government.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_fcgov_backup.to_csv(\"./Backups/STG_BEA_CA5N_Federal_Civilian_Government_BACKUP.txt\")\n\n# Create new dataframe for Federal_Civilian_Government\nfilter1 = df[\"LineCode\"] == 2001\ndf_federal = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_federal.to_csv(\"./Updates/STG_BEA_CA5N_Federal_Civilian_Government.txt\", sep=\"\\t\")\n\n# # Accommodation and Food Services\n\n# In[ ]:\n\n\nprint(\"Done. Updating Accommodation and Food Services..\")\n\n# Create Backups\ndf_acc_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Accommodation_and_Food_Services.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_acc_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Accommodation_and_Food_Services_BACKUP.txt\"\n)\n\n# Create new dataframe for Accommodation_and_Food_Services\nfilter1 = df[\"LineCode\"] == 1800\ndf_food = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_food.to_csv(\"./Updates/STG_BEA_CA5N_Accommodation_and_Food_Services.txt\", sep=\"\\t\")\n\n# # Administrative Support\n\n# In[ ]:\n\n\nprint(\"Done. Updating Administrative Support..\")\n\n# Create Backups\ndf_as_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Administrative_and_Support_and_Waste_Management_and_Remediation_Services.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_as_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Administrative_and_Support_and_Waste_Management_and_Remediation_Services_BACKUP.txt\"\n)\n\n# Create new dataframe for Administrative_and_Support_and_Waste_Management_and_Remediation_Services\nfilter1 = df[\"LineCode\"] == 1400\ndf_admin = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_admin.to_csv(\n \"./Updates/STG_BEA_CA5N_Administrative_and_Support_and_Waste_Management_and_Remediation_Services.txt\",\n sep=\"\\t\",\n)\n\n# # Arts, Entertainment, and Recreation\n\n# In[ ]:\n\n\nprint(\"Done. Updating Arts, Entertainment, and Recreation..\")\n\n# Create Backups\ndf_aer_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Arts_Entertainment_and_Recreation.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_aer_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Arts_Entertainment_and_Recreation_BACKUP.txt\"\n)\n\n# Create new dataframe for Arts_Entertainment_and_Recreation\nfilter1 = df[\"LineCode\"] == 1700\ndf_arts = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_arts.to_csv(\"./Updates/STG_BEA_CA5N_Arts_Entertainment_and_Recreation.txt\", sep=\"\\t\")\n\n# # Construction\n\n# In[ ]:\n\n\nprint(\"Done. Updating Construction..\")\n\n# Create Backups\ndf_con_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Construction.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_con_backup.to_csv(\"./Backups/STG_BEA_CA5N_Construction_BACKUP.txt\")\n\n# Create new dataframe for Construction\nfilter1 = df[\"LineCode\"] == 400\ndf_construction = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_construction.to_csv(\"./Updates/STG_BEA_CA5N_Construction.txt\", sep=\"\\t\")\n\n# # Educational Services\n\n# In[ ]:\n\n\nprint(\"Done. Updating Educational Services..\")\n\n# Create Backups\ndf_es_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Educational_Services.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_es_backup.to_csv(\"./Backups/STG_BEA_CA5N_Educational_Services_BACKUP.txt\")\n\n# Create new dataframe for Educational_Services\nfilter1 = df[\"LineCode\"] == 1500\ndf_eduserv = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_eduserv.to_csv(\"./Updates/STG_BEA_CA5N_Educational_Services.txt\", sep=\"\\t\")\n\n\n# # Finance and Insurance\n\n# In[ ]:\n\n\nprint(\"Done. Updating Finance and Insurance..\")\n\n# Create Backups\ndf_fi_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Finance_and_Insurance.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_fi_backup.to_csv(\"./Backups/STG_BEA_CA5N_Finance_and_Insurance_BACKUP.txt\")\n\n# Create new dataframe for Finance_and_Insurance\nfilter1 = df[\"LineCode\"] == 1000\ndf_finance = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_finance.to_csv(\"./Updates/STG_BEA_CA5N_Finance_and_Insurance.txt\", sep=\"\\t\")\n\n\n# # Forestry, Fishing, and Related Activities\n\n# In[ ]:\n\n\nprint(\"Done. Updating Forestry, Fishing, and Related Activities..\")\n\n# Create Backups\ndf_ffr_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Forestry_Fishing_and_Related_Activities.txt\",\n encoding=\"ISO-8859-1\",\n sep=\"\\t\",\n)\ndf_ffr_backup.to_csv(\n \"./Backups/STG_BEA_CA5N_Forestry_Fishing_and_Related_Activities_BACKUP.txt\"\n)\n\n# Create new dataframe for Forestry_Fishing_and_Related_Activities\nfilter1 = df[\"LineCode\"] == 100\ndf_forestry = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_forestry.to_csv(\n \"./Updates/STG_BEA_CA5N_Forestry_Fishing_and_Related_Activities.txt\", sep=\"\\t\"\n)\n\n# # Military\n\n# In[ ]:\n\n\nprint(\"Done. Updating Govt Type Federal Civilian..\")\n\n# Create Backups\ndf_mgov_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Military_Government.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_mgov_backup.to_csv(\"./Backups/STG_BEA_CA5N_Military_Government_BACKUP.txt\")\n\n# Create new dataframe for Military_Government\nfilter1 = df[\"LineCode\"] == 2002\ndf_military = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_military.to_csv(\"./Updates/STG_BEA_CA5N_Military_Government.txt\", sep=\"\\t\")\n\n# # State and Local\n\n# In[ ]:\n\n\nprint(\"Done. Updating Govt Type State Local..\")\n\n# Create Backups\ndf_slgov_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_State_Local_Government.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_slgov_backup.to_csv(\"./Backups/STG_BEA_CA5N_State_Local_Government_BACKUP.txt\")\n\n# Create new dataframe for State_Local_Government\nfilter1 = df[\"LineCode\"] == 2010\ndf_state_local = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_state_local.to_csv(\"./Updates/STG_BEA_CA5N_State_Local_Government.txt\", sep=\"\\t\")\n\n# # State Government\n\n# In[ ]:\n\n\nprint(\"Done. Updating Govt Type State..\")\n\n# Create Backups\ndf_sgov_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_State_Government.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_sgov_backup.to_csv(\"./Backups/STG_BEA_CA5N_State_Government_BACKUP.txt\")\n\n# Create new dataframe for State_Government\nfilter1 = df[\"LineCode\"] == 2011\ndf_state = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_state.to_csv(\"./Updates/STG_BEA_CA5N_State_Government.txt\", sep=\"\\t\")\n\n# # Local Government\n\n# In[ ]:\n\n\nprint(\"Done. Updating Govt Type Local..\")\n\n# Create Backups\ndf_lgov_backup = pd.read_csv(\n \"./Updates/STG_BEA_CA5N_Local_Government.txt\", encoding=\"ISO-8859-1\", sep=\"\\t\"\n)\ndf_lgov_backup.to_csv(\"./Backups/STG_BEA_CA5N_Local_Government_BACKUP.txt\")\n\n# Create new dataframe for Local_Government\nfilter1 = df[\"LineCode\"] == 2012\ndf_local = df[filter1]\n\n# Save as tab-delimited txt file for export to SSMS\ndf_local.to_csv(\"./Updates/STG_BEA_CA5N_Local_Government.txt\", sep=\"\\t\")\n","sub_path":"Earnings/Scripts/CAINC5N_NC.py","file_name":"CAINC5N_NC.py","file_ext":"py","file_size_in_byte":20058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"192429889","text":"# -*- coding: utf-8 -*-\r\nfrom backend.lib.callbackWrapper import callbackWrapper\r\nfrom backend.lib.required.category import CategoryRequired\r\nfrom backend.lib.required.item import ItemRequired\r\nfrom backend.lib.required.vendor import VendorRequired\r\nfrom backend.lib.required.order import OrderRequired\r\nfrom backend.lib.required.unit import UnitRequired\r\nfrom backend.lib.required.purchase import PurchaseRequired\r\nfrom backend.lib.required.invoice import InvoiceRequired\r\nfrom backend.lib.required.itemProduct import ItemProductRequired\r\nfrom backend.lib.required.sendmail import SendmailRequired\r\nfrom backend.lib.required.itemMatch import ItemMatchRequired\r\nfrom backend.lib.required.productsPurchase import ProductsPurchaseRequired\r\nimport logging\r\nlogger = logging.getLogger('backend') # logger from settings.py\r\n\r\ndef wrapper(**kwargs):\r\n \"\"\"\r\n обработка входных параметров\r\n \"\"\"\r\n request = kwargs['request']\r\n req_params = kwargs['req_params']\r\n _context = kwargs['context']\r\n\r\n json = ''\r\n\r\n if request.user.is_authenticated():\r\n if _context == 'category':\r\n req = CategoryRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'item':\r\n req = ItemRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'vendor':\r\n req = VendorRequired(request=request, req_params=req_params)\r\n \r\n if _context == 'order':\r\n req = OrderRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'unit':\r\n req = UnitRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'purchase':\r\n req = PurchaseRequired(request=request, req_params=req_params)\r\n \r\n if _context == 'invoice':\r\n req = InvoiceRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'itemProduct':\r\n req = ItemProductRequired(request=request, req_params=req_params)\r\n \r\n if _context == 'sendmail':\r\n req = SendmailRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'item_match':\r\n req = ItemMatchRequired(request=request, req_params=req_params)\r\n\r\n if _context == 'products_purchase':\r\n req = ProductsPurchaseRequired(request=request, req_params=req_params)\r\n \r\n if req.success():\r\n out = kwargs['worker'](req)\r\n\r\n if 'success' in out:\r\n\r\n if out['success']:\r\n json = out\r\n else:\r\n json = { \"success\": False, \"errors\": out['errors'] }\r\n\r\n else:\r\n logger.error(req.errors())\r\n json = { \"success\": False, \"errors\": req.errors() }\r\n\r\n return callbackWrapper(request, json)\r\n\r\n else:\r\n #non-authorized request\r\n json = { \"success\": False, \"error\": \"Authorization is failed\" }\r\n return callbackWrapper(request, json)\r\n","sub_path":"backend/lib/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"309512195","text":"class WorldGrid(object):\n \"\"\"\n This class represent a world grid.\n You can add and get people to the grid and see people in specific areas.\n \"\"\"\n\n DEGREES = 360\n KM_PER_DEGREE = 111\n MINUS_MINUS = 0\n MINUS_PLUS = 90\n PLUS_MINUS = 180\n PLUS_PLUS = 270\n\n def __init__(self, resolution=10):\n \"\"\"\n Ctor. Can add a list of people to the grid or create an empty world.\n\n :param people: list of people\n :type people: list\n \"\"\"\n self.cubes = self.KM_PER_DEGREE / resolution\n self.world = self._create_world()\n self.people_locations = {}\n\n def _create_world(self):\n \"\"\"\n This function creates an empty world with the given resolution.\n\n :return: an empty list of lists\n \"\"\"\n return [[[] for j in xrange(self.DEGREES * self.cubes)]\n for i in xrange(self.DEGREES * self.cubes)]\n\n def add_person(self, person):\n \"\"\"\n This function converts a persons location to numbers and adds him to the relevant place in the world.\n\n :param person: the person (dict with id, longitude and latitude and whatever else you want)\n \"\"\"\n self.remove_person_if_exists(person)\n longitude, latitude = self._degrees_to_numbers(person['longitude'], person['latitude'])\n i, j = int(round(longitude * self.cubes)), int(round(latitude * self.cubes))\n self.world[i][j].append(person)\n self.people_locations[person['id']] = (i, j)\n\n def remove_person_if_exists(self, person):\n \"\"\"\n This function checks if we already added that person before and removes previous\n tries.\n \"\"\"\n if person['id'] in self.people_locations:\n i, j = self.people_locations[person['id']]\n for resident in self.world[i][j]:\n if resident['id'] == person['id']:\n self.world[i][j].remove(resident)\n break\n\n def add_people(self, people):\n for person in people:\n self.add_person(person)\n\n def get_nearby_people(self, person):\n longitude, latitude = self._degrees_to_numbers(person['longitude'], person['latitude'])\n return self.world[int(round(longitude * self.cubes))][int(round(latitude * self.cubes))]\n\n def _degrees_to_numbers(self, longitude, latitude):\n \"\"\"\n converts degrees to 360 number range\n\n :type longitude: float\n :type latitude: float\n :return: the converted location\n \"\"\"\n if longitude > 0 and latitude > 0:\n return longitude + self.PLUS_MINUS, latitude + self.PLUS_PLUS\n elif longitude > 0 and latitude < 0:\n return longitude + self.PLUS_MINUS, latitude + self.PLUS_MINUS\n elif longitude < 0 and latitude > 0:\n return longitude + self.MINUS_PLUS, latitude + self.MINUS_PLUS\n return longitude + self.MINUS_MINUS, latitude + self.MINUS_MINUS\n","sub_path":"grid_algorithm/world_grid.py","file_name":"world_grid.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373744374","text":"from random import randint\r\nfrom numpy import array\r\nfrom numpy import argmax\r\nfrom pandas import concat\r\nfrom pandas import DataFrame\r\nimport csv\r\nimport numpy as np\r\nfrom tensorflow.keras.models import Sequential, load_model\r\nfrom tensorflow.keras.layers import LSTM\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint\r\nimport pandas as pd\r\n\r\n\r\n#D:/Brand Personal/Programming/Machine Learning/Lucky games/DATA/testing/CSV/July_no_head.csv\r\n#read CSV and turn into 1 big array\r\n########################################################################################\r\nnum_of_rows=0\r\ndata = []\r\nwith open('predict_encode.csv', 'r') as csvfile: #changed to input just for one run online... use output_file.csv\r\n reader = csv.reader(csvfile)\r\n for row in reader:\r\n data.append([int(val) for val in row])\r\n num_of_rows=num_of_rows+1\r\n\r\n#print(num_of_rows)\r\narray_1=[]\r\na1=0\r\nb1=0\r\nfor a1 in range(num_of_rows):\r\n for b1 in range(20):\r\n array_1.append(data[a1][b1])\r\nprint(array_1)\r\n#########################################################################################\r\n\r\n\"\"\"\r\n#read CSV and turn into 1 big array\r\n########################################################################################\r\nnum_of_rows=0\r\ndata = []\r\nwith open('D:/Brand Personal/Programming/Machine Learning/Lucky games/DATA/testing/CSV/predict_encode.csv', 'r') as csvfile: #changed to input just for one run online... use output_file.csv\r\n reader = csv.reader(csvfile)\r\n for row in reader:\r\n data.append([int(val) for val in row])\r\n num_of_rows=num_of_rows+1\r\n\r\n#print(num_of_rows)\r\narray_2=[]\r\nfor x in range(num_of_rows):\r\n for y in range(20):\r\n array_2.append(data[x][y])\r\n#print(array_1)\r\n#########################################################################################\r\n\"\"\"\r\n\r\n\"\"\"\r\n# generate a sequence of random numbers in [0, 99]\r\ndef generate_sequence(length=25):\r\n\treturn [randint(0, 99) for _ in range(length)]\r\n\"\"\"\r\n\r\n\r\n\r\n#So now in order to have a shape of 80 instead of 81 (easier for usage with reshaping)\r\n#We shift everything -1 so table is 0-79 but the real thing is everything+1\r\n# one hot encode sequence\r\ndef one_hot_encode(sequence, n_unique=80):\r\n encoding = list()\r\n \r\n for value in sequence:\r\n vector=[0]*80\r\n #vector = [0 for _ in range(n_unique)]\r\n _ = 0\r\n for _ in range(n_unique):\r\n vector[_]=0\r\n vector[value-1] = 1\r\n encoding.append(vector)\r\n return array(encoding)\r\n\r\n# decode a one hot encoded string\r\ndef one_hot_decode(encoded_seq):\r\n \r\n\treturn [argmax(vector) for vector in encoded_seq]\r\n\r\n\"\"\"\r\ndef split_sequence(sequence, n_steps):\r\n\tX, y = list(), list()\r\n\tfor i in range(len(sequence)):\r\n\t\t# find the end of this pattern\r\n\t\tend_ix = i + n_steps\r\n\t\t# check if we are beyond the sequence\r\n\t\tif end_ix > len(sequence)-1:\r\n\t\t\tbreak\r\n\t\t# gather input and output parts of the pattern\r\n\t\tseq_x, seq_y = sequence[i:end_ix], sequence[end_ix]\r\n\t\tX.append(seq_x)\r\n\t\ty.append(seq_y)\r\n\treturn array(X), array(y)\r\n\r\n\"\"\"\r\n\r\ndef generate_data(array_1):\r\n print(\"array ...... \")\r\n print(array_1)\r\n\t# generate sequence\r\n sequence = array_1\r\n\r\n encoded = one_hot_encode(sequence)\r\n\r\n print(\"encoded\")\r\n print(encoded)\r\n\t# create lag inputs\r\n df = DataFrame(encoded)\r\n \r\n df = concat([df.shift(19), df.shift(18), df.shift(17),df.shift(16), df.shift(15),\r\n df.shift(14), df.shift(13),df.shift(12), df.shift(11), df.shift(10),\r\n df.shift(9),df.shift(8), df.shift(7), df.shift(6), df.shift(5),df.shift(4),\r\n df.shift(3), df.shift(2), df.shift(1), df], axis=1)\r\n \r\n \r\n #at X1,Y1 there is a table with 0s & 1s size(1x80)\r\n #so X1 has 5 tables (0..4) which are of 0s &1s\r\n # remove non-viable rows\r\n values = df.values\r\n values = values[19:,:]\r\n print(\"values all\")\r\n print(values)\r\n print(\"df\")\r\n print(df)\r\n \r\n print(\"X shape before encode\")\r\n print(values.shape)\r\n \r\n\r\n X = values.reshape(len(values), 20, 80)\r\n print(\"X\")\r\n print(X)\r\n print(\"X shape\")\r\n print(X.shape)\r\n x_decoded=one_hot_decode(X)\r\n x_decoded_correct=[ x+1 for x in x_decoded]\r\n print(x_decoded_correct)\r\n \r\n \r\n #sequence_2 = array_1\r\n #sequence_2 = np.delete(sequence_2, 0)\r\n #sequence_2 = np.delete(sequence_2, 0)\r\n #sequence_2 = np.delete(sequence_2, 0)\r\n #sequence_2 = np.delete(sequence_2, 0)\r\n #sequence_2 = np.delete(sequence_2, 0)\r\n\r\n #encoded_2 = one_hot_encode(sequence_2)\r\n\r\n print()\r\n \r\n print(\"encoded 22222222\")\r\n #print(encoded_2)\r\n #print(encoded_2.shape)\r\n\r\n #y=encoded_2\r\n\r\n print(\"y shape before encode\")\r\n #print(y.shape)\r\n\r\n print(\"y\")\r\n #print(y)\r\n print(\"y shape\")\r\n #print(y.shape)\r\n\r\n return X#, y\r\n\r\n\r\n#X,y=generate_data(array_1)\r\nprint(\"X\")\r\n#print(X)\r\nprint(\"y\")\r\n#print(y)\r\n\r\n#X,encoded=generate_data(array_1)\r\n\r\n\r\n#filepath = \"steps_20.h5\"\r\nfilepath = \"steps_20_shape_2.h5\"\r\nmodel = load_model(filepath)\r\n\r\n\r\n#model.save(filepath)\r\n# evaluate model on new data\r\n#array_2=[40,73,72,34,69]\r\nX = generate_data(array_1)\r\n\"\"\"\r\n#X_simple=[73,72,34,69,79]\r\n\r\n#array_simple=np.array(X_simple)\r\narray_simple=np.array(array_1)\r\narray_simple=one_hot_encode(array_simple)\r\narray_simple=array_simple.reshape(len(array_simple), 5, 80)\r\n\"\"\"\r\n\r\n#yhat = model.predict_proba(X, batch_size=3515) #1\r\n#yhat = model.predict_proba(X)\r\nyhat = model.predict(X)\r\n#yhat = model.predict(X)\r\n# we run x+1 for each element in the list to counter the -1 shift we made during encoding\r\n\r\n\r\n#array_2=np.delete(array_1, 0)\r\n#yhat_decoded=one_hot_decode(yhat)\r\n#yhat_decoded_correct=[ x+1 for x in yhat_decoded]\r\n#array_2=array_2.astype(int)\r\n#yhat=int(yhat)\r\n#print(\"yhat\")\r\n#print(yhat_decoded_correct)\r\n\r\n\"\"\"\r\narray_2=np.delete(array_1, 0)\r\n\r\n\r\nlen_y=yhat_decoded_correct.__len__()\r\nprint(\"len\")\r\nprint(len_y)\r\ny1=yhat_decoded_correct[len_y-1]\r\n\r\narray_2 = np.append(array_2, y1, axis=None)\r\n\r\nprint(\"array_2 shape\")\r\nprint(array_2.shape)\r\n\r\nX, y = generate_data(array_2)\r\nyhat2= model.predict(X, batch_size=3515)\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n#yhat = model.predict(X, batch_size=3515)\r\n\r\nx_decoded=one_hot_decode(X)\r\nx_decoded_correct=[ x+1 for x in x_decoded]\r\n\r\n#y_decoded=one_hot_decode(y)\r\n#y_decoded_correct=[ x+1 for x in y_decoded]\r\n\r\nyhat_decoded=one_hot_decode(yhat)\r\nyhat_decoded_correct=[ x+1 for x in yhat_decoded]\r\n\r\n\r\nprint('Input: %s' % x_decoded_correct)\r\nprint()\r\n#print('Expected: %s' % y_decoded_correct)\r\nprint()\r\nprint('Predicted: %s' % yhat_decoded_correct)\r\n\r\n","sub_path":"predict_20_steps.py","file_name":"predict_20_steps.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"274151636","text":"\"\"\"\npython ./fids_capstone_asl_translation__dataflow__main.py \\\n --work-dir gs:// \\\n --max-target-videos <-1 for ALL | n max videos to process> \\\n --beam-gcp-project YOUR-PROJECT \\\n --beam-gcp-region us-central1 \\\n --dataflow-job-name fids-capston-asl-translation-$USER\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport argparse\nimport logging\nimport os\n\nfrom api import preprocessor\n\nif __name__ == '__main__':\n# logging.getLogger().setLevel(logging.INFO) # too much output!\n\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n '--work-dir',\n required=True,\n help='Directory for staging and working files. '\n 'This can be a Google Cloud Storage path.'\n )\n\n parser.add_argument(\n '--max-target-videos',\n type=int,\n default=-1,\n help='Maximum number of target videos to process. '\n 'Set to -1 to download/process all available target videos (and segments).'\n )\n\n parser.add_argument(\n '--beam-gcp-project',\n default=None,\n help='The GCP project containing the GCS bucket to use for beam temp as well as data storage.'\n )\n\n parser.add_argument(\n '--beam-gcp-region',\n default=None,\n help='The GCP region of the bucket.'\n )\n\n parser.add_argument(\n '--beam-gcp-dataflow-job-name',\n default=None,\n help='The name of the GCP Dataflow job to create.'\n )\n\n parser.add_argument(\n '--beam-gcp-dataflow-setup-file',\n default=None,\n help='The path to the setup.py file (used by Apache Beam worker nodes).'\n )\n\n args = parser.parse_args()\n print(f\"args: {args}\")\n\n preprocessor.run(\n work_dir=args.work_dir,\n beam_runner='DirectRunner',\n beam_gcp_project=args.beam_gcp_project,\n beam_gcp_region=args.beam_gcp_region,\n beam_gcp_dataflow_job_name=args.beam_gcp_dataflow_job_name,\n beam_gcp_dataflow_setup_file=args.beam_gcp_dataflow_setup_file\n )\n","sub_path":"run_local__preprocess.py","file_name":"run_local__preprocess.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"527071512","text":"from django import template\nfrom contents.models import *\nfrom contents.models import *\nregister = template.Library()\n\n\n@register.simple_tag\ndef status_current(status):\n\tif status == 1:\n\t\tstatus = \"Pendiente\"\n\telif status== 2:\n\t\tstatus = \"Proceso\"\n\telif status == 3:\n\t\tstatus = \"Terminado\"\n\telif status== 4:\n\t\tstatus = \"Cancelado\"\n\t\t\n\treturn status\n\n\n@register.simple_tag\ndef status_current_hosting(status):\n\tif status == 1:\n\t\tstatus = \"Pendiente\"\n\telif status== 2:\n\t\tstatus = \"Activo\"\n\telif status == 3:\n\t\tstatus = \"Terminado\"\n\t\t\n\treturn status\n\n\n\n@register.simple_tag\ndef seemore(count):\n\tif count == 4:\n\t\tval = True\n\telse:\n\t\tval = False\n\treturn val\n\n","sub_path":"customers/templatetags/sectiontagcustomer.py","file_name":"sectiontagcustomer.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86993344","text":"\"\"\"\nCopyright ©2021. The Regents of the University of California (Regents). All Rights Reserved.\n\nPermission to use, copy, modify, and distribute this software and its documentation\nfor educational, research, and not-for-profit purposes, without fee and without a\nsigned licensing agreement, is hereby granted, provided that the above copyright\nnotice, this paragraph and the following two paragraphs appear in all copies,\nmodifications, and distributions.\n\nContact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue,\nSuite 510, Berkeley, CA 94720-1620, (510) 643-7201, otl@berkeley.edu,\nhttp://ipira.berkeley.edu/industry-info for commercial licensing opportunities.\n\nIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\nINCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF\nTHE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n\nREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE\nSOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED\n\"AS IS\". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,\nENHANCEMENTS, OR MODIFICATIONS.\n\"\"\"\n\nfrom boac.api.errors import BadRequestError, ResourceNotFoundError\nfrom boac.api.util import can_edit_degree_progress, can_read_degree_progress\nfrom boac.lib.http import tolerant_jsonify\nfrom boac.lib.util import get as get_param\nfrom boac.models.degree_progress_category import DegreeProgressCategory, TRANSIENT_CATEGORY_POSITION\nfrom flask import current_app as app, request\nfrom flask_cors import cross_origin\n\n\n@app.route('/api/degree/category/create', methods=['POST'])\n@can_edit_degree_progress\ndef create_category():\n params = request.get_json()\n category_type = get_param(params, 'categoryType')\n course_units = get_param(params, 'units')\n description = get_param(params, 'description')\n name = get_param(params, 'name')\n parent_category_id = get_param(params, 'parentCategoryId')\n position = get_param(params, 'position')\n template_id = get_param(params, 'templateId')\n # Categories/courses can be mapped to degree_progress_unit_requirements\n value = get_param(request.get_json(), 'unitRequirementIds')\n unit_requirement_ids = list(filter(None, value.split(','))) if isinstance(value, str) else value\n\n if not category_type or not name or not _is_valid_position(position) or not template_id:\n raise BadRequestError(\"Insufficient data: categoryType, name, position and templateId are required.'\")\n if category_type == 'Category' and parent_category_id:\n raise BadRequestError('Categories cannot have parents.')\n if category_type in ('Course Requirement', 'Subcategory') and not parent_category_id:\n raise BadRequestError(\"The parentCategoryId param is required when categoryType equals 'Subcategory'.\")\n if parent_category_id:\n parent = _get_degree_category(parent_category_id)\n parent_type = parent.category_type\n if parent_type == 'Course Requirement' or (parent_type == 'Subcategory' and category_type == 'Category'):\n raise BadRequestError(f'Type {category_type} not allowed, based on parent type: {parent_type}.')\n if position not in [TRANSIENT_CATEGORY_POSITION, parent.position]:\n raise BadRequestError(f'Category position ({position}) must match its parent ({parent.position}).')\n\n category = DegreeProgressCategory.create(\n category_type=category_type,\n course_units=course_units,\n description=description,\n name=name,\n parent_category_id=parent_category_id,\n position=position,\n template_id=template_id,\n unit_requirement_ids=unit_requirement_ids,\n )\n return tolerant_jsonify(category.to_api_json())\n\n\n@app.route('/api/degree/category/')\n@can_read_degree_progress\ndef get_degree_category(category_id):\n return tolerant_jsonify(_get_degree_category(category_id))\n\n\n@app.route('/api/degree/category/', methods=['DELETE'])\n@can_edit_degree_progress\n@cross_origin(allow_headers=['Content-Type'])\ndef delete_degree_category(category_id):\n DegreeProgressCategory.delete(category_id)\n return tolerant_jsonify({'message': f'Template {category_id} deleted'}), 200\n\n\n@app.route('/api/degree/category//update', methods=['POST'])\n@can_edit_degree_progress\ndef update_category(category_id):\n params = request.get_json()\n course_units = get_param(params, 'units')\n description = get_param(params, 'description')\n name = get_param(params, 'name')\n parent_category_id = get_param(params, 'parentCategoryId')\n # Courses can be mapped to degree_progress_unit_requirements\n value = get_param(request.get_json(), 'unitRequirementIds')\n unit_requirement_ids = list(filter(None, value.split(','))) if isinstance(value, str) else value\n\n category = DegreeProgressCategory.update(\n category_id=category_id,\n course_units=course_units,\n description=description,\n parent_category_id=parent_category_id,\n name=name,\n unit_requirement_ids=unit_requirement_ids,\n )\n return tolerant_jsonify(category.to_api_json())\n\n\ndef _get_degree_category(category_id):\n category = DegreeProgressCategory.find_by_id(category_id)\n if not category:\n raise ResourceNotFoundError(f'No category found with id={category_id}.')\n return category\n\n\ndef _is_valid_position(position):\n # Transient categories are identified by position=-1 and are deleted when the course is unassigned.\n return position and (position == TRANSIENT_CATEGORY_POSITION or 0 < position < 4)\n","sub_path":"boac/api/degree_progress_category_controller.py","file_name":"degree_progress_category_controller.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"207580057","text":"#!/usr/bin/python\n# Copyright (c) 2018 Dell Inc.\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 http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT\n# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS\n# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n\nimport cps_object\nimport cps\nimport nas_common_header as common\nimport nas_os_if_utils as nas_if\n\nyang_breakout_reverse = dict((v, k) for k, v in common.yang_breakout.iteritems())\nyang_phy_mode_reverse = dict((v, k) for k, v in common.yang_phy_mode.iteritems())\nyang_speed_reverse = dict((v, k) for k, v in common.yang_speed.iteritems())\nyang_phy_mode_ether = 1\nyang_phy_mode_fc = 2\n\nhg_state_key = cps.key_from_name('observed', 'base-pg/dell-pg/port-groups-state/hybrid-group-state')\nhg_key = cps.key_from_name('target', 'base-pg/dell-pg/port-groups/hybrid-group')\n\n\ndef hg_attr(t):\n return 'dell-pg/port-groups/hybrid-group/' + t\n\n\ndef base_hg_attr(t):\n return 'base-pg/' + hg_attr(t)\n\n\ndef hg_state_attr(t):\n return 'dell-pg/port-groups-state/hybrid-group-state/' + t\n\n\ndef base_hg_state_attr(t):\n return 'base-pg/' + hg_state_attr(t)\n\n\ndef print_hg_cps_obj(o):\n if o is None:\n return None\n \n obj = cps_object.CPSObject(obj=o)\n hg_name = nas_if.get_cps_attr(obj, hg_attr('id'))\n hg_profile = nas_if.get_cps_attr(obj, hg_attr('profile'))\n port_list = nas_if.get_cps_attr(obj, hg_attr('port'))\n print(\"Hybrid Group Name: %s Profile: %s \" % (hg_name, hg_profile))\n\n for port_idx in port_list:\n port = port_list[port_idx]\n port_id = port['port-id'] \n phy_mode = port['phy-mode'] \n breakout_mode = port['breakout-mode'] \n port_speed = port['port-speed'] \n breakout_option = (breakout_mode,port_speed)\n breakout = common.get_key(common.yang_breakout_port_speed,breakout_option)\n print(\"Port ID: %s Phy-mode: %s Breakout-mode: %s \" % (str(port_id),\n str(yang_phy_mode_reverse[phy_mode]),\n str(breakout)))\n\n\n#Get Hybrid Group State Object\ndef get_hg_state(hg_name=\"\"):\n resp = []\n obj = cps_object.CPSObject('base-pg/dell-pg/port-groups-state/hybrid-group-state',\n qual='observed',\n data={hg_state_attr('id'):hg_name})\n cps.get([obj.get()], resp)\n return resp\n\n\n#Get Hybrid Group Object\ndef get_hg(hg_name=\"\"):\n resp = []\n obj = cps_object.CPSObject('base-pg/dell-pg/port-groups/hybrid-group',\n qual='target',\n data={hg_attr('id'):hg_name})\n cps.get([obj.get()], resp)\n return resp\n\n\n#Set Hybrid Group State Object\ndef set_hg(hg_name, profile=None, port_id=None, br_mode=None, port_speed=None, phy_mode=None):\n cps_obj = cps_object.CPSObject(module=\"base-pg/dell-pg/port-groups/hybrid-group\", data={})\n cps_obj.add_attr(hg_attr('id'), hg_name)\n\n if profile is not None:\n cps_obj.add_attr(hg_attr('profile'), profile)\n \n if port_id is not None and br_mode is not None and port_speed is not None and phy_mode is not None:\n cps_obj.add_embed_attr([hg_attr('port'), \"0\", \"port-id\"], str(port_id), 4)\n cps_obj.add_embed_attr([hg_attr('port'), \"0\", \"breakout-mode\"], br_mode, 4)\n cps_obj.add_embed_attr([hg_attr('port'), \"0\", \"port-speed\"], port_speed, 4)\n cps_obj.add_embed_attr([hg_attr('port'), \"0\", \"phy-mode\"], phy_mode, 4)\n \n cps.transaction([{\"operation\": \"set\", \"change\": cps_obj.get()}])\n","sub_path":"scripts/lib/python/nas_hybrid_group_utils.py","file_name":"nas_hybrid_group_utils.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"414297807","text":"\n\ndef _create_table_optimize_block(self, pserver_index, pserver_program, pre_block_idx, grad_to_block_id):\n origin_param_var = self.origin_program.global_block().vars[self.table_name]\n zero_dim = int(math.ceil((origin_param_var.shape[0] / len(self.pserver_endpoints))))\n table_shape = list(origin_param_var.shape)\n table_shape[0] = zero_dim\n param_var = pserver_program.global_block().create_var(name=origin_param_var.name, shape=table_shape, dtype=origin_param_var.dtype, type=core.VarDesc.VarType.SELECTED_ROWS, persistable=True)\n param_var.desc.set_type(core.VarDesc.VarType.SELECTED_ROWS)\n grad_var = pserver_program.global_block()._clone_variable(self.origin_program.global_block().vars[grad_var_name(self.table_name)])\n table_opt_op = [op for op in self.optimize_ops if (('Param' in op.input_names) and (op.input('Param')[0] == self.table_name))][0]\n table_opt_block = pserver_program.create_block(pre_block_idx)\n if self.sync_mode:\n table_grad_var = self.table_param_grad[1]\n pserver_side_table_grad_list = [pserver_program.global_block().create_var(name=('%s.trainer_%d.pserver_%d' % (table_grad_var.name, index, pserver_index)), type=table_grad_var.type, shape=table_grad_var.shape, dtype=table_grad_var.dtype) for index in range(self.trainer_num)]\n table_opt_block.append_op(type='sum', inputs={\n 'X': pserver_side_table_grad_list,\n }, outputs={\n 'Out': [grad_var],\n }, attrs={\n 'use_mkldnn': False,\n })\n else:\n origin_grad_name = grad_var.name\n splited_grad_name = self.trainer_side_table_grad_list[pserver_index].name\n if (not splited_grad_name.startswith(origin_grad_name)):\n raise ValueError(((('origin_grad_var: ' + splited_grad_name) + ' grad_var:') + grad_var.name))\n grad_var = pserver_program.global_block()._rename_var(origin_grad_name, splited_grad_name)\n lr_var = pserver_program.global_block().vars[table_opt_op.input('LearningRate')[0]]\n inputs = {\n 'Param': [param_var],\n 'Grad': [grad_var],\n 'LearningRate': [lr_var],\n }\n outputs = {\n 'ParamOut': [param_var],\n }\n import logging\n logging.warn((\"distribute lookup table only support sgd optimizer, change it's optimizer to sgd instead of \" + table_opt_op.type))\n table_opt_block.append_op(type='sgd', inputs=inputs, outputs=outputs)\n grad_to_block_id.append(((grad_var.name + ':') + str(table_opt_block.idx)))\n return table_opt_block\n","sub_path":"Data Set/bug-fixing-2/6bc16ff33b7deec0ecf70378cc505e8f6ba02bc7-<_create_table_optimize_block>-bug.py","file_name":"6bc16ff33b7deec0ecf70378cc505e8f6ba02bc7-<_create_table_optimize_block>-bug.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506032638","text":"#!/usr/bin/env python\n\"\"\"\nsfr_inst_vs_m_line_clip_sim_linexp.py Python3 script\n\nTHIS VERSION FOR 2015-05-16-A/sample02/run03b lin-exp SFH FITS.\n\nusage: sfr_inst_vs_m_line_clip_sim.py [-h] [-v] [-d] [-i ITERATIONS]\n [-c CLIP_SIGMA] [-z ZSPEAGLE2014]\n input_file output_file\n\nAnalyzes SFR-M* relation of input data with various methods and compares\nresults to the literature (Speagle+2014). Performs clipping of outliers to a\nspecitied threshold (default 3 sigma), and re-fits the data. Estimates\nintrinsic scatter of the data using various methods. Performs simulations to\nestimate errors. Outputs pdf files showing data, best fit model(s) and\nresiduals, and optional text data to console.\n\npositional arguments:\n input_file The input .fits file. See program listing for columns\n used.\n output_file The output .pdf file\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --verbose Print descriptive text, including results of analysis.\n -d, --display Display the plot.\n -i ITERATIONS, --iterations ITERATIONS\n Number of iterations in simulation. Default = 1000\n -c CLIP_SIGMA, --clip_sigma CLIP_SIGMA\n Outlier threshold (sigma). Default = 3.0\n -z ZSPEAGLE2014, --zSpeagle2014 ZSPEAGLE2014\n Redshift for Speagle+2014 Main Sequence correlation\n\n\nExample:\n\nExecution time for 10000 realizations is about 30 seconds.\n\nSee Experiment 2014-11-26-A, 2014-11-13-A, 2014-09-05-A, 2015-05-16-A. \n\nv0 01/05/2015\nv1 02/16/2015 include residual plots, improved output format, anova\nv3 04/03/2015 updated with most recent versions of \nv4 04/21/2015 minor cosmetic changes\nv5 05/30/2015 estimate parameters using covariances; output refit data\n with covariances, for upload to khuseti...run IDL program.\nv6 06/30/2015\tnew clipping method. residuals saved as txt file\nv7 08/04/2015 error ellipse estimates, and corrected a mistake in input\n of covariance data, see Table 1.\nv8 09/17/2015 corrected minor inconsistencies in the way k07 fit results\n are computed and reported.\nv9 10/02/2015 updated revisions of v8 and changed output to F87 estimates\n in Executive Summary. Compute Y(XRef) for F87 best fit line.\n Include SFR-M* correlation from Whitaker+2014 in plot.\nv10 11/11/2015 Add selection functions computed in ...Manuscripts/2015/\n Kurczynski - SFR-M*/Analysis/2015-10-14-A/. This version\n created by modifying sfr_100...py (v10) script. Changes\n needed for each sampleXX: (1) update k07 fit params.\n (2) update whitaker+2014 model params. (3) update SFR-M* \n selection function params.\n\"\"\"\n\nimport argparse\nimport astropy\nfrom astropy.cosmology import WMAP9 as cosmo\nimport astropy.io.fits as pyfits\nfrom datetime import datetime\nfrom linfit_multi_methods import linfit_f87, linfit_multi, linfit_multi_simerr, scatter_variance_adhoc\nimport math\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.collections import EllipseCollection\nfrom matplotlib.ticker import NullFormatter, MultipleLocator\nimport numpy as np\nimport sys\nimport scipy.stats as s\n \nif __name__ == '__main__': \n\n parser = argparse.ArgumentParser(description=\"Analyzes SFR-M* relation of input data with various methods and compares results to the literature (Speagle+2014, Whitaker+2014). Performs clipping of outliers to a specitied threshold (default 3 sigma), and re-fits the data. Estimates intrinsic scatter of the data using various methods. Performs simulations to estimate errors. Outputs pdf files showing data, best fit model(s) and residuals, and optional text data to console.\")\n parser.add_argument('input_file', help='The input .fits file. See program listing for columns used.')\n parser.add_argument('output_file', help='The output .pdf file')\n parser.add_argument('-v','--verbose', action = 'store_true', help='Print descriptive text, including results of analysis.')\n parser.add_argument('-d','--display', action = 'store_true', help='Display the plot.')\n parser.add_argument('-i','--iterations', type = int, default = '1000', help='Number of iterations in simulation. Default = 1000')\n parser.add_argument('-c','--clip_sigma', type = float, default = '3.0', help='Outlier threshold (sigma). Default = 3.0')\n parser.add_argument('-z','--zSpeagle2014', type = float, default = '1.0', help='Redshift for Speagle+2014 Main Sequence correlation line. Default = 1.1.')\n \n args = parser.parse_args()\n \n if (args.verbose):\n print(\"sfr_inst_vs_m_line_clip_sim_linexp.py \\n\")\n \n print(\"Run date and time : \", str(datetime.now()))\n print(\"Python Version : \", sys.version)\n print(\"Astropy version : \", astropy.__version__)\n \n \"\"\" \n Read the input data: retrieve SFR, M* values\n \"\"\"\n hduList = pyfits.open(args.input_file)\n tbData = hduList[1].data\n \n logStellarMass_Input_Value = tbData.field('LogStellarMass_Msun_Expected_Value')\n logStellarMass_Input_Err = tbData.field('LogStellarMass_Msun_Expected_Err68')\n \n logSFR_Input_Value = tbData.field('LogSFR_Inst_Expected_Value')\n logSFR_Input_Err = tbData.field('LogSFR_Inst_Expected_Err68')\n \n \"\"\"\n Parameter indices for determining covariance matrix elements:\n \n Table 1. Parameters in 2015-05-16-A/sample00/run03\n \n Number of parameters : 20\n Parameter list (use for indexing Cov and Corr matrix elements):\n\t1 = LogAge_Yr\n\t2 = Age_Gyr\n\t3 = LogGalaxyMass_Msun\n\t4 = GalaxyMass_9\n\t5 = EBV\n\t6 = LogTau_Yr\n\t7 = Tau_Gyr\n\t8 = LogStellarMass_Msun\n\t9 = StellarMass_9\n\t10 = LogSFR_Inst\n\t11 = SFR_Inst\n\t12 = LogSFR_Life\n\t13 = SFR_Life\n\t14 = Logsfr_inst\n\t15 = sfr_inst\n\t16 = LogT50_Yr\n\t17 = T50_Gyr\n\t18 = LogSFR_Max\n\t19 = LogSFR_MaxAvg\n\t20 = LogGalaxyMass_Inf_Msun\n \n Caption: parameter list used to refer to estimated parameters \n from getdist analysis of speedymc output. See *fixed*.ini files\n in khuseti:~/analysis/candels/2015-05-16-A/sample00/run03/analysis/\n See also caption for table in database ecdfs.candels_2015a.\n sample00_run03_speedymc_results.\n \n Use parameter indices to identify the proper correlation matrix \n element, e.g. Cov(8,12) is Cov(log StellarMass, logSFR_Life).\n \"\"\"\n\n Covariance_LogStellarMass_LogSFR = tbData.field('Cov_8_10')\n Variance_LogStellarMass = tbData.field('Cov_8_8')\n Variance_LogSFR = tbData.field('Cov_10_10')\n\n Chisq_BestFit = tbData.field('Chisq_BestFit')\n \n Correlation_LogStellarMass_LogSFR = tbData.field('Corr_8_10')\n Source_ID = tbData.field('ID')\n\n \"\"\" \n Slice the data: Select subset of input data for fitting\n \n Description Selection criterion syntax\n (1) (2)\n \n good chisq goodData = (tbData.field('Chisq_BestFit') < 50.0)\n only\n \n good chisq\n good GR conv. goodData = ((tbData.field('Chisq_BestFit') < 50.0) & (tbData.field('GR_StellarMass') < 0.2))\n\n \"\"\"\n #goodData = (tbData.field('Chisq_BestFit') < 50.0)\n goodData = ((tbData.field('Chisq_BestFit') < 100.0) & (tbData.field('LogStellarMass_Msun_GR_Converge') < 0.2))\n \n \"\"\"\n Compute Chisq statistics of SED fits\n \n Table 1.5. Parameters in SED fits; chisq degrees of freedom\n \n \tRunID\tdf\t\tFree Parameters\n \t(1)\t(2)\t\t(3)\n \t\n \trun02\t14\t\tAge, EBV, GalMass\n \trun03\t13\t\tAge, EBV, GalMass, tau\n \trun04\t13\t\tAge, EBV, GalMass, tau\n \t\n Caption: Free parameters used to determine degrees of freedom in \n reduced chisq. (1) is the SpeedyMC Run ID. (2) is the df for chisq \n estimate: 17 - (Number of free parameters). NB: There are 17 \n photometry measurements in the SEDs. (3) is the list of free \n parameters, ie parameters in .ini file that are allowed to vary.\n \"\"\"\n chisq_df = 13.0\n Chisqv_BestFit = Chisq_BestFit / chisq_df\n chisqv_goodData = Chisqv_BestFit[goodData]\n chisqv_goodData_median = np.median(chisqv_goodData)\n chisqv_goodData_min = np.min(chisqv_goodData)\n chisqv_goodData_max = np.max(chisqv_goodData)\n \n x_goodData_unscaled = logStellarMass_Input_Value[goodData]\n x_goodData_unscaled_err = logStellarMass_Input_Err[goodData]\n\n y_goodData_unscaled = logSFR_Input_Value[goodData]\n y_goodData_unscaled_err = logSFR_Input_Err[goodData]\n \n covxy_goodData = Covariance_LogStellarMass_LogSFR[goodData]\n varxx_goodData = Variance_LogStellarMass[goodData]\n varyy_goodData = Variance_LogSFR[goodData]\n \n corrxy_goodData = Correlation_LogStellarMass_LogSFR[goodData]\n \n source_id_goodData = Source_ID[goodData]\n \n num_input_data = tbData.size\n num_goodData = list(goodData).count(True)\t\n x_goodData_unscaled_median = np.median(x_goodData_unscaled)\n y_goodData_unscaled_median = np.median(y_goodData_unscaled)\n\n x_goodData_unscaled_min = np.min(x_goodData_unscaled)\n y_goodData_unscaled_min = np.min(y_goodData_unscaled)\n\n x_goodData_unscaled_max = np.max(x_goodData_unscaled)\n y_goodData_unscaled_max = np.max(y_goodData_unscaled)\n\n if (args.verbose): \n print(\"\\n\\nDescription of input data\") \n print(\"\\tInput file : \", args.input_file)\n print(\"\\tOutput file : \", args.output_file)\n print(\"\\tNumber of input data : \",num_input_data)\n print(\"\\tNumber of good data : \",num_goodData )\n print(\"\\nGood data (used in subsequent analysis)\")\n print(\"\\tNumber of data : \", num_goodData)\n print(\"\\tX data\")\n print(\"\\t min : \",x_goodData_unscaled_min)\n print(\"\\t median : \",x_goodData_unscaled_median)\n print(\"\\t max : \",x_goodData_unscaled_max)\n print(\"\\tY data\")\n print(\"\\t min : \",y_goodData_unscaled_min)\n print(\"\\t median : \",y_goodData_unscaled_median)\n print(\"\\t max : \",y_goodData_unscaled_max)\n\n \"\"\" \n Rescale the input data for fitting: subtract median value in x,y\n \"\"\"\n x_scale = x_goodData_unscaled_median\n y_scale = y_goodData_unscaled_median\n if (args.verbose):\n print(\"\\nScaling (for decorrelating slope & intercept errors)\")\n print(\"\\tx_scale: {:.3f}\".format(x_scale) )\n print(\"\\ty_scale: {:.3f}\".format(y_scale) )\n\n \n x_goodData_rescaled = x_goodData_unscaled - x_scale\n y_goodData_rescaled = y_goodData_unscaled - y_scale\n \n \"\"\" \n fit the good input data only\n \"\"\"\n x = x_goodData_rescaled\n y = y_goodData_rescaled\n sx = x_goodData_unscaled_err\n sy = y_goodData_unscaled_err\n \n x_unscaled = x_goodData_unscaled\n y_unscaled = y_goodData_unscaled \n \n \n \"\"\" \n INITIAL FITS\n \"\"\" \n \n (f87_rescaled_initialfit_slope,\\\n f87_rescaled_initialfit_intercept,\\\n f87_rescaled_initialfit_scatter_variance) = linfit_f87(x,y,sx,sy)\n\n \"\"\"\n Convert rescaled fit quantities back to unscaled values \n \"\"\"\n f87_unscaled_initialfit_slope = f87_rescaled_initialfit_slope\n f87_unscaled_initialfit_intercept = f87_rescaled_initialfit_intercept - x_scale * f87_rescaled_initialfit_slope\n\n x_rescaled_initialfit_model = x\n y_rescaled_initialfit_model = f87_rescaled_initialfit_intercept + f87_rescaled_initialfit_slope * x_rescaled_initialfit_model\n y_rescaled_initialfit_residual = y - y_rescaled_initialfit_model\n y_rescaled_initialfit_residual_sigma = y_rescaled_initialfit_residual / sy\n\n if (args.verbose): \n print(\"\\nInitial fit to good data\") \n print(\"\\tBest fit slope : {:.2f}\".format(f87_unscaled_initialfit_slope))\n print(\"\\tBest fit intercept : {:.2f}\".format(f87_unscaled_initialfit_intercept))\n print(\"\\tIntrinsic scatter variance F87 : {:.3f}\".format(f87_rescaled_initialfit_scatter_variance))\n print(\"\\tResiduals (ie residual = (y-y_fit))\") \n print(\"\\t Mean : {:.2f}\".format(y_rescaled_initialfit_residual.mean()))\n print(\"\\t Std deviation : {:.2f}\".format(y_rescaled_initialfit_residual.std()))\n print(\"\\tResiduals (unitless; ie residual = (y-y_fit)/y_err)\") \n print(\"\\t Mean : {:.2f}\".format(y_rescaled_initialfit_residual_sigma.mean()))\n print(\"\\t Std deviation : {:.2f}\".format(y_rescaled_initialfit_residual_sigma.std()))\n print(\"\\nInitial fit to good data\")\n scatter_variance_adhoc(x,y,sx,sy,f87_rescaled_initialfit_slope,f87_rescaled_initialfit_intercept, verbose = True)\n \n \"\"\" \n CLIPPING - Compute the residuals to the best fit model and identify outliers \n new method of clipping\n pk 6/29/2015\n \"\"\"\n\n outlierThreshold_sigma = float(args.clip_sigma) * y_rescaled_initialfit_residual.std()\n outliers = ((y_rescaled_initialfit_residual > outlierThreshold_sigma) | (y_rescaled_initialfit_residual < -1*outlierThreshold_sigma))\n nonoutliers = ((y_rescaled_initialfit_residual < outlierThreshold_sigma) & (y_rescaled_initialfit_residual > -1*outlierThreshold_sigma))\n\n outliers_positive = ((y_rescaled_initialfit_residual > outlierThreshold_sigma))\n outliers_negative = ((y_rescaled_initialfit_residual < -1*outlierThreshold_sigma))\n num_outliers_positive = list(outliers_positive).count(True)\n num_outliers_negative = list(outliers_negative).count(True)\n outlier_fraction_positive = num_outliers_positive / num_goodData\n outlier_fraction_negative = num_outliers_negative / num_goodData\n\n \"\"\"\n Report clipping results, outliers.\n Save initial fit data to file\n \"\"\"\n if (args.verbose):\n print(\"\\nClipping of outliers\")\n print(\"Data outside the clipping region are classified as outliers\") \n print(\"\\tClipping threshold (sigma) : \", outlierThreshold_sigma)\n print(\"\\tNumber of non-outliers : \", nonoutliers.sum()) \n print(\"\\tTotal number of outliers : \", outliers.sum()) \n print(\"\\tNumber of positive outliers : \", num_outliers_positive) \n print(\"\\tNumber of negative outliers : \", num_outliers_negative) \n print(\"\\tOutlier fraction (positive) : {:.2f}\".format(outlier_fraction_positive))\n print(\"\\tOutlier fraction (negative) : {:.2f}\".format(outlier_fraction_negative))\n\n initial_fit_residual_filename = 'sfr_inst_vs_m_initial_fit_residuals.txt'\n np.savetxt(initial_fit_residual_filename, \\\n np.column_stack((x,sx,y,sy,y_rescaled_initialfit_model,y_rescaled_initialfit_residual)), \\\n fmt=('%5.6f','%5.6f','%5.6f','%5.6f','%5.6f','%5.6f'), \\\n header='x xerr y yerr ymodel yresidual')\n print(\"Initial fit data, model, residuals saved to file: \",initial_fit_residual_filename)\n \n \"\"\" \n REFIT - refit the nonoutlier data to determine a more\n robust estimate of the best fit relationship.\n \"\"\"\n \n \"\"\" \n refit the nonoutlier (from initial fit) data only\n \"\"\"\n x_refit = x[nonoutliers]\n y_refit = y[nonoutliers]\n sx_refit = sx[nonoutliers]\n sy_refit = sy[nonoutliers]\n covxy_refit = covxy_goodData[nonoutliers]\n varxx_refit = varxx_goodData[nonoutliers]\n varyy_refit = varyy_goodData[nonoutliers]\n \n corrxy_refit = corrxy_goodData[nonoutliers]\n source_id_refit = source_id_goodData[nonoutliers]\n \n f87_rescaled_refit_cov_slope,\\\n f87_rescaled_refit_cov_intercept,\\\n f87_rescaled_refit_cov_scatter_variance = linfit_f87(x_refit,\\\n y_refit,\\\n sx_refit,\\\n sy_refit,\\\n covxy = covxy_refit)\n\n \"\"\"\n Compute scatter of refit data with covariance\n \"\"\"\n (ols_rescaled_refit_cov_scatter_variance, total_scatter_variance, xerr_scatter_term, yerr_scatter_term) = scatter_variance_adhoc(x_refit,\\\n y_refit,\\\n sx_refit,\\\n sy_refit,\\\n f87_rescaled_refit_cov_slope,\\\n f87_rescaled_refit_cov_intercept,\\\n covxy = covxy_refit)\n \n \"\"\"\n Convert rescaled refit quantities back to unscaled values \n \"\"\"\n f87_unscaled_refit_cov_slope = f87_rescaled_refit_cov_slope\n f87_unscaled_refit_cov_intercept = f87_rescaled_refit_cov_intercept - x_scale * f87_rescaled_refit_cov_slope\n \n \"\"\"\n Compute model values and residuals\n \"\"\"\n x_rescaled_refit_model = x_refit\n y_rescaled_refit_model = f87_rescaled_refit_cov_intercept + f87_rescaled_refit_cov_slope * x_rescaled_refit_model\n y_rescaled_refit_residual = y_refit - y_rescaled_refit_model\n y_rescaled_refit_residual_sigma = y_rescaled_refit_residual / sy_refit\n\n if (args.verbose): \n print(\"\\nRefit to good data\") \n print(\"\\tBest fit slope : {:.2f}\".format(f87_unscaled_refit_cov_slope))\n print(\"\\tBest fit intercept : {:.2f}\".format(f87_unscaled_refit_cov_intercept))\n print(\"\\tIntrinsic scatter variance F87 : {:.3f}\".format(f87_rescaled_refit_cov_scatter_variance))\n print(\"\\tResiduals (ie residual = (y-y_fit))\") \n print(\"\\t Mean : {:.2f}\".format(y_rescaled_refit_residual.mean()))\n print(\"\\t Std deviation : {:.2f}\".format(y_rescaled_refit_residual.std()))\n print(\"\\tResiduals (unitless; ie residual = (y-y_fit)/y_err)\") \n print(\"\\t Mean : {:.2f}\".format(y_rescaled_refit_residual_sigma.mean()))\n print(\"\\t Std deviation : {:.2f}\".format(y_rescaled_refit_residual_sigma.std()))\n print(\"\\nRefit to good data\")\n scatter_variance_adhoc(x_refit,y_refit,sx_refit,sy_refit,f87_rescaled_refit_cov_slope,f87_rescaled_refit_cov_intercept, verbose = True)\n\n\n (bces_rescaled_refit_slope,\\\n bces_rescaled_refit_intercept,\\\n bces_rescaled_refit_scatter_variance,\\\n f87_rescaled_refit_slope,\\\n f87_rescaled_refit_intercept,\\\n f87_rescaled_refit_scatter_variance,\\\n k07_rescaled_refit_slope,\\\n k07_rescaled_refit_intercept,\\\n k07_rescaled_refit_scatter_variance,\\\n mle_rescaled_refit_slope,\\\n mle_rescaled_refit_intercept,\\\n mle_rescaled_refit_scatter_variance, \\\n odr_rescaled_refit_slope,\\\n odr_rescaled_refit_intercept,\\\n odr_rescaled_refit_scatter_variance,\\\n ols_rescaled_refit_slope,\\\n ols_rescaled_refit_intercept,\\\n ols_rescaled_refit_scatter_variance,\\\n t02_rescaled_refit_slope,\\\n t02_rescaled_refit_intercept,\\\n t02_rescaled_refit_scatter_variance, \\\n wls_rescaled_refit_slope,\\\n wls_rescaled_refit_intercept,\\\n wls_rescaled_refit_scatter_variance) = linfit_multi(x_refit,\\\n y_refit,\\\n sx_refit,\\\n sy_refit)\n\n \"\"\"\n Compute errors to estimated quantities from simulation\n \"\"\"\n (bces_rescaled_refit_slope_bias,\n bces_rescaled_refit_slope_error,\n f87_rescaled_refit_slope_bias,\n f87_rescaled_refit_slope_error,\n k07_rescaled_refit_slope_bias,\n k07_rescaled_refit_slope_error,\n mle_rescaled_refit_slope_bias,\n mle_rescaled_refit_slope_error,\n odr_rescaled_refit_slope_bias,\n odr_rescaled_refit_slope_error,\n ols_rescaled_refit_slope_bias,\n ols_rescaled_refit_slope_error,\n t02_rescaled_refit_slope_bias,\n t02_rescaled_refit_slope_error,\n wls_rescaled_refit_slope_bias,\n wls_rescaled_refit_slope_error,\n bces_rescaled_refit_intercept_bias,\n bces_rescaled_refit_intercept_error,\n f87_rescaled_refit_intercept_bias,\n f87_rescaled_refit_intercept_error,\n k07_rescaled_refit_intercept_bias,\n k07_rescaled_refit_intercept_error,\n mle_rescaled_refit_intercept_bias,\n mle_rescaled_refit_intercept_error,\n odr_rescaled_refit_intercept_bias,\n odr_rescaled_refit_intercept_error,\n ols_rescaled_refit_intercept_bias,\n ols_rescaled_refit_intercept_error,\n odr_rescaled_refit_intercept_bias,\n odr_rescaled_refit_intercept_error,\n t02_rescaled_refit_intercept_bias,\n t02_rescaled_refit_intercept_error,\n wls_rescaled_refit_intercept_bias,\n wls_rescaled_refit_intercept_error,\n bces_rescaled_refit_scatter_variance_bias,\n bces_rescaled_refit_scatter_variance_error,\n f87_rescaled_refit_scatter_variance_bias,\n f87_rescaled_refit_scatter_variance_error,\n k07_rescaled_refit_scatter_variance_bias,\n k07_rescaled_refit_scatter_variance_error,\n mle_rescaled_refit_scatter_variance_bias,\n mle_rescaled_refit_scatter_variance_error,\n odr_rescaled_refit_scatter_variance_bias,\n odr_rescaled_refit_scatter_variance_error,\n ols_rescaled_refit_scatter_variance_bias,\n ols_rescaled_refit_scatter_variance_error,\n odr_rescaled_refit_scatter_variance_bias,\n odr_rescaled_refit_scatter_variance_error,\n t02_rescaled_refit_scatter_variance_bias,\n t02_rescaled_refit_scatter_variance_error,\n wls_rescaled_refit_scatter_variance_bias,\n wls_rescaled_refit_scatter_variance_error)= linfit_multi_simerr(x_refit,\\\n sx_refit,\\\n sy_refit,\\\n f87_rescaled_refit_slope,\\\n f87_rescaled_refit_intercept,\\\n f87_rescaled_refit_scatter_variance,\\\n iterations=args.iterations,\\\n plot_realization=None,\\\n plot_results=None,\\\n write_tables=None,\\\n xerr_type = 'normal',\\\n yerr_type = 'normal', \\\n verbose=None )\n\n \"\"\"\n Model parameter estimates from Kelly (2007)\n Run in IDL and hard-coded here.\n See khsueti:~/analysis/CANDELS/2015-05-16-A/sample01/analysis/run03/\n summary__run03.txt\n \n Table 2. Fit results for method of Kelly (2007) on \n log SFR vs. log M* data for sample01 run03\n \n Version Scatter Var. Slope Intercept\n (1) (2) (3) (4) \n \n --- SFR(100) ---\n v8 0.0570 0.0045 0.9739 0.0143 0.07738 0.0114\n v9* 0.0586 0.0044 0.9723 0.0142 0.0761 0.0113\n v14 0.0516 0.0038 0.9767 0.0141 0.08932 0.0078\n \n --- SFR(Inst) ---\n v10 0.0552 0.0052 0.8402 0.0150 0.0976 0.0116\n v11* 0.0573 0.0052 0.8375 0.0143 0.1000 0.0117\n v15 0.0507 0.0041 0.8601 0.0120 0.0861 0.0089\n \n --- SFR(Life) ---\n v12 0.0024 0.00019 1.0103 0.00039 0.03318 0.00082\n v13* 0.0264 0.00259 1.0385 0.01240 0.08114 0.01000\n v16 0.0228 0.00245 1.0498 0.01172 0.09787 0.00922\n \n Caption: (1) is the version of the fit run, see corresponding .sav file \n for results. v8, v10, v12 were done with mistaken covariance matrix\n elements. This was corrected in v14, v15, v16 (pk 8/10/2015). \n *fits done without covariance. (2) is the best fit \n intrinsic scatter variance and error, determined from mean and std \n deviation of the posterior distribution. (3) is the best fit slope \n (beta, in usage of IDL program) and error. (4) is Intercept and error \n (alpha in usage of IDL program).\n \"\"\"\n k07_rescaled_refit_slope = 9999\n k07_rescaled_refit_slope_error = 9999\n \n k07_rescaled_refit_cov_slope = 9999\n k07_rescaled_refit_cov_slope_error = 9999\n \n k07_rescaled_refit_intercept = 9999\n k07_rescaled_refit_intercept_error = 9999\n \n k07_rescaled_refit_cov_intercept = 9999\n k07_rescaled_refit_cov_intercept_error = 9999\n \n k07_rescaled_refit_scatter_variance = 9999\n k07_rescaled_refit_scatter_variance_error = 9999\n\n k07_rescaled_refit_cov_scatter_variance = 9999\n k07_rescaled_refit_cov_scatter_variance_error = 9999\n k07_rescaled_refit_scatter_variance_frac_error = k07_rescaled_refit_scatter_variance_error / k07_rescaled_refit_scatter_variance\n\n k07_rescaled_refit_cov_scatter_variance_frac_error = k07_rescaled_refit_cov_scatter_variance_error / k07_rescaled_refit_cov_scatter_variance\n \n k07_rescaled_refit_scatter_sigma = np.sqrt(k07_rescaled_refit_scatter_variance)\n k07_rescaled_refit_scatter_sigma_frac_error = 0.5 * k07_rescaled_refit_scatter_variance_frac_error\n k07_rescaled_refit_scatter_sigma_error = k07_rescaled_refit_scatter_sigma * k07_rescaled_refit_scatter_sigma_frac_error\n \n k07_rescaled_refit_cov_scatter_sigma = np.sqrt(k07_rescaled_refit_cov_scatter_variance)\n k07_rescaled_refit_cov_scatter_sigma_frac_error = 0.5 * k07_rescaled_refit_cov_scatter_variance_frac_error\n k07_rescaled_refit_cov_scatter_sigma_error = k07_rescaled_refit_cov_scatter_sigma * k07_rescaled_refit_cov_scatter_sigma_frac_error\n\n k07_refit_slope = k07_rescaled_refit_slope\n k07_refit_intercept = k07_rescaled_refit_intercept - x_scale * k07_rescaled_refit_slope\n\n \"\"\"\n Output text data files with refit logM, logSFR data for use in external\n fitting routines(eg. Kelly (2007) method implemented in IDL)\n \"\"\"\n if (args.verbose):\n refit_data_table_id_cov_corr_filename = 'sfr_inst_vs_m_refit_id_cov_corr.txt' \n refit_data_table_cov_filename = 'sfr_inst_vs_m_refit_cov.txt'\n refit_data_table_filename = 'sfr_inst_vs_m_refit.txt'\n np.savetxt(refit_data_table_filename, \\\n np.column_stack((x_refit,sx_refit,y_refit,sy_refit)), \\\n fmt=('%5.6f','%5.6f','%5.6f','%5.6f'), \\\n header='x_refit,sx_refit,y_refit,sy_refit')\n print(\"Refit data saved to file: \",refit_data_table_filename)\n\n np.savetxt(refit_data_table_cov_filename, \\\n np.column_stack((x_refit,sx_refit,y_refit,sy_refit, covxy_refit)), \\\n fmt=('%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f'), \\\n header='x_refit,sx_refit,y_refit,sy_refit,covxy_refit')\n\n print(\"Refit data and covariances saved to file: \",refit_data_table_cov_filename)\n \n np.savetxt(refit_data_table_id_cov_corr_filename,\n np.column_stack((source_id_refit,x_refit,sx_refit,y_refit,sy_refit,covxy_refit,corrxy_refit)),\n fmt=('%d', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f'), \n header = 'id,x_refit,sx_refit,y_refit,sy_refit,covxy_refit,corrxy_refit')\n\n print(\"Refit id, data, covariances, correlations saved to file: \",refit_data_table_id_cov_corr_filename)\n \n \"\"\"\n Output data for import to database\n \n Save as structured array because np.column_stack chokes\n on mixed string/float data types.\n \"\"\"\n db_import_filename = 'sfr_inst_vs_m_refit_db_table.txt'\n np.savetxt(db_import_filename,\n np.column_stack((source_id_goodData,\n outliers,\n x_goodData_unscaled,\n x_goodData_unscaled_err,\n y_goodData_unscaled,\n y_goodData_unscaled_err,\n covxy_goodData,\n corrxy_goodData)),\n fmt=('%d', '%d', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f'), \n header = 'id outlier x sx y sy covxy corrxy')\n \n print(\"Good data saved to file: \",db_import_filename)\n \n \"\"\"\n Convert rescaled fit quantities back to unscaled values \n \"\"\"\n x_unscaled_refit = x_unscaled[nonoutliers]\n y_unscaled_refit = y_unscaled[nonoutliers]\n\n bces_unscaled_refit_slope = bces_rescaled_refit_slope\n f87_unscaled_refit_slope = f87_rescaled_refit_slope\n k07_unscaled_refit_slope = k07_rescaled_refit_slope\n mle_unscaled_refit_slope = mle_rescaled_refit_slope\n odr_unscaled_refit_slope = odr_rescaled_refit_slope\n ols_unscaled_refit_slope = ols_rescaled_refit_slope\n t02_unscaled_refit_slope = t02_rescaled_refit_slope\n wls_unscaled_refit_slope = wls_rescaled_refit_slope\n \n f87_unscaled_refit_cov_slope = f87_rescaled_refit_cov_slope\n k07_unscaled_refit_cov_slope = k07_rescaled_refit_cov_slope\n\n bces_unscaled_refit_intercept = bces_rescaled_refit_intercept - x_scale * bces_rescaled_refit_slope\n f87_unscaled_refit_intercept = f87_rescaled_refit_intercept - x_scale * f87_rescaled_refit_slope\n k07_unscaled_refit_intercept = k07_rescaled_refit_intercept - x_scale * k07_rescaled_refit_slope\n mle_unscaled_refit_intercept = mle_rescaled_refit_intercept - x_scale * mle_rescaled_refit_slope\n odr_unscaled_refit_intercept = odr_rescaled_refit_intercept - x_scale * odr_rescaled_refit_slope\n ols_unscaled_refit_intercept = ols_rescaled_refit_intercept - x_scale * ols_rescaled_refit_slope\n t02_unscaled_refit_intercept = t02_rescaled_refit_intercept - x_scale * t02_rescaled_refit_slope\n wls_unscaled_refit_intercept = wls_rescaled_refit_intercept - x_scale * wls_rescaled_refit_slope\n\n f87_unscaled_refit_cov_intercept = f87_rescaled_refit_cov_intercept - x_scale * f87_rescaled_refit_cov_slope\n k07_unscaled_refit_cov_intercept = k07_rescaled_refit_cov_intercept - x_scale * k07_rescaled_refit_cov_slope\n\n\n bces_unscaled_refit_scatter_variance = bces_rescaled_refit_scatter_variance\n f87_unscaled_refit_scatter_variance = f87_rescaled_refit_scatter_variance\n k07_unscaled_refit_scatter_variance = k07_rescaled_refit_scatter_variance\n mle_unscaled_refit_scatter_variance = mle_rescaled_refit_scatter_variance\n odr_unscaled_refit_scatter_variance = odr_rescaled_refit_scatter_variance\n ols_unscaled_refit_scatter_variance = ols_rescaled_refit_scatter_variance\n t02_unscaled_refit_scatter_variance = t02_rescaled_refit_scatter_variance\n wls_unscaled_refit_scatter_variance = wls_rescaled_refit_scatter_variance\n\n f87_unscaled_refit_cov_scatter_variance = f87_rescaled_refit_cov_scatter_variance\n ols_unscaled_refit_cov_scatter_variance = ols_rescaled_refit_cov_scatter_variance\n k07_unscaled_refit_cov_scatter_variance = k07_rescaled_refit_cov_scatter_variance\n\n bces_unscaled_refit_scatter_variance_snr = bces_unscaled_refit_scatter_variance/bces_rescaled_refit_scatter_variance_error\n f87_rescaled_refit_scatter_variance_snr = f87_unscaled_refit_scatter_variance/f87_rescaled_refit_scatter_variance_error\n k07_rescaled_refit_scatter_variance_snr = k07_unscaled_refit_scatter_variance/k07_rescaled_refit_scatter_variance_error\n mle_rescaled_refit_scatter_variance_snr = mle_unscaled_refit_scatter_variance/mle_rescaled_refit_scatter_variance_error\n odr_rescaled_refit_scatter_variance_snr = odr_unscaled_refit_scatter_variance/odr_rescaled_refit_scatter_variance_error\n ols_rescaled_refit_scatter_variance_snr = ols_unscaled_refit_scatter_variance/ols_rescaled_refit_scatter_variance_error\n t02_rescaled_refit_scatter_variance_snr = t02_unscaled_refit_scatter_variance/t02_rescaled_refit_scatter_variance_error\n wls_rescaled_refit_scatter_variance_snr = wls_unscaled_refit_scatter_variance/wls_rescaled_refit_scatter_variance_error\n\n f87_rescaled_refit_cov_scatter_variance_snr = f87_unscaled_refit_cov_scatter_variance/f87_rescaled_refit_scatter_variance_error\n\n f87_rescaled_refit_scatter_variance_frac_error = f87_rescaled_refit_scatter_variance_error / f87_rescaled_refit_scatter_variance\n f87_rescaled_refit_cov_scatter_variance_frac_error = f87_rescaled_refit_scatter_variance_error / f87_rescaled_refit_cov_scatter_variance\n f87_rescaled_refit_scatter_sigma = np.sqrt(f87_rescaled_refit_scatter_variance)\n f87_rescaled_refit_scatter_sigma_frac_error = 0.5 * f87_rescaled_refit_scatter_variance_frac_error\n f87_rescaled_refit_scatter_sigma_error = f87_rescaled_refit_scatter_sigma * f87_rescaled_refit_scatter_sigma_frac_error\n \n f87_rescaled_refit_cov_scatter_sigma = np.sqrt(f87_rescaled_refit_cov_scatter_variance)\n f87_rescaled_refit_cov_scatter_sigma_frac_error = 0.5 * f87_rescaled_refit_cov_scatter_variance_frac_error\n f87_rescaled_refit_cov_scatter_sigma_error = f87_rescaled_refit_cov_scatter_sigma * f87_rescaled_refit_cov_scatter_sigma_frac_error\n\n \"\"\"\n correlation coefficients of data set\n \"\"\"\n spearman_rho, spearman_pvalue = s.spearmanr(x_refit,y_refit)\n pearson_rho, pearson_pvalue = s.pearsonr(x_refit,y_refit)\n\n \"\"\"\n y value at a specified x reference value\n \n This determines the value b, in the model equation\n \n y = a (x - x_reference_value) + b\n\n these values are for use in comparing with literature\n log_mass_reference_value = 9.0 means compute log_sfr(log_mass = 9.0) \n (as opposed to using the intercept, which is log sfr(log mass = 0)\n \"\"\"\n x_reference_value = 9.0\n f87_y_at_x_reference_value = f87_unscaled_refit_cov_intercept + x_reference_value * f87_unscaled_refit_cov_slope\n f87_y_at_x_reference_value_error = np.sqrt(f87_rescaled_refit_slope_error**2 + f87_rescaled_refit_intercept_error**2)\n \n if (args.verbose): \n print(\"\\nResults of re-fit to model data\")\n print(\"\\tNumber of data in fit : \", len(y_refit))\n print(\"\\tx_scale : {:.3f}\".format(x_scale))\n print(\"\\ty_scale : {:.3f}\".format(y_scale))\n print(\"\\tSpearman correlation (rho,p) : {:.2f}\".format(spearman_rho), \", {:.6f}\".format(spearman_pvalue))\n print(\"\\tPearson correlation (r,p) : {:.2f}\".format(pearson_rho), \", {:.6f}\".format(pearson_pvalue))\n print(\"\\tQuality of fit\")\n print(\"\\tr^2 (OLS) : {:.3f}\".format(pearson_rho**2))\n print(\"\\nSimulation Inputs and Execution Time (Errors)\")\n print(\"\\tNumber of Realizations : {:d}\".format(args.iterations))\n print(\"\\txerr_type :\",'normal')\n print(\"\\tyerr_type :\",'normal') \n #print(\"\\tElapsed time (seconds) : {:.3f}\".format(elapsed))\n print(\"Parameter Estimates, Bias and Errors from Simulation\")\n print(\"\\tSlope Estimates\")\n print(\"\\t BCES : {:.2f}\".format(bces_unscaled_refit_slope))\n print(\"\\t F87 : {:.2f}\".format(f87_unscaled_refit_slope))\n print(\"\\t k07 : {:.2f}\".format(k07_unscaled_refit_slope))\n print(\"\\t mle : {:.2f}\".format(mle_unscaled_refit_slope))\n print(\"\\t odr : {:.2f}\".format(odr_unscaled_refit_slope))\n print(\"\\t ols : {:.2f}\".format(ols_unscaled_refit_slope))\n print(\"\\t t02 : {:.2f}\".format(t02_unscaled_refit_slope))\n print(\"\\t wls : {:.2f}\".format(wls_unscaled_refit_slope))\n print(\"\\tSlope Bias From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_slope_bias))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_slope_bias))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_slope_bias))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_slope_bias))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_slope_bias))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_slope_bias))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_slope_bias))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_slope_bias))\n print(\"\\tSlope Error From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_slope_error))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_slope_error))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_slope_error))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_slope_error))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_slope_error))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_slope_error))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_slope_error))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_slope_error))\n print(\"\\tIntercept Estimates\")\n print(\"\\t BCES : {:.2f}\".format(bces_unscaled_refit_intercept))\n print(\"\\t F87 : {:.2f}\".format(f87_unscaled_refit_intercept))\n print(\"\\t k07 : {:.2f}\".format(k07_unscaled_refit_intercept))\n print(\"\\t mle : {:.2f}\".format(mle_unscaled_refit_intercept))\n print(\"\\t odr : {:.2f}\".format(odr_unscaled_refit_intercept))\n print(\"\\t ols : {:.2f}\".format(ols_unscaled_refit_intercept))\n print(\"\\t t02 : {:.2f}\".format(t02_unscaled_refit_intercept))\n print(\"\\t wls : {:.2f}\".format(wls_unscaled_refit_intercept))\n print(\"\\tIntercept Bias From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_intercept_bias))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_intercept_bias))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_intercept_bias))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_intercept_bias))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_intercept_bias))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_intercept_bias))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_intercept_bias))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_intercept_bias))\n print(\"\\tIntercept Error From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_intercept_error))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_intercept_error))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_intercept_error))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_intercept_error))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_intercept_error))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_intercept_error))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_intercept_error))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_intercept_error))\n print(\"\\tScatter Variance Estimates\")\n print(\"\\t BCES : {:.5f}\".format(bces_unscaled_refit_scatter_variance))\n print(\"\\t F87 : {:.5f}\".format(f87_unscaled_refit_scatter_variance))\n print(\"\\t k07 : {:.5f}\".format(k07_unscaled_refit_scatter_variance))\n print(\"\\t mle : {:.5f}\".format(mle_unscaled_refit_scatter_variance))\n print(\"\\t odr : {:.5f}\".format(odr_unscaled_refit_scatter_variance))\n print(\"\\t ols : {:.5f}\".format(ols_unscaled_refit_scatter_variance))\n print(\"\\t t02 : {:.5f}\".format(t02_unscaled_refit_scatter_variance))\n print(\"\\t wls : {:.5f}\".format(wls_unscaled_refit_scatter_variance))\n print(\"\\tScatter Variance Bias From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_scatter_variance_bias))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_scatter_variance_bias))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_scatter_variance_bias))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_scatter_variance_bias))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_scatter_variance_bias))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_scatter_variance_bias))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_scatter_variance_bias))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_scatter_variance_bias))\n print(\"\\tScatter Variance Estimate (Bias Adjusted)\")\n print(\"\\t BCES : {:.5f}\".format(bces_unscaled_refit_scatter_variance - bces_rescaled_refit_scatter_variance_bias))\n print(\"\\t F87 : {:.5f}\".format(f87_unscaled_refit_scatter_variance - f87_rescaled_refit_scatter_variance_bias))\n print(\"\\t k07 : {:.5f}\".format(k07_unscaled_refit_scatter_variance - k07_rescaled_refit_scatter_variance_bias))\n print(\"\\t mle : {:.5f}\".format(mle_unscaled_refit_scatter_variance - mle_rescaled_refit_scatter_variance_bias))\n print(\"\\t odr : {:.5f}\".format(odr_unscaled_refit_scatter_variance - odr_rescaled_refit_scatter_variance_bias))\n print(\"\\t ols : {:.5f}\".format(ols_unscaled_refit_scatter_variance - ols_rescaled_refit_scatter_variance_bias))\n print(\"\\t t02 : {:.5f}\".format(t02_unscaled_refit_scatter_variance - t02_rescaled_refit_scatter_variance_bias))\n print(\"\\t wls : {:.5f}\".format(wls_unscaled_refit_scatter_variance - wls_rescaled_refit_scatter_variance_bias))\n print(\"\\tScatter Variance Error From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_rescaled_refit_scatter_variance_error))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_scatter_variance_error))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_scatter_variance_error))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_scatter_variance_error))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_scatter_variance_error))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_scatter_variance_error))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_scatter_variance_error))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_scatter_variance_error))\n print(\"\\tScatter Variance SNR From Simulations\")\n print(\"\\t BCES : {:.5f}\".format(bces_unscaled_refit_scatter_variance/bces_rescaled_refit_scatter_variance_error))\n print(\"\\t F87 : {:.5f}\".format(f87_rescaled_refit_scatter_variance/f87_rescaled_refit_scatter_variance_error))\n print(\"\\t k07 : {:.5f}\".format(k07_rescaled_refit_scatter_variance/k07_rescaled_refit_scatter_variance_error))\n print(\"\\t mle : {:.5f}\".format(mle_rescaled_refit_scatter_variance/mle_rescaled_refit_scatter_variance_error))\n print(\"\\t odr : {:.5f}\".format(odr_rescaled_refit_scatter_variance/odr_rescaled_refit_scatter_variance_error))\n print(\"\\t ols : {:.5f}\".format(ols_rescaled_refit_scatter_variance/ols_rescaled_refit_scatter_variance_error))\n print(\"\\t t02 : {:.5f}\".format(t02_rescaled_refit_scatter_variance/t02_rescaled_refit_scatter_variance_error))\n print(\"\\t wls : {:.5f}\".format(wls_rescaled_refit_scatter_variance/wls_rescaled_refit_scatter_variance_error))\n print(\"Parameter Estimates - Fits with covariances\")\n print(\"\\tSlope Estimates\")\n print(\"\\t F87 : {:.2f}\".format(f87_rescaled_refit_cov_slope))\n print(\"\\t K07 : {:.2f}\".format(k07_rescaled_refit_cov_slope))\n print(\"\\tIntercept Estimates\")\n print(\"\\t F87 : {:.2f}\".format(f87_unscaled_refit_cov_intercept))\n print(\"\\t k07 : {:.2f}\".format(k07_unscaled_refit_cov_intercept))\n print(\"\\tScatter Variance Estimates\")\n print(\"\\t F87 : {:.5f}\".format(f87_unscaled_refit_cov_scatter_variance))\n print(\"\\t OLS : {:.5f}\".format(ols_unscaled_refit_cov_scatter_variance))\n print(\"\\t k07 : {:.5f}\".format(k07_unscaled_refit_cov_scatter_variance))\n print(\"Intercept Estimates at log mass reference value\")\n print(\"\\tX reference value : {:.5f}\".format(x_reference_value))\n print(\"\\tY(ref value) F87 : {:.5f}\".format(f87_y_at_x_reference_value))\n print(\"\\tY(ref value) error F87 : {:.5f}\".format(f87_y_at_x_reference_value_error))\n \n scatter_variance_adhoc(x_refit,y_refit,sx_refit,sy_refit,f87_rescaled_refit_slope,f87_rescaled_refit_intercept, covxy = covxy_refit, verbose = True)\n\n\n spearman_rho, spearman_pvalue = s.spearmanr(x_refit,y_refit)\n pearson_rho, pearson_pvalue = s.pearsonr(x_refit,y_refit)\n \n\n \"\"\"\n Best fit model values\n \"\"\"\n y_refit_model_f87 = f87_rescaled_refit_intercept + f87_rescaled_refit_slope * x_refit \n y_refit_model_odr = odr_rescaled_refit_intercept + odr_rescaled_refit_slope * x_refit\n y_refit_model_ols = ols_rescaled_refit_intercept + ols_rescaled_refit_slope * x_refit\n\n \"\"\"\n Best fit models regularized to 100 data values\n \"\"\"\n x_refit_model100 = np.linspace(x_refit.min(),x_refit.max(),100)\n y_refit_model100_f87 = f87_rescaled_refit_intercept + f87_rescaled_refit_slope * x_refit_model100 \n y_refit_model100_odr = odr_rescaled_refit_intercept + odr_rescaled_refit_slope * x_refit_model100\n y_refit_model100_ols = ols_rescaled_refit_intercept + ols_rescaled_refit_slope * x_refit_model100\n y_refit_model100_bces = bces_rescaled_refit_intercept + bces_rescaled_refit_slope * x_refit_model100\n y_refit_model100_k07 = k07_rescaled_refit_intercept + k07_rescaled_refit_slope * x_refit_model100\n\n \"\"\"\n Best fit, regularized models converted back to unscaled data\n \"\"\"\n x_unscaled_refit_model100 = x_refit_model100 + x_scale \n y_unscaled_refit_model100_f87 = y_scale + f87_rescaled_refit_intercept - x_scale * f87_rescaled_refit_slope + f87_rescaled_refit_slope * x_unscaled_refit_model100 \n y_unscaled_refit_model100_odr = y_scale + odr_rescaled_refit_intercept - x_scale * odr_rescaled_refit_slope + odr_rescaled_refit_slope * x_unscaled_refit_model100\n y_unscaled_refit_model100_ols = y_scale + ols_rescaled_refit_intercept - x_scale * ols_rescaled_refit_slope + ols_rescaled_refit_slope * x_unscaled_refit_model100\n y_unscaled_refit_model100_bces = y_scale + bces_rescaled_refit_intercept - x_scale * bces_rescaled_refit_slope + bces_rescaled_refit_slope * x_unscaled_refit_model100\n y_unscaled_refit_model100_k07 = y_scale + k07_rescaled_refit_intercept - x_scale * k07_rescaled_refit_slope + k07_rescaled_refit_slope * x_unscaled_refit_model100\n \n intercept_high_err = f87_rescaled_refit_intercept + f87_rescaled_refit_intercept_error\n intercept_low_err = f87_rescaled_refit_intercept - f87_rescaled_refit_intercept_error \n slope_high_err = f87_rescaled_refit_slope + f87_rescaled_refit_slope_error\n slope_low_err = f87_rescaled_refit_slope - f87_rescaled_refit_slope_error\n \n y_refit_model100_f87_higherr = intercept_high_err + slope_high_err * x_refit_model100\n y_refit_model100_f87_lowerr = intercept_low_err + slope_low_err * x_refit_model100\n \n y_unscaled_refit_model100_f87_higherr = y_scale + y_refit_model100_f87_higherr \n y_unscaled_refit_model100_f87_lowerr = y_scale + y_refit_model100_f87_lowerr \n \n\n \"\"\" \n Generate the model fit results figure (output file)\n \"\"\" \n # figsize in inches\n # use [4,4] by default\n # use [5,4] when including colorbar\n fig = plt.figure(dpi=300, figsize=[4,4])\n fig.set_tight_layout({'pad':1.08,'h_pad':0.25, 'w_pad':0.25, 'rect':(0,0,0.95,0.95)})\n \n \"\"\"\n Figure - subplot - Data + Model\n \"\"\"\n plot_xlim = [6.25,11]\n #plot_ylim= [-3.0,3.0]\n plot_ylim= [-4.5,3.0]\n\n axis5 = fig.add_subplot(111)\n axis5.set_xlabel(r\"Log Stellar Mass, $M_\\odot$\", fontsize = 12)\n axis5.set_ylabel(r\"Log SFR$_{Inst}$, $M_\\odot$ yr$^{-1}$\", fontsize = 12)\n axis5.set_xlim(plot_xlim)\n axis5.set_ylim(plot_ylim)\n \n \"\"\"\n Main Sequence (Speagle+2014)\n \n NB: Fitted mass range is logM = [9.7,11.1]\n see Speagle+2014, pg. 21, Equation 26 and discussion\n \n \n log SFR = slope * logMass - intercept\n \n time = age of universe at redshift, Gyr\n NB: time(z=1.0) = 5.75\n time(z=2.0) = 3.23\n \n slope = 0.83 pm 0.03 - (0.027 pm 0.004) x time\n intercept = 6.38 pm 0.27 - (0.12 pm 0.04) x time\n \n scaling to M/M^10.5 ...\n \n log SFR = xi * log (Mass/10^10.5) - eta\n \n xi = slope\n eta = intercept - 10.5 * slope\n \n errors (from e-mail exchange with J. Speagle): \n sigma_xi = sigma_slope (no change)\n sigma_eta = 0.003 (time independent term); 0.01 (time dependent term)\n \"\"\"\n \n logMass_Speagle2014 = np.linspace(x_unscaled_refit.min(),x_unscaled_refit.max(),100)\n time_Gyr = cosmo.age(args.zSpeagle2014).value \n slope_Speagle2014 = 0.83 - 0.027 * time_Gyr\n intercept_Speagle2014 = 6.38 - 0.12 * time_Gyr \n logSFR_Speagle2014 = slope_Speagle2014 * logMass_Speagle2014 - intercept_Speagle2014\n \n lowExtrapolation = ((logMass_Speagle2014 > x.min()) & (logMass_Speagle2014 <= 9.7))\n noExtrapolation = ((logMass_Speagle2014 > 9.7) & (logMass_Speagle2014 <= 11.1))\n highExtrapolation= (logMass_Speagle2014 > 11.1)\n \n \n \"\"\"\n Compute errors in Speagle+2014 relationship:\n These are un-rescaled values (taken directly from\n Speagle+2014) they are replaced by mass rescaled\n analysis below.\n \n HighErr - maximize slope and intercept\n LowErr - minimize slope and intercept\n \"\"\"\n slope_HighErr_Speagle2014 = 0.86 - 0.023 * time_Gyr\n intercept_HighErr_Speagle2014 = 6.65 - 0.08 * time_Gyr \n slope_LowErr_Speagle2014 = 0.80 - 0.031 * time_Gyr\n intercept_LowErr_Speagle2014 = 6.11 - 0.16 * time_Gyr \n \n \"\"\"\n recompute Speagle+2014 relation rescaled to M/10^10.5 Msun. \n Rescaling is better for the error analysis. The MS relation\n then takes the form: \n logSFR = xi * log( M/10^10.5 Msun) - eta\n \n To scale relative to log(10.5), set to this:\n x_scale_Speagle2014 = 10.5 \n \n Otherwise, rescale value will be set to the same as the\n input data set \n pk 7/30/2015\n \"\"\"\n x_scale_Speagle2014 = x_scale \n xi = slope_Speagle2014\n eta = intercept_Speagle2014 - x_scale_Speagle2014 * slope_Speagle2014\n xi_HighErr = slope_HighErr_Speagle2014\n xi_LowErr = slope_LowErr_Speagle2014\n \n \"\"\"\n empirical error terms for mass scaled MS relationship. These\n numbers are from Josh Speagle, e-mail 10/7/2014\n \n eta0_err = time independent term error = 0.01\n eta1_err = time dependent term error = 0.003\n \"\"\"\n eta0_err = 0.01\n eta1_err = 0.003\n eta_err = math.sqrt(eta0_err**2 + time_Gyr**2 * eta1_err**2)\n eta_LowErr = eta - eta_err\n eta_HighErr = eta + eta_err\n \n logMass_Rescaled = logMass_Speagle2014 - x_scale_Speagle2014\n logSFR_Rescaled = xi * logMass_Rescaled - eta\n\n \"\"\"\n error curves incorporate errors to both rescaled slope and intercept\n \"\"\"\n logSFR_Speagle2014_HighErr_MassRescaled = xi_HighErr * logMass_Rescaled - eta_LowErr\n logSFR_Speagle2014_LowErr_MassRescaled = xi_LowErr * logMass_Rescaled - eta_HighErr\n\n \"\"\"\n plot the MS line from Speagle+2014 and error region\n \"\"\"\n axis5.plot(logMass_Speagle2014[lowExtrapolation],\\\n logSFR_Speagle2014[lowExtrapolation],\\\n color='Red',\\\n linewidth = 2, \\\n linestyle='dashed')\n axis5.plot(logMass_Speagle2014[noExtrapolation],\\\n logSFR_Speagle2014[noExtrapolation],\\\n color='Red',\\\n linestyle='solid',\\\n linewidth = 2, \\\n label='Speagle+14')\n axis5.plot(logMass_Speagle2014[highExtrapolation],\\\n logSFR_Speagle2014[highExtrapolation],\\\n color='Red',\\\n linewidth = 2, \\\n linestyle='dashed')\n \"\"\"\n axis5.fill_between(logMass_Speagle2014, \\\n logSFR_Speagle2014_LowErr_MassRescaled, \\\n logSFR_Speagle2014_HighErr_MassRescaled, \\\n facecolor = 'Pink',\\\n # hatch = \"X\",\\\n edgecolor = 'Pink', \\\n linewidth=0.0) \n \"\"\" \n \n \"\"\" \n Main Sequence (Whitaker+2014)\n\n Plot the MS best fit curve from Whitaker+2014, based on \n values in Whitaker+2014 Table 1:\n \n redshift\t alow\t\t ahigh\t b\n 0.5 x.min()) & (log_mass_whitaker2014 <= log_mass_lower_limit_whitaker2014))\n whitaker2014_no_extrapolation = ((log_mass_whitaker2014 > log_mass_lower_limit_whitaker2014))\n\n \"\"\"\n plot the MS line from Whitaker+2014\n \"\"\"\n axis5.plot(log_mass_whitaker2014[whitaker2014_low_extrapolation],\\\n log_sfr_whitaker2014[whitaker2014_low_extrapolation],\\\n color='darkcyan',\\\n linewidth = 2, \\\n linestyle='dashed')\n axis5.plot(log_mass_whitaker2014[whitaker2014_no_extrapolation],\\\n log_sfr_whitaker2014[whitaker2014_no_extrapolation],\\\n color='darkcyan',\\\n linestyle='solid', \\\n linewidth = 2, \\\n label = \"Whitaker+14\")\n \n \"\"\"\n Plot My Model Fit:\n error region (bottom layer), data and outliers (middle layer), \n best fit lines and text label (top layer)\n \"\"\"\n axis5.fill_between(x_unscaled_refit_model100, y_unscaled_refit_model100_f87_lowerr, y_unscaled_refit_model100_f87_higherr, \\\n facecolor = 'Thistle',\\\n edgecolor = 'Thistle', \\\n linewidth=0.0)\n\n \"\"\"\n plot points with error bars\n \"\"\"\n \"\"\" \n axis5.errorbar(x_unscaled_refit, \\\n y_unscaled_refit, \\\n xerr=sx_refit, \\\n yerr=sy_refit, \\\n linestyle='None', \\\n color = 'gray', \\\n capsize = 0, \\\n marker='s', \\\n markerfacecolor='gray', \\\n markeredgecolor='gray', \\\n markersize=2, \\\n markeredgewidth=0.5, \\\n alpha = 0.3)\n \"\"\"\n\n \"\"\"\n plot points with no error bars\n \"\"\"\n \n axis5.plot(x_unscaled_refit, \\\n y_unscaled_refit, \\\n linestyle='None', \\\n color = 'black', \\\n alpha = 0.25, \\\n marker='o', \\\n markerfacecolor='black', \\\n markeredgecolor='black', \\\n markersize=2, \\\n markeredgewidth=0.5)\n \n \n \"\"\"\n plot points as error ellipses:\n \n ellipses are color-coded according to the correlation coeff.\n and a color bar is added on the rhs of the plot.\n \n change figure dimensions above to [5,4] when using colorbar \n \n https://m.youtube.com/watch?v=717fVhFKn8E\n http://stackoverflow.com/questions/20126061/creating-a-confidence-ellipses-in-a-sccatterplot-using-matplotlib\n\n http://matplotlib.org/examples/pylab_examples/ellipse_collection.html\n http://stackoverflow.com/questions/20126061/creating-a-confidence-ellipses-in-a-sccatterplot-using-matplotlib\n http://matplotlib.org/api/collections_api.html\n http://matplotlib.org/users/transforms_tutorial.html\n http://matplotlib.org/examples/api/colorbar_only.html\n \"\"\"\n \n \"\"\" \n xydata = np.vsplit(np.transpose(np.vstack([x_unscaled_refit,y_unscaled_refit])),1)\n sigx = sx_refit\n sigy = sy_refit\n sigxy = covxy_refit \n sigxyterm = np.sqrt(0.25 * (sigx**2 - sigy**2)**2 + sigxy**2) \n sigxp2 = 0.5 * (sigx**2 + sigy**2) + sigxyterm\n # this value can go negative, which corresponds to a degenerate ellipse\n # that is a straight line. max(..,0) prevents numerical error in sqrt()\n sigyp2 = max(0.5 * (sigx**2 + sigy**2) - sigxyterm, 0.0)\n semi_major_axis = np.sqrt(sigxp2)\n semi_minor_axis = np.sqrt(sigyp2)\n theta = np.degrees(0.5 * np.arctan2(2*sigxy,(sigx**2 - sigy**2))) \n #norm = mpl.colors.Normalize(vmin = -1.0, vmax = 1.0) \n norm = mpl.colors.Normalize(vmin = corrxy_refit.min(), vmax = corrxy_refit.max()) \n cmap = mpl.cm.jet\n ec = EllipseCollection(2*semi_major_axis,\n 2*semi_minor_axis,\n theta,\n units='x',\n array = corrxy_refit, \n cmap = cmap,\n norm = norm, \n alpha = 0.10,\n offsets=xydata,\n transOffset=axis5.transData)\n #cbar = plt.colorbar(ec, label = 'corr',ticks = [-1,-0.5,0,0.5,1])\n cbar = plt.colorbar(ec, label = 'Corr(SFR,M*)')\n axis5.add_collection(ec)\n \"\"\"\n\n \"\"\"\n Output text data files with refit x,y values and covariance, correlation\n and ellipse theta values for debugging ellipse computation.\n \"\"\"\n \"\"\"\n if (args.verbose):\n refit_data_table_id_cov_corr_theta_filename = 'sfr_inst_vs_m_refit_id_cov_corr_ellipse.txt' \n np.savetxt(refit_data_table_id_cov_corr_theta_filename,\n np.column_stack((source_id_refit,x_refit,sx_refit,y_refit,sy_refit,sx_refit2, sy_refit2, covxy_refit,corrxy_refit, sigxp2, sigyp2, theta)),\n fmt=('%d', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f', '%5.6f'), \n header = 'id,x_refit,sx_refit,y_refit,sy_refit,sx_refit**2,sy_refit**2,covxy_refit,corrxy_refit,sigxp2,sigyp2,theta')\n\n print(\"Refit id, data, covariances, correlations, ellipse theta saved to file: \",refit_data_table_id_cov_corr_theta_filename)\n \"\"\"\n\n \"\"\"\n Draw representative error ellipse in the upper left\n \n https://m.youtube.com/watch?v=717fVhFKn8E\n http://stackoverflow.com/questions/20126061/creating-a-confidence-ellipses-in-a-sccatterplot-using-matplotlib\n \n See error ellipses in action\n https://www.youtube.com/watch?v=E7rnPrwbLmI\n \"\"\"\n \n typical_point_x_value = 7.0\n typical_point_y_value = 1.25\n typical_point_x_error = np.median(sx_refit)\n typical_point_y_error = np.median(sy_refit)\n typical_point_xy_cov = np.median(covxy_refit)\n \n sigx = typical_point_x_error\n sigy = typical_point_y_error\n sigxy = typical_point_xy_cov \n sigxyterm = np.sqrt(0.25 * (sigx**2 - sigy**2)**2 + sigxy**2) \n sigxp2 = 0.5 * (sigx**2 + sigy**2) + sigxyterm\n # this value can go negative, which corresponds to a degenerate ellipse\n # that is a straight line. max(..,0) prevents numerical error in sqrt()\n sigyp2 = max(0.5 * (sigx**2 + sigy**2) - sigxyterm, 0.0)\n semiMajorAxis = np.sqrt(sigxp2)\n semiMinorAxis = np.sqrt(sigyp2)\n # arctan2: \"y\" is the first parameter, \"x\" is the second parameter \n theta = np.degrees(0.5 * np.arctan2(2*sigxy,(sigx**2 - sigy**2))) \n \n ell = Ellipse(xy = (typical_point_x_value,typical_point_y_value), \\\n width = 2*semiMajorAxis, \\\n height = 2*semiMinorAxis, \\\n angle = theta, \\\n alpha = 0.5, \\\n color = 'blue')\n ell.set_facecolor('blue')\n axis5.add_artist(ell)\n \n \"\"\"\n plot a representative point with error bars in the upper left\n \"\"\"\n \"\"\"\n typical_point_x_value = 7.0\n typical_point_y_value = 1.25\n typical_point_x_error = np.median(sx_refit)\n typical_point_y_error = np.median(sy_refit)\n axis5.plot(typical_point_x_value, \\\n typical_point_y_value, \\\n linestyle='None', \\\n color = 'black', \\\n alpha = 0.6, \\\n marker='o', \\\n markerfacecolor='black', \\\n markeredgecolor='black', \\\n markersize=2, \\\n markeredgewidth=0.5)\n \n axis5.errorbar(typical_point_x_value, \\\n typical_point_y_value, \\\n xerr=typical_point_x_error, \\\n yerr=typical_point_y_error, \\\n linestyle='None', \\\n color = 'gray', \\\n capsize = 0, \\\n alpha = 0.6, \\\n marker='s', \\\n markerfacecolor='gray', \\\n markeredgecolor='gray', \\\n markersize=2, \\\n markeredgewidth=0.5)\n \"\"\"\n \n \"\"\"\n plot outliers from fit (clipped points)\n \"\"\"\n \"\"\" \n axis5.errorbar(x_unscaled[outliers], \\\n y_unscaled[outliers], \\\n xerr=sx[outliers], \\\n yerr=sy[outliers], \\\n linestyle='None', \\\n color = 'red', \\\n capsize = 0, \\\n marker='s', \\\n markerfacecolor='lightgray', \\\n markeredgecolor='lightgray', \\\n markersize=2, \\\n markeredgewidth=0.5)\n \"\"\"\n axis5.plot(x_unscaled[outliers], \\\n y_unscaled[outliers], \\\n linestyle='None', \\\n color = 'red', \\\n alpha = 0.25, \\\n marker='o', \\\n markerfacecolor='red', \\\n markeredgecolor='red', \\\n markersize=2, \\\n markeredgewidth=0.5)\n \n axis5.plot(x_unscaled_refit_model100,\\\n y_unscaled_refit_model100_ols,\\\n linewidth = 3, \\\n color='Indigo',\\\n label='Best Fit') \n \"\"\"\n axis5.plot(x_unscaled_refit_model100,\\\n y_unscaled_refit_model100_k07,\\\n color='blueviolet',\\\n label='Kelly (2007)') \n axis5.plot(x_unscaled_refit_model100,\\\n y_unscaled_refit_model100_bces,\\\n color='slateblue',\\\n label='BCES') \n \"\"\"\n \n \"\"\"\n Plot empirical selection functions from Experiment 2015-10-14-A\n\n parameters a-d, f_thresh are defined in Experiment 2015-10-14-A.\n See Summary file and documents therein.\n \n Table 1. sample01 log F160W vs logMass sample02\t\t\n \t\t\n Description\tSlope, c\tIntercept, d\n Avg \t 0.92819\t-7.967815\n sample01&sample03 \n Age > 1.0 Gyr\t\t\n EBV > 0.5\t\t\n EBV < 0.1\t\t\n \t\t\n Table 2a. log F435W vs logSFR\t(100)\t\n \t\t\n Description\t Slope, a\tIntercept, b\n SFR-M* non-outliers\t0.59397\t-1.16422\n Age < 0.1 Gyr \t0.58949\t-1.12391\n Age > 1.0 Gyr \t0.49613\t-1.10587\n \n \n Table 2c. sample02 log F435W vs logSFR (Inst)\t\t\n \t\t\n Description\t Slope, a\tIntercept, b\n Good Correlation\t0.63056\t -1.26\n \n Table 3. Flux threshold\n \n Description Value\n Orig. value 0.012\n Uniform value 0.025\n\n Caption: Flux threshold used below as f_thresh. See Excel\n Spreadsheet in ...Manuscripts/2015/.../Analysis/2015-10-14-A/\n\n Below parameters correspond to age > 1.0 Gyr subsample of sample00,\n which leads to the most extreme selection function (ie that which\n impinges most upon the range sampled by our data)\n \"\"\"\n a=0.63056\n b=-1.26\n c=0.92819\n d=-7.967815\n f_thresh = 0.025\n\n x_selection_function = np.linspace(5.0,10.0,1000) \n y_selection_function = -1*b/a + (1/a)*np.log10(2*f_thresh - 10**(c*x_selection_function + d))\n axis5.plot(x_selection_function, \n y_selection_function,\n linewidth = 3, \n color = 'Black')\n\n \"\"\"\n Plot text label: intrinsic scatter\n \"\"\" \n text_label_scatter =r\"$\\sigma_{is} = \" + r\"{:.3f}\".format(f87_rescaled_refit_cov_scatter_sigma) + r\"\\pm\"+ r\"{:.3f}\".format(f87_rescaled_refit_cov_scatter_sigma_error)+r\"$\"\n text_label_r2 = r\"$r^2 = \" + r\"{:.2f}\".format(pearson_rho**2) + r\"$\"\n \n \"\"\"\n Text labels in lower left\n \"\"\"\n \"\"\"\n axis5.text(8.75,-2.0,text_label_r2,fontsize='small', fontweight=\"bold\")\n axis5.text(8.75,-2.3,text_label_scatter,fontsize='small', fontweight=\"bold\")\n \"\"\"\n\n \"\"\"\n Text labels in upper right\n \"\"\" \n axis5.text(6.5, 2.4,text_label_r2,fontsize='small', fontweight=\"bold\")\n axis5.text(6.5, 2.0,text_label_scatter,fontsize='small', fontweight=\"bold\")\n \n #axis5.legend(loc='upper left', fontsize='small')\n\n fig.savefig(args.output_file, format='pdf') \n if (args.display):\n plt.show()\n\n\n\n \"\"\"\n ANALYZE FINAL MODEL FIT RESIDUALS \n \n Compute the residuals to the best refit model and identify outliers \n \"\"\" \n y_refit_residual = y_refit - y_refit_model_f87\n y_refit_residual_squared = y_refit_residual**2\n y_refit_residual_sigma = y_refit_residual / sy_refit\n y_refit_residual_sigma_squared = y_refit_residual_sigma**2\n if (args.verbose):\n print(\"\\nSummary of Refit Residuals\")\n print(\"Units of data, ie residual = y-y_fit\") \n print(\"\\tMin : {:.2f}\".format(y_refit_residual.min()))\n print(\"\\tMean : {:.2f}\".format(y_refit_residual.mean()))\n print(\"\\tMax : {:.2f}\".format(y_refit_residual.max()))\n print(\"\\tStd deviation : {:.2f}\".format(y_refit_residual.std()))\n print(\"\\tSum of squares (ESS) : {:.2f}\".format(y_refit_residual_squared.sum()))\n print(\"Unitless ('sigma'), ie residual = (y-y_fit)/y_err\")\n print(\"\\tMin : {:.2f}\".format(y_refit_residual_sigma.min()))\n print(\"\\tMean : {:.2f}\".format(y_refit_residual_sigma.mean()))\n print(\"\\tMax : {:.2f}\".format(y_refit_residual_sigma.max()))\n print(\"\\tStd deviation : {:.2f}\".format(y_refit_residual_sigma.std()))\n print(\"\\tSum of squares (chisq) : {:.2f}\".format(y_refit_residual_sigma_squared.sum()))\n\n \"\"\" \n RESIDUALS - BIN SCAT \n \n Histogram analysis of refit residuals\n \"\"\"\n \n \"\"\"\n x_bins must be consistent with y_binscat_binX definitions below\n eg. x_bins = np.array([1.0, 8.0, 9.0, 20.0])\n where bin1 = [1.0, 8.0]\n bin2 = [8.0, 9.0]\n bin3 = [9.0, 20.0]\n \"\"\"\n x_bins = np.array([1.0, 8.0, 9.0, 20.0])\n \n \n x_binscat = x_unscaled_refit\n \"\"\" \n Old method of plotting residuals\n \"\"\"\n #y_binscat = y_refit_residual_sigma\n \"\"\"\n New method of plotting residuals\n pk 7/1/2015\n \"\"\" \n y_binscat = y_refit_residual\n \n ndata_in_x_bin, _ = np.histogram(x_binscat, bins=x_bins)\n sum_y_binscat, _ = np.histogram(x_binscat, bins=x_bins, weights=y_binscat)\n sum_y2_binscat, _ = np.histogram(x_binscat, bins=x_bins, weights=y_binscat*y_binscat)\n \n \"\"\"\n mean, stddev of residuals in each x_bin\n \"\"\"\n mean_binscat = sum_y_binscat / ndata_in_x_bin\n std_binscat = np.sqrt(sum_y2_binscat/ndata_in_x_bin - mean_binscat*mean_binscat)\n \n \"\"\"\n indices of galaxies in each x_bin. Values are 1...Number of \n x Bins, where the integer specifies which bin for each galaxy\n \"\"\"\n x_indices = np.digitize(x_binscat,x_bins)\n \n \"\"\"\n compute descriptive statistics of x for each x bin\n \n e.g. element i of mean_x_bin is the mean x\n of all elements in bin i of x_bins (ie. data with \n x_bins[i-1] <= x < x_bins[i]) \n \"\"\"\n mean_x_bin = np.zeros(x_bins.size)\n median_x_bin = np.zeros(x_bins.size)\n std_x_bin = np.zeros(x_bins.size)\n for index, value in np.ndenumerate(x_bins):\n if index[0] > 0: \n mean_x_bin[index] = np.nanmean(x_binscat[(x_indices == index)])\n median_x_bin[index] = np.median(x_binscat[(x_indices == index)])\n std_x_bin[index] = np.std(x_binscat[(x_indices == index)])\n \n \"\"\"\n assign y values in each of 3 x bins (for boxplot).\n This binning scheme must match definition of x_bins above\n \"\"\"\n y_binscat_bin1 = y_binscat[(x_indices == 1)]\n y_binscat_bin2 = y_binscat[(x_indices == 2)]\n y_binscat_bin3 = y_binscat[(x_indices == 3)]\n y_boxplot_data = [y_binscat_bin1, y_binscat_bin2, y_binscat_bin3]\n \n if (args.verbose):\n print(\"\\nSummary of x binned residuals\")\n print(\"Number of bins: \",np.size(x_bins)-1)\n print(\"\\nBin 1\")\n print(\"\\tNumber of data in bin : \", y_binscat_bin1.size)\n print(\"\\tx Range : \", x_bins[0:2])\n print(\"\\tx Bin - Mean : {:.2f}\".format(mean_x_bin[1]))\n print(\"\\tx Bin - Median : {:.2f}\".format(median_x_bin[1]))\n print(\"\\tx Bin - Std Dev : {:.2f}\".format(std_x_bin[1])) \n print(\"\\tResidual - Mean : {:.2f}\".format(y_binscat_bin1.mean()))\n print(\"\\tResidual - Median : {:.2f}\".format(np.median(y_binscat_bin1)))\n print(\"\\tResidual - Std Dev : {:.2f}\".format(np.std(y_binscat_bin1)))\n \n print(\"\\nBin 2\")\n print(\"\\tNumber of data in bin : \", y_binscat_bin2.size)\n print(\"\\tx Range : \", x_bins[1:3])\n print(\"\\tx Bin - Mean : {:.2f}\".format(mean_x_bin[2]))\n print(\"\\tx Bin - Median : {:.2f}\".format(median_x_bin[2]))\n print(\"\\tx Bin - Std Dev : {:.2f}\".format(std_x_bin[2])) \n print(\"\\tResidual - Mean : {:.2f}\".format(y_binscat_bin2.mean()))\n print(\"\\tResidual - Median : {:.2f}\".format(np.median(y_binscat_bin2)))\n print(\"\\tResidual - Std Dev : {:.2f}\".format(np.std(y_binscat_bin2)))\n \n print(\"\\nBin 3\")\n print(\"\\tNumber of data in bin : \", y_binscat_bin3.size)\n print(\"\\tx Range : \", x_bins[2:4])\n print(\"\\tx Bin - Mean : {:.2f}\".format(mean_x_bin[3]))\n print(\"\\tx Bin - Median : {:.2f}\".format(median_x_bin[3]))\n print(\"\\tx Bin - Std Dev : {:.2f}\".format(std_x_bin[3])) \n print(\"\\tResidual - Mean : {:.2f}\".format(y_binscat_bin3.mean()))\n print(\"\\tResidual - Median : {:.2f}\".format(np.median(y_binscat_bin3)))\n print(\"\\tResidual - Std Dev : {:.2f}\".format(np.std(y_binscat_bin3)))\n \n \n \"\"\"\n CREATE FIGURE - RESIDUAL PLOT\n \n Generate combined box plot and residual plot\n \n See David Wittman's example page:\n http://www.physics.ucdavis.edu/~dwittman/Matplotlib-examples/\n http://www.physics.ucdavis.edu/~dwittman/Matplotlib-examples/plotexpresids.txt\n \n \"\"\"\n \n # figsize in inches\n fig2 = plt.figure(dpi=300, figsize=[4,4])\n #fig.set_tight_layout({'pad':1.08,'h_pad':0.25, 'w_pad':0.25, 'rect':(0.05,0.05,0.95,0.95)})\n #fig.suptitle('y vs x (sample01/run01; ODR Estimation)', fontsize=12)\n \n plot_xlim= [6.25,11]\n #plot_ylim = [-3.5,2.0]\n plot_ylim = [-5.5,2.5]\n\n \"\"\"\n FIGURE - RESIDUAL PLOT\n \n Plot y residuals vs x. Outliers that were discarded\n from the clipping/refit process are shown in red.\n \"\"\"\n axis6 = fig2.add_subplot(211)\n #axis1.set_title(\"Data\", fontsize = 12)\n #axis1.set_xlabel(r\"log Stellar Mass, $M_\\odot$\", fontsize = 12)\n #axis1.set_ylabel(r\"residual ($\\sigma$) in log SFR\", fontsize = 12)\n \"\"\"\n Plot the data with error bars in x, y\n marker options: \n 's' square\n 'o' filled circle\n \"\"\"\n plt.scatter(x_unscaled_refit, \\\n y_refit_residual, \\\n color = 'blue', \\\n marker='o', \\\n alpha = 0.5)\n \n plt.scatter(x_unscaled[outliers], \\\n y_rescaled_initialfit_residual[outliers], \\\n color = 'red', \\\n marker='o', \\\n alpha = 0.5)\n axis6.set_xlim(plot_xlim)\n axis6.set_ylim(plot_ylim)\n axis6.xaxis.set_major_formatter( NullFormatter() )\n\n \n \"\"\"\n FIGURE - BOX PLOT\n \n Draw the box plot, illustrating quartiles of the y residuals\n in bins of x. Boxes are labeld \n \n see: http://en.wikipedia.org/wiki/Box_plot\n http://matplotlib.org/examples/pylab_examples/boxplot_demo2.html\n \n median value: red line\n IQR (inter-quartile range): box (upper Q3, lower Q1)\n Q1 - 1.5xIQR, Q3 + 1.5 x IQR: upper, lower whiskers\n \n NB: Quartile\n http://en.wikipedia.org/wiki/Quartile\n \n quartiles of a ranked set of data values are the three points that divide \n the data set into four equal groups, each group comprising a quarter of \n the data. A quartile is a type of quantile. The first quartile (Q1) is \n defined as the middle number between the smallest number and the median \n of the data set. The second quartile (Q2) is the median of the data. \n The third quartile (Q3) is the middle value between the median and \n the highest value of the data set.\n \"\"\"\n \n axis7 = fig2.add_subplot(212)\n #plot_ylim = [-1.9,1.9]\n plot_ylim = [-2.5,2.5]\n bp = plt.boxplot(y_boxplot_data, positions = median_x_bin[1:], notch=0, sym='+', vert=1, whis=1.5)\n plt.setp(bp['boxes'], color='black')\n plt.setp(bp['whiskers'], color='black')\n plt.setp(bp['fliers'], color='blue', marker='+')\n axis7.set_xlim(plot_xlim)\n axis7.set_ylim(plot_ylim)\n axis7.xaxis.set_major_locator(MultipleLocator(1.0))\n \n plt.figtext(0.3,0.02,\"Log Stellar Mass, $M_\\odot$\",fontdict={'fontsize':12})\n #plt.figtext(0.01,0.7,\"residual ($\\sigma$) in log SFR\",fontdict={'fontsize':12},rotation=90)\n plt.figtext(0.01,0.7,\"Residual in Log SFR\",fontdict={'fontsize':12},rotation=90)\n plt.subplots_adjust(wspace=0,hspace=0)\n \n \"\"\"\n Save the plot as a .pdf file\n \"\"\"\n residual_output_file= args.output_file[:-4]+'_residual.pdf'\n fig2.savefig(residual_output_file, format='pdf')\n \n if (args.display):\n plt.show()\n\n if (args.verbose): \n print(\"\\nExecutive summary\") \n print(\"\\tNumber of data in fit : \", len(y_refit)) \n print(\"\\tSlope F87 : {:.3f}\".format(f87_unscaled_refit_cov_slope) + \"$\\pm${:.3f}\".format(f87_rescaled_refit_slope_error))\n print(\"\\tIntercept F87 : {:.3f}\".format(f87_unscaled_refit_cov_intercept) + \"$\\pm${:.3f}\".format(f87_rescaled_refit_intercept_error))\n print(\"\\tXRef : {:.3f}\".format(x_reference_value)) \n print(\"\\tY(XRef) F87 : {:.3f}\".format(f87_y_at_x_reference_value) +\"$\\pm${:.3f}\".format(f87_y_at_x_reference_value_error))\n print(\"\\tIntrinsic scatter (sigma) F87 : {:.3f}\".format(f87_rescaled_refit_cov_scatter_sigma) + \"$\\pm${:.3f}\".format(f87_rescaled_refit_cov_scatter_sigma_error))\n print(\"\\tTotal scatter (dex) F87 : {:.3f}\".format(y_rescaled_refit_residual.std()))\n print(\"\\tOutlier fraction (positive) : {:.3f}\".format(outlier_fraction_positive))\n print(\"\\tOutlier fraction (negative) : {:.3f}\".format(outlier_fraction_negative))\n print(\"\\tMedian (reduced) chisq : {:.3f}\".format(chisqv_goodData_median))\n\n print(\"\\nsfr_inst_vs_m_line_clip_sim_linexp.py Done!\")","sub_path":"sample02/run03b/analysis/sfr_vs_m_linfit_py/sfr_inst_vs_m_line_clip_sim_linexp_chisq100.py","file_name":"sfr_inst_vs_m_line_clip_sim_linexp_chisq100.py","file_ext":"py","file_size_in_byte":78001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"470379063","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 14 22:08:47 2021\n\n@author: Caven\n\"\"\"\n\n\nclass Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n n = len(graph)\n safe = [False] * n\n \n graph = [set(i) for i in graph]\n rgraph = [set() for i in range(n)]\n q = collections.deque([])\n \n for i, js in enumerate(graph):\n if not js:\n q.append(i)\n for j in js:\n rgraph[j].add(i)\n \n while q:\n j = q.popleft()\n \n safe[j] = True\n \n for i in rgraph[j]:\n graph[i].remove(j)\n if len(graph[i]) == 0:\n q.append(i)\n \n return [i for i,v in enumerate(safe) if v]","sub_path":"802. Find Eventual Safe States.py","file_name":"802. Find Eventual Safe States.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"242999002","text":"class Fur():\n def __init__(self, name, area):\n self.name = name\n self.area = area\n\n # def __str__(self):\n # return f'家具名字:{self.name},家具面积:{self.area}'\n\n\nclass Home():\n # 这是构造方法,构造的时候传入参数\n def __init__(self, address, area):\n self.area = area\n self.address = address\n # 剩余面积\n self.free_area = area\n # 家具列表\n self.furs = []\n\n def __str__(self):\n return f'家具地址:{self.address},还剩下:{self.free_area},有那些家具:{self.furs}'\n\n def add_fur(self, item):\n # 该家具的面积 <=剩余的面积 ,可以添置\n if item.area <= self.free_area:\n # 这里注意为name,如果直接传入 item这个对象,好像item对象有_str_()方法也不toString\n self.furs.append(item.name)\n self.free_area -= item.area\n else:\n print('没地方啊')\n\n\nfur = Fur('椅子', 10)\nfur2 = Fur('桌子', 2)\n\nhome = Home('beij', 1000)\nhome.add_fur(fur)\nhome.add_fur(fur2)\nprint(home)\n","sub_path":"day12/5.家具案例.py","file_name":"5.家具案例.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"493276576","text":"from pyecharts import options as opts\nfrom pyecharts.charts import Bar\nfrom pyecharts.faker import Faker\nfrom pymysql import *\n\nnamelist = []\nnumlist = []\n\ndef getdata():\n conn = connect(host='localhost',\n port=3306,\n user='root',\n password='1234',\n database='db_lp',\n charset='utf8')\n cursor = conn.cursor()\n try:\n sql_name = \"\"\" SELECT b_grade FROM statistics \"\"\"\n cursor.execute(sql_name)\n names = cursor.fetchall()\n for name in names:\n namelist.append(name[0])\n # print(namelist)\n sql_num = \"\"\" SELECT count FROM statistics \"\"\"\n cursor.execute(sql_num)\n nums = cursor.fetchall()\n for num in nums:\n numlist.append(num[0])\n # print(numlist)\n except:\n print(\"未查询到数据!\")\n conn.rollback()\n finally:\n conn.close()\n\ndef drawecharts():\n bar = Bar()\n bar.add_xaxis(namelist)\n bar.add_yaxis(\"图书本数\", numlist, color=Faker.rand_color())\n bar.set_global_opts(\n title_opts=opts.TitleOpts(title=\"评分-本数\"),\n datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_=\"inside\")],\n )\n bar.render(\"评分-本数.html\")\n\n\nif __name__ == '__main__':\n getdata()\n drawecharts()\n","sub_path":"bookcommend-python/评分-本数.py","file_name":"评分-本数.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"209461114","text":"import torch\nimport torch.nn as nn\n\nfrom .resnet50_ft_dag import Resnet50_ft_dag\n\n\nclass CnnSelfAttSum(nn.Module):\n def __init__(self, num_patch, embed_dim, output_dim, num_heads, dropout, cnn_ckpt=None):\n super(CnnSelfAttSum, self).__init__()\n\n self.embed_dim = embed_dim\n self.num_patch = num_patch\n self.num_heads = num_heads\n\n self.cnn = Resnet50_ft_dag(output_dim=self.embed_dim)\n if cnn_ckpt:\n self._load_pretrain_resnet50vgg(cnn_ckpt)\n self.norm_cnn = nn.LayerNorm(self.embed_dim)\n\n self.self_att1 = nn.MultiheadAttention(embed_dim=self.embed_dim, num_heads=self.num_heads)\n self.norm_att1 = nn.LayerNorm(self.embed_dim)\n self.self_att2 = nn.MultiheadAttention(embed_dim=self.embed_dim, num_heads=self.num_heads)\n self.norm_att2 = nn.LayerNorm(self.embed_dim)\n\n self.norm_sum = nn.BatchNorm1d(self.embed_dim)\n\n self.fc = nn.Linear(self.embed_dim, output_dim)\n\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n # cnn\n bs, num_patch, num_c, H, W = x.shape\n assert num_patch == self.num_patch\n\n x = x.reshape(bs*self.num_patch, num_c, H, W).contiguous()\n x = self.cnn(x)\n # reshape for transformer input\n x = x.reshape(bs, self.num_patch, self.embed_dim).contiguous()\n x = self.norm_cnn(x)\n\n # only torch 1.9 above support batch_first\n x = x.permute(1, 0, 2)\n x, _ = self.self_att1(x, x, x) # output: attn_output, attn_output_weights\n x = self.dropout(self.norm_att1(x))\n x, _ = self.self_att2(x, x, x) # output: attn_output, attn_output_weights\n x = self.dropout(self.norm_att2(x))\n\n # reshape for output\n x = x.permute(1, 0, 2)\n x = self.norm_sum(torch.sum(x, dim=1))\n # classifier\n x = self.fc(x)\n\n return x\n\n def _load_pretrain_resnet50vgg(self, ckpt):\n checkpoint = torch.load(ckpt)\n\n classifier_name = 'classifier'\n del checkpoint[classifier_name + '.weight']\n del checkpoint[classifier_name + '.bias']\n print('checkpoint head is discarded.')\n\n self.cnn.load_state_dict(checkpoint, strict=False)\n print(f'CNN pretrained weights is loaded')\n\n # freeze weights\n # for p in self.cnn.parameters():\n # p.requires_grad = False\n # # unfreeze classifier\n # self.cnn.classifier.weight.requires_grad = True\n # self.cnn.classifier.bias.requires_grad = True\n # print('Partial weights freezed')\n\n\n\n\n\n\n\n\n","sub_path":"models/cnn_self_attention_sum.py","file_name":"cnn_self_attention_sum.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106724656","text":"from artists.artist import Artist\nfrom data.colors import WHITE\nfrom data.constants import SCREEN_SIZE\nfrom models.combat_model import CombatModel\nfrom views.pygame_screen import Screen\n\n\nclass ActorArtist(Artist):\n ENEMY_SCALE = 1.9\n ENEMY_SIZE = (int(90 * ENEMY_SCALE), int(140 * ENEMY_SCALE))\n CHARACTER_SCALE = 4\n CHARACTER_SIZE = (int(32 * CHARACTER_SCALE), int(32 * CHARACTER_SCALE))\n ENEMY_X = SCREEN_SIZE[0] - 500\n ENEMY_Y = 200\n CHAR_X = 300\n CHAR_Y = 300\n\n def render(self, screen: Screen, model: CombatModel) -> None:\n enemy_life_str = '{}/{}'.format(model.skeleton.hp, model.skeleton.max_hp)\n screen.render_text(enemy_life_str, 30, ActorArtist.ENEMY_X, ActorArtist.ENEMY_Y-20, WHITE)\n screen.render_enemy(model.skeleton.sprite, ActorArtist.ENEMY_X,\n ActorArtist.ENEMY_Y, ActorArtist.ENEMY_SIZE)\n\n char_life_str = '{}/{}'.format(model.character.hp, model.character.max_hp)\n screen.render_text(char_life_str, 30, ActorArtist.CHAR_X, ActorArtist.CHAR_X - 20, WHITE)\n screen.render_character(model.character.sprite, ActorArtist.CHAR_X,\n ActorArtist.CHAR_Y, ActorArtist.CHARACTER_SIZE)\n","sub_path":"src/artists/actor_artist.py","file_name":"actor_artist.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440483029","text":"# Notes:\n# 1. References at the end.\n# 2. Used reference [2] throughout.\n# 3. Data downloaded from reference [7].\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n'''\nUsed reference [3] and [4] for dealing with lists and arrays here. \n'''\n# Taking in data from the csv file\nwith open('iris.csv', 'r') as csvFile:\n # Reading that data\n reader = csv.reader(csvFile)\n # Create lists for seperated data\n setosaList = []\n versicolorList = []\n virginicaList = []\n allDataSet = []\n \n # Seperate data in accordance with the iris type\n for row in reader:\n if row[4] == \"Iris-setosa\":\n setosaList.append(row[0:4])\n\n elif row[4] == \"Iris-versicolor\":\n versicolorList.append(row[0:4])\n \n elif row[4] == \"Iris-virginica\":\n virginicaList.append(row[0:4])\n \n else:\n print(\"Unlabled entry.\")\n \n # Collect all data into one array\n allDataSet.append(row[0:4])\n \n# Check to see if all data is there (50 in each)\nif len(virginicaList) != 50 | len(versicolorList) != 50 | len(setosaList):\n print(\"Error with size of Lists.\")\n'''\nUsed reference [8] here to determine what to do whit the arrays\n'''\n# Convert lists to numpy arrays with floats\nSetosa = np.array(setosaList).astype(np.float)\nVersicolor = np.array(versicolorList).astype(np.float)\nVirginica = np.array(virginicaList).astype(np.float)\nirisDataSet = np.array(allDataSet).astype(np.float)\n\n# Make an array with each iris as an element for easier access\nflowers = [Setosa, Versicolor, Virginica]\n\n# Function that will go through and lable iris type (name) and call minMaxMean\ndef allFlowers(allFlowers):\n for i in range(0,len(allFlowers)):\n \n if i == 0:\n name = \"Setosa\"\n elif i == 1:\n name = \"Versicolor\"\n elif i == 2:\n name = \"Virginica\"\n else:\n print(\"Error with data set. Please investigate.\")\n minMaxMean(allFlowers[i], name)\n\n# Calculate min, max and mean of each element of the data for each iris\ndef minMaxMean(arrayName, name):\n\n name = name\n #set values for each\n SepLmin = np.min(arrayName[:,0])\n SepLmax = np.max(arrayName[:,0])\n SepLmean = np.mean(arrayName[:,0])\n SepLstd = np.std(arrayName[:,0])\n \n SepWmin = np.min(arrayName[:,1])\n SepWmax = np.max(arrayName[:,1])\n SepWmean = np.mean(arrayName[:,1])\n SepWstd = np.std(arrayName[:,1])\n \n PetLmin = np.min(arrayName[:,2])\n PetLmax = np.max(arrayName[:,2])\n PetLmean = np.mean(arrayName[:,2])\n PetLstd = np.std(arrayName[:,2])\n \n PetWmin = np.min(arrayName[:,3])\n PetWmax = np.max(arrayName[:,3])\n PetWmean = np.mean(arrayName[:,3])\n PetWstd = np.std(arrayName[:,3])\n \n # Print all values\n print(f\"\\nFor {name}:\\n\"\n f\"Sepal Length min, max, mean and standard deviation: {round(SepLmin, 2)}, {round(SepLmax, 2)}, {round(SepLmean, 2)}, {round(SepLstd, 2)}\\n\"\n f\"Sepal width min, max, mean and standard deviation: {round(SepWmin, 2)}, {round(SepWmax, 2)}, {round(SepWmean, 2)}, {round(SepWstd, 2)}\\n\"\n f\"Petal length min, max, mean and standard deviation: {round(PetLmin, 2)}, {round(PetLmax, 2)}, {round(PetLmean, 2)}, {round(PetLstd, 2)}\\n\"\n f\"Petal width min, max, mean and standard deviation: {round(PetWmin, 2)}, {round(PetWmax, 2)}, {round(PetWmean, 2)}, {round(PetWstd, 2)}\")\n print(\"\\n\")\n\n# Call function to go through each Iris and produce min, max and mean\nallFlowers(flowers)\n'''\nUsed reference [5] and [6] to mainly get the graphs looking the way I wanted and to tidy code\n'''\n# Creating scatter plots\n\n# First scatter plot: Sepal length vs. sepal width\n\n# Setosa Sepal length and width\nsetSepLvW = (Setosa[:,0], Setosa[:,1])\n# Versicolor Sepal length and width\nverSepLvW = (Versicolor[:,0], Versicolor[:,1])\n# Virginica Sepal length and width\nvirSepLvW = (Virginica[:,0], Virginica[:,1])\n\n# Setting up graph\ndata = (setSepLvW, verSepLvW, virSepLvW)\ncolors = (\"red\", \"green\", \"blue\")\ngroups = (\"Setosa\", \"Versicolor\", \"Virginica\")\n\n# Create plot\nfig = plt.figure()\n# Set one by one grid\nax = fig.add_subplot(1, 1, 1)\n\nfor data, color, group in zip(data, colors, groups):\n x, y = data\n ax.scatter(x, y, alpha = 0.8, c=color, edgecolors='none', s=30, label=group)\n\nplt.xlabel(\"length (cm)\")\nplt.ylabel(\"width (cm)\")\n\nplt.title(\"Sepal Length vs Sepal Width\")\nplt.legend(loc=2)\nplt.show()\n\n# Second scatter plot: Petal length vs. Petal width\n\n# Setosa Petal length and width\nsetPetLvW = (Setosa[:,2], Setosa[:,3])\n# Versicolor Petal length and width\nverPetLvW = (Versicolor[:,2], Versicolor[:,3])\n# Virginica Petal length and width\nvirPetLvW = (Virginica[:,2], Virginica[:,3])\n\n# Setting up graph\ndata = (setPetLvW, verPetLvW, virPetLvW)\ncolors = (\"red\", \"green\", \"blue\")\ngroups = (\"Setosa\", \"Versicolor\", \"Virginica\")\n\n# Create plot\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\nfor data, color, group in zip(data, colors, groups):\n x, y = data\n ax.scatter(x, y, alpha = 0.8, c=color, edgecolors='none', s=30, label=group)\n\nplt.xlabel(\"length (cm)\")\nplt.ylabel(\"width (cm)\")\n\nplt.title(\"Petal Length vs Petal Width\")\nplt.legend(loc=2)\nplt.show()\n\n# Third scatter plot: Sepal length*width vs. Petal length*width\n\n# Setosa Sepal length*width\nsetSepLbW = (Setosa[:,0]*Setosa[:,1])\n# Setosa Petal length*width\nsetPetLbW = (Setosa[:,2]*Setosa[:,3])\n# Setosa Sepal and Petal\nsetosaPlot = (setSepLbW, setPetLbW)\n\n# Versicolor Sepal length*width\nverSepLbW = (Versicolor[:,0]*Versicolor[:,1])\n# Versicolor Petal length*width\nverPetLbW = (Versicolor[:,2]*Versicolor[:,3])\n# Versicolor Sepal and Petal\nversicolorPlot = (verSepLbW, verPetLbW)\n\n# Virginica length*width\nvirSepLbW = (Virginica[:,0]*Virginica[:,1])\n# Virginica length*width\nvirPetLbW = (Virginica[:,2]*Virginica[:,3])\n# Virginica Sepal and Petal\nvirginicaPlot = (virSepLbW, virPetLbW)\n\n\n# Setting up graph\ndata = (setosaPlot, versicolorPlot, virginicaPlot)\ncolors = (\"red\", \"green\", \"blue\")\ngroups = (\"Setosa\", \"Versicolor\", \"Virginica\")\n\n# Create plot\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\nfor data, color, group in zip(data, colors, groups):\n x, y = data\n ax.scatter(x, y, alpha = 0.8, c=color, edgecolors='none', s=30, label=group)\n\nplt.xlabel(\"Sepal L x W (cm^2)\")\nplt.ylabel(\"Petal L X W (cm^2)\")\n\nplt.title(\"Sepal Length by Width vs. Petal Length by Width\")\nplt.legend(loc=2)\nplt.show()\n\n'''\nUsed Reference 1 'Machine Learning with Python Cookbook' for all next section except prompts and if statement.\n'''\n# K-Nearest Neighbors\n# Using this algorithm wit the data we have we can find a new data entry (an unidentified iris)\n# and find a closest match to it.\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\n\nx = irisDataSet\n# Set targets\ny = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2])\n\n# Create standardizer\nstandardizer = StandardScaler()\n\n# Standardize data set\ndata_standardized = standardizer.fit_transform(x)\n\n# Train knn classifier\nnearest_neighbors = KNeighborsClassifier(n_neighbors=5, n_jobs=-1).fit(data_standardized, y)\n\n# A new entry to test (i.e. a new unidentified iris with measurements)\n\nsepalLength = float(input(\"Please enter sepal length measurement for unidentified iris: \"))\nsepalWidth = float(input(\"Please enter sepal width measurement for unidentified iris: \"))\npetalLength = float(input(\"Please enter petal length measurement for unidentified iris: \"))\npetalWidth = float(input(\"Please enter petal width measurement for unidentified iris: \"))\n\nprint(\"\\n\")\n\nnew_entry = [sepalLength, sepalWidth, petalLength, petalWidth]\n\n#Predict the class of new_entry\npredict = nearest_neighbors.predict([new_entry, new_entry])\n\n# Print what type it is to console\nif predict[0] == 0:\n print(\"It matches close to a Setosa in data set.\")\nelif predict[0] == 1:\n print(\"It matches close to a virginica in data set.\")\nelif predict[0] == 2:\n print(\"It matches close to a versicolor in data set.\")\n\n'''References:\nBooks:\n[1] - Albon, C., 2018. Machine Learning with Python Cookbook: Practical Solutions from \nPreprocessing to Deep Learning. 1st ed. 1005 Gravenstein Highway North Sebastopol, CA 95472: O'Reilly Media, \nIncorporated, 2018.\n[2] - Shaw, Zed. Learn Python 3 the hard way : a very simple introduction to the terrifyingly beautiful \nworld of computers and code. Boston: Addison-Wesley, 2017. Print.\n\nWebsites:\n[3] - https://www.dataquest.io/blog/numpy-tutorial-python/\n[4] - https://stackoverflow.com/questions/28393103/typeerror-cannot-perform-reduce-with-flexible-type\n[5] - https://pythonspot.com/matplotlib-scatterplot/\n[6] - https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xlabel.html\n[7] - http://archive.ics.uci.edu/ml/datasets/Iris\n[8] - https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html\n'''\n","sub_path":"fisherIrisData.py","file_name":"fisherIrisData.py","file_ext":"py","file_size_in_byte":9291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573031148","text":"'''\nBuild an RNN Generative Model on the Polyphonic Music dataset\n'''\nimport pdb\nimport sys\nimport time\nimport logging\n#import cPickle\nimport scipy.io\nimport numpy as np\nimport theano\nimport theano.tensor as tensor\nfrom collections import OrderedDict\n\nfrom model.gru_model_modify_sep_10 import init_params_modify_sep_10, init_tparams, build_model_modify_sep_10\n#from model.optimizers import Santa\nfrom model.optimizers_modify_sep_10_v3 import Santa_modify, SGD\n#from model.optimizers_modify_sep_10_v2 import Santa_modify\n\nfrom theano.compile.nanguardmode import NanGuardMode\n\n#theano.config.compute_test_value = 'off'\n\ndef v_dk(beta):\n betas = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n vs = np.array([-.33, -.472, -.631, -.792, -.953, -1.11, -1.29, -1.49, -1.74, -2.10, -10])\n from scipy.interpolate import interp1d\n return interp1d(betas, vs)(beta)\n\ndef zipp(params, tparams):\n \"\"\"\n When we reload the model. Needed for the GPU stuff.\n \"\"\"\n for kk, vv in params.iteritems():\n tparams[kk].set_value(vv)\n\ndef unzip(zipped):\n \"\"\"\n When we pickle the model. Needed for the GPU stuff.\n \"\"\"\n new_params = OrderedDict()\n for kk, vv in zipped.iteritems():\n new_params[kk] = vv.get_value()\n return new_params\n\ndef calc_negLoglike(f_cost, te):\n \n idx_list = np.arange(len(te), dtype=\"int32\")\n total_cost = 0\n total_len = 0\n #pdb.set_trace()\n for idx in idx_list:\n x = te[idx] \n n_steps = len(x)\n total_cost = total_cost + f_cost(x) * n_steps\n total_len = total_len + n_steps\n \n return total_cost / total_len\n \n\"\"\" Training the model. \"\"\"\n\ndef train_model(tr, va, te, n_x=88, n_h=200, patience=10, max_epochs=40, \n lrate=0.001, ntrain = 10000, dispFreq=10, validFreq=200, \n saveFreq=1000, saveto = 'example.npz', beta=0.5, batchsize=32):\n \n \"\"\" tr, va, te : datasets\n n_x : observation dimension\n n_h : LSTM/GRU number of hidden units \n patience : Number of epoch to wait before early stop if no progress\n max_epochs : The maximum number of epoch to run\n lrate : learning rate\n ntrain : how any training time-steps we have in total\n dispFreq : Display to stdout the training progress every N updates\n validFreq : Compute the validation error after this number of update.\n \"\"\"\n \n options = {}\n options['n_x'] = n_x\n options['n_h'] = n_h\n options['patience'] = patience\n options['max_epochs'] = max_epochs\n options['lrate'] = lrate\n options['dispFreq'] = dispFreq\n options['validFreq'] = validFreq\n options['saveFreq'] = saveFreq\n \n logger.info('Model options {}'.format(options))\n logger.info('Building model...')\n \n params = init_params_modify_sep_10(options, beta)\n tparams = init_tparams(params)\n\n (x, f_pred, cost) = build_model_modify_sep_10(tparams,options)\n \n #f_cost = theano.function([x], cost, name='f_cost', \n # mode=NanGuardMode(nan_is_error=True, inf_is_error=True, big_is_error=True))\n #f_cost = theano.function([x], cost, name='f_cost', mode='DebugMode')\n f_cost = theano.function([x], cost, name='f_cost')\n lr_ = tensor.scalar(name='lr',dtype=theano.config.floatX)\n eidx_ = tensor.scalar(name='edix',dtype='int32')\n ntrain_ = tensor.scalar(name='ntrain',dtype='int32')\n maxepoch_ = tensor.scalar(name='maxepoch',dtype='int32')\n \n v_dk_beta = v_dk(beta)\n \n f_grad_shared, f_update = Santa_modify(beta, v_dk_beta, batchsize, tparams, cost, [x], lr_, eidx_, ntrain_, maxepoch_)\n #f_grad_shared, f_update = SGD(tparams, cost, [x], lrate)\n \n logger.info('Training model...')\n \n estop = False # early stop\n history_negll = []\n best_p = None\n bad_counter = 0 \n uidx = 0 # the number of update done\n start_time = time.time()\n \n for eidx in xrange(max_epochs):\n idx_list = np.arange(len(tr), dtype=\"int32\")\n #np.random.shuffle(idx_list)\n #print('epoch=', eidx) \n #time.sleep(5)\n for train_index in idx_list:\n uidx += 1\n #print(uidx)\n #if uidx > 0:\n #pdb.set_trace()\n \n x = tr[train_index].astype(theano.config.floatX) \n cost = f_grad_shared(x)\n #if tensor.isnan(cost):\n #if np.mod(uidx, 100) == 0:\n # pdb.set_trace()\n #ddw_Lhat_wo_Ez, ddw_logprior_o_w_wq, g, alpha, m, v, w, pcder = f_update(lrate,eidx,ntrain,max_epochs)\n ddw_Lhat_wo_Ez, ddw_logprior_o_w_wq, g, alpha, v, w, pcder = f_update(lrate,eidx,ntrain,max_epochs)\n if np.mod(uidx, dispFreq) == 0:\n logger.info('Epoch {} Update {} Cost {} Beta {}'.format(eidx, uidx, cost, beta))\n \n if np.mod(uidx, saveFreq) == 0:\n logger.info('Saving ...')\n \n if best_p is not None:\n params = best_p\n else:\n params = unzip(tparams)\n np.savez(saveto, history_negll=history_negll, **params)\n logger.info('Done ...')\n\n if np.mod(uidx, validFreq) == 0:\n #pdb.set_trace()\n train_negll = calc_negLoglike(f_cost,tr)\n valid_negll = calc_negLoglike(f_cost,va)\n test_negll = calc_negLoglike(f_cost,te)\n history_negll.append([valid_negll, test_negll, train_negll])\n \n if (uidx == 0 or\n valid_negll <= np.array(history_negll)[:,0].min()):\n best_p = unzip(tparams)\n bad_counter = 0\n \n logger.info('Train {} Valid {} Test {} Beta {}'.format(train_negll, valid_negll, test_negll, beta))\n \n if (len(history_negll) > patience and\n valid_negll >= np.array(history_negll)[:-patience,0].min()):\n bad_counter += 1\n if bad_counter > patience:\n logger.info('Early Stop!')\n estop = True\n break\n \n if estop:\n break\n\n end_time = time.time()\n if best_p is not None:\n zipp(best_p, tparams)\n else:\n best_p = unzip(tparams)\n \n train_negll = calc_negLoglike(f_cost,tr)\n valid_negll = calc_negLoglike(f_cost,va)\n test_negll = calc_negLoglike(f_cost,te)\n\n logger.info('Train {} Valid {} Test {} Beta {}'.format(train_negll, valid_negll, test_negll, beta))\n np.savez(saveto, train_negll=train_negll,\n valid_negll=valid_negll, test_negll=test_negll,\n history_negll=history_negll, **best_p)\n\n logger.info('The code run for {} epochs, with {} sec/epochs'.format(eidx + 1, \n (end_time - start_time) / (1. * (eidx + 1))))\n \n return train_negll, valid_negll, test_negll\n\nif __name__ == '__main__':\n \n dataset = 'Piano'#sys.argv[1]\n lrate = 'small_lrate'#sys.argv[2] \n \n # create logger with 'eval_music_santa'\n logger = logging.getLogger('eval_{}_santa'.format(dataset))\n logger.setLevel(logging.INFO)\n fh = logging.FileHandler('eval_{}_santa.log'.format(dataset))\n fh.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n logger.addHandler(fh)\n\n if dataset == \"JSB\":\n logger.info('loading JSB data...')\n data = scipy.io.loadmat('./data/JSB_Chorales.mat')\n elif dataset == \"Muse\":\n logger.info('loading Muse data...')\n data = scipy.io.loadmat('./data/MuseData.mat')\n elif dataset == \"Nott\":\n logger.info('loading Nott data...')\n data = scipy.io.loadmat('./data/Nottingham.mat')\n elif dataset == \"Piano\":\n logger.info('loading Piano data...')\n data = scipy.io.loadmat('./data/Piano_midi.mat')\n \n tr = data['traindata'][0]\n va = data['validdata'][0]\n te = data['testdata'][0]\n del data\n logger.info('data loaded!')\n \n #for beta in [0, 0.2, 0.4, 0.6, 0.8, 1.0]: \n beta = 0.9\n \n saveto = \"{}_Santa_with_Domke_beta_{}\".format(dataset, beta)\n \n # validate the performance once every one epoch\n validFreq = len(tr)\n \n # calculate how many training frames we have in total\n ntrain = 0\n for seq in tr:\n ntrain = ntrain + len(seq)\n \n if lrate == \"large_lrate\":\n lrate_val = 1.*1e-3\n elif lrate == \"small_lrate\":\n lrate_val = 2.*1e-4\n \n [tr_negll, va_negll, te_negll] = train_model(tr, va, te, \n lrate=lrate_val, ntrain = ntrain, validFreq=validFreq, \n saveto = saveto, beta=beta)\n","sub_path":"rnn_music/eval_music_santa_modify_sep_10.py","file_name":"eval_music_santa_modify_sep_10.py","file_ext":"py","file_size_in_byte":8922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"280862583","text":"from control_remoto import Control_Remoto\nfrom simulador import Simulador\nfrom televisor import Televisor\n\ntv = Televisor('83U94H7BG-4YVHBF', \"SAMSUNG\", \"SG-345\")\ntv.configurar_consumo_kw(50)\ntv.conectar_cable_de_energia()\n\ncontrol = Control_Remoto(\"98654GTFE-341\", \"SAMSUNG\")\ncontrol.configurar_tv(tv)\n\nsimulador_tv = Simulador(tv, control)\nsimulador_tv.iniciar_simulacion(10, 1, 8)\nsimulador_tv.reporte_consumo_energia()\n","sub_path":"Televisor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"293621075","text":"import os\nimport platform\nfrom django.shortcuts import render, redirect\nfrom .modelforms import PersonForm\nfrom .models import Person\nimport boto3\nimport botocore\n\n\ndef guestlist(request):\n form = PersonForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('guestbook:guestlist')\n\n context = {\n 'people': Person.objects.order_by('-date_created'),\n }\n\n return render(request, 'guestlist.html', context)\n\n\ndef s3test(request):\n BUCKET_NAME = 'cloud-platform-reference-bucket'\n FILE_NAME = 'hello.txt'\n with open(FILE_NAME, 'rb') as f:\n fstr = f.read()\n if request.method == 'POST':\n pass\n else:\n if (os.getppid() == 1):\n osname = 'Docker'\n else:\n osname = platform.system()\n status = \"\"\n try:\n session = boto3.Session()\n s3_client = session.client('s3')\n s3_client.put_object(Body=fstr, Bucket=BUCKET_NAME, Key='upload-' + FILE_NAME)\n status = \"Write OK\"\n except botocore.exceptions.ClientError as e:\n status = \"Write Failed: \", e\n return render(request, 'test-s3.html', {'osname': osname, 'status': status})\n","sub_path":"guestbook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"559445512","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.urls import reverse\nimport requests\n\nfrom githuborganizations.views import Main\nfrom apps.organization.forms import SearchForm\nfrom apps.organization.models import Organizations\nfrom apps.repository.models import Repositories\nfrom apps.member.models import Members\n\n\nclass Organization(Main, View):\n def get(self, request):\n errors = []\n organization_login = ''\n organization_data = False\n\n if 'organization' in request.GET:\n organization_login = request.GET['organization']\n\n try:\n organization_data = Organizations.objects.get(login=organization_login)\n except Organizations.DoesNotExist:\n request_organization = requests.get('https://api.github.com/orgs/' + organization_login, auth=self.auth)\n if request_organization.status_code == 200:\n organization_data = request_organization.json()\n else:\n errors.append('No se encontro la organizacion enviada')\n\n return render(request, 'organization/search.html', {\n 'form': SearchForm({'organization': organization_login}),\n 'organization': organization_data,\n 'errors': errors\n })\n\n\nclass Import(Main, View):\n repositories = []\n\n def get(self, request, organization_login=False):\n\n try:\n organization = Organizations.objects.get(login=organization_login)\n return HttpResponseRedirect(reverse('repository:index', args=[organization_login]))\n except Organizations.DoesNotExist:\n # Obtener Datos de Organización\n organization_request_url = 'https://api.github.com/orgs/' + organization_login\n organization_request = requests.get(url=organization_request_url, auth=self.auth)\n organization = organization_request.json()\n\n # Guardar Organización\n organization = self.saveOrganization(organization)\n\n # Guardar Repositorios\n self.saveRepositories(organization)\n\n # Guardar Miembros\n self.saveMembers(organization)\n\n return HttpResponseRedirect(reverse('repository:index', args=[organization.login]))\n\n @staticmethod\n def saveOrganization(organization):\n return Organizations.objects.create(\n login=organization['login'],\n name=organization['name'],\n description=organization['description'],\n avatar_url=organization['avatar_url'],\n blog=organization['blog'],\n email=organization['email'],\n public_repos=organization['public_repos'],\n )\n\n def saveRepositories(self, organization):\n if organization.public_repos > 0:\n self.getAllRepositories('https://api.github.com/orgs/' + organization.login + '/repos?type=public')\n repositoriesObjects = []\n for repository in self.repositories:\n repositoriesObjects.append(Repositories(\n name=repository['name'],\n html_url=repository['html_url'],\n description=repository['description'],\n language=repository['language'],\n stargazers_count=repository['stargazers_count'],\n forks_count=repository['forks_count'],\n created_at=repository['created_at'],\n updated_at=repository['updated_at'],\n organization=organization,\n ))\n Repositories.objects.bulk_create(repositoriesObjects)\n\n def getAllRepositories(self, repositories_url_request):\n repositories_request = requests.get(url=repositories_url_request, auth=self.auth)\n repositories_links = repositories_request.links\n\n if ('next' in repositories_links.keys()):\n self.getAllRepositories(repositories_links['next']['url'])\n\n self.repositories += repositories_request.json()\n\n def saveMembers(self, organization):\n members_request_url = 'https://api.github.com/orgs/' + organization.login + '/members'\n members_request = requests.get(url=members_request_url, auth=self.auth)\n\n membersObjects = []\n for members in members_request.json():\n membersObjects.append(Members(\n login=members['login'],\n avatar_url=members['avatar_url'] + '&s=96',\n html_url=members['html_url'],\n organization=organization,\n ))\n Members.objects.bulk_create(membersObjects)\n","sub_path":"githuborganizations/apps/organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"493215210","text":"from odoo import api, fields, models\n\n\nclass Partner(models.Model):\n\n _inherit = 'res.partner'\n\n instructor = fields.Boolean(\n default=False,\n string='Instructor')\n session_ids = fields.Many2many(\n comodel_name='odooacademy.session',\n readonly=False,\n string='Attended Sessions'\n )\n\n # @api.model\n # def create(self, values):\n # pass\n\n # @api.multi\n # def write(self, values):\n # pass\n","sub_path":"models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"296758013","text":"import os\nimport sys\nimport json\nimport spotipy\nimport webbrowser\nimport spotipy.util as util\nfrom json.decoder import JSONDecodeError\nfrom collections import OrderedDict\nimport pickle\nfrom collections import Counter\n\n# Get username from terminal\nusername = sys.argv[1]\n\n# User Id: 123181425\n\n# Erase cache and prompt for user permission\ntry:\n\ttoken = util.prompt_for_user_token(username)\nexcept:\n\tos.remove(f\".cache-{username}\")\n\ttoken = util.prompt_for_user_token(username)\n\n# Create our spotipyObject\nspotipyObject = spotipy.Spotify(auth=token)\n\nuser = spotipyObject.current_user()\n# print(user)\n\ndisplayName = user['display_name']\nfollowers = user['followers']['total']\nprint()\nprint()\nrecommendation = spotipyObject.recommendation_genre_seeds()\nprint(recommendation)\nprint()\nprint()\ni = 0\n# rec = spotipyObject.recommendations(seed_artists='2YZyLoL8N0Wb9xBt1NhZWg')\n# print(rec)\n\nwhile True:\n\tprint()\n\tprint('>>> Welcome to Spotipy ' + displayName + '!')\n\tprint('>>> You have ' + str(followers) + ' followers.')\n\tprint()\n\tprint('0 - Search for an artist')\n\tprint('1 - exit')\n\tprint()\n\tchoice = input('Your choice: ')\n\td = {}\n\n# Search for the artist\n\tif choice == '0':\n\t\t# print(spotipyObject.me( ))\n\t\tprint()\n\t\tsearchQuery = input(\"Aight, what's their name?: \")\n\t\tprint()\n\t\t# Get search results\n\t\tsearchResults = spotipyObject.search(searchQuery,1,0,'artist')\n\t\tprint(json.dumps(searchResults, sort_keys=True,indent=4))\n\n\t\t# artist details\n\n\t\tartist = searchResults['artists']['items'][0]\n\t\tname_of_artist = artist['name']\n\t\tpopularity = artist['popularity']\n\t\tfollowers = str(artist['followers']['total']) \n\t\tgenres = artist['genres']\n\t\tprint(popularity)\n\t\tprint(name_of_artist)\n\t\tprint(followers)\n\t\tprint(genres)\n\t\tprint()\n\t\t# commented out line below shows artists picture\n\t\t# webbrowser.open(artist['images'][0]['url'])\n\t\tartistID = artist['id']\n\n\t\t# album and track details\n\t\ttrackURIs = []\n\t\ttrackArt = []\n\t\tz = 0\n\n\t\t# Extract album data\n\t\talbumResults = spotipyObject.artist_albums(artistID)\n\t\talbumResults = albumResults['items']\n\t\t# print(current_user_playing_track)\n\t\talbums = []\n\n\t\tfor item in albumResults:\n\t\t\t# looping through album\n\t\t\tno_repeat_albums = item['name']\n\t\t\talbums.append(no_repeat_albums)\n\t\t\t# print('ALBUM ' + item['name'])\n\t\t\talbumID = item['id']\n\t\t\t# print(albums)\n\t\t\t# albumArt = item['images'][0]['url']\n\n\t\t\t# Extract track data\n\t\t\ttrackResults = spotipyObject.album_tracks(albumID)\n\t\t\ttrackResults = trackResults['items']\n\n\n\t\t\t# for item in trackResults:\n\t\t\t# \t# looping through track results\n\t\t\t# \tprint(str(z) + ':' + item['name'])\n\t\t\t# \ttrackURIs.append(item['uri'])\n\t\t\t# \ttrackArt.append(albumArt)\n\t\t\t\t# z += 1\n\t\t\talbums2 = set(albums)\n\n\t\td['artist'] = name_of_artist\n\t\td['spotify_artist_id'] = artistID\n\t\td['popularity'] = popularity\n\t\td['followers'] = followers\n\t\td['genres'] = genres\n\t\td['count_of_genres'] = Counter(genres)\n\t\td['total_of_genres'] = len(genres)\n\t\td['albums'] = albums2\n\t\tprint(d)\n\t\t# with open('wayne.pkl', 'wb') as handle:\n\t\t# \tpickle.dump(d, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\t\t# see album art\n\t\twhile True:\n\t\t\tsongSelection = input('Enter a song number to see the album art associated with it (or set x to exit): ')\n\t\t\tif songSelection == 'x':\n\t\t\t\tbreak\n\t\t\twebbrowser.open(trackArt[int(songSelection)])\n\n\n# End the program\n\tif choice == '1':\n\t\tbreak\n\n\n\n# print(json.dumps(VARIABLE, sort_keys=True,indent=4))\n\n\n\n\n\n\n\n","sub_path":"Album_Sales_Prediction/Code/spotify_album_search.py","file_name":"spotify_album_search.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304760901","text":"#Question-1\nli=[]\na=input(\"Enter numbers\")\nli.append(a)\nprint(li)\n\n#Question-2\nlo=[\"google\",\"apple\",\"facebook\",\"microsoft\",\"tesla\"]\nli.append(lo)\nprint(li)\n\n#Question-3\nco=[\"apple\",\"banana\",\"apple\"]\nprint(co.count(\"apple\"))\n\n#Question-4\nso=[34,67,19,54,3,9,55,8]\nso.sort()\nprint(so)\n\n#Question-5\na=[1,2,34,56]\nb=[18,23,45,98]\nc=a+b\nc.sort()\nprint(c)\n\n#Question-6\nstck=[3,2,4,2]\nstck.append(9)\nprint(stck)\nstck.pop()\nprint(stck)\n\n\n","sub_path":"Assignment-3.py","file_name":"Assignment-3.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272859950","text":"'''\nswea 1240. [S/W 문제해결 응용] 1일차 - 단순 2진 암호코드 D3\n'''\n\ndef is_valid(nums):\n result = 0\n sum_ = 0\n\n patterns = {\n '0001101': 0,\n '0011001': 1,\n '0010011': 2,\n '0111101': 3,\n '0100011': 4,\n '0110001': 5,\n '0101111': 6,\n '0111011': 7,\n '0110111': 8,\n '0001011': 9\n }\n last = nums.rindex('1')\n nums = nums[last - 55: last + 1]\n\n for i in range(8):\n n = patterns[nums[:7]]\n nums = nums[7:]\n sum_ += n\n\n if i == 7:\n result += n\n elif i % 2 == 0:\n result += n * 3\n else:\n result += n\n\n result = sum_ if result % 10 == 0 else 0\n\n return result\n\nt = int(input())\nans = ''\n\nfor i in range(1, t + 1):\n n, m = map(int, input().split())\n\n codes = [input() for _ in range(n)]\n\n for code in codes:\n if code.count('1') >= 24:\n res = is_valid(code)\n break\n ans += \"#{} {}\\n\".format(i, res)\nprint(ans)","sub_path":"20191011/swea 1240 복습.py","file_name":"swea 1240 복습.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"389438977","text":"N,M = map(int,input().split())\n\ndef dfs(V,s):\n if len(V) == M:\n \n print(' '.join(V))\n else:\n for i in range(s,N+1):\n if str(i) not in V:\n dfs(V+[str(i)],i) \ndfs([],1)\n","sub_path":"15650 N과 M(2) 실버3.py","file_name":"15650 N과 M(2) 실버3.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"127308858","text":"#################################################################\n# MET v2 Metadate Explorer Tool\n#\n# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md\n# Copyright (c) 2012, TERENA All rights reserved.\n#\n# This Software is based on MET v1 developed for TERENA by Yaco Sistemas, http://www.yaco.es/\n# MET v2 was developed for TERENA by Tamim Ziai, DAASI International GmbH, http://www.daasi.de\n# Current version of MET has been revised for performance improvements by Andrea Biancini,\n# Consortium GARR, http://www.garr.it\n##########################################################################\n\nimport csv\nfrom xml.dom.minidom import Document\n\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.template.defaultfilters import slugify\nimport simplejson as json\n\n\ndef export_summary_csv(qs, relation, filename, counters):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = ('attachment; filename=%s.csv'\n % slugify(filename))\n writer = csv.writer(response, quoting=csv.QUOTE_NONNUMERIC)\n labels = ['name']\n labels.extend([label for (label, _) in counters])\n writer.writerow(labels)\n # Write data to CSV file\n for obj in qs:\n row = [unicode(obj).encode('utf-8')]\n for _, counter_filter in counters:\n row.append(getattr(obj, relation).filter(**counter_filter).count())\n writer.writerow(row)\n # Return CSV file to browser as download\n return response\n\n\ndef export_summary_json(qs, relation, filename, counters):\n objs = {}\n for obj in qs:\n item = {}\n for counter_label, counter_filter in counters:\n item[counter_label] = getattr(\n obj, relation).filter(**counter_filter).count()\n objs[unicode(obj)] = item\n # Return JS file to browser as download\n serialized = json.dumps(objs)\n response = HttpResponse(serialized, content_type='application/json')\n response['Content-Disposition'] = ('attachment; filename=%s.json'\n % slugify(filename))\n return response\n\n\ndef export_summary_xml(qs, relation, filename, counters):\n xml = Document()\n root = xml.createElement(filename)\n # Write data to CSV file\n for obj in qs:\n item = xml.createElement(\"federation\")\n item.setAttribute(\"name\", unicode(obj))\n for counter_label, counter_filter in counters:\n val = getattr(obj, relation).filter(**counter_filter).count()\n element = xml.createElement(counter_label)\n xmlval = xml.createTextNode(unicode(val))\n element.appendChild(xmlval)\n item.appendChild(element)\n root.appendChild(item)\n xml.appendChild(root)\n\n # Return XML file to browser as download\n response = HttpResponse(xml.toxml(), content_type='application/xml')\n response['Content-Disposition'] = ('attachment; filename=%s.xml'\n % slugify(filename))\n return response\n\n\nexport_summary_modes = {\n 'csv': export_summary_csv,\n 'json': export_summary_json,\n 'xml': export_summary_xml,\n}\n\n\ndef export_summary(mode, qs, relation, filename, counters):\n if mode in export_summary_modes:\n return export_summary_modes[mode](qs, relation, filename, counters)\n else:\n content = \"Error 400, Format %s is not supported\" % mode\n return HttpResponseBadRequest(content)\n","sub_path":"met/metadataparser/summary_export.py","file_name":"summary_export.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"68401862","text":"\"\"\"\n\nPython utility to find and delete unused image files in the icon_pngs folder.\nWill scan all .jlxs in the appropriate folders.\nFor use with GSE Systems Inc. JEditor All Rights Reserved. \n\n\"\"\"\n##\n# May need to add an exception for /icon_pngs/static \n\nimport os\n\n# Set the paths manually.\npng_path = 'C:\\Documents and Settings\\joe.marchese\\Desktop\\JADE\\gseLibrary\\FortMartin1_softpanel_library\\icon_pngs'\njlx_path = 'C:\\Documents and Settings\\joe.marchese\\Desktop\\JADE\\gseLibrary\\FortMartin1_softpanel_library'\n\n# Get all the PNGs from the folders\njlx_list = []\npng_dict = {}\nfor root, dirs, files in os.walk(jlx_path):\n for name in files:\n if name.endswith('.png') or name.endswith('.jpg'):\n png_dict[name] = os.path.join(root, name)\n if name.endswith('.jlx'):\n jlx_list.append(os.path.join(root, name)) \n\nprint('Total Image Files: ', len(png_dict))\nprint('Total JLX Files: ', len(jlx_list))\nprint('Finding Unused Files . . .') \n\n# There should be a way to stop checking a png_path once it's removed\n# Thought it was break. This try except is working for now. \n# Iterate over all of the jlxs looking for instances of .pngs from png_list\nto_delete_paths = list(png_dict.values()) \nfor jlx in jlx_list:\n with open(jlx) as f:\n for line in f:\n for png_name, path in png_dict.items():\n if png_name in line:\n try:\n to_delete_paths.remove(path)\n except ValueError:\n pass\n\nprint('Total Unused Image Files: ', len(to_delete_paths))\nif len(to_delete_paths) == 0:\n print('No Unused Images. Exiting Program.')\n quit()\n\nconfirm_delete = None\nwhile confirm_delete not in ['y', 'n', 'yes', 'no']:\n confirm_delete = input('Would you like to delete all unused images? (y/n)').lower()\nif confirm_delete in ['y', 'yes']:\n for image in to_delete_paths:\n os.remove(image)\n print('Success.') \nelse:\n print('Operation Cancelled.')\n","sub_path":"JEditor_Cleanup.py","file_name":"JEditor_Cleanup.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"391424826","text":"#python3\n\nusers = ['admin', 'jake', 'Hera', 'Jade', 'Lief']\nusers = []\n\nif users:\n for user in users:\n if user == 'admin':\n print('Hello, admin. Would you like a status report?')\n else:\n print('Hello, ' + user.title() + ', its good to see you again.')\nelse:\n print('We need to find some users!')\n","sub_path":"hello_admin.py","file_name":"hello_admin.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"269205139","text":"import itertools\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport Levenshtein\n\nfrom intake import models, groups\nfrom intake.constants import SMS, EMAIL\nfrom intake.service_objects import ConfirmationNotification\n\n\nclass MissingAnswersError(Exception):\n pass\n\n\ndef check_for_existing_duplicates(submission, applicant_id):\n dups = []\n other_subs = models.FormSubmission.objects.filter(\n applicant_id=applicant_id).exclude(id=submission.id)\n for other in other_subs:\n if are_duplicates(submission, other):\n dups.append(other)\n return dups\n\n\ndef link_with_any_duplicates(submission, applicant_id):\n \"\"\"Links submission with any duplicates from the same applicant\n\n If duplicates are found, returns the DuplicateSubmissionSet id\n If no duplicates are found, returns False\n \"\"\"\n duplicates = check_for_existing_duplicates(submission, applicant_id)\n if duplicates:\n dup_set_id = None\n unadded_duplicates = []\n for dup in duplicates:\n if dup.duplicate_set_id:\n dup_set_id = dup.duplicate_set_id\n else:\n unadded_duplicates.append(dup)\n if not dup_set_id:\n new_dup_set = models.DuplicateSubmissionSet()\n new_dup_set.save()\n new_dup_set.submissions.add(*unadded_duplicates)\n dup_set_id = new_dup_set.id\n submission.duplicate_set_id = dup_set_id\n submission.save()\n return dup_set_id\n return False\n\n\ndef create_submission(form, organizations, applicant_id):\n \"\"\"Save the submission data\n \"\"\"\n submission = models.FormSubmission(\n answers=form.cleaned_data,\n applicant_id=applicant_id)\n submission.save()\n submission.organizations.add_orgs_to_sub(*organizations)\n link_with_any_duplicates(submission, applicant_id)\n models.ApplicationEvent.log_app_submitted(applicant_id)\n return submission\n\n\ndef fill_pdfs_for_submission(submission):\n \"\"\"Checks for and creates any needed `FilledPDF` objects\n \"\"\"\n fillables = models.FillablePDF.objects.filter(\n organization__submissions=submission)\n for fillable in fillables:\n fillable.fill_for_submission(submission)\n\n\ndef get_paginated_submissions_for_user(\n user, page_index, max_count_per_page=25, min_count_per_page=5):\n qset = get_permitted_submissions(user, related_objects=True)\n paginator = Paginator(\n qset, max_count_per_page, orphans=min_count_per_page)\n try:\n return paginator.page(page_index)\n except PageNotAnInteger:\n return paginator.page(1)\n except EmptyPage:\n if int(page_index) <= 0:\n return paginator.page(1)\n else:\n return paginator.page(paginator.num_pages)\n\n\ndef get_permitted_submissions(user, ids=None, related_objects=False):\n query = models.FormSubmission.objects\n if related_objects:\n prefetch_relations = [\n 'logs__user__profile__organization'\n ]\n if user.groups.filter(name=groups.FOLLOWUP_STAFF).exists():\n prefetch_relations.extend(['notes', 'tags'])\n query = query.prefetch_related(*prefetch_relations)\n if ids:\n query = query.filter(pk__in=ids)\n if user.is_staff:\n return query.all()\n org = user.profile.organization\n return query.filter(organizations=org).distinct()\n\n\ndef find_duplicates(search_space):\n duplicate_sets = []\n for pair in itertools.combinations(search_space, 2):\n if are_duplicates(*pair):\n pair_set = set(pair)\n attached_to_existing_set = False\n for dup_set in duplicate_sets:\n if dup_set & pair_set:\n dup_set |= pair_set\n attached_to_existing_set = True\n break\n if not attached_to_existing_set:\n duplicate_sets.append(pair_set)\n return duplicate_sets\n\n\nNAME_DIFFERENCE_THRESHOLD = 0.8\n\n\ndef are_duplicates(a, b):\n \"\"\"Two submissions are defined as duplicates if:\n they have very similar names\n AND\n they are going to the same set of organizations\n \"\"\"\n name_score = get_name_similarity_ratio(a, b)\n same_orgs = have_same_orgs(a, b)\n return name_score > NAME_DIFFERENCE_THRESHOLD and same_orgs\n\n\ndef get_full_lowercase_name(sub):\n return ' '.join([\n sub.answers.get(key, '')\n for key in ('first_name', 'middle_name', 'last_name')]\n ).lower()\n\n\ndef get_name_similarity_ratio(a, b):\n names = (get_full_lowercase_name(sub) for sub in (a, b))\n return Levenshtein.ratio(*names)\n\n\ndef have_same_orgs(a, b):\n a_orgs, b_orgs = (\n set(sub.organizations.values_list('id', flat=True))\n for sub in (a, b))\n return a_orgs == b_orgs\n\n\ndef get_confirmation_flash_messages(confirmation_notification):\n messages = []\n message_templates = {\n EMAIL: _(\"We've sent you an email at {}\"),\n SMS: _(\"We've sent you a text message at {}\")\n }\n for method in confirmation_notification.successes:\n template = message_templates[method]\n contact_info = confirmation_notification.contact_info[method]\n messages.append(template.format(contact_info))\n return messages\n\n\ndef send_confirmation_notifications(sub):\n confirmation_notification = ConfirmationNotification(sub)\n confirmation_notification.send()\n return get_confirmation_flash_messages(confirmation_notification)\n\n\n# These methods are used for test setup only\ndef create_for_organizations(organizations, **kwargs):\n submission = models.FormSubmission(**kwargs)\n submission.save()\n submission.organizations.add_orgs_to_sub(*organizations)\n return submission\n\n\ndef create_for_counties(counties, **kwargs):\n organizations = [\n county.get_receiving_agency(kwargs['answers'])\n for county in counties\n ]\n return create_for_organizations(\n organizations=organizations, **kwargs)\n\n\ndef get_unopened_submissions_for_org(organization):\n opened_sub_ids = models.ApplicationLogEntry.objects.filter(\n event_type=models.ApplicationLogEntry.OPENED,\n user__profile__organization=organization,\n submission_id__isnull=False\n ).values_list('submission_id', flat=True)\n return organization.submissions.all().exclude(pk__in=opened_sub_ids)\n","sub_path":"intake/services/submissions.py","file_name":"submissions.py","file_ext":"py","file_size_in_byte":6401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537122053","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# https://www.acmicpc.net/problem/15652\n\n# 자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.\n\n# 1부터 N까지 자연수 중에서 M개를 고른 수열\n# 같은 수를 여러 번 골라도 된다.\n# 고른 수열은 비내림차순이어야 한다.\n# 길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.\n\nn,m = map(int, input().split())\n\ndef solution(n, m):\n arr = [0] * m\n # visited = [False] * n + 1\n\n def dfs(n, m, d) : \n if (d == m):\n print(arr)\n return\n\n for i in range(1, n + 1):\n if d > 0 and i < arr[d - 1]: \n continue\n # visited[i] = True\n arr[d] = i\n dfs(n, m, d + 1)\n # visited[i] = False\n dfs(n, m, 0)\n\nsolution(n, m)\n\n \n\n\n","sub_path":"_basic/combinations/_04_/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446553794","text":"class Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.next = None\r\n\r\n\r\nclass LinkList:\r\n def __init__(self):\r\n self.head = None\r\n\r\n # Add a node at the front\r\n def push(self, new_data):\r\n new_node = Node(new_data)\r\n new_node.next = self.head\r\n self.head = new_node\r\n\r\n # Add a node after a given node\r\n def insert_after(self, prev_node, new_data):\r\n if prev_node is None:\r\n print(\"given node must be in link list\")\r\n return\r\n new_node = Node(new_data)\r\n new_node.next = prev_node.next\r\n prev_node.next = new_node\r\n\r\n # Add a node at the end\r\n def append(self, new_data):\r\n new_node = Node(new_data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n return\r\n\r\n temp = self.head\r\n while (temp.next):\r\n temp = temp.next\r\n temp.next = new_node\r\n\r\n # search elemnet in link list\r\n def search_ele(self,key):\r\n current_node = self.head\r\n while current_node:\r\n if current_node.data == key:\r\n return True\r\n current_node = current_node.next\r\n return False\r\n\r\n def print_list(self):\r\n current_node = self.head\r\n while current_node:\r\n print(current_node.data)\r\n current_node = current_node.next\r\n\r\nlink_li = LinkList()\r\nlink_li.push(12)\r\nlink_li.push(63)\r\nlink_li.push(11)\r\nlink_li.append(56)\r\nlink_li.append(88)\r\nlink_li.append(36)\r\nlink_li.append(25)\r\nlink_li.append(22)\r\nlink_li.append(14)\r\nlink_li.insert_after(link_li.head.next,99)\r\nlink_li.print_list()\r\nprint(link_li.search_ele(66))\r\n\r\n\r\n","sub_path":"Python_coding/singly_link_list.py","file_name":"singly_link_list.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409519443","text":"\n# -*- coding: utf-8 -*-\n\n#3- Write a program that repeatedly prompts \n#the user to enter a capital for a state. Upon receiving the user input, \n#the program reports whether the answer is correct. The program prompts the user \n#to answer all the states capital and displays the total correct count. \n#The answer should not be case sensitive. Implement using a dictionary.\n\n\nimport sys\nfrom random import shuffle\n\ncapital_dict = {\n 'Alabama': 'Montgomery',\n 'Alaska': 'Juneau',\n 'Arizona':'Phoenix',\n 'Arkansas':'Little Rock',\n 'California': 'Sacramento',\n 'Colorado':'Denver',\n 'Connecticut':'Hartford',\n 'Delaware':'Dover',\n 'Florida': 'Tallahassee',\n 'Georgia': 'Atlanta',\n 'Hawaii': 'Honolulu',\n 'Idaho': 'Boise',\n 'Illinois': 'Springfield',\n 'Indiana': 'Indianapolis',\n 'Iowa': 'Des Moines',\n 'Kansas': 'Topeka',\n 'Kentucky': 'Frankfort',\n 'Louisiana': 'Baton Rouge',\n 'Maine': 'Augusta',\n 'Maryland': 'Annapolis',\n 'Massachusetts': 'Boston',\n 'Michigan': 'Lansing',\n 'Minnesota': 'St. Paul',\n 'Mississippi': 'Jackson',\n 'Missouri': 'Jefferson City',\n 'Montana': 'Helena',\n 'Nebraska': 'Lincoln',\n 'Nevada': 'Carson City',\n 'New Hampshire': 'Concord',\n 'New Jersey': 'Trenton',\n 'New Mexico': 'Santa Fe',\n 'New York': 'Albany',\n 'North Carolina': 'Raleigh',\n 'North Dakota': 'Bismarck',\n 'Ohio': 'Columbus',\n 'Oklahoma': 'Oklahoma City',\n 'Oregon': 'Salem',\n 'Pennsylvania': 'Harrisburg',\n 'Rhode Island': 'Providence',\n 'South Carolina': 'Columbia',\n 'South Dakota': 'Pierre',\n 'Tennessee': 'Nashville',\n 'Texas': 'Austin',\n 'Utah': 'Salt Lake City',\n 'Vermont': 'Montpelier',\n 'Virginia': 'Richmond',\n 'Washington': 'Olympia',\n 'West Virginia': 'Charleston',\n 'Wisconsin': 'Madison',\n 'Wyoming': 'Cheyenne' \n}\n\n\nleave = 'quit'\n\nwhile True:\n right_answers = 0\n wrong_answers = 0\n quit = 'quit'\n print(\"Type \\'quit\\' anytime to exit the game!\")\n for k,v in capital_dict.items():\n printstring = (\"What is the capitol for %s : \") % (k)\n answer = input(printstring)\n if answer.lower() == v.lower():\n print(\"Correct!\")\n right_answers += 1\n elif answer.lower() == quit.lower():\n print(\"quitting game! \\nscore can be found below\")\n print(\"Total right answers\",right_answers)\n print(\"Total wrong answers\", wrong_answers)\n sys.exit()\n elif answer.lower() != v.lower():\n print(\"Wrong!\")\n print(\"your answer was:\",answer)\n print(\"correct answer was : \", v)\n wrong_answers += 1\n","sub_path":"Week1/H1.py","file_name":"H1.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"385796400","text":"# This program is a simple demo on how to use serch hook in pymilvus.\n# Customize a search hook class to count search time\nimport random\nimport datetime\nimport time\nfrom milvus import Milvus\nfrom milvus.client.hooks import BaseSearchHook\n\n\n# Define a subclass of `BaseSearchHook` which print time stamp\n# when client call server and call done.\nclass CustomizedSearchHook(BaseSearchHook):\n\n def __init__(self):\n self._start_stamp = None\n self._end_stamp = None\n\n def pre_search(self, *args, **kwargs):\n # record time when call on server start.\n self._start_stamp = datetime.datetime.now()\n print(\"[{}] Start send request to server.\".format(self._start_stamp))\n\n def aft_search(self, *args, **kwargs):\n # record time when call on server done.\n self._end_stamp = datetime.datetime.now()\n print(\"[{}] Server done.\".format(self._end_stamp))\n\n\nif __name__ == '__main__':\n # Server host and port, you may need to change accordingly\n _ADDRESS = {\n \"host\": \"127.0.0.1\",\n \"port\": \"19530\"\n }\n\n # Table name\n collection_name = \"demo_hooks\"\n # Dimension of vectors\n dim = 128\n\n collection_param = {\n \"collection_name\": collection_name,\n \"dimension\": dim\n }\n\n # generate 10000 vectors with dimension of 128 randomly\n vectors = [[random.random() for _ in range(dim)] for _ in range(10000)]\n\n # select part of vectors as query vectors\n query_vectors = vectors[5: 10]\n\n # Start request to server.\n # You can invoke without `with` here to interact with server:\n #\n # client = Milvus()\n # client.connect(**_ADDRESS)\n # ......\n # client.disconnect()\n #\n with Milvus(**_ADDRESS) as client:\n # Set search hook\n client.set_hook(search=CustomizedSearchHook())\n\n # Create table\n client.create_collection(collection_param)\n\n # Insert vectors into table\n client.insert(collection_name, vectors)\n\n time.sleep(5)\n\n # specify search param\n search_param = {\n \"nprobe\": 10\n }\n\n # Search approximate vectors in table `demo_hooks`,\n # you can find call information in console output\n client.search(collection_name, 10, query_vectors, params=search_param)\n\n # delete table\n client.drop_collection(collection_name)\n","sub_path":"examples/example_hooks.py","file_name":"example_hooks.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84043361","text":"from django import template\nfrom django.urls import reverse\nfrom django.utils.html import escape\nfrom django.utils.safestring import mark_safe\n\nimport markdown2\n\nregister = template.Library()\n\n\n@register.simple_tag(name='markdown')\ndef markdown_format(text, safe=False):\n \"\"\"Devuelve el texto markdown en HTML.\n\n Example:\n Con un texto seguro.\n {% markdown resource.description safe=True %}\n {% markdown resource.description True %}\n\n Con un texto inseguro.\n {% markdown resource.description safe=False %}\n {% markdown resource.description False %}\n {% markdown resource.description %}\n\n Args:\n text (str): Texto markdown\n safe (bool): El texto es seguro? de lo contrario lo escapa.\n\n Returns:\n str: El markdown convertido en HTML.\n \"\"\"\n if not safe:\n # Si no es safe, el texto siempre se escapa.\n text = escape(text)\n return mark_safe(\n markdown2.markdown(\n text,\n extras=['fenced-code-blocks']\n )\n )\n\n\n@register.simple_tag(takes_context=True)\ndef is_active(context, urlconf_name, **kwargs):\n \"\"\"Devolverá active si request.path coincide con urlconf_name.\n\n Comprueba con URLConf con request.path.\n\n Example:\n
  • \n\n Args:\n context: Contexto en el template.\n urlconf_name (str): URLConf\n kwargs (dict): parámetros de reverse('', kwargs=kwargs)\n\n Returns:\n (str): si coincide devolverá 'active' en caso contrario un string vacío ''.\n \"\"\"\n url_reverse = reverse(urlconf_name, kwargs=kwargs)\n if context['request'].path == url_reverse:\n return 'active'\n return ''\n\n\n@register.simple_tag(name='pagination')\ndef pagination(page_obj):\n initial = 1\n radius = 3\n pages = radius * 2 + 1\n num_pages = page_obj.paginator.num_pages\n last = pages if num_pages > pages else num_pages\n if page_obj.number > (radius + 1):\n initial = page_obj.number - radius\n if num_pages > page_obj.number + radius:\n last = page_obj.number + radius\n else:\n last = num_pages\n context = {\n 'initial': initial,\n 'last': last,\n 'num_pages': num_pages,\n 'current': page_obj.number,\n 'range': range(initial, last + 1),\n 'has_pagination': True if num_pages > 1 else False\n }\n return context\n\n\n@register.simple_tag(name='next_pagination', takes_context=True)\ndef next_pagination(context):\n \"\"\"La paginación se hace en función de si tiene un query en GET.\n\n Para paginación, pagina siguiente si existe.\n\n Example:\n next\n\n Si en el query de una URI existe ?page=xx, cambiara solo la parte\n del ?page=xxx por el nuevo numero de pagina. En caso contrario,\n añadirá page=xxx al query string.\n \"\"\"\n request = context['request']\n page_obj = context['page_obj']\n uri = request.GET.urlencode()\n if not uri:\n return '?page={}'.format(page_obj.next_page_number())\n if 'page' in uri:\n page = 'page={}'.format(page_obj.number)\n new_uri = uri.replace(page, 'page={}'.format(page_obj.next_page_number()))\n return '?{}'.format(new_uri)\n else:\n return '?{}&page={}'.format(uri, page_obj.next_page_number())\n\n\n@register.simple_tag(name='previous_pagination', takes_context=True)\ndef previous_pagination(context):\n \"\"\"La paginación se hace en función de si tiene un query en GET.\n\n Para paginación, pagina previa si existe.\n\n Example:\n previous\n\n Si en el query de una URI existe ?page=xx, cambiara solo la parte\n del ?page=xxx por el nuevo numero de pagina. En caso contrario,\n añadirá page=xxx al query string.\n \"\"\"\n request = context['request']\n page_obj = context['page_obj']\n uri = request.GET.urlencode()\n if not uri:\n return '?page={}'.format(page_obj.previous_page_number())\n if 'page' in uri:\n page = 'page={}'.format(page_obj.number)\n new_uri = uri.replace(page, 'page={}'.format(page_obj.previous_page_number()))\n return '?{}'.format(new_uri)\n else:\n return '?{}&page={}'.format(uri, page_obj.previous_page_number())\n","sub_path":"src/apps/utils/templatetags/utils_tags.py","file_name":"utils_tags.py","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560647206","text":"# Copyright 2013 Mellanox Technologies, Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport glob\nimport os\nimport re\n\nimport ethtool\nfrom oslo_concurrency import processutils\nfrom oslo_log import log as logging\n\nfrom networking_mlnx._i18n import _LE, _LW\nfrom networking_mlnx.eswitchd.common import constants\nfrom networking_mlnx.eswitchd.utils import command_utils\n\nLOG = logging.getLogger(__name__)\n\n\nclass pciUtils(object):\n\n ETH_PATH = \"/sys/class/net/%(interface)s\"\n ETH_DEV = ETH_PATH + \"/device\"\n ETH_PORT = ETH_PATH + \"/dev_id\"\n INFINIBAND_PATH = 'device/infiniband'\n VENDOR_PATH = ETH_DEV + '/vendor'\n DEVICE_TYPE_PATH = ETH_DEV + '/virtfn%(vf_num)s/device'\n _VIRTFN_RE = re.compile(\"virtfn(?P\\d+)\")\n VFS_PATH = ETH_DEV + \"/virtfn*\"\n\n def get_vfs_info(self, pf):\n vfs_info = {}\n try:\n dev_path = self.ETH_DEV % {'interface': pf}\n dev_info = os.listdir(dev_path)\n for dev_filename in dev_info:\n result = self._VIRTFN_RE.match(dev_filename)\n if result and result.group('vf_num'):\n dev_file = os.path.join(dev_path, dev_filename)\n vf_pci = os.readlink(dev_file).strip(\"./\")\n vf_num = result.group('vf_num')\n vf_device_type = self.get_vf_device_type(pf, vf_num)\n vfs_info[vf_pci] = {'vf_num': vf_num,\n 'vf_device_type': vf_device_type}\n except Exception:\n LOG.error(_LE(\"PCI device %s not found\"), pf)\n return vfs_info\n\n def get_dev_attr(self, attr_path):\n try:\n fd = open(attr_path)\n return fd.readline().strip()\n except IOError:\n return\n\n def verify_vendor_pf(self, pf, vendor_id=constants.VENDOR):\n vendor_path = pciUtils.VENDOR_PATH % {'interface': pf}\n if self.get_dev_attr(vendor_path) == vendor_id:\n return True\n else:\n return False\n\n def get_vf_device_type(self, pf, vf_num):\n device_vf_type = None\n device_type_file = pciUtils.DEVICE_TYPE_PATH % {'interface': pf,\n 'vf_num': vf_num}\n try:\n with open(device_type_file, 'r') as fd:\n device_type = fd.read()\n device_type = device_type.strip(os.linesep)\n if device_type in constants.MLNX4_VF_DEVICE_TYPE_LIST:\n device_vf_type = constants.MLNX4_VF_DEVICE_TYPE\n elif device_type in constants.MLNX5_VF_DEVICE_TYPE_LIST:\n device_vf_type = constants.MLNX5_VF_DEVICE_TYPE\n else:\n raise Exception(_LE('device type %s is not '\n 'supported'), device_type)\n except IOError:\n pass\n return device_vf_type\n\n def is_sriov_pf(self, pf):\n vfs_path = pciUtils.VFS_PATH % {'interface': pf}\n vfs = glob.glob(vfs_path)\n if vfs:\n return True\n else:\n return\n\n def get_interface_type(self, ifc):\n cmd = ['ip', '-o', 'link', 'show', 'dev', ifc]\n try:\n out, err = command_utils.execute(*cmd)\n except (processutils.ProcessExecutionError, OSError) as e:\n LOG.warning(_LW(\"Failed to execute command %(cmd)s due to %(e)s\"),\n {\"cmd\": cmd, \"e\": e})\n raise\n if out.find('link/ether') != -1:\n return 'eth'\n elif out.find('link/infiniband') != -1:\n return 'ib'\n else:\n return None\n\n def is_ifc_module(self, ifc):\n if 'ipoib' in ethtool.get_module(ifc):\n return True\n\n def filter_ifcs_module(self, ifcs):\n return [ifc for ifc in ifcs if self.is_ifc_module(ifc)]\n\n def get_pf_mlx_dev(self, pf):\n dev_path = (\n os.path.join(pciUtils.ETH_PATH % {'interface': pf},\n pciUtils.INFINIBAND_PATH))\n dev_info = os.listdir(dev_path)\n return dev_info.pop()\n\n def get_guid_index(self, pf_mlx_dev, dev, hca_port):\n guid_index = None\n path = constants.MLNX4_GUID_INDEX_PATH % (pf_mlx_dev, dev, hca_port)\n with open(path) as fd:\n guid_index = fd.readline().strip()\n return guid_index\n\n def get_eth_port(self, dev):\n port_path = pciUtils.ETH_PORT % {'interface': dev}\n try:\n with open(port_path) as f:\n dev_id = int(f.read(), 0)\n return dev_id + 1\n except IOError:\n return\n\n def get_vfs_macs_ib(self, fabric_details):\n macs_map = {}\n for pf_fabric_details in fabric_details.values():\n if (pf_fabric_details['pf_device_type'] ==\n constants.MLNX4_VF_DEVICE_TYPE):\n macs_map.update(self.get_vfs_macs_ib_mlnx4(pf_fabric_details))\n elif (pf_fabric_details['pf_device_type'] ==\n constants.MLNX5_VF_DEVICE_TYPE):\n macs_map.update(self.get_vfs_macs_ib_mlnx5(pf_fabric_details))\n return macs_map\n\n def get_vfs_macs_ib_mlnx4(self, fabric_details):\n hca_port = fabric_details['hca_port']\n pf_mlx_dev = fabric_details['pf_mlx_dev']\n macs_map = {}\n guids_path = constants.MLNX4_ADMIN_GUID_PATH % (pf_mlx_dev, hca_port,\n '[1-9]*')\n paths = glob.glob(guids_path)\n for path in paths:\n vf_index = path.split('/')[-1]\n with open(path) as f:\n guid = f.readline().strip()\n if guid == constants.MLNX4_INVALID_GUID:\n mac = constants.INVALID_MAC\n else:\n head = guid[:6]\n tail = guid[-6:]\n mac = \":\".join(re.findall('..?', head + tail))\n macs_map[str(int(vf_index))] = mac\n return macs_map\n\n def get_vfs_macs_ib_mlnx5(self, fabric_details):\n vfs = fabric_details['vfs']\n macs_map = {}\n for vf in vfs.values():\n vf_num = vf['vf_num']\n pf_mlx_dev = fabric_details['pf_mlx_dev']\n guid_path = (\n constants.MLNX5_GUID_NODE_PATH % {'module': pf_mlx_dev,\n 'vf_num': vf_num})\n with open(guid_path) as f:\n guid = f.readline().strip()\n head = guid[:8]\n tail = guid[-9:]\n mac = head + tail\n macs_map[vf_num] = mac\n return macs_map\n\n def get_device_address(self, hostdev):\n domain = hostdev.attrib['domain'][2:]\n bus = hostdev.attrib['bus'][2:]\n slot = hostdev.attrib['slot'][2:]\n function = hostdev.attrib['function'][2:]\n dev = \"%.4s:%.2s:%2s.%.1s\" % (domain, bus, slot, function)\n return dev\n","sub_path":"networking_mlnx/eswitchd/utils/pci_utils.py","file_name":"pci_utils.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"324160556","text":"import string\n\n#Task 1:\n#Write a python program that print the first letter of your name with star. You have to use the instructions in the class.\n# For this you should use nested loop to implement.\n#The expected output should be something like this:\n# ****\n# *\n# *\n# ***\n# *\n# *\n# ****\n\n#declare function\ndef ascii_initial():\n\t\t#index to determine where we are in the letter\n row = 0\n #string patterns for the letter\n first= ' ****'\n middle = '* '\n #outer loop\n while(row<7):\n\t\t\t\t#logic to determine which pattern to use based on index value\n if(row==0):\n print(first)\n elif(00) :\n\n images, labs = CreateBatch(40) #later from validation set\n images = np.expand_dims(images, 3)\n\n logs, pre, pre2, acc = sess.run([\n logits, \n pred, \n pred2, \n accuracy\n ] ,feed_dict = {input: images, labels: labs})\n \n #accVal= 1-np.mean(np.abs(np.round(1 / (1 + np.exp(-logs))) -labs ))\n accVal = np.mean(np.equal(labs,np.round(logs)))\n\n print(f'Validation: {episode} {los:10.6f} {accVal:10.6f}')\n summary.value.add(tag='Accurarcy/Validation', simple_value = accVal) \n\n writer.add_summary(summary, episode)\n\n if (episode % 50==0) and (episode>0) : #50 just for testing\n \n preImg = pre2.reshape((54,80)) #discretized logits !!\n original = np.squeeze(images[0])\n pic = Image.fromarray(preImg)\n pic = pic.resize(size=(200,135))\n\n plt.imshow(np.squeeze(images[0]))\n #plt.imshow(pic,cmap='Blues', alpha=0.6)\n plt.imshow(pic,cmap='seismic', alpha=0.5)\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=200)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/overlay', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n\n plt.imshow(np.squeeze(images[0]), cmap='bone') \n ll = np.squeeze(labs[0]).reshape((54,80))\n pic2 = Image.fromarray(ll)\n pic2 = pic2.resize(size=(200,135))\n plt.imshow(pic2, alpha=0.4, cmap='seismic')\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=200)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/original', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n\n\n '''\n preImgX = pre.reshape((80,54)) #discretized logits !! \n picX = Image.fromarray(preImgX)\n picX = picX.resize(size=(160,108))\n \n plt.imshow(picX, cmap='winter_r')\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=100)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/prediction', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n '''\n\n\n '''\n if (episode % 2==0) and (episode>0) :\n\n preImg = pre.reshape((54,80))\n original = np.squeeze(images[0])\n pic = Image.fromarray(preImg)\n pic = pic.resize(size=(200,135))\n\n\n plt.imshow(np.squeeze(images[0]), cmap='bone')\n plt.imshow(pic,cmap='Blues', alpha=0.6)\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=200)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/overlay', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n\n \n \n plt.imshow(np.squeeze(images[0]), cmap='bone') \n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=200)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/original', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n\n\n \n plt.imshow(pic, cmap='winter_r')\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png', dpi=100)\n buf.seek(0) \n image = tf.image.decode_png(buf.getvalue(), channels=4)\n image = tf.expand_dims(image, 0) \n \n sum1 = tf.summary.image(f'{episode}/prediction', image)\n writer.add_summary(sum1.eval(session = sess), episode) \n \n plt.close()\n '''\n","sub_path":"attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":9456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455521758","text":"from numpy import dot, array\nfrom IBUtility import EnsureNumpyArray, cross\nfrom FiberUtility import MakeTriangle, TrianglesToVEF\nfrom Tethered import Tethered\n\nclass Sphere(Tethered):\n\t\"\"\"A hollow sphere, formed via tether points.\"\"\"\n\t\n\t@staticmethod\n\tdef N_to_dt(N, s):\n\t\t\"\"\"Return the largest stable timestep for an explicit simulation.\"\"\"\n\t\t\n\t\th = 1. / N\n\t\treturn .05 * h / s**.5\n\t\t\n\t@staticmethod\n\tdef N_to_Nb_x(N):\n\t\t\"\"\"Return the preferred value of Nb_x for a given value of N.\n\t\t\n\t\tNb_x is the number of fiber points along the edge of one triangle of the generating icosohedron.\"\"\"\n\t\t\n\t\treturn int(N / 2 * 2.**.5)\n\t\n\t@staticmethod\n\tdef MakeSphere(N, c, r):\n\t\t\"\"\"Create a discretized sphere centered at c with radius r.\n\t\t\n\t\tN determines how many points to use in the discretization.\"\"\"\n\t\t\n\t\tc = EnsureNumpyArray(c)\n\n\t\tTriangles, Points = [], []\n\n\t\t# Make an icosohedron, where each face is further triangulated.\n\t\tMakeTriangle(N, c + [0,-r,0], c + [r,0,0], c + [0,0,r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,-r,0], c + [-r,0,0], c + [0,0,r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,r,0], c + [r,0,0], c + [0,0,r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,r,0], c + [-r,0,0], c + [0,0,r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,-r,0], c + [r,0,0], c + [0,0,-r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,-r,0], c + [-r,0,0], c + [0,0,-r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,r,0], c + [r,0,0], c + [0,0,-r], Triangles = Triangles)\n\t\tMakeTriangle(N, c + [0,r,0], c + [-r,0,0], c + [0,0,-r], Triangles = Triangles)\n\n\t\t# Convert the list of triangles into Verticies, Edges, and Triangles\n\t\tPoints, Edges, Triangles = TrianglesToVEF(Triangles)\n\n\t\tPoints = array(Points)\n\n\t\t# Project every point onto the sphere the icosohedron is inscribed in.\n\t\t# First shift the points so the center is the origin.\n\t\tdif = Points - c\n\t\tdifsq = dif**2\n\t\tl = (difsq[:,0] + difsq[:,1] + difsq[:,2])**.5\n\t\tdif[:,0] *= r / l\n\t\tdif[:,1] *= r / l\n\t\tdif[:,2] *= r / l\n\n\t\t# Shift the points back to the original center.\n\t\tPoints = dif + c\n\n\t\treturn Points, array(Triangles), array(Edges)\t\n\t\n\tdef __init__(self, Nb_x=0, s=0, center=[.5,.5,.5], r=.2):\n\t\t\"\"\"Nb_x is the number of fiber points along the edge of one triangle of the generating icosohedron.\n\t\t\n\t\ts is an elasticity constant.\"\"\"\n\n\t\tcenter = EnsureNumpyArray(center)\n\t\t\n\t\t# Make the sphere\n\t\tPoints, Triangles, Edges = self.MakeSphere(Nb_x, center, r)\n\t\t\n\t\t# Make the fiber\n\t\tTethered.__init__(self, Nb = Points.shape[0], Dim = 3, s = s)\n\t\t\n\t\tself.X = Points\n\t\tself.Tether = self.X.copy()\n\t\t\n\t\tself.s = s\n\t\t\n\t\t# Save the corresponding unit sphere\n\t\tself.UnitSphere = (self.X - center) / r\n","sub_path":"Fiber/Sphere.py","file_name":"Sphere.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"17032363","text":"import os\n\nimport hms.app.data.rules\nimport hms.utilities.highlighter\n\ndef prepare(parent_application):\n '''Prepares highlighter and returns reference to highlighter.'''\n # Instatiate dict with name and parent app.\n highlighter = hms.utilities.highlighter.Highlighter(parent_application)\n rules_data_module_path = hms.app.data.rules.__path__[0]\n data_path = os.path.join(rules_data_module_path,\n 'highlight_rules.json')\n highlighter.add_rules_json(data_path)\n return highlighter\n","sub_path":"hms/app/setup/highlighter.py","file_name":"highlighter.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"604943569","text":"from django import forms\n\nfrom .models import Products\n#build-in method to transformation Django form to html form {{ form.as_p }}\nclass ProductsForm(forms.ModelForm):\n class Meta:\n model = Products\n fields = [\n 'title',\n 'description',\n 'price'\n ] #all have to do is rander this in the veiw","sub_path":"products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"599346350","text":"from opengever.activity.model import NotificationSetting\nfrom opengever.activity.roles import TASK_ISSUER_ROLE\nfrom opengever.activity.roles import TASK_RESPONSIBLE_ROLE\nfrom opengever.activity.roles import WATCHER_ROLE\nfrom opengever.core.upgrade import SchemaMigration\nfrom sqlalchemy.sql.expression import column\nfrom sqlalchemy.sql.expression import table\nimport json\n\n\nDEFAULT_SETTINGS = [\n {\n 'kind': 'task-added-or-reassigned',\n 'badge_notification_roles': [TASK_RESPONSIBLE_ROLE, TASK_ISSUER_ROLE, WATCHER_ROLE]\n },\n {\n 'kind': 'task-transition-modify-deadline',\n 'badge_notification_roles': [TASK_RESPONSIBLE_ROLE, TASK_ISSUER_ROLE, WATCHER_ROLE]\n },\n {\n 'kind': 'task-commented',\n 'badge_notification_roles': [TASK_RESPONSIBLE_ROLE, TASK_ISSUER_ROLE, WATCHER_ROLE]\n },\n {\n 'kind': 'task-status-modified',\n 'badge_notification_roles': [TASK_RESPONSIBLE_ROLE, TASK_ISSUER_ROLE, WATCHER_ROLE]\n }\n]\n\ndefaults_table = table(\n \"notification_defaults\",\n column(\"id\"),\n column(\"kind\"),\n column(\"badge_notification_roles\"))\n\n\nclass AddWatcherRoleToTaskNotificationSettings(SchemaMigration):\n \"\"\"Add watcher role to task notification settings.\n \"\"\"\n\n def migrate(self):\n self.update_notification_defaults()\n self.migrate_user_settings()\n\n def update_notification_defaults(self):\n for item in DEFAULT_SETTINGS:\n\n self.execute(\n defaults_table.update()\n .values(badge_notification_roles=json.dumps(item['badge_notification_roles']))\n .where(defaults_table.columns.kind == item.get('kind'))\n )\n\n def migrate_user_settings(self):\n kinds = [default_setting.get('kind') for default_setting in DEFAULT_SETTINGS]\n settings = NotificationSetting.query.filter(NotificationSetting.kind.in_(kinds))\n for setting in settings:\n notification_roles = [role for role in setting.badge_notification_roles]\n notification_roles.append(WATCHER_ROLE)\n setting.badge_notification_roles = notification_roles\n","sub_path":"opengever/core/upgrades/20200511132410_add_watcher_role_to_task_notification_settings/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"137716432","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.addons import decimal_precision as dp\n\nfrom datetime import datetime\n\n\nclass AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n\n currency_rate_type_id = fields.Many2one('res.currency.rate.type', string='Para Birimi Kur Tipi')\n\n currency_rate_type_id_virtual = fields.Many2one('res.currency.rate.type', string=\"Para Birimi Kur Tipi(Virtual)\")\n\n currency_rate = fields.Float(string=\"Para Birimi Kuru\", digits=(12, 4), default=1.0,\n compute='_compute_currency_inverse_rate')\n\n currency_inverse_rate = fields.Float(string=\"Para Birimi Kuru (inverse)\", digits=(12, 4),\n compute='update_currency_rate', store=True, default=1.0)\n\n custom_rate = fields.Float(string='Custom Rate(Özel Kur Değeri)', digits=(12, 4))\n\n use_currency_rate = fields.Boolean(string=\"Use Currency Rate\", compute='onchange_currency_id')\n\n use_custom_rate = fields.Boolean(string=\"Özel Kur\")\n\n @api.multi\n @api.depends('currency_id', 'company_currency_id')\n def onchange_currency_id(self):\n for invoice in self:\n if not invoice.currency_id:\n invoice.use_currency_rate = False\n elif invoice.currency_id.id == invoice.company_currency_id.id:\n invoice.use_currency_rate = False\n else:\n invoice.use_currency_rate = True\n\n @api.model\n def create(self, vals):\n res = super(AccountInvoice, self).create(vals)\n if vals.get('currency_rate'):\n res.update({\n 'currency_inverse_rate': vals['currency_rate']\n })\n return res\n\n # tODO: trying onchange currency\n @api.onchange('currency_id')\n def onchange_currency_id_value(self):\n if self.currency_id and self.currency_id.id != self.env.user.company_id.currency_id.id and self.currency_rate_type_id.id is False:\n rate_type = self.env['res.currency.rate.type'].search([('name', '=', 'Efektif Satış')])\n self.currency_rate_type_id_virtual = rate_type\n self.currency_rate_type_id = self.currency_rate_type_id_virtual\n\n @api.one\n @api.depends('currency_inverse_rate')\n def _compute_currency_inverse_rate(self):\n self.currency_rate = self.currency_inverse_rate\n\n @api.onchange('use_custom_rate')\n def onchange_custom_rate(self):\n if self.use_custom_rate:\n self.currency_rate_type_id = False\n else:\n self.onchange_currency_id_value()\n\n @api.multi\n @api.depends('currency_id', 'currency_rate_type_id', 'date_invoice', 'use_custom_rate', 'custom_rate')\n def update_currency_rate(self):\n for record in self:\n if record.currency_rate_type_id:\n currency = record.currency_id\n rate_type = record.currency_rate_type_id\n currency_rate_obj = self.env['res.currency.rate']\n expected_currency = self.env['res.currency'].search([('id', '=', currency.id)])\n currencyRateIds = currency_rate_obj.search([('currency_id', '=', expected_currency.id)])\n if currencyRateIds:\n last_id = max(currencyRateIds)\n if len(currencyRateIds) > 1:\n last_id = currencyRateIds and currencyRateIds[1]\n if record.date_invoice:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n if record.date_invoice != today:\n rate_by_date = currency_rate_obj.search([('currency_id', '=', expected_currency.id),\n ('name', '=', record.date_invoice)], limit=1)\n last_id = currency_rate_obj.search([('currency_id', '=', expected_currency.id),\n ('id', '<', rate_by_date.id)], order=\"id desc\", limit=1)\n if rate_type.name == 'Efektif Satış':\n if last_id.rate > 0.0:\n record.currency_inverse_rate = 1 / last_id.rate\n elif rate_type.name == 'Efektif Alış':\n if last_id.banknot_buying_rate > 0.0:\n record.currency_inverse_rate = 1 / last_id.banknot_buying_rate\n elif rate_type.name == 'Döviz Satış':\n if last_id.forex_selling_rate > 0.0:\n record.currency_inverse_rate = 1 / last_id.forex_selling_rate\n elif rate_type.name == 'Döviz Alış':\n if last_id.forex_buying_rate > 0.0:\n record.currency_inverse_rate = 1 / last_id.forex_buying_rate\n\n elif record.use_custom_rate is False and not record.currency_rate_type_id:\n currency = record.currency_id\n currency_rate_obj = self.env['res.currency.rate']\n expected_currency = record.env['res.currency'].search([('id', '=', currency.id)])\n currencyRateIds = currency_rate_obj.search([('currency_id', '=', expected_currency.id)])\n if currencyRateIds:\n last_id = max(currencyRateIds)\n if len(currencyRateIds) > 1:\n last_id = currencyRateIds and currencyRateIds[1]\n if record.date_invoice:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n if record.date_invoice != today:\n rate_by_date = currency_rate_obj.search([('currency_id', '=', expected_currency.id),\n ('name', '=', record.date_invoice)], limit=1)\n last_id = currency_rate_obj.search([('currency_id', '=', expected_currency.id),\n ('id', '<', rate_by_date.id)], order=\"id desc\", limit=1)\n if last_id.rate > 0.0:\n record.currency_inverse_rate = 1 / last_id.rate\n\n elif record.use_custom_rate and not record.currency_rate_type_id and record.custom_rate:\n record.currency_inverse_rate = record.custom_rate\n\n\n\n\n\n\n\n\n\n","sub_path":"currency_rate_update_tcmb/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"634746761","text":"\"\"\"\nLoad the wilt data set detecting diseased trees\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\ndef load_wilt():\n fp_train = \"wilt_training.csv\"\n fp_test = \"wilt_testing.csv\"\n\n raw_data_train = pd.read_csv(fp_train, delimiter=',')\n raw_data_test = pd.read_csv(fp_test, delimiter=',')\n frames = [raw_data_train, raw_data_test]\n raw_data = pd.concat(frames)\n data = np.array(raw_data.iloc[:,1:6])\n y = np.array(raw_data.iloc[:,0])\n target = LabelEncoder().fit_transform(y)\n return data, target\n\nif __name__ == '__main__':\n data, target = load_wilt()\n print(type(data))\n print(data)\n print(type(target))\n print(target)\n","sub_path":"datasets/wilt_data_proc.py","file_name":"wilt_data_proc.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"442867205","text":"from writers.writer_text import TextWriter\nimport unittest\n\nclass TestCsvValidationTests(unittest.TestCase):\n def test_write_ingredient_list(self):\n ingredients = {\n 'ingredient 02' : { 'kilo': 1, 'stuk': 20 },\n 'ingredient 01' : { 'gram': 200 }\n }\n writer = TextWriter()\n self.assertEqual(\n writer.create_lines(ingredients),\n sorted(['ingredient 02 - 1 kilo', \n 'ingredient 02 - 20 stuk', \n 'ingredient 01 - 200 gram']))\n\n\n","sub_path":"tests/tests_writer_txt.py","file_name":"tests_writer_txt.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"580295625","text":"from gpiozero import MotionSensor\nimport sys\nfrom omxplayer.player import OMXPlayer\nfrom time import sleep\nimport json\n\nwith open('/home/pi/Videos/markers.json') as myfile:\n data = myfile.read()\n\nobj = json.loads(data)\n\nx = sys.argv[1]\ny = sys.argv[2]\nwidth = '1700'\nheight = '1100'\nprint(\"Starting up....\")\ntgr = 0\ntry:\n player = OMXPlayer('/home/pi/Videos/portraitsallhd.mp4', args=['--no-osd', '--loop', '--win', '{0} {1} {2} {3}'.format(x, y, width, height)])\n pir = MotionSensor(4)\n sleep(1)\n print(\"Ready to trigger\")\n #player.play()\n while True:\n player.pause()\n if pir.motion_detected:\n print('trigger count {}'.format(tgr))\n print('sleeping for {}'.format(obj[tgr]['duration']))\n player.play()\n sleep(obj[tgr]['duration'])\n print(\"Ready to trigger\")\n tgr = tgr + 1\n if tgr < len(obj) : \n player.set_position(obj[tgr]['start'])\n else:\n tgr = 0\n player.set_position(0)\n else:\n pass\n\nexcept KeyboardInterrupt:\n player.quit()\n sleep(3)\n sys.exit()\n","sub_path":"portrait.py","file_name":"portrait.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"633224867","text":"from sqlalchemy.engine.url import make_url\nimport sqlalchemy as sa\nfrom sqlalchemy.exc import ProgrammingError, OperationalError\nimport os\nfrom copy import copy\n\n\ndef escape_like(string, escape_char='*'):\n \"\"\"\n Escape the string paremeter used in SQL LIKE expressions.\n\n ::\n\n from sqlalchemy_utils import escape_like\n\n\n query = session.query(User).filter(\n User.name.ilike(escape_like('John'))\n )\n\n\n :param string: a string to escape\n :param escape_char: escape character\n \"\"\"\n return (\n string\n .replace(escape_char, escape_char * 2)\n .replace('%', escape_char + '%')\n .replace('_', escape_char + '_')\n )\n\n\ndef has_index(column):\n \"\"\"\n Return whether or not given column has an index. A column has an index if\n it has a single column index or it is the first column in compound column\n index.\n\n :param column: SQLAlchemy Column object\n\n .. versionadded: 0.26.2\n\n ::\n\n from sqlalchemy_utils import has_index\n\n\n class Article(Base):\n __tablename__ = 'article'\n id = sa.Column(sa.Integer, primary_key=True)\n title = sa.Column(sa.String(100))\n is_published = sa.Column(sa.Boolean, index=True)\n is_deleted = sa.Column(sa.Boolean)\n is_archived = sa.Column(sa.Boolean)\n\n __table_args__ = (\n sa.Index('my_index', is_deleted, is_archived),\n )\n\n\n table = Article.__table__\n\n has_index(table.c.is_published) # True\n has_index(table.c.is_deleted) # True\n has_index(table.c.is_archived) # False\n\n\n Also supports primary key indexes\n\n ::\n\n from sqlalchemy_utils import has_index\n\n\n class ArticleTranslation(Base):\n __tablename__ = 'article_translation'\n id = sa.Column(sa.Integer, primary_key=True)\n locale = sa.Column(sa.String(10), primary_key=True)\n title = sa.Column(sa.String(100))\n\n\n table = ArticleTranslation.__table__\n\n has_index(table.c.locale) # False\n has_index(table.c.id) # True\n \"\"\"\n return (\n column is column.table.primary_key.columns.values()[0]\n or\n any(\n index.columns.values()[0] is column\n for index in column.table.indexes\n )\n )\n\n\ndef is_auto_assigned_date_column(column):\n \"\"\"\n Returns whether or not given SQLAlchemy Column object's is auto assigned\n DateTime or Date.\n\n :param column: SQLAlchemy Column object\n \"\"\"\n return (\n (\n isinstance(column.type, sa.DateTime) or\n isinstance(column.type, sa.Date)\n )\n and\n (\n column.default or\n column.server_default or\n column.onupdate or\n column.server_onupdate\n )\n )\n\n\ndef database_exists(url):\n \"\"\"Check if a database exists.\n\n :param url: A SQLAlchemy engine URL.\n\n Performs backend-specific testing to quickly determine if a database\n exists on the server. ::\n\n database_exists('postgres://postgres@localhost/name') #=> False\n create_database('postgres://postgres@localhost/name')\n database_exists('postgres://postgres@localhost/name') #=> True\n\n Supports checking against a constructed URL as well. ::\n\n engine = create_engine('postgres://postgres@localhost/name')\n database_exists(engine.url) #=> False\n create_database(engine.url)\n database_exists(engine.url) #=> True\n\n \"\"\"\n\n url = copy(make_url(url))\n database = url.database\n if url.drivername.startswith('postgresql'):\n url.database = 'template1'\n else:\n url.database = None\n\n engine = sa.create_engine(url)\n\n if engine.dialect.name == 'postgresql':\n text = \"SELECT 1 FROM pg_database WHERE datname='%s'\" % database\n return bool(engine.execute(text).scalar())\n\n elif engine.dialect.name == 'mysql':\n text = (\"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \"\n \"WHERE SCHEMA_NAME = '%s'\" % database)\n return bool(engine.execute(text).scalar())\n\n elif engine.dialect.name == 'sqlite':\n return database == ':memory:' or os.path.exists(database)\n\n else:\n text = 'SELECT 1'\n try:\n url.database = database\n engine = sa.create_engine(url)\n engine.execute(text)\n return True\n\n except (ProgrammingError, OperationalError):\n return False\n\n\ndef create_database(url, encoding='utf8', template=None):\n \"\"\"Issue the appropriate CREATE DATABASE statement.\n\n :param url: A SQLAlchemy engine URL.\n :param encoding: The encoding to create the database as.\n :param template:\n The name of the template from which to create the new database. At the\n moment only supported by PostgreSQL driver.\n\n To create a database, you can pass a simple URL that would have\n been passed to ``create_engine``. ::\n\n create_database('postgres://postgres@localhost/name')\n\n You may also pass the url from an existing engine. ::\n\n create_database(engine.url)\n\n Has full support for mysql, postgres, and sqlite. In theory,\n other database engines should be supported.\n \"\"\"\n\n url = copy(make_url(url))\n\n database = url.database\n\n if url.drivername.startswith('postgresql'):\n url.database = 'template1'\n elif not url.drivername.startswith('sqlite'):\n url.database = None\n\n engine = sa.create_engine(url)\n\n if engine.dialect.name == 'postgresql':\n if engine.driver == 'psycopg2':\n from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\n engine.raw_connection().set_isolation_level(\n ISOLATION_LEVEL_AUTOCOMMIT\n )\n\n if not template:\n template = 'template0'\n\n text = \"CREATE DATABASE %s ENCODING '%s' TEMPLATE %s\" % (\n database, encoding, template\n )\n engine.execute(text)\n\n elif engine.dialect.name == 'mysql':\n text = \"CREATE DATABASE %s CHARACTER SET = '%s'\" % (database, encoding)\n engine.execute(text)\n\n elif engine.dialect.name == 'sqlite' and database != ':memory:':\n open(database, 'w').close()\n\n else:\n text = \"CREATE DATABASE %s\" % database\n engine.execute(text)\n\n\ndef drop_database(url):\n \"\"\"Issue the appropriate DROP DATABASE statement.\n\n :param url: A SQLAlchemy engine URL.\n\n Works similar to the :ref:`create_database` method in that both url text\n and a constructed url are accepted. ::\n\n drop_database('postgres://postgres@localhost/name')\n drop_database(engine.url)\n\n \"\"\"\n\n url = copy(make_url(url))\n\n database = url.database\n\n if url.drivername.startswith('postgresql'):\n url.database = 'template1'\n elif not url.drivername.startswith('sqlite'):\n url.database = None\n\n engine = sa.create_engine(url)\n\n if engine.dialect.name == 'sqlite' and url.database != ':memory:':\n os.remove(url.database)\n\n elif engine.dialect.name == 'postgresql' and engine.driver == 'psycopg2':\n from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\n engine.raw_connection().set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n # Disconnect all users from the database we are dropping.\n text = '''\n SELECT pg_terminate_backend(pg_stat_activity.pid)\n FROM pg_stat_activity\n WHERE pg_stat_activity.datname = '%s'\n AND pid <> pg_backend_pid()\n ''' % database\n engine.execute(text)\n\n # Drop the database.\n text = \"DROP DATABASE %s\" % database\n engine.execute(text)\n\n else:\n text = \"DROP DATABASE %s\" % database\n engine.execute(text)\n","sub_path":"env/lib/python2.7/site-packages/sqlalchemy_utils/functions/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"227387520","text":"import collections\r\nimport json\r\nimport os\r\nfrom center import network_handler, traceback\r\n\r\ndebug = True\r\ntestLocal = True\r\nstat = 1\r\n# json_file = \"nokia.json\"\r\n\r\n# testLocal = True\r\n# json_file = \"test.json\"\r\n\r\n\"\"\"Structure for Payload\"\"\"\r\nData = collections.namedtuple('Data', 'target, p0, p1, H, quad')\r\nStep = collections.namedtuple(\r\n\t'Step', 'id, val_name, val_order_name, val_main, ctr_pos_3D, ctr_pos, patch, mask, val_result, val_dur, val_thr, msg, msg_pos, three_d')\r\nObj = collections.namedtuple('Obj', 'name, path, shaders, init_size')\r\nObj_prop = collections.namedtuple(\r\n\t'Obj_prop', 'name, shader, animation, base, bump')\r\n\r\n\r\n\"\"\"Path for Platform\"\"\"\r\nif os.name == \"nt\": # windows\r\n\tmid = \"\\\\\"\r\n\tfront = str(os.getcwd())\r\n\tfront = front.split('\\\\')\r\n\ts = '\\\\'\r\n\tfront = s.join(front) + \"\\\\\"\r\nelif os.name == \"posix\": # linux\r\n\tmid = \"/\"\r\n\tfront = \"\"\r\n\r\nrootDir = \"data\" + mid + \"db_\"\r\nassets_path = front + \"data\" + mid + \"asset\" + mid\r\n\r\n\"\"\"UI Assets\"\"\"\r\nui_path = \"data\" + mid + \"asset\" + mid + \"UI\" + mid\r\n\r\n\r\n# \"\"\"Load Json for Payload\"\"\"\r\n# with open(json_file, \"r\") as read_file:\r\n# config_data = json.load(read_file)\r\n\r\n# \"\"\"Load Json for Payload\"\"\"\r\n# with open(json_file, \"r\") as read_file:\r\n# smacar_client = json.load(read_file)\r\n# station_id = smacar_client[\"station_id\"]\r\n# server_ip = smacar_client[\"server_ip\"]\r\n\r\n\r\n# client_id = config_data[\"client_id\"]\r\n# client_ip = config_data[\"client_ip\"]\r\n# server_id = config_data[\"server_id\"]\r\n# server_ip = config_data[\"server_ip\"]\r\n\r\n#prefix\r\n# station_prefix = \"station_\"\r\n# threed_model_prefix = \"3d_model\"\r\n# steps_prefix = \"steps\"\r\n\r\n# station_id = station_prefix + config_data[\"station_id\"]\r\n\r\n# station_msg = config_data[station_id][0][\"station_msg\"]\r\n# station_msg_pos = tuple(config_data[station_id][0][\"station_msg_pos\"])\r\n# station_msg = config_data[\"station_msg\"]\r\n# station_msg_pos = tuple(config_data[\"station_msg_pos\"])\r\n\r\n# three_d_data = config_data[station_id][1][threed_model_prefix]\r\n# steps_data = config_data[station_id][2][steps_prefix]\r\n# three_d_data = config_data[threed_model_prefix]\r\n# steps_data = config_data[steps_prefix]\r\n\r\n\r\n# model_list = {}\r\n# model_properties_list = {}\r\n# data = []\r\n\r\n# \"\"\"3D models to load\"\"\"\r\n# for model in three_d_data:\r\n# model_list[model[\"name\"]] = Obj(name=model[\"name\"], path=assets_path + model[\"name\"] + mid + \"object.obj\", shaders=None, init_size=(model[\"init_size\"][\"x\"], model[\"init_size\"][\"y\"],\r\n# model[\"init_size\"][\"z\"], model[\"init_size\"][\"sx\"], model[\"init_size\"][\"sy\"], model[\"init_size\"][\"sz\"], model[\"init_size\"][\"rx\"], model[\"init_size\"][\"ry\"], model[\"init_size\"][\"rz\"]))\r\n# if model[\"base\"]:\r\n# model[\"base\"] = assets_path + model[\"name\"] + mid + \"base.png\"\r\n# if model[\"bump\"]:\r\n# model[\"bump\"] = assets_path + model[\"name\"] + mid + \"bump.png\"\r\n# model_properties_list[model[\"name\"]] = Obj_prop(name=model[\"name\"], shader=model[\"shader\"],\r\n# animation = model[\"anmination\"],\r\n# base=model[\"base\"], bump=model[\"bump\"])\r\n\r\n\r\n# \"\"\"Steps to validate\r\n# \"\"\"\r\n\r\n# for step in steps_data:\r\n# three_d = None\r\n# if not step[\"val_name\"] == \"Text\":\r\n# three_d = model_properties_list[step[\"three_d\"]]\r\n# data.append(\r\n# Step(\r\n# id=step[\"id\"],\r\n# val_name=step[\"val_name\"],\r\n# val_main=step[\"val_main\"], ctr_pos_3D=step[\"ctr_pos_3D\"],\r\n# ctr_pos=step[\"ctr_pos\"], patch=step[\"patch\"],\r\n# mask=step[\"mask\"], val_result=step[\"val_result\"],\r\n# val_thr=step[\"val_thr\"], val_dur=step[\"val_dur\"],\r\n# msg=step[\"msg\"], msg_pos=step[\"msg_pos\"],\r\n# three_d=three_d))\r\n\r\nclass LocalJson(object):\r\n\tdef __init__(self):\r\n\t\tself.local_json_file = \"smacar.json\"\r\n\t\tself.text_json_file = \"text.json\"\r\n\t\tself.load_local_json()\r\n\r\n\tdef load_local_json(self):\r\n\t\t\"\"\"Load Json from local\"\"\"\r\n\t\ttry:\r\n\t\t\twith open(self.local_json_file, \"r\") as read_file:\r\n\t\t\t\tsmacar_client = json.load(read_file)\r\n\t\t\t\tself.station_id = smacar_client[\"station_id\"]\r\n\t\t\t\tself.server_ip = smacar_client[\"server_ip\"]\r\n\t\t\t\tself.token=smacar_client[\"token\"]\r\n\r\n\t\texcept:\r\n\t\t\tnetwork_handler.CreateErrorLog(network_handler.LogObject, \" File \\\"config.py\\\", line 117, in \")\r\n\t\tself.station_uid = self.station_id\r\n\tdef text_local_file(self):\r\n\t\twith open(self.text_json_file, \"r\") as read_file:\r\n\t\t\tstation_text = json.load(read_file)\r\n\t\t\tself.station = station_text[str(\"station_\"+(self.station_uid))]\r\n\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t# \texcept:\r\n\t# \t\tnetwork_handler.CreateErrorLog(network_handler.LogObject, \" File \\\"config.py\\\", line 117, in \")\r\n\r\nclass ServerJson(object):\r\n\tdef __init__(self, data):\r\n\t\tself.model_list = {}\r\n\t\tself.model_properties_list = {}\r\n\t\tself.data = []\r\n\t\tself.steps_data = data[\"steps\"]\r\n\t\tself.three_d_data = data[\"3d_model\"]\r\n\r\n\t# def get_other_info(self, data):\r\n\t\tself.station_msg = data[\"station_msg\"]\r\n\t\tself.station_msg_pos = tuple(data[\"station_msg_pos\"])\r\n\t\tself.version = data[\"version\"]\r\n\t\tself.client_id = data[\"client_id\"]\r\n\r\n\r\n\tdef get_model(self):\r\n\t\t\"\"\"3D models to load\"\"\"\r\n\t\tfor model in self.three_d_data:\r\n\t\t\tself.model_list[model[\"name\"]] = Obj(\r\n\t\t\t\tname=model[\"name\"], shaders=None,\r\n\t\t\t\tpath=assets_path + model[\"name\"] + mid + \"object.pkl\",\r\n\t\t\t\tinit_size=(model[\"init_size\"][\"x\"], model[\"init_size\"][\"y\"],\r\n\t\t\t\tmodel[\"init_size\"][\"z\"], model[\"init_size\"][\"sx\"], model[\"init_size\"][\"sy\"], model[\"init_size\"][\"sz\"], model[\"init_size\"][\"rx\"], model[\"init_size\"][\"ry\"], model[\"init_size\"][\"rz\"]))\r\n\t\t\tif model[\"base\"]:\r\n\t\t\t\tmodel[\"base\"] = assets_path + model[\"name\"] + mid + \"base.png\"\r\n\t\t\tif model[\"bump\"]:\r\n\t\t\t\tmodel[\"bump\"] = assets_path + model[\"name\"] + mid + \"bump.png\"\r\n\t\t\tself.model_properties_list[model[\"name\"]] = Obj_prop(\r\n\t\t\t\tname=model[\"name\"], shader=model[\"shader\"],\r\n\t\t\t\tanimation=model[\"anmination\"],\r\n\t\t\t\tbase=model[\"base\"], bump=model[\"bump\"])\r\n\t\treturn self.model_list\r\n\r\n\tdef get_steps(self):\r\n\t\t\"\"\"Steps to validate\"\"\"\r\n\t\tfor step in self.steps_data:\r\n\t\t\tthree_d = None\r\n\t\t\tif not (step[\"val_name\"]).startswith(\"Text\"):\r\n\t\t\t\tthree_d = self.model_properties_list[step[\"three_d\"]]\r\n\t\t\tself.data.append(\r\n\t\t\t\tStep(\r\n\t\t\t\t\tid=step[\"id\"],\r\n\t\t\t\t\tval_name=step[\"val_name\"],\r\n\t\t\t\t\tval_order_name=step[\"val_order_name\"],\r\n\t\t\t\t\tval_main=step[\"val_main\"], ctr_pos_3D=step[\"ctr_pos_3D\"],\r\n\t\t\t\t\tctr_pos=step[\"ctr_pos\"], patch=step[\"patch\"],\r\n\t\t\t\t\tmask=step[\"mask\"], val_result=step[\"val_result\"],\r\n\t\t\t\t\tval_thr=step[\"val_thr\"], val_dur=step[\"val_dur\"],\r\n\t\t\t\t\tmsg=step[\"msg\"], msg_pos=step[\"msg_pos\"],\r\n\t\t\t\t\tthree_d=three_d))\r\n\r\n\r\n\t\t# del model_properties_list #clean model_properties_list\r\n\t\treturn self.data\r\n","sub_path":"utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"491140215","text":"import os\nimport numpy as np\nfrom PIL import Image\nimport cv2\nfrom time import time\nimport json\n\nimport torch\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset\n\nclass HDRDataset(Dataset):\n def __init__(self, image_path, params=None, suffix='', mode='train', illum_mode='123'):\n assert mode in ['train', 'val', 'test']\n self.mode = mode\n self.image_path = image_path\n self.suffix = suffix\n in_files = self.list_files(os.path.join(image_path, mode))\n self.in_files = sorted([f for f in in_files if f.split('/')[-1].count('_') == 1 and f[-4:] == 'tiff'])\n\n # for 1-illum only\n if illum_mode == '1':\n self.in_files = [f for f in self.in_files if \"_1.tiff\" in f]\n # for 2-illum only\n elif illum_mode == '2':\n self.in_files = [f for f in self.in_files if \"_12.tiff\" in f]\n # for 3-illum only\n elif illum_mode == '3':\n self.in_files = [f for f in self.in_files if \"_123.tiff\" in f]\n # for 2 & 3\n elif illum_mode == '23':\n self.in_files = [f for f in self.in_files if (\"_12.tiff\" in f or \"_123.tiff\" in f)]\n\n\n self.max = 2 ** params['bit_depth'] - 1\n self.ls = params['net_input_size']\n self.fs = params['net_output_size']\n self.low = transforms.Compose([\n transforms.ToTensor(),\n ])\n self.full = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n def __len__(self):\n return len(self.in_files)\n\n def __getitem__(self, idx):\n fname = os.path.split(self.in_files[idx])[-1]\n path = self.in_files[idx].replace(fname, '')\n fname_split = fname.split('.')\n fname = fname_split[0]\n extension = fname_split[1]\n\n imagein = cv2.imread(self.in_files[idx], cv2.IMREAD_UNCHANGED)\n imagein = cv2.cvtColor(imagein, cv2.COLOR_BGR2RGB).astype('float32') / self.max\n\n imagein_low = cv2.resize(imagein, (self.ls, self.ls))\n \n imageout = cv2.imread(path + fname + '_gt.' + extension, cv2.IMREAD_UNCHANGED)\n imageout = cv2.cvtColor(imageout, cv2.COLOR_BGR2RGB).astype('float32') / self.max\n\n imagein_low = self.low(imagein_low)\n imagein_full = self.full(imagein)\n imageout = self.full(imageout)\n \n gt_illum = imagein_full / (imageout + 1e-8)\n \n return imagein_low, imagein_full, imageout, gt_illum, fname\n\n def list_files(self, in_path):\n files = []\n for (dirpath, dirnames, filenames) in os.walk(in_path):\n files.extend(filenames)\n break\n files = sorted([os.path.join(in_path, x) for x in files])\n return files\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"470892997","text":"#!/bin/python3\n\n\"\"\"\nHackerrank ProjectEuler+ Challenge: \nProject Euler #3: Largest Prime Factor\n\"\"\"\n\nif __name__ == '__main__':\n t = int(input().strip())\n \n for a0 in range(t):\n n = int(input().strip())\n i = 2\n factors = []\n while i**2 <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n\n print(max(factors))","sub_path":"ProjectEuler+/p3_largest_prime_factor.py","file_name":"p3_largest_prime_factor.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"31001655","text":"# Copyright 2014-2015 PUNCH Cyber Analytics Group\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\"\"\"\nOverview\n========\n\nSends and retrieves content from MongoDB\n\n\"\"\"\n\nfrom gridfs import GridFS\nfrom pymongo import MongoClient\nfrom pymongo.errors import DuplicateKeyError\nfrom gridfs.errors import FileExists\n\nfrom stoq.plugins import StoqConnectorPlugin\n\n\nclass MongoConnector(StoqConnectorPlugin):\n\n def __init__(self):\n super().__init__()\n\n def activate(self, stoq):\n self.stoq = stoq\n\n super().activate()\n\n self.archive = False\n\n def get_file(self, **kwargs):\n \"\"\"\n Retrieve a file from GridFS\n\n :param **kwargs md5: md5 hash of payload to be retrieved\n :param **kwargs sha1: SHA1 hash of payload to be retrieved\n :param **kwargs sha256: SHA256 hash of payload to be retrieved\n :param **kwargs sha512: SHA512 hash of payload to be retrieved\n\n :returns: Content of file retrieved\n :rtype: bytes or None\n\n \"\"\"\n\n # Make sure we only use GridFS\n self.archive = True\n\n # What keys are OK to use to validate if a file exists and retrieve it?\n valid_keys = ['sha1', 'md5', 'sha256', 'sha512']\n\n # Iterate over each valid key and see if it exists in the arguments\n # passed\n for key in valid_keys:\n if key in kwargs:\n # Make sure we have a valid mongodb connection\n self.connect()\n\n # So gridfs' documentation states we can use find_one, but\n # it doesn't exist. So instead, we are going to use find,\n # then just use the first item in the index, since we\n # should always only return a single result anyway.\n results = self.collection.find({key: kwargs[key]})\n\n if results.count:\n try:\n with self.collection.get(results[0]._id) as requested_file:\n return requested_file.read()\n except Exception as e:\n self.log.error(\"Unable to retrieve file {} :: {}\".format(kwargs, str(e)))\n return None\n\n # No results, carry on.\n return None\n\n def save(self, payload, archive=False, **kwargs):\n \"\"\"\n Save results to mongodb\n\n :param dict/bytes payload: Content to be inserted into mongodb\n :param bool archive: Define whether the payload to be inserted as a\n binary sample that should be saved in GridFS.\n :param **kwargs sha1: SHA1 hash of payload. Used with saving results\n as well as payloads to GridFS. Automatically\n generated if not value is provided.\n :param **kwargs index: Index name to save content to\n :param **kwargs *: Any additional attributes that should be added\n to the GridFS object on insert\n\n \"\"\"\n\n self.archive = archive\n\n # Define the index name, if available.\n index = kwargs.get('index', None)\n\n if not hasattr(self, 'collection'):\n self.connect(index)\n\n if not self.archive:\n # Make sure json is sanitized (remove '.' and ' ' from keys) so\n # mongodb can handle it.\n payload = self.stoq.sanitize_json(payload)\n\n # Let's attempt to save our data to mongo at most 3 times.\n for save_attempt in range(3):\n try:\n if self.archive:\n # Assign the indexed _id key to be that of the sha1 for the\n # file. This will eliminate duplicate files stored within\n # GridFS.\n if save_attempt == 0:\n kwargs['_id'] = kwargs['sha1']\n try:\n # Attempt to insert the payload into GridFS\n with self.collection.new_file(**kwargs) as fp:\n fp.write(payload)\n break\n except (DuplicateKeyError, FileExists):\n # Looks like the file is a duplicate, let's just\n # continue on.\n break\n else:\n if save_attempt == 0:\n # Make sure json is sanitized (remove '.' and ' ' from keys) so\n # mongodb can handle it.\n payload = self.stoq.sanitize_json(payload)\n\n self.collection.insert(payload)\n\n # Success..let's break out of our loop.\n break\n except:\n # We probably don't have a valid MongoDB connection. Time to\n # make one.\n self.connect(index)\n\n super().save()\n\n def connect(self, collection_name=None):\n \"\"\"\n Connect to a mongodb instance\n\n :param bytes collection: Name of MongoDB collection to utilize\n\n \"\"\"\n\n # self.conn is defined in the stoq plugin config file.\n self.mongo_client = MongoClient(self.conn)\n\n if self.archive:\n self.__connect_gridfs(collection_name)\n else:\n self.__connect_mongodb(collection_name)\n\n super().connect()\n\n def __connect_gridfs(self, collection_name=None):\n # We are handling an archived sample with GridFS\n self.gridfs_db = self.mongo_client.stoq_gridfs\n\n # No collection, we assume that the query is for binary data\n if not collection_name:\n self.collection = GridFS(self.gridfs_db)\n else:\n # We have a collection, let's use it to query/update metadata\n self.collection = self.gridfs_db[collection_name]\n\n def __connect_mongodb(self, collection_name=None):\n # If no collection name was passed, let's set it to the name of the\n # worker plugin that called us\n if not collection_name:\n collection_name = self.parentname\n\n # No, we are saving a json document from a plugin\n self.mongo_db = self.mongo_client.stoq\n self.collection = self.mongo_db[collection_name]\n\n def disconnect(self):\n \"\"\"\n Disconnect from mongodb instance\n\n \"\"\"\n\n self.mongo_client.disconnect()\n super().disconnect()\n","sub_path":"connector/mongodb/mongodb/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"206143438","text":"def divisible(n):\n\t\"\"\"function to print number divisible by five and seven\"\"\"\n\tfor i in range(0,n):\n\t\tif(i%5==0):\n\t\t\tif(i%7==0):\n\t\t\t\tyield i\n\t\t\t\ti=i+1\nn=input(\"enter the range\")\na=divisible(n)\nfor j in range(0,n):\n\tprint(a.next())\n\n\n\n","sub_path":"function/1541607946797_d.py","file_name":"1541607946797_d.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537092110","text":"from __future__ import (absolute_import, print_function, division, unicode_literals)\r\nfrom scipy import io, optimize, integrate\r\nfrom numpy import diag, zeros, ones, dot, copy, mean, asarray, array\r\nfrom scipy.linalg import lu\r\nfrom numpy.linalg import inv, matrix_rank, cond, cholesky, norm\r\nimport time\r\nimport csv\r\n# from PyFoam.Error import error\r\n# from PyFoam.Execution.BasicRunner import BasicRunner\r\n# from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile\r\nimport mpctools as mpc\r\nfrom casadi import *\r\nfrom math import *\r\nimport matplotlib.pyplot as plt\r\n\r\nprint(\"I am starting up\")\r\nstart_time = time.time()\r\n# First sections: Geometry/Physical domain##############################################################################\r\n# Define the geometry\r\nlengthOfZ = 0.67 # meter\r\n# Define the nodes\r\nnodesInZ = 32\r\n# nodesInZinOF = nodesInZ+1\r\nnodesInPlane = 1\r\nnumberOfNodes = nodesInZ\r\ndzList = lengthOfZ/nodesInZ\r\n# Label the nodes\r\nindexOfNodes = []\r\nfor i in range(0, numberOfNodes):\r\n indexOfNodes.append(i)\r\npositionOfNodes = []\r\nfor k in range(0, nodesInZ):\r\n positionOfNodes.append([0, 0, k])\r\n\r\n# Second sections: Parameters/Initial conditions ######################################################################\r\n# Initial Parameters\r\nKs = 0.00000288889 # [m/s]\r\nTheta_s = 0.43\r\nTheta_r = 0.078\r\nAlpha = 3.6\r\nN = 1.56\r\n\r\nS = 0.0001 # [per m]\r\nPET = 0.0000000070042 # [per sec]\r\n\r\n# Initial state\r\nthetaIni = array([30.2, 8.8, 8.7, 10.0])/100\r\n# thetaIni = array([26.0, 26.0, 13.0, 11.0])/100\r\nhIni = zeros(4)\r\nfor i in range(0, 4):\r\n hIni[i] = ((((thetaIni[i] - Theta_r)/(Theta_s-Theta_r))**(1./(-(1-1/N))) - 1)**(1./N))/(-Alpha)\r\n\r\nassignPlane = array([8.54925, 7.164, 7.164, 9.12238]) # the sum of assignPlane need to be the same as nodesInZ\r\n# assignPlane = array([8, 8, 8, 8])\r\n# assignPlane = array([9, 7, 7, 9])\r\nsection = array([nodesInPlane*assignPlane[3], nodesInPlane*(assignPlane[3]+assignPlane[2]),\r\n nodesInPlane*(assignPlane[3]+assignPlane[2]+assignPlane[1]),\r\n numberOfNodes])\r\nhMatrix = zeros(numberOfNodes)\r\nhMatrix[0: int(section[0])] = hIni[3]\r\nhMatrix[int(section[0]):int(section[1])] = hIni[2]\r\nhMatrix[int(section[1]):int(section[2])] = hIni[1]\r\nhMatrix[int(section[2]):int(section[3])] = hIni[0]\r\n\r\n\r\n# Third sections: ODEs #################################################################################################\r\n# Calculation of hydraulic conductivity\r\ndef hydraulic_conductivity(h, ks, alpha, n):\r\n term3 = (1+((-1*alpha*-1*(h**2)**(1./2.))**n))\r\n term4 = (term3**(-(1-1/n)))\r\n term5 = term4**(1./2.)\r\n term6 = term4**(n/(n-1))\r\n term7 = (1-term6)**(1-1/n)\r\n term8 = ((1-term7)**2)\r\n term1 = ((1 + sign(h)) * ks)\r\n term2 = (1-sign(h))*ks*term5*term8\r\n term0 = (term1+term2)\r\n hc = 0.5*term0\r\n return hc\r\n\r\n\r\n# Calculation of capillary capacity\r\ndef capillary_capacity(h, theta_s, theta_r, alpha, n, s=S):\r\n cc = 0.5*(((1+np.sign(h))*s)+\r\n (1-np.sign(h))*(s+((theta_s-theta_r)*alpha*n*(1-1/n))*((-1*alpha*-1*((h)**2)**(0.5))**(n-1))*\r\n ((1+(-1*alpha*-1*((h)**2)**(0.5))**n)**(-(2-1/n)))))\r\n return cc\r\n\r\n\r\ndef mean_hydra_conductivity(left_boundary, right_boundary, ks, alpha, n):\r\n lk = hydraulic_conductivity(left_boundary, ks, alpha, n)\r\n rk = hydraulic_conductivity(right_boundary, ks, alpha, n)\r\n mk = mean([lk, rk])\r\n return mk\r\n\r\n\r\n# def qpet(pet=PET):\r\n# q_pet = pet*()\r\n# def aet():\r\n\r\n\r\ndef getODE(x, u, p):\r\n # Optimized parameters\r\n ks = p[0]\r\n theta_s = p[1]\r\n theta_r = p[2]\r\n alpha = p[3]\r\n n = p[4]\r\n irr = u\r\n state = x\r\n dhdt = SX.zeros(numberOfNodes)\r\n # dhdt = zeros(numberOfNodes)\r\n for i in range(0, numberOfNodes):\r\n # print('time: ', timeList)\r\n # print('nodes: ', i)\r\n dz = dzList\r\n current_state = state[i]\r\n if i == 0:\r\n bc_zl = current_state\r\n # bc_zl = 0\r\n bc_zu = state[i + nodesInPlane]\r\n elif i == nodesInZ - 1:\r\n bc_zl = state[i - nodesInPlane]\r\n KzU1 = hydraulic_conductivity(current_state, ks, alpha, n)\r\n bc_zu = current_state + dz * (-1 + irr / KzU1)\r\n else:\r\n bc_zl = state[i - nodesInPlane]\r\n bc_zu = state[i + nodesInPlane]\r\n\r\n KzL = mean_hydra_conductivity(state[i], bc_zl, ks, alpha, n)\r\n KzU = mean_hydra_conductivity(state[i], bc_zu, ks, alpha, n)\r\n deltaHzL = (state[i] - bc_zl) / dz\r\n deltaHzU = (bc_zu - state[i]) / dz\r\n\r\n temp2 = 1 / (0.5 * 2 * dz) * (KzU * deltaHzU - KzL * deltaHzL)\r\n temp3 = 1 / (0.5 * 2 * dz) * (KzU - KzL)\r\n temp4 = 0 # source term\r\n temp5 = temp2 + temp3 - temp4\r\n temp6 = temp5 / capillary_capacity(current_state, theta_s, theta_r, alpha, n)\r\n dhdt[i] = temp6\r\n return dhdt\r\n\r\n\r\ndef simulate(p):\r\n h = zeros((len(timeList), numberOfNodes))\r\n h[0] = hMatrix\r\n h0 = h[0]\r\n theta = zeros((len(timeList), numberOfNodes))\r\n h_avg = zeros((len(timeList), 4)) # 4 sensors\r\n h_avg[0] = hIni\r\n theta_avg = zeros((len(timeList), 4))\r\n theta_avg[0] = thetaIni*100\r\n for i in range(len(timeList)-1):\r\n print('At time:', i+1, ' min(s)')\r\n ts = [timeList[i], timeList[i+1]]\r\n y = integrate.odeint(getODE, h0, ts, args=(irr_amount[i], p))\r\n h0 = y[-1]\r\n h[i+1] = h0\r\n\r\n temp11 = (1 + (-p[3] * h0) ** p[4])\r\n temp22 = temp11 ** (-(1 - 1 / p[4]))\r\n temp33 = (p[1] - p[2]) * temp22\r\n theta0 = 100 * (temp33 + p[2])\r\n theta[i+1] = theta0\r\n\r\n start = 2\r\n end = 9\r\n for j in range(0, 4):\r\n h_avg[i+1][j] = (sum(h0[start * nodesInPlane:end * nodesInPlane]) / (\r\n (end - start) * nodesInPlane))\r\n theta_avg[i+1][j] = (sum(theta0[start * nodesInPlane:end * nodesInPlane]) / (\r\n (end - start) * nodesInPlane))\r\n start += 7\r\n end += 7\r\n h_avg[i+1] = h_avg[i+1][::-1]\r\n theta_avg[i+1] = theta_avg[i+1][::-1]\r\n return h_avg, theta_avg\r\n\r\n\r\ndef objective(x, p, theta_e):\r\n # Simulate objective\r\n # print(p)\r\n # hp, theta_p = simulate(p)\r\n\r\n # hp = ((((theta_p / 100 - p[2]) / (p[1] - p[2])) ** (1. / (-(1 - 1 / p[4]))) - 1) ** (1. / p[4])) / (\r\n # -p[3])\r\n #\r\n # he = ((((theta_e / 100 - p[2]) / (p[1] - p[2])) ** (1. / (-(1 - 1 / p[4]))) - 1) ** (1. / p[4])) / (\r\n # -p[3])\r\n ks = p[0]\r\n theta_s = p[1]\r\n theta_r = p[2]\r\n alpha = p[3]\r\n n = p[4]\r\n\r\n temp11 = (1 + (-alpha * x) ** n)\r\n temp22 = temp11 ** (-(1 - 1. / n))\r\n temp33 = (theta_s - theta_r) * temp22\r\n theta = 100 * (temp33 + theta_r)\r\n\r\n obj = 0\r\n # theta_avg = MX.sym('theta_avg', 4)\r\n for i in range(0, 4):\r\n start = 2\r\n end = 9\r\n total = 0\r\n for j in range(0, 7):\r\n k = start + i * (end-start)\r\n total += theta[k]\r\n start += 1\r\n end += 1\r\n # theta_avg[i] = total / (end - start)\r\n theta_avg = total/(end-start)\r\n obj += (theta_avg - theta_e[-(i+1)])**2\r\n\r\n # theta_avg = theta_avg[::-1]\r\n #\r\n # obj = (theta_avg[0] - theta_e[0]) ** 2 \\\r\n # + (theta_avg[1] - theta_e[1]) ** 2 \\\r\n # + (theta_avg[2] - theta_e[2]) ** 2 \\\r\n # + (theta_avg[3] - theta_e[3]) ** 2\r\n # obj += ((hp[i, 0]-he[i, 0])/he[i, 0])**2 + \\\r\n # ((hp[i, 1]-he[i, 1])/he[i, 1])**2 + \\\r\n # ((hp[i, 2]-he[i, 2])/he[i, 2])**2 + \\\r\n # ((hp[i, 3]-he[i, 3])/he[i, 3])**2\r\n return obj\r\n\r\n\r\n# Fourth section: main##########################################################################################\r\n# Initial decision variables\r\nKs = 0.00000288889 # [m/s]\r\nTheta_s = 0.43\r\nTheta_r = 0.078\r\nAlpha = 3.6\r\nN = 1.56\r\np0 = array([Ks, Theta_s, Theta_r, Alpha, N])\r\n# plb = array([Ks, 0.39, 0.075, 3.2, 1.4])\r\n# pub = array([Ks, 0.45, 0.082, 3.8, 2])\r\nplb = array([Ks, Theta_s, Theta_r, Alpha, N])\r\npub = array([Ks, Theta_s, Theta_r, Alpha, N])\r\n# Time interval\r\ndt = 60.0 # second\r\n# timeSpan = 1444 # min # 19 hour\r\ntimeSpan = 2683 # minutes\r\ninterval = int(timeSpan*60/dt)\r\n\r\n# Reading experimental data from the file\r\nhe = zeros((timeSpan, 4)) # four sensors\r\ntheta_e = zeros((timeSpan, 4))\r\nwith open('exp_data_original.dat', 'r') as f:\r\n whole = f.readlines()\r\n for index, line in enumerate(whole):\r\n one_line = line.rstrip().split(\",\")\r\n one_line = one_line[1:5]\r\n h_temp = []\r\n theta_temp = []\r\n for index1, item in enumerate(one_line):\r\n item = float(item)\r\n theta_temp.append(item)\r\n temp1 = ((item/100 - Theta_r) / (Theta_s - Theta_r))\r\n temp2 = (temp1 ** (1. / (-(1. - (1. / N)))))\r\n temp3 = (temp2 - 1)\r\n temp4 = (temp3 ** (1. / N))\r\n item = temp4 / (-Alpha)\r\n h_temp.append(item)\r\n h_temp = array(h_temp, dtype='O')\r\n theta_temp = array(theta_temp, dtype='O')\r\n he[index] = h_temp\r\n theta_e[index] = theta_temp\r\n\r\n# Irrigation amount\r\nirr_amount = zeros((interval, 1))\r\nfor i in range(0, interval):\r\n if i in range(1152, 1217):\r\n irr_amount[i] = (0.004 / (pi * 0.22 * 0.22) / ((1216-1152) * 60))\r\n # irr_amount = 7.3999e-08\r\n else:\r\n irr_amount[i] = 0\r\n # irr_amount = 7.3999e-08\r\n\r\n# Create symbolic variables\r\nx = SX.sym('x', numberOfNodes, 1)\r\nu = SX.sym('u')\r\nk = SX.sym('k', len(p0), 1)\r\n# xe = SX.sym('xe', 4, 1) # 4 sensors\r\n\r\nprint(\"I am ready to create ODE\")\r\n# Create ODE and Objective functions\r\nf_x = getODE(x, u, k)\r\n# f_q = objective(x, k, xe)\r\nprint(\"I am done creating ODE\")\r\n# Create integrator\r\node = {'x': x, 'p': vertcat(u, k), 'ode': f_x}\r\nopts = {'tf': 60} # seconds\r\nI = integrator('I', 'cvodes', ode, opts) # Build casadi integrator\r\n\r\n# All parameter sets and irrigation amount\r\nU = irr_amount\r\nK = MX.sym('K', 5)\r\nXE = theta_e\r\n#K1 = p0\r\nprint(\"I am ready to create MX\")\r\n# Construct graph of integrator calls\r\nG = hMatrix # Initial state\r\nJ = 0 # Initial cost function\r\nfor i in range(interval):\r\n Ik = I(x0=G, p=vertcat(U[i], K)) # integrator with initial state G, and input U[k]\r\n J += objective(G, K, XE[i])\r\n G = Ik['xf'] # Assign the finial state to the initial state\r\nprint(\"I am doing creating MX\")\r\n# Allocate an NLP solver\r\nnlp = {'x': K, 'f': J, 'g': G} # x: Solve for P (parameters), which gives the lowest J (cost fcn), with the constraints G (propagated model)\r\n# opts = {\"ipopt.linear_solver\":\"ma97\"}\r\n# opts = {\"ipopt.linear_solver\": \"ma57\"}\r\nopts = {\"ipopt.linear_solver\": \"mumps\"}\r\nopts[\"ipopt.print_level\"] = 5\r\nopts[\"regularity_check\"] = True\r\nopts[\"verbose\"] = True\r\n\r\nprint(\"I am ready to build\")\r\nsolver = nlpsol(\"solver\", \"ipopt\", nlp, opts)\r\n\r\nprint(\"I am ready to solve\")\r\n\r\nsol = solver(# constraints are missing here\r\n lbx = plb,\r\n ubx = pub,\r\n x0=p0 # Initial guess of decision variable\r\n )\r\nprint (sol)\r\npe = sol['x'].full().squeeze()\r\nprint (\"\")\r\nprint (\"Estimated parameter(s) is(are): \" + str(pe))\r\nprint (\"\")\r\nprint (\"Actual value(s) is(are): \" + str(p0))\r\n\r\n\r\n#\r\n# timeList = []\r\n# for i in range(interval):\r\n# current_t = i*dt\r\n# timeList.append(current_t)\r\n# timeList = array(timeList, dtype='O')\r\n#\r\n#\r\n#\r\n\r\n#\r\n# obj_fun = int(input('Enter 1 for Theta-base objective function, or 2 for h-base: '))\r\n#\r\n# p0 = array([Ks, Theta_s, Theta_r, Alpha, N])\r\n# print('Initial SSE Objective: ' + str(objective(p0)))\r\n# bnds = ((1e-10, 1e-2), (0.302, 1.0), (0.0, 0.084), (-inf, inf), (0.8, inf))\r\n# solution = optimize.minimize(objective, p0, bounds=bnds)\r\n# p = solution.x\r\n# print('Final SSE Objective: ' + str(objective(p)))\r\n# Ks = p[0]\r\n# Theta_s = p[1]\r\n# Theta_r = p[2]\r\n# Alpha = p[3]\r\n# N = p[4]\r\n# print('Ks: ' + str(Ks))\r\n# print('Theta_s: ' + str(Theta_s))\r\n# print('Theta_r: ' + str(Theta_r))\r\n# print('Alpha: ' + str(Alpha))\r\n# print('N: ' + str(N))\r\n#\r\n# hi, theta_i = simulate(p0)\r\n# hp, theta_p = simulate(p)\r\n#\r\n# hi = ((((theta_i / 100 - p0[2]) / (p0[1] - p0[2])) ** (1. / (-(1 - 1 / p0[4]))) - 1) ** (1. / p0[4])) / (\r\n# -p0[3])\r\n# hp = ((((theta_p / 100 - p[2]) / (p[1] - p[2])) ** (1. / (-(1 - 1 / p[4]))) - 1) ** (1. / p[4])) / (\r\n# -p[3])\r\n# hp[0] = hIni[0]\r\n#\r\n# plt.figure(1)\r\n# # plt.subplot(4, 1, 1)\r\n# plt.plot(timeList/60.0, hi[:, 0], 'y--', label=r'$h_1$ initial')\r\n# plt.plot(timeList/60.0, he[:, 0], 'b:', label=r'$h_1$ measured')\r\n# plt.plot(timeList/60.0, hp[:, 0], 'r-', label=r'$h_1$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Pressure head (m)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(2)\r\n# # plt.subplot(4, 1, 2)\r\n# plt.plot(timeList/60.0, hi[:, 1], 'y--', label=r'$h_2$ initial')\r\n# plt.plot(timeList/60.0, he[:, 1], 'b:', label=r'$h_2$ measured')\r\n# plt.plot(timeList/60.0, hp[:, 1], 'r-', label=r'$h_2$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Pressure head (m)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(3)\r\n# # plt.subplot(4, 1, 3)\r\n# plt.plot(timeList/60.0, hi[:, 2], 'y--', label=r'$h_3$ initial')\r\n# plt.plot(timeList/60.0, he[:, 2], 'b:', label=r'$h_3$ measured')\r\n# plt.plot(timeList/60.0, hp[:, 2], 'r-', label=r'$h_3$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Pressure head (m)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(4)\r\n# # plt.subplot(4, 1, 4)\r\n# plt.plot(timeList/60.0, hi[:, 3], 'y--', label=r'$h_4$ initial')\r\n# plt.plot(timeList/60.0, he[:, 3], 'b:', label=r'$h_4$ measured')\r\n# plt.plot(timeList/60.0, hp[:, 3], 'r-', label=r'$h_4$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Pressure head (m)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(5)\r\n# # plt.subplot(4, 1, 1)\r\n# plt.plot(timeList/60.0, theta_i[:, 0], 'y--', label=r'$theta_1$ initial')\r\n# plt.plot(timeList/60.0, theta_e[:, 0], 'b:', label=r'$theta_1$ measured')\r\n# plt.plot(timeList/60.0, theta_p[:, 0], 'r-', label=r'$theta_1$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Water content (%)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(6)\r\n# # plt.subplot(4, 1, 2)\r\n# plt.plot(timeList/60.0, theta_i[:, 1], 'y--', label=r'$theta_2$ initial')\r\n# plt.plot(timeList/60.0, theta_e[:, 1], 'b-', label=r'$theta_2$ measured')\r\n# plt.plot(timeList/60.0, theta_p[:, 1], 'r-', label=r'$theta_2$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Water content (%)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(7)\r\n# # plt.subplot(4, 1, 3)\r\n# plt.plot(timeList/60.0, theta_i[:, 2], 'y--', label=r'$theta_3$ initial')\r\n# plt.plot(timeList/60.0, theta_e[:, 2], 'b:', label=r'$theta_3$ measured')\r\n# plt.plot(timeList/60.0, theta_p[:, 2], 'r-', label=r'$theta_3$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Water content (%)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# plt.figure(8)\r\n# # plt.subplot(4, 1, 4)\r\n# plt.plot(timeList/60.0, theta_i[:, 3], 'y--', label=r'$theta_4$ initial')\r\n# plt.plot(timeList/60.0, theta_e[:, 3], 'b:', label=r'$theta_4$ measured')\r\n# plt.plot(timeList/60.0, theta_p[:, 3], 'r-', label=r'$theta_4$ optimized')\r\n# plt.xlabel('Time (min)')\r\n# plt.ylabel('Water content (%)')\r\n# plt.legend(loc='best')\r\n# plt.show()\r\n#\r\n# print('Time elapsed: {:.3f} sec'.format(time.time() - start_time))\r\n#\r\n# # io.savemat('sim_results_1D_odeint.mat', dict(y_1D_odeint=theta_i))\r\n","sub_path":"Ubuntu_codes/parameter_estimation_minimize_garbage_bin/1_parameter_estimation_exp/central_FDM_explicit_para_est_casadi_1D_no_scale.py","file_name":"central_FDM_explicit_para_est_casadi_1D_no_scale.py","file_ext":"py","file_size_in_byte":15547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"339368023","text":"from openprocurement.api.utils import APIResource, json_view, upload_objects_documents\nfrom openprocurement.framework.core.utils import apply_patch\nfrom openprocurement.framework.core.validation import validate_milestone_data\nfrom openprocurement.framework.electroniccatalogue.utils import contractresource, MILESTONE_CONTRACT_STATUSES\nfrom openprocurement.framework.electroniccatalogue.validation import (\n validate_agreement_operation_not_in_allowed_status,\n validate_milestone_type,\n validate_contract_operation_not_in_allowed_status,\n validate_contract_banned,\n)\n\n\n@contractresource(\n name=\"electronicCatalogue:Agreements:Contracts:Milestones\",\n collection_path=\"/agreements/{agreement_id}/contracts/{contract_id}/milestones\",\n path=\"/agreements/{agreement_id}/contracts/{contract_id}/milestones/{milestone_id}\",\n agreementType=\"electronicCatalogue\",\n description=\"Agreement contract milestones resource\",\n)\nclass ContractMilestoneResource(APIResource):\n @json_view(permission=\"view_agreement\")\n def collection_get(self):\n contract = self.context\n return {\"data\": [milestone.serialize(\"view\") for milestone in contract.milestones]}\n\n @json_view(permission=\"view_agreement\")\n def get(self):\n return {\"data\": self.request.validated[\"milestone\"].serialize(\"view\")}\n\n @json_view(\n content_type=\"application/json\",\n validators=(\n validate_milestone_data,\n validate_agreement_operation_not_in_allowed_status,\n validate_contract_operation_not_in_allowed_status,\n validate_contract_banned,\n validate_milestone_type,\n ),\n permission=\"edit_agreement\"\n )\n def collection_post(self):\n milestone = self.request.validated[\"milestone\"]\n self.request.context.date = milestone.dateModified\n self.request.context.milestones.append(milestone)\n upload_objects_documents(\n self.request, milestone,\n route_kwargs={\"milestone_id\": milestone.id},\n )\n if apply_patch(\n self.request,\n obj_name=\"agreement\",\n data={\"status\": MILESTONE_CONTRACT_STATUSES[milestone.type]},\n src=self.request.validated[\"contract\"].to_primitive()\n ):\n self.request.response.status = 201\n return {\"data\": milestone.serialize(\"view\")}\n","sub_path":"src/openprocurement/framework/electroniccatalogue/views/milestone.py","file_name":"milestone.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205293161","text":"import requests\nimport logging\n\nfrom ..constants import REQUEST_URL\n\nlogger = logging.getLogger(\"api_worker\")\n\n\nclass Metrika:\n @staticmethod\n def request(oauth_token, ids, date1, date2, metrics, dimensions, filters='', group='', accuracy='full', sort=' '):\n \"\"\"\n Return answer from YMetrika API\n All params are APIs needed params which described\n - https://tech.yandex.ru/metrika/doc/api2/api_v1/data-docpage/\n :param oauth_token: str\n :param ids: str\n :param date1: str\n :param date2: str\n :param metrics: str\n :param dimensions: str\n :param filters: str\n :param group: str\n :param accuracy: str\n :param sort: str\n :return: requests.models.Response\n \"\"\"\n return requests.get(REQUEST_URL, params={\"ids\": ids,\n \"date1\": date1,\n \"date2\": date2,\n \"metrics\": metrics,\n \"dimensions\": dimensions,\n \"filters\": filters,\n \"group\": group,\n \"accuracy\": accuracy,\n \"sort\": sort,\n \"oauth_token\": oauth_token\n })\n","sub_path":"modules/api/metrika.py","file_name":"metrika.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"300869191","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\n\nuse_cuda = torch.cuda.is_available()\n\n\ndef data_loaders(batch_size):\n torch.manual_seed(1)\n\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip()])\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n trainset = datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n shuffle=True, **kwargs)\n sampleloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, **kwargs)\n testset = datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n shuffle=False, **kwargs)\n \n return trainloader, testloader, sampleloader\n","sub_path":"EVA5 S7/dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"382676448","text":"from django.contrib.sites.shortcuts import get_current_site\n\n\ndef get_full_url_for_context(path, context):\n scheme = (\n \"{}://\".format(context[\"request\"].scheme)\n if \"request\" in context\n else \"https://\"\n )\n\n return \"\".join(\n [scheme, get_current_site(context.get(\"request\", None)).domain, path]\n )\n","sub_path":"feder/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"530126427","text":"import sys\nfrom utils.Graph import Graph\n\ntry:\n path = str(sys.argv[1])\n graph = Graph(path)\n r, cycle = graph.eulerian()\n if r:\n print(1)\n print(*cycle, sep = \",\")\n else:\n print(0)\nexcept FileNotFoundError:\n print(\"Não achei esse arquivo\")\n","sub_path":"a1/item3.py","file_name":"item3.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"173886651","text":"#Code based on dials\n\nfrom __future__ import absolute_import, division\nfrom cctbx.array_family import flex\n\nimport iotbx.phil\n\nhelp_message = '''\n'''\n\n\nphil_scope = iotbx.phil.parse(\n'''\nspace_group = None\n .type = space_group\nmax_deviation = 5\n .type = float(value_min=0)\n .help = \"Maximum angular deviation from previous experiments orientation matrix (in degrees)\"\noutput {\n prefix = reindexed_experiments_\n .type = str\n}\n''')\n\n\ndef run(args):\n\n from dials.util.options import OptionParser\n from dials.util.options import flatten_experiments\n import libtbx.load_env\n\n usage = \"%s [options] experiments.json\" %libtbx.env.dispatcher_name\n\n parser = OptionParser(\n usage=usage,\n phil=phil_scope,\n read_experiments=True,\n check_format=False,\n epilog=help_message)\n\n params, options = parser.parse_args(show_diff_phil=True)\n experiments = flatten_experiments(params.input.experiments)\n if len(experiments) <= 1:\n parser.print_help()\n return\n\n from dials.algorithms.indexing.compare_orientation_matrices import \\\n difference_rotation_matrix_axis_angle\n crystals = []\n for experiment in experiments:\n crystal = experiment.crystal\n if params.space_group is not None:\n crystal.set_space_group(params.space_group.group())\n crystals.append(crystal)\n\n angles = flex.double()\n\n import math\n padding = int(math.ceil(math.log10(len(experiments))))\n output_template = '%s%%0%ii.json' %(params.output.prefix, padding)\n\n prev_expt = experiments[0]\n for i in range(1, len(experiments)):\n R_ij, axis, angle, cb_op = difference_rotation_matrix_axis_angle(\n prev_expt.crystal, experiments[i].crystal)\n angles.append(angle)\n #print i, angle\n if abs(angle) > params.max_deviation:\n continue\n experiments[i].crystal = experiments[i].crystal.change_basis(cb_op)\n prev_expt = experiments[i]\n\n from dxtbx.serialize import dump\n dump.experiment_list(experiments[i:i+1], output_template %i)\n \n from matplotlib import pyplot\n n, bins, patches = pyplot.hist(angles.as_numpy_array(), 100)\n pyplot.show()\n\nif __name__ == '__main__':\n import sys\n run(sys.argv[1:])\n","sub_path":"pipeline/I24/indexing_stills/consistent_indexing.py","file_name":"consistent_indexing.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605185858","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\n\"\"\"\nZadanie 501\n\nModel w regresji liniowej to po prostu wektor wag, które \nbędą przemnażane przez wartości na wejściu, by po zsumowaniu dać wynik na wyjściu.\n\nW tym zadaniu napiszemy funkcję, która inicjalizuje wektor wag.\nOkazuje się, że można po prostu zainicjalizować zerami.\n\nA zatem napisz funkcję `init_weight_vector(nb_of_features)`, która\nzwraca wektor zer, jedna zero dla każdej cechy (feature). Liczba cech\njest podana jako argument (`nb_of_features`).\n\nCzym jest cecha (feature)? Cecha to dowolny parametr pozwalający\nodgadywać docelową wartość. Jeśli prognozujemy cenę mieszkania, możemy\nsię umówić, że pierwsza cecha reprezentuje liczbę pokoi, druga —\npowierzchnię, trzecia — piętro itd.\n\nPodpowiedź: najprościej użyć funkcji `append` w pętli (choć są\nbardziej idiomatyczne sposoby).\n\nNAME: init_weight_vector\nPARAMS: int\nRETURN: vector\nPOINTS: 2\n\"\"\"\n\nimport unittest\n\nfrom Task501 import init_weight_vector\n\nclass Task501Test(unittest.TestCase):\n \"\"\"Testy do zadania Task501.\"\"\"\n\n def test(self):\n \"\"\"Proste testy.\"\"\"\n\n self.assertEqual(init_weight_vector(3), [0.0, 0.0, 0.0])\n self.assertEqual(init_weight_vector(10),\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"regression/Task501Test.py","file_name":"Task501Test.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82209680","text":"# coding: utf8\n\nimport unittest\nimport Sofa\nimport numpy as np\nimport ad\nfrom ad import *\nimport SofaRuntime\n\nclass MyForceField(Sofa.ForceField):\n def __init__(self, *args, **kwargs):\n kwargs[\"ks\"] = kwargs.get(\"ks\", 1.0)\n kwargs[\"kd\"] = kwargs.get(\"kd\", 0.1)\n Sofa.ForceField.__init__(self, *args, **kwargs)\n \n def init(self):\n self.initpos = self.mstate.position.array().copy()\n self.k = np.zeros((1,1))\n self.f = []\n self.d = 0.5\n\n def addForce(self, m, out_force, pos, vel):\n ## Position are declared as autodiff numbers\n p = np.array([ adnumber(pos[i], i) for i in range(len(pos)) ])\n u = self.initpos-p\n res = np.array((u * self.ks))\n \n ## This is needed to compute the ad jacobian (in a really ugly way)\n self.res = np.ndarray.flatten(res)\n self.p = np.ndarray.flatten(p)\n \n np.set_printoptions({\"all\" : lambda x : str(x.x)+\"xx, d:\"+str(x.d())})\n print(\"s: \", res)\n \n # To me doing this is fundamentally ugly as we create a matrix full of zero. \n self.jacobian = jacobian(self.res, self.p) \n \n ## Needed to extract the 'number' part of the autodiff array \n def f(x):\n return x.x\n vf=np.vectorize(f)\n \n out_force += vf(res)\n \n\n def addDForce(self, df, dx, kFactor, bFactor):\n ## We multiply the big supersparse matrix by the flattened version of x\n tdf = self.jacobian @ (dx.reshape((-1)) * kFactor)\n df += tdf.reshape((-1,3))\n \n def addKToMatrix(self, a, b):\n print(\" NOT IMPLEMENTED a,b are non\" )\n\nclass CreateObject(object):\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\ndef RestShapeObject(impl, name=\"unnamed\", position=[]):\n node = Sofa.Node(name)\n c = node.addObject(\"MechanicalObject\", name=\"mechanical\", position=position)\n c.showObject = True\n c.drawMode = 1\n\n m = node.addObject(\"UniformMass\", name=\"mass\", vertexMass=0.1)\n \n if isinstance(impl, CreateObject): \n node.createObject(*impl.args, **impl.kwargs) \n else: \n d = node.addObject(impl)\n return node\n \ndef createScene(node):\n node.addObject(\"OglLineAxis\")\n node.addObject(\"RequiredPlugin\", name=\"SofaSparseSolver\")\n node.addObject(\"DefaultAnimationLoop\", name=\"loop\")\n node.addObject(\"EulerImplicit\")\n node.addObject(\"CGLinearSolver\", tolerance=1e-12, threshold=1e-12)\n \n a=node.addChild( RestShapeObject( MyForceField(\"customFF\", ks=5.0) , name=\"python\", position=[[i-7.5, 0, 0] for i in range(10)] ) )\n a.mechanical.showColor = [1.0,0.0,0.0,1.0]\n \n b=node.addChild( RestShapeObject( CreateObject(\"RestShapeSpringsForceField\", stiffness=5.0) , name=\"c++\", position=[[i-2.5, 0, 0] for i in range(10)]))\n b.mechanical.showColor = [1.0,1.0,0.0,1.0]\n\n######################################### TESTS ####################################################\n## In the following is the code used to consider this example as a test.\n####################################################################################################\nclass Test(unittest.TestCase):\n def test_example(self):\n createScene(Sofa.Node(\"root\"))\n\ndef getTestsName():\n suite = unittest.TestLoader().loadTestsFromTestCase(Test)\n return [ test.id().split(\".\")[2] for test in suite]\n\ndef runTests():\n import sys\n suite = None\n if( len(sys.argv) == 1 ):\n suite = unittest.TestLoader().loadTestsFromTestCase(Test)\n else:\n suite = unittest.TestSuite()\n suite.addTest(Test(sys.argv[1]))\n return unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful()\n","sub_path":"bindings/Sofa/tests/Core/AutoDiffForceField.py","file_name":"AutoDiffForceField.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"38441080","text":"adjective0 = input(\"type adjective\")\nnoun0 = input(\"type noun\")\n\nprint(\"Safty Rules %s %s\" % (adjective0, noun0))\n\nadjective1 = input(\"type in an adjective\")\nnoun1 = input(\"type a noun\")\n\nprint(\"First Do not jump on %s %s\" % (adjective1, noun1))\n\nadjective2 = input(\"type in an adjective\")\nnoun2 = input(\"type a noun\")\n\nnoun3 = input(\"type a noun\")\n\nprint(\"Third, %s %s is bad so don't touch it\" % (adjective3, noun3))\n\nadjective4 = input(\"type in an adjective\")\nnoun4 = input(\"type a noun\")\nprint(\"Next, eating %s pineapple %s is bad\" % (adjective2, noun2))\n\nadjective3 = input(\"type in an adjective\")\n\nprint(\"Fourth rule is %s %s so touch that because its good\" % (adjective4, noun4))\n\nadjective5 = input(\"type in an adjective\")\nnoun5 = input(\"type a noun\")\n\nprint(\"Fifth, eat %s ,running down %s street\" % (adjective5, noun5))\n\nadjective6 = input(\"type in an adjective\")\nnoun6 = input(\"type a noun\")\n\nprint(\"lastly have %s dragon and %s at all times\" % (adjective6, noun6))\n\nprint (\"thank you\")","sub_path":"notes/Brad Yang - Mad Lib.py","file_name":"Brad Yang - Mad Lib.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168436350","text":"# Copyright (c) 2017, Mayo Clinic\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, this\n# list of conditions and the following disclaimer.\n#\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#\n# Neither the name of the Mayo Clinic 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\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport unittest\n\nimport os\nfrom _csv import QUOTE_NONE\nfrom csv import DictReader\nfrom typing import Dict\n\nfrom i2fhirb2.loadfacts import load_facts\nfrom tests.utils.base_test_case import test_data_directory, test_conf_directory, make_and_clear_directory\n\n\nclass ObservationComponentTestCase(unittest.TestCase):\n dirname, _ = os.path.split(os.path.abspath(__file__))\n output_dir = os.path.abspath(os.path.join(dirname, 'data_out', 'test_observation_component'))\n\n def setUp(self):\n make_and_clear_directory(self.output_dir)\n\n def tearDown(self):\n make_and_clear_directory(self.output_dir)\n\n def create_test_output(self, infilename: str):\n mv = os.path.abspath(os.path.join(test_data_directory, 'fhir_metadata_vocabulary'))\n conf = os.path.abspath(os.path.join(test_conf_directory, 'db_conf'))\n input_file = os.path.abspath(os.path.join(self.dirname, 'data', infilename))\n load_facts(\"-mv {} --conf {} -i {} -t rdf -od {}\".format(mv, conf, input_file, self.output_dir).split())\n\n def test_boyle(self):\n self.create_test_output('Boyle963_Kathleen891_83.ttl')\n with open(os.path.join(self.output_dir, 'observation_fact.tsv')) as output_tsv_file:\n rslt = DictReader(output_tsv_file, delimiter=\"\\t\", quoting=QUOTE_NONE)\n sbp_idx = dbp_idx = sbp_res_idx = dbp_res_idx = 0\n for row in rslt:\n if row['tval_char'] == '8462-4':\n dbp_idx = row['instance_num']\n elif row['tval_char'] == '8480-6':\n sbp_idx = row['instance_num']\n elif row['nval_num'] == '116':\n dbp_res_idx = row['instance_num']\n elif row['nval_num'] == '172':\n sbp_res_idx = row['instance_num']\n self.assertTrue(sbp_idx == sbp_res_idx and dbp_idx == dbp_res_idx and sbp_idx != dbp_idx)\n\n def test_issue_6(self):\n self.create_test_output('Boyle963_Kathleen891_83.ttl')\n with open(os.path.join(self.output_dir, 'observation_fact.tsv')) as output_tsv_file:\n rslt = DictReader(output_tsv_file, delimiter=\"\\t\", quoting=QUOTE_NONE)\n inst_codes = {} # type: Dict[int, str]\n for row in rslt:\n # print('\\t'.join((row['instance_num'], row['concept_cd'], row['modifier_cd'],\n # row['tval_char'], row['nval_num'])))\n inst_num = int(row['instance_num'])\n if inst_num > 0:\n if inst_num in inst_codes:\n self.assertEqual(inst_codes[inst_num], row['concept_cd'])\n else:\n inst_codes[inst_num] = row['concept_cd']\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/issue_fixes/test_observation_component.py","file_name":"test_observation_component.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"281752993","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Atari Breakout DQN\nimport pdb\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport gym\nimport os\nimport datetime\nimport imageio\nimport numpy as np\nimport argparse\nimport pickle\nimport shutil\nfrom DQNAgent import DQN_Agent\n\n#========= parameter \nparser = argparse.ArgumentParser(description='Chang parameter for DQN')\nparser.add_argument('-ep', '--EPOCHS', type=int, default=2000, help=\"change epochs\")\nparser.add_argument('-e', '--EPSILON', type=float, default=0.3, help=\"change epsilon\")\nparser.add_argument('-ed', '--EPSILON_DC', type=float, default=0.9997, help=\"change epsilon decay\")\nparser.add_argument('-b', '--BATCH_SIZE', type=int, default=32, help=\"change batch size in train\")\nparser.add_argument('-m', '--MEMORY_SIZE', type=int, default=2000, help=\"change memorysize\")\nargs = parser.parse_args()\n\nEPOCHS = args.EPOCHS\nEPSILON = args.EPSILON\nEPSILON_DC = args.EPSILON_DC\nBATCH_SIZE = args.BATCH_SIZE\nMEMORY_SIZE = args.MEMORY_SIZE\n\n#============== initial\nenv_name = 'Breakout-v0'\nenv = gym.make(env_name)\n\nN_ACT = env.action_space.n\nN_OB = env.observation_space.shape\n\n#============= make dir path for log and figure\n\nROOT_DIR = \"../../gym_graph\"\nDIR = os.path.join(ROOT_DIR,datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))\nos.makedirs(DIR)\n\nlog_file = open(DIR+'/log_'+datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),'w')\n\nDIR_PNG = os.path.join(DIR,'temp')\n\n#================ env run\nagent = DQN_Agent(N_ACT,N_OB, MEMORY_SIZE = MEMORY_SIZE, \\\n BATCH_SIZE = BATCH_SIZE, EPSILON = EPSILON, EPSILON_DC = EPSILON_DC)\n\nreward_summary = {\n 'max':[],\n 'min':[],\n 'ave':[],\n 'sum':[]\n}\n\n\nfor ep in range(EPOCHS):\n \n ob = env.reset()\n \n agent.EPSILON = agent.EPSILON*agent.EPSILON_DC\n all_reward = []\n step = 0\n \n os.makedirs(DIR_PNG)\n while(1):\n # render monitoring \n plt.imsave(os.path.join(DIR_PNG,str(step)+'.png'),env.render(mode='rgb_array'))\n \n # take action\n act = agent.take_action(ob)\n \n # env step\n ob_next, reward, done, info = env.step(act)\n # reward modified\n # reward = reward if done else -1\n reward = 200 if reward else -1\n # memorize: sars(a) : [ob, act, reward, ob_next, done]\n agent.memorize([ob, act, reward, ob_next, done])\n \n # q-value update\n if len(agent.replay_memory) > (agent.MEMORY_SIZE/10):\n agent.train() \n if step % 50 == 0:\n #set_trace()\n agent.target_model_update()\n \n ob = ob_next\n all_reward.append(reward)\n step += 1\n \n if done:\n #set_trace()\n log_file.write(\"Epoch {} - average rewards {} with step {}\\n\".format(ep,sum(all_reward)/len(all_reward),step))\n print(\"Epoch {} - average rewards {} with step {}\".format(ep,sum(all_reward)/len(all_reward),step))\n reward_summary['max'].append(max(all_reward))\n reward_summary['min'].append(min(all_reward))\n reward_summary['sum'].append(sum(all_reward))\n reward_summary['ave'].append(sum(all_reward)/len(all_reward))\n break\n images = []\n for f in os.listdir(DIR_PNG):\n images.append(imageio.imread(os.path.join(DIR_PNG,f)))\n imageio.mimsave(os.path.join(DIR,str(ep)+'.gif'),images)\n shutil.rmtree(DIR_PNG)\n#=============== Show the reward every ep\nprint('Show the reward every ep')\nplt.figure()\nplt.plot(reward_summary['max'],label='max')\nplt.plot(reward_summary['min'],label='min')\nplt.plot(reward_summary['ave'],label='ave')\nplt.legend(loc=2)\nplt.savefig(DIR+'/rewards.png')\n#================== Store the model and reward\nprint('Store the model and reward')\n# In[ ]:\nwith open(DIR+'/rewards.pickle','wb') as f:\n pickle.dump(reward_summary,f)\n# agent.model.save('model'+datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))\n\n#=================== Test the final round\nprint('Test the final round')\n# observe the final run\nob = env.reset()\nall_reward = []\nstep = 0\nDIR_FINAL = os.path.join(DIR,'final')\nos.makedirs(DIR_FINAL)\nwhile(1):\n plt.imsave(os.path.join(DIR_FINAL,str(step)+'.png'),env.render(mode='rgb_array'))\n act = np.argmax(agent.get_q(ob))\n \n ob_next,reward,done,infor = env.step(act)\n \n all_reward.append(reward)\n step +=1\n ob = ob_next\n \n if done:\n log_file.write('Final: ave rewards - {}, step - {}\\n'.format(sum(all_reward)/len(all_reward),step))\n print('Final: ave rewards - {}, step - {}'.format(sum(all_reward)/len(all_reward),step))\n break\n \nimages = []\nfor f in os.listdir(DIR_FINAL):\n images.append(imageio.imread(os.path.join(DIR_FINAL,f)))\nimageio.mimsave(os.path.join(DIR,'final.gif'),images)\nshutil.rmtree(DIR_FINAL)\n \nlog_file.close()\nenv.close()\nprint(\"Done\")\n","sub_path":"tensorflow/DQN/dqn_failed/DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"239910909","text":"from uvtool import slider\nfrom PySide2.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QLabel\n\nclass TabUndervolt(QWidget):\n def __init__(self, tool):\n QWidget.__init__(self)\n\n self.tool = tool\n\n self.sliders = [slider.Slider(\n self.tool,\n text=name,\n tooltip=self.tool.find_offset_tooltip(name),\n precision=0.01,\n minimal=-200,\n maximal=0,\n interval=10) for i, (name, default) in self.tool.vars.offsets.items()]\n\n self.slider_grid = slider.SliderGrid(self.tool, self.sliders)\n \n for i in range(len(self.sliders)):\n self.slider_grid.layout().addWidget(QLabel(\"mV\"), i, 3) # wtf why layout()\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.slider_grid)\n\n self.setLayout(self.layout)","sub_path":"uvtool/tabs/undervolt.py","file_name":"undervolt.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"351483976","text":"\"\"\" Functions for backend rendering with MapD \"\"\"\n\nimport ast\nimport base64\nimport uuid\nimport yaml\n\nimport vdom\n\ntry:\n import altair as alt\nexcept ImportError:\n alt = None\n\nfrom IPython.core.magic import register_cell_magic\nfrom IPython.display import display\n\nclass MapDBackendRenderer:\n \"\"\"\n Class that produces a mimebundle that the notebook\n mapd renderer can understand.\n \"\"\"\n def __init__(self, connection, data=None, vl_data=None):\n \"\"\"\n Initialize the backend renderer. Either `data` or `vl_data`\n is required.\n\n Parameters\n =========\n\n connection: dict\n A dictionary containing the connection data for the mapd\n server. Must include 'user', 'password', 'host', 'port',\n 'dbname', and 'protocol'\n\n data: dict\n Vega data to render.\n \n data: dict\n Vega lite data to render.\n \"\"\"\n if (not (data or vl_data)) or (data and vl_data):\n raise RuntimeError('Either vega or vega lite data must be specified')\n self.connection = connection\n self.data = data\n self.vl_data = vl_data\n\n def _repr_mimebundle_(self, include=None, exclude=None):\n \"\"\"\n Return a mimebundle with 'application/vnd.mapd.vega+json'\n data, which is a custom mimetype for rendering mapd vega\n in Jupyter notebooks.\n \"\"\"\n bundle = {\n 'connection': self.connection\n }\n if self.data:\n bundle['vega'] = self.data\n else:\n bundle['vegalite'] = self.vl_data\n return {\n 'application/vnd.mapd.vega+json': bundle\n }\n\ndef render_vega(connection, vega):\n _widget_count = 1\n nonce = str(uuid.uuid1())\n result = connection._client.render_vega(\n connection._session,\n _widget_count,\n vega,\n 1,\n nonce)\n data = base64.b64encode(result.image).decode()\n return vdom.img([], src=f'data:image/png;base64,{data}')\n\n\n@register_cell_magic\ndef mapd(line, cell):\n \"\"\"\n Cell magic for rendering vega produced by the mapd backend.\n\n Usage: Initiate it with the line `%% mapd $connection_data`,\n where `connection_data` is the dictionary containing the connection\n data for the MapD server. The rest of the cell should be yaml-specified\n vega data.\n \"\"\"\n connection_data = ast.literal_eval(line)\n vega = yaml.load(cell)\n display(MapDBackendRenderer(connection_data, vega))\n\n@register_cell_magic\ndef mapd_vl(line, cell):\n \"\"\"\n Cell magic for rendering vega lite produced by the mapd backend.\n\n Usage: Initiate it with the line `%% mapd $connection_data`,\n where `connection_data` is the dictionary containing the connection\n data for the MapD server. The rest of the cell should be yaml-specified\n vega lite data.\n \"\"\"\n connection_data = ast.literal_eval(line)\n vl = yaml.load(cell)\n display(MapDBackendRenderer(connection_data, vl_data=vl))\n \ndef mapd_mimetype(spec, conn):\n \"\"\"\n Returns a mapd vega lite mimetype, assuming that the URL\n for the vega spec is actually the SQL query\n \"\"\"\n data = spec['data']\n data['sql'] = data.pop('url')\n return {'application/vnd.mapd.vega+json': {\n 'vegalite': spec,\n 'connection': {\n 'host': conn.host,\n 'protocol': conn.protocol,\n 'port': conn.port,\n 'user': conn.user,\n 'dbName': conn.db_name,\n 'password': conn.password\n }\n }}\n\nif alt:\n alt.renderers.register('mapd', mapd_mimetype)\n","sub_path":"mapd_renderer.py","file_name":"mapd_renderer.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121693723","text":"\"\"\"\nCaching/memoization decorators,\nImplement basic caching/memoization functionality; Useful when working with performance heavy methods/functions & recursions.\n\"\"\"\nfrom functools import wraps\nimport inspect\nimport weakref\n\n_simple_cache = {}\ndef simple_cache(f):\n\t\"\"\" \t\n\t@Decorator\n\tBarebone caching system - Caches function/method results for quicker access. Useful when working with performance heavy methods/functions.\n\tStores all functions after their names and uses repr(args/kwargs) to store the argument representation.\n\tWorks on:\n\tall\n\t_\n\tStores where?:\n\tExternally in the caching module\n\t\"\"\"\n\tglobal _simple_cache\n\t@wraps(f)\n\tdef newf(*_args, **_kwds): \t\n\t\tname = f.func_name\n\t\tcache = _simple_cache.setdefault(name, dict()) \n\t\tkey = hash(repr(_args)+repr(_kwds)) \n\t\tif key not in cache: \n\t\t cache[key] = f(*_args, **_kwds)\n\t\treturn cache[key]\n\treturn newf \n\n_custom_cache = {}\ndef custom_cache(a_group,a_skip_ref=0,a_custom_fname=0):\n\t\"\"\" \t\n\t@Decorator\n\tCustom function/method caching method that implements groups and ability to skip object refs (Usable if you're in a class and want all instances to share cache for example).\n\n\tATTRIBUTES:\n\ta_group: \tName of the cache group \n\ta_skip_ref: If set to 1 removes the first attribute of the function -> meant to remove self/cls in classes/objects.\n\t\n\tWorks on:\n\tall\n\t_\n\tStores where?:\n\tExternally in the caching module\n\t\"\"\"\n\tglobal _custom_cache\n\tdef dec(f):\n\t\t@wraps(f)\n\t\tdef newf(*_args, **_kwds):\n\t\t\tif a_custom_fname != 0:\n\t\t\t\tname = a_custom_fname\n\t\t\tif a_custom_fname == 0:\n\t\t\t\tname = f.func_name\n\t\t\t_custom_cache.setdefault(str(a_group), dict()) \n\t\t\tcache = _custom_cache[a_group].setdefault(name, dict()) \n\t\t\tif a_skip_ref:\n\t\t\t\tkey = hash(repr(_args[1:])+repr(_kwds))\n\t\t\telse:\n\t\t\t\tkey = hash(repr(_args)+repr(_kwds)) \n\t\t\tif key not in cache: \n\t\t\t\tcache[key] = f(*_args, **_kwds) \n\t\t\treturn cache[key]\n\t\treturn newf\n\treturn dec\n\n_file_cache = {}\ndef file_cache(f):\n\t\"\"\" \t\n\t@Decorator\n\tSame as mod_cache, except the cache is stored externally in the caching module and the \"namespacing\" is dependent on the \n\tfile the function/method is defined in (instead of module) [this can be useful when using merged modules etc]\n\t\"\"\"\n\tglobal _file_cache\n\t@wraps(f) \n\tdef newf(*_args, **_kwds): \n\t\t_file = inspect.getmodule(f).__file__ \n\t\tname = f.func_name\n\t\t_file_cache.setdefault(str(_file), dict()) \n\t\tcache = _file_cache[str(_file)].setdefault(name, dict()) \n\t\tkey = hash(repr(_args)+repr(_kwds)) \n\t\tif key not in cache: \n\t\t cache[key] = f(*_args, **_kwds) \n\t\treturn cache[key]\n\treturn newf \n\ndef mod_cache(f):\n\t\"\"\" \t\n\t@Decorator\n\tCaches function/method results for quicker access. Useful when working with performance heavy methods/functions.\n\tWorks on: \n\tAll methods/functions, although, should only be used on independent module functions. Use other decorators for classes/objects etc.\n\t-\n\tStores where?:\n\tStores cache in current module -> instanced classes with same names WILL NOT share cache (except @staticmethod/@classmethod).\n\t__dict__[\"_mod_cache\"]\n\t\"\"\"\n\t@wraps(f) \n\tdef newf(*_args, **_kwds): \n\t mod = inspect.getmodule(f)\n\t name = f.func_name \n\t mod.__dict__.setdefault(\"_mod_cache\", dict()) \n\t cache = mod.__dict__[\"_mod_cache\"].setdefault(name, dict()) \n\t key = hash(repr(_args)+ repr(_kwds)) \n\t if key not in cache: \n\t cache[key] = f(*_args, **_kwds)\n\t return cache[key] \n\treturn newf \n\ndef obj_cache(f):\n\t\"\"\"\n\t@Decorator\n\tCaches function/method results for quicker access. Useful when working with performance heavy methods/functions.\n\tWorks on: \n\tinstance methods only.\n\t-\n\tStores where?:\n\tStores cache in current instance of object -> Objects do not share cache.\n\t__dict__[\"_obj_cache\"]\n\t\"\"\" \n\t@wraps(f) \n\tdef newf(*_args, **_kwds): \n\t self = _args[0] \n\t name = f.func_name \n\t self.__dict__.setdefault(\"_obj_cache\", dict()) \n\t cache = self.__dict__[\"_obj_cache\"].setdefault(name, dict()) \n\t key = hash(repr(_args[1:])+repr(_kwds)) \n\t if key not in cache: \n\t cache[key] = f(*_args, **_kwds) \n\t return cache[key] \n\treturn newf \n\ndef cls_cache(f):\n\t\"\"\"\n\t@Decorator\n\tCaches function/method results for quicker access. Useful when working with performance heavy methods/functions.\n\tWorks on: \n\tinstance methods and class methods(@classmethod).\n\t-\n\tStores where?:\n\tStores cache in class(satic variable) -> multiple instances can share cache.\n\t__dict__[\"_cls_cache\"]\n\t\"\"\"\n\t@wraps(f) \n\tdef newf(*_args, **_kwds):\n\t\tif inspect.isclass(_args[0]): \n\t\t\tcls = _args[0]\n\t\telse:\n\t\t\tcls = _args[0].__class__\n\t\tname = f.func_name \n\t\ttry:\n\t\t\tcls._cls_cache\n\t\texcept:\n\t\t\tcls._cls_cache = dict()\n\t\tcache = cls._cls_cache.setdefault(name, dict()) \n\t\tkey = hash(repr(_args[1:])+repr(_kwds)) \n\t\tif key not in cache: \n\t\t cache[key] = f(*_args, **_kwds) \n\t\treturn cache[key] \n\treturn newf \n\n\n\n##\n# Cache Get/Set functions etc.\n##\n#_simple_cache\ndef getSimpleCache():\n\treturn _simple_cache\ndef setSimpleCache(a):\n\tglobal _simple_cache\n\t_simple_cache = a\n#_file_cache\ndef getFileCache():\n\treturn _file_cache\ndef setFileCache(a):\n\tglobal _file_cache\n\t_file_cache = a\n#_custom_cache\ndef getCustomCache():\n\treturn _custom_cache\ndef setCustomCache(a):\n\tglobal _custom_cache\n\t_custom_cache = a\ndef clearCustomCacheGroup(a_group):\n\tglobal _custom_cache\n\ttry:\n\t\tdel _custom_cache[a_group]\n\texcept:\n\t\tpass\ndef getCustomCacheGroup(a_group):\n\ttry:\n\t\treturn _custom_cache[a_group]\n\texcept:\n\t\tpass\n\n#simple flush\ndef clearAll():\n\t_custom_cache = {}\n\t_simple_cache = {}\n\t_file_cache = {}\n\n","sub_path":"engine/core/utils/mipy/caching/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579791463","text":"import os\nimport boto3\n\nAMI = os.environ['AMI']\nINSTANCE_TYPE = os.environ['INSTANCE_TYPE']\nKEY_NAME = os.environ['KEY_NAME']\nSUBNET_ID = os.environ['SUBNET_ID']\nTAG_SPEC = [\n {\n \"ResourceType\":\"instance\",\n \"Tags\": [\n {\n \"Key\": \"Flag\",\n \"Value\": \"Easyun\"\n }\n ]\n }\n ]\n\nec2 = boto3.resource('ec2')\n \ninstance = ec2.create_instance(\n ImageID=AMI,\n InstanceType=INSTANCE_TYPE,\n KeyName=KEY_NAME,\n SubnetID=SUBNET_ID,\n TagSpecifications = TAG_SPEC,\n MaxCount=1,\n MinCount=1\n )\n \nprint(\"New instance created:\", instance[0].id)","sub_path":"api-test/create_ec2.py","file_name":"create_ec2.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"109585750","text":"import json\nfrom check_mulsubcol import check_multiple_subcolumns\nfrom mark_mulsubcol import mark_subcolumns\nfrom use_noteid import calc_order\n\n# A 是否包含在B当中\ndef is_contained_in(A,B):\n threshold = 20\n if A['x']-B['x']>=-threshold:\n if A['x']+A['w']-B['x']-B['w']<=threshold:\n if A['y']-B['y']>=-threshold:\n if A['y']+A['h']-B['y']-B['h']<=threshold:\n return True\n return False\n\n\n\n\n# main 函数\n#########################################################################\nif __name__ == '__main__':\n # 文件路径\n filename = \"data/JX_165_7_12\"\n # 加载字框数据\n with open(filename+\".json\", 'r', encoding='UTF-8') as load_f:\n data_dict = json.load(load_f)\n coordinate_char_list = data_dict['chars']\n # 加载栏框和列框数据\n with open(filename + \"_column\" + \".json\", 'r') as load_f:\n data_dict = json.load(load_f)\n coordinate_block_list = data_dict['blocks']\n coordinate_column_list = data_dict['columns']\n#########################################################################\n # 定义新的字框数据结构\n char_list = []\n for i in range(0, len(coordinate_char_list)):\n char_list.append({'block_id': 0, 'column_id': 0, 'ch_id': 0, 'subcolumn_id': 0, 'note_id': 0, 'column_order':0})\n\n # 标记栏框和列框\n for i in range(0, len(coordinate_char_list)):\n for i_b in range(0, len(coordinate_block_list)):\n if is_contained_in(coordinate_char_list[i], coordinate_block_list[i_b]):\n char_list[i]['block_id'] = i_b+1\n for i_c in range(0, len(coordinate_column_list)):\n if is_contained_in(coordinate_char_list[i], coordinate_column_list[i_c]):\n char_list[i]['column_id'] = i_c+1\n##########################################################################\n # 逐列处理\n for i_b in range(0, len(coordinate_block_list)):\n for i_c in range(0, len(coordinate_column_list)):\n # 统计列内字框的索引\n char_indices_in_column = []\n for i in range(0, len(coordinate_char_list)):\n if char_list[i]['column_id'] == i_c+1 and char_list[i]['block_id']==i_b+1:\n char_indices_in_column.append(i)\n # 按高度重新排序\n idx_sorted = sorted(range(len(char_indices_in_column)),\n key=lambda k: coordinate_char_list[char_indices_in_column[k]]['y'])\n sorted_char_indices = []\n for i in range(0, len(char_indices_in_column)):\n sorted_char_indices.append(char_indices_in_column[idx_sorted[i]])\n\n # 判断是否存在夹注小字\n flag_multiple_subcolumns = check_multiple_subcolumns(coordinate_char_list, sorted_char_indices)\n # 按高度排序,标记大字\n if flag_multiple_subcolumns == 0:\n order = 1\n for i in sorted_char_indices:\n char_list[i]['ch_id'] = order\n char_list[i]['column_order'] = order\n order = order + 1\n else:\n # 标记夹注小字\n mark_subcolumns(coordinate_char_list, char_list, sorted_char_indices)\n calc_order(char_list, sorted_char_indices)\n # 保存数据\n py2json = {}\n py2json['char_list'] = char_list\n json_str = json.dumps(py2json)\n #print(char_list)\n #print(json_str)\n\n\n\n","sub_path":"controller/layout_demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"639707982","text":"from distutils.core import setup\n# Use \"Extension\" from Cython.Distutils so that \"cython_directives\" works.\n# from distutils.extension import Extension\nfrom Cython.Distutils import build_ext, Extension\nimport sys\nimport platform\nfrom Cython.Compiler import Options\n\n# Stop on first error, otherwise hundreds of errors appear in the console.\nOptions.fast_fail = True\n\n# Written to cython_includes/compile_time_constants.pxi\nCEF_VERSION = 1\n\n\"\"\"\nBuilding libcef_dll_wrapper\n---------------------------\n\nlibcef_dll_wrapper needs to be compiled with /MD, otherwise you get linker errors\nof type \"already defined\". When you try to compile using /MD you may get warnings:\n\n warning C4275: non dll-interface class 'stdext::exception' used as base for\n dll-interface class 'std::bad_typeid' see declaration of 'stdext::exception'\n see declaration of 'std::bad_typeid'\n\nWhich results in build errors. To solve it you need to add command line option:\n\n -D_HAS_EXCEPTIONS=1\n\nEnabling C++ exceptions (\"/EHsc\") is not required.\n\"\"\"\n\n# Python version string: \"27\" or \"32\".\nPYTHON_VERSION = str(sys.version_info.major) + str(sys.version_info.minor)\n\ndef CompileTimeConstants():\n\n print(\"Generating: cython_includes/compile_time_constants.pxi\")\n with open(\"./../../../cython_includes/compile_time_constants.pxi\", \"w\") as fd:\n fd.write('# This file was generated by setup.py\\n')\n # A way around Python 3.2 bug: UNAME_SYSNAME is not set.\n fd.write('DEF UNAME_SYSNAME = \"%s\"\\n' % platform.uname()[0])\n fd.write('DEF CEF_VERSION = %s\\n' % CEF_VERSION)\n fd.write('DEF PY_MAJOR_VERSION = %s\\n' % sys.version_info.major)\n\nCompileTimeConstants()\n\next_modules = [Extension(\n\n \"cefpython_py%s\" % PYTHON_VERSION,\n [\"cefpython.pyx\"],\n\n # Ignore the warning in the console:\n # > C:\\Python27\\lib\\distutils\\extension.py:133: UserWarning: \n # > Unknown Extension options: 'cython_directives' warnings.warn(msg)\n cython_directives={\n # Any conversion to unicode must be explicit using .decode().\n \"c_string_type\": \"bytes\",\n \"c_string_encoding\": \"utf8\",\n },\n\n language='c++',\n\n include_dirs=[\n r'./../',\n r'./../../',\n r'./../../../',\n r'./../../../cython_includes/',\n ],\n\n library_dirs=[\n r'./',\n r\"c:/Program Files (x86)/Windows Kits/8.0/Lib/win8/um/x86/\",\n r'./../../http_authentication/Release/',\n r'./../../v8function_handler/Release_py%s/' % PYTHON_VERSION,\n r'./../../client_handler/Release_py%s/' % PYTHON_VERSION,\n r'./../../../cpp_utils/Release/cpp_utils.lib',\n ],\n\n libraries=[\n 'libcef',\n 'libcef_dll_wrapper',\n 'User32',\n 'Gdi32',\n 'http_authentication', # Build with /MD.\n 'v8function_handler_py%s' % PYTHON_VERSION, # Build with /MD.\n 'client_handler_py%s' % PYTHON_VERSION # Build with /MD.\n ],\n\n # /EHsc - using STL string, multimap and others that use C++ exceptions.\n extra_compile_args=['/EHsc'],\n\n # '/ignore:4217' - silence warnings: \"locally defined symbol _V8FunctionHandler_Execute\n # imported in function \"public: virtual bool __thiscall V8FunctionHandler::Execute\".\n # client_handler or other vcprojects include setup/cefpython.h,\n # this is a list of functions with \"public\" statement that is\n # accessible from c++.\n extra_link_args=['/ignore:4217'],\n\n # Defining macros:\n # define_macros = [(\"UNICODE\",\"1\"), (\"_UNICODE\",\"1\"), ]\n)]\n\nsetup(\n name = 'cefpython_py%s' % PYTHON_VERSION,\n cmdclass = {'build_ext': build_ext},\n ext_modules = ext_modules\n)\n","sub_path":"cefpython/cef1/windows/setup/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"65938061","text":"import transaction\nimport feedparser\nimport dateutil.parser\nfrom redis import ConnectionError\n\nfrom oe_daemonutils.circuit import DaemonCircuitBreaker\nfrom oe_daemonutils.dossierservice import MasterdataNotFoundException\n\n\nclass EntryProcessor(object):\n def __init__(self, settings, logger, retrieve_system_token_command, service_cls):\n self.settings = settings\n self.logger = logger\n self.retrieve_system_token_command = retrieve_system_token_command\n self.process_uri = self._process_uri_list(settings.get('daemon.process.uri'))\n self.service_cls = service_cls\n\n @staticmethod\n def _process_uri_list(daemon_process_uri):\n if daemon_process_uri is not None:\n return daemon_process_uri.split()\n else:\n return []\n\n def process_entries(self, entries, last_entry_ts, daemon_manager):\n \"\"\"\n Process the given entries and adapt the latest processed entry id\n\n :param entries: current feed entries to process\n :param last_entry_ts: the latest entry timestamp\n :param daemon_manager: data manager for the current daemon\n \"\"\"\n service = self.service_cls(self.settings, self.logger, self.retrieve_system_token_command.execute())\n notifications_dict = {}\n\n for entry in entries:\n current_entry_ts = entry.updated\n process_uri = next(\n (link['href'] for link in entry.links if link['rel'] == 'related' and link['title'] == 'proces'), None)\n if not process_uri:\n self.logger.error('Entry {0} has no process!'.format(entry.id))\n else:\n self._process_entry(entry, service, notifications_dict)\n current = last_entry_ts\n last_entry_ts = current_entry_ts if current_entry_ts is not None else last_entry_ts\n with transaction.manager as manager:\n daemon_manager.update_last_entry_id(current=current, last=last_entry_ts)\n manager.commit()\n\n return notifications_dict\n\n def _process_entry(self, entry, service, notifications_dict):\n \"\"\"\n Common method to create a dossier from an entry\n Keep track of the entry to notify the persons concerned\n\n :param entry: entry to process\n :param service: service to use for processing\n :param notifications_dict: notifications_dict\n \"\"\"\n self.logger.info('Processing entry {0}'.format(entry.id))\n print('Processing entry {0}'.format(entry.id))\n try:\n entry_process_uri = next(\n (link['href'] for link in entry.links if link['rel'] == 'related' and link['title'] == 'proces'), None)\n self.logger.info('Entry Process URI {0}'.format(entry_process_uri))\n if entry_process_uri in self.process_uri:\n service.create_dossier(entry, notifications_dict)\n except MasterdataNotFoundException as e:\n self.logger.warn(e.__str__())\n\n\nclass FeedProcessor(object):\n def __init__(self, logger, feed_endpoint, failure_threshold, timeout_default, max_timeout, invocation_timeout,\n retrieve_system_token_command):\n self.logger = logger\n self.feed_endpoint = feed_endpoint\n self.failure_threshold = failure_threshold\n self.timeout_default = timeout_default\n self.max_timeout = max_timeout\n self.invocation_timeout = invocation_timeout\n self.retrieve_system_token_command = retrieve_system_token_command\n\n def _parse_feed(self, feed_endpoint):\n \"\"\"\n Parse the feed given the feed endpoint\n\n :rtype : Feed object\n \"\"\"\n\n feed = feedparser.parse(feed_endpoint,\n request_headers={'OpenAmSSOID': self.retrieve_system_token_command.execute(),\n 'Accept': 'application/atom+xml'})\n summary = feed.feed.summary if 'summary' in feed.feed else ''\n if not hasattr(feed, 'status'):\n ex = feed.get('bozo_exception', {})\n self.logger.error('Unknown Error for url: ')\n self.logger.error(feed_endpoint)\n self.logger.error(\"{0} {1}\".format(ex.__class__.__name__, repr(ex)))\n raise IOError('Unknown Error for url: {0}'.format(feed_endpoint), ex)\n elif 400 <= feed.status < 500:\n self.logger.error(feed.status)\n self.logger.error('Client Error for url: ')\n self.logger.error(feed_endpoint)\n self.logger.error(summary)\n raise IOError('Client Error for url: {0}'.format(feed_endpoint))\n elif 500 <= feed.status < 600:\n self.logger.error(feed.status)\n self.logger.error('Server Error for url: ')\n self.logger.error(feed_endpoint)\n self.logger.error(summary)\n raise IOError('Server Error for url: {0}'.format(feed_endpoint))\n else:\n return feed\n\n def _process_previous_feed(self, feed, last_entry_ts):\n \"\"\"\n Check if the entries of the previous feed must be processed\n\n :param feed: current feed\n :param last_entry_ts: last processed entry id\n :return:\n \"\"\"\n entries = []\n if hasattr(feed.feed, 'links'):\n previous_endpoint = next((link['href'] for link in feed.feed.links if link['rel'] == 'prev-archive'), None)\n if previous_endpoint:\n circuit = DaemonCircuitBreaker(self._parse_feed, self.logger, (IOError, ValueError),\n failure_threshold=self.failure_threshold,\n timeout_default=self.timeout_default,\n max_timeout=self.max_timeout,\n invocation_timeout=self.invocation_timeout)\n previous_feed = circuit.call(previous_endpoint)\n entries = self._process_feed_entries(previous_feed, last_entry_ts)\n return entries\n\n def _process_feed_entries(self, feed, last_entry_ts):\n \"\"\"\n Get the entries of the current that are not yet processed\n\n :param feed: current feed\n :param last_entry_ts: last processed entry id\n :return:\n \"\"\"\n entries = []\n first_ts = self.date_from_string(feed.entries[0].updated) if len(feed.entries) > 0 else None\n if first_ts is None:\n entries.extend(self._process_previous_feed(feed, last_entry_ts))\n elif first_ts and last_entry_ts is None:\n previous_endpoint = next((link['href'] for link in feed.feed.links if link['rel'] == 'prev-archive'), None)\n if previous_endpoint:\n entries.extend(self._process_previous_feed(feed, last_entry_ts))\n entries.extend(feed.entries)\n else:\n entries = feed.entries\n elif first_ts and first_ts <= last_entry_ts:\n entries = [entry for entry in feed.entries if self.date_from_string(entry.updated) > last_entry_ts]\n elif first_ts and first_ts > last_entry_ts:\n entries.extend(self._process_previous_feed(feed, last_entry_ts))\n entries.extend(feed.entries)\n return entries\n\n def process_feed(self, last_entry_ts_datetime):\n \"\"\"\n process the feed and return the entries\n \n :param last_entry_ts_datetime: last entry timestamp in datetime format\n :return: entries_to_process: list of entries to process\n \"\"\"\n entries_to_process = []\n\n circuit = DaemonCircuitBreaker(self._parse_feed, self.logger, (IOError, ValueError, ConnectionError),\n failure_threshold=self.failure_threshold,\n timeout_default=self.timeout_default,\n max_timeout=self.max_timeout,\n invocation_timeout=self.invocation_timeout)\n feed = circuit.call(self.feed_endpoint)\n\n if feed:\n entries_to_process = self._process_feed_entries(feed, last_entry_ts_datetime)\n\n self.logger.debug('found {0} entries to process'.format(len(entries_to_process)))\n return entries_to_process\n\n @staticmethod\n def date_from_string(s):\n d = dateutil.parser.parse(s) if s else None\n return d\n","sub_path":"oe_daemonutils/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":8412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560930674","text":"from flask import Flask, render_template, request, Blueprint\nfrom flask import current_app as app\nfrom flask import jsonify\nfrom flask_login import login_required\nimport json\nimport sys\nimport os, re\nimport logging\nfrom logging import Formatter, FileHandler\nimport os\nfrom werkzeug import secure_filename\nfrom application.utils.voice_processing import GSUtility as GS\nfrom pathlib import Path\nfrom application.utils import voice_main as vm\nfrom .models.users import mongodb, Users\nfrom .models.groups import db\nfrom application.utils import bot_operations as bo\nfrom .dao.groupdao import GroupDao\nfrom .dao.surveydao import SurveyDao\nfrom .dao.general_dao import GeneralDao\nimport traceback\nfrom kafka import KafkaConsumer, KafkaProducer\nimport time\nimport threading\nfrom multiprocessing import Process\nfrom loggers import *\n\nlogger = createLogger(__name__)\nmain_app = Blueprint('main_app', __name__,\n template_folder='templates',\n static_folder='static')\n\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(Formatter(\n '%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]'\n ))\n\nLIB=app.config['LIB']\nHOME=app.config['HOME']\nROOT=app.config['ROOT']\ngs = GS()\nconversation_historys = [];\ndao = GroupDao()\nsurveydao = SurveyDao()\ngendao = GeneralDao()\nuserList = gendao.getUsersList()\nGroups = []\n\nsend = 'from-bot'\nrecieve = 'onetoone'\nbootstrap = app.config['KAFKA_BOOTSTRAP']\n\n@main_app.route('/send', methods=['POST'])\n@login_required\ndef send():\n file = request.files['file']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n fnew = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n gs.convertToFlac(fnew)\n gs.combineAll()\n resp = {}\n resp[\"message\"] = \"success\"\n return jsonify(status=200, response=resp)\n\n@main_app.route('/train', methods=['POST'])\n@login_required\ndef trainbot():\n import importlib\n try:\n vm.train()\n importlib.reload(vm)\n resp = {}\n resp[\"message\"] = \"success\"\n return jsonify(status=200, response=resp)\n except:\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=200, response=resp)\n\n#load all the existing users \n@app.route('/loadAllUsers', methods=['POST'])\ndef loadAllUsers():\n try:\n users = dao.getAllUsers()\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = [json.loads(ob) for ob in users] \n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/loadAllGroups', methods=['POST'])\ndef loadAllGroups():\n try:\n groups = dao.loadAllGroups()\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = groups\n return jsonify(status=200, response=resp)\n except Exception :\n logger.error(\"Error \",exc_info=1)\n traceback.print_exc()\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/loadGroup/', methods=['POST'])\ndef loadGroup(groupId):\n try:\n data = dao.singleGroup(db, groupId)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n logger.error(\"Error \",exc_info=1)\n traceback.print_exc()\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/updateGroup/', methods=['POST'])\ndef updateGroup(groupId):\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n\n try:\n data = request.get_json()\n dao.updateGroups(group_id=groupId, data=data, db=db)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = None\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/createGroup', methods=['POST'])\ndef createGroup():\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n data = request.get_json()\n dao.createNewGroup(data, db)\n groupName = None\n for element in data:\n if 'groupName' in element:\n groupName = element.get('groupName')\n launchGroup(groupName)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/updateUser', methods=['POST'])\ndef updateUser():\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n data = request.get_json()\n dao.updateUser(user=data, db=db)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/sendInvitation', methods=['POST'])\ndef sendInvitationH():\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n data = request.get_json()\n dao.sendInvitation(data=data, db=db)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\ndef response(message):\n res = {}\n res['message'] = message\n return res\n\n@app.route(\"/group\", methods=['GET'])\n@login_required\ndef groups():\n return render_template('groups.html', title='reBot - Group')\n\n@app.route('/deleteGroup/', methods=['POST'])\ndef deleteGroup(groupId):\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n dao.deleteGroup(id=groupId, db=db)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = \"Group Deleted\"\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error. Cannot delete group.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/addNewuser', methods=['POST'])\ndef addFirstUser():\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n data = request.get_json()\n user = Users(name=data.get('user').get('name'), userId=data.get('user').get('userid'),messenger=data.get('user').get('messenger'))\n dao.addNewUser(user,mongodb)\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\n@app.route('/sendMessage', methods=['POST'])\ndef sendMessageH():\n if not request.content_type == 'application/json':\n resp = {}\n resp[\"message\"] = \"Invalid Content-Type\"\n resp[\"data\"] = None\n return jsonify(status=501, response=resp) \n try:\n data = request.get_json()\n userList = data.get('userList')\n textMessage = data.get('message')\n producer = KafkaProducer(bootstrap_servers=[bootstrap],\n value_serializer=lambda m: json.dumps(m).encode('ascii'))\n for USER in userList:\n message = {}\n message['chat_id'] = USER.get('userId')\n message['messageType'] = 'outgoing'\n message['text'] = textMessage\n message['userMessage'] = None\n producer.send(topic='from-bot', value=message)\n producer.flush()\n resp = {}\n resp[\"message\"] = \"success\"\n resp[\"data\"] = data\n return jsonify(status=200, response=resp)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n resp = {}\n resp[\"message\"] = \"Internal error.\"\n return jsonify(status=500, response=resp)\n\ndef conversations(userText,userId,userName):\n res = ''\n if((userText=='hello') or (userText =='hi') or (userText =='Hello') or (userText =='Hi')):\n if (gendao.checkUserExist(userId = userId, userList = userList)):\n res =\"Hi \"+userName+\", Welcome back. What can i do for you .\"\n else:\n userList[userId] = userName\n bo.addUserToDB(userName, 'Telegram',userId)\n res = userName+\" : \"+vm.main(userText)\n elif( (userText.lower()=='appointment') ):\n res = 'To book appointment Type : Appointment:book Timing:2019-12-08 03:15 PM Purpose:Your purpose'\n elif ('appointment:' in userText.lower()):\n res = bo.appointment(userText, userId, userName)\n message = {}\n message['msg'] = userText \n message['userName'] = userName \n message['userId'] = userId\n res['chat_id'] = userId\n res['messageType'] = 'outgoing'\n res['userMessage'] = message\n return res\n else:\n try:\n res = vm.main(userText)\n except Exception:\n traceback.print_exc()\n logger.error(\"Error \",exc_info=1)\n res = 'Sorry there is some internal error. I cannot answer this question at this time'\n botresponse = {}\n message = {}\n message['msg'] = userText \n message['userName'] = userName \n message['userId'] = userId\n botresponse['chat_id'] = userId\n botresponse['messageType'] = 'outgoing'\n botresponse['text'] = res\n botresponse['userMessage'] = message\n return botresponse\n\ndef get_bot_response(userMessage, prod):\n userText = userMessage.get('text')\n userName = userMessage.get('userName')\n userId = userMessage.get('userId')\n botText = conversations(userText,userId,userName)\n prod.send(topic='from-bot', value=botText)\n prod.flush()\n \n\n''' Must be called when new group is created '''\ndef launchGroup(GNAME):\n import sys\n from distutils.dir_util import copy_tree\n \n ''' Create a copy of slave bot inside root directory of Master bot'''\n botDirectory = ROOT+\"/botinstance\"\n instanceDirectory = ROOT+\"/bot/instances/\"+GNAME\n copy_tree(botDirectory, instanceDirectory)\n ''' Add python import path of new bot instance'''\n sys.path.insert(0, instanceDirectory)\n \n from botapp import BotInstance\n \n bot_instance = BotInstance(GNAME, bootstrap)\n port = bot_instance.get_free_tcp_port()\n p = Process(target=bot_instance.run,args=(port,)) \n p.name = GNAME\n p.start()\n Groups.append(p)\n return str(port)\n\ndef startNormalBot(prod, consumer):\n for message in consumer:\n get_bot_response(message.value, prod)\n time.sleep(1)\n\ndef initialize(recieve, bootstrap):\n consumer = KafkaConsumer(\n recieve, bootstrap_servers=[bootstrap],\n auto_offset_reset='latest',enable_auto_commit=True,\n group_id='single',\n value_deserializer=lambda m: json.loads(m.decode('ascii')))\n\n producer = KafkaProducer(bootstrap_servers=[bootstrap],\n value_serializer=lambda m: json.dumps(m).encode('ascii'))\n \n a = threading.Thread(target = startNormalBot, name=\"bot-thread\", daemon=True, args=(producer,consumer,))\n a.start()\n \ninitialize(recieve, bootstrap)","sub_path":"bot/application/mlapp - Copy.py","file_name":"mlapp - Copy.py","file_ext":"py","file_size_in_byte":11962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"67302541","text":"'''\nCreated on Feb 27, 2011\n\n@author: skretzig\n'''\nimport dateManagement\nfrom datetime import date\nimport calendar\nimport csv\n\ndef interestAmountWithTenor (notional, rate, tenor, yearBasis, basis):\n # Calculate the effective rate for each type of interest calculation\n # Simple basis uses simple interest calculation\n if str.upper(basis) == 'SIMPLE_BASIS':\n effectiveRate = rate * tenor / yearBasis\n # Annual basis uses annual compounding\n elif str.upper(basis) == 'ANNUAL_BASIS':\n effectiveRate = ((1 + rate) ** (tenor / yearBasis)) - 1\n # By default use SIMPLE BASIS\n else:\n effectiveRate = rate * tenor / yearBasis\n interest = round(notional * effectiveRate, 12)\n return interest\n\ndef interestAmount (notional, rate, startDate, endDate, dcc, bdcc, basis, firstDayIn, passedCalendar):\n endDate = dateManagement.nextBusinessDate(endDate, bdcc, passedCalendar)\n tenor = dateManagement.daysByDCC(startDate, endDate, dcc) + firstDayIn\n \n if str.upper(dcc) == 'ACT/ACT':\n interestAmount = interestAmountWithTenor(notional, rate, tenor, tenor, basis)\n elif str.upper(dcc) == 'ACT/365F':\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 365, basis)\n elif str.upper(dcc) == 'ACT/366':\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 366, basis)\n elif str.upper(dcc) == 'ACT/360':\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 360, basis)\n elif str.upper(dcc) == 'ACT/365':\n if not calendar.isleap(endDate.year):\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 365, basis)\n else:\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 366, basis)\n elif str.upper(dcc) == '30/360':\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 360, basis)\n else:\n interestAmount = interestAmountWithTenor(notional, rate, tenor, 365, basis)\n \n return interestAmount\n\ndef getCouponAmortization (couponNumber, amortizations):\n amortization = 0\n for coupon in amortizations:\n if coupon['couponNumber'] == couponNumber:\n amortization = coupon['amortization']\n \n return amortization\n\ndef getCouponCapitalization (couponNumber, capitalizations):\n capitalization = 0\n for coupon in capitalizations:\n if coupon['couponNumber'] == couponNumber:\n capitalization = coupon['capitalization']\n \n return capitalization\n\ndef interestAmountAssert (notional, rate, startDate, endDate, dcc, bdcc, basis, firstDayIn, calendar, resultingAmount, comment):\n testAmount = interestAmount(notional, rate, startDate, endDate, dcc, bdcc, basis, firstDayIn, calendar)\n \n if testAmount == resultingAmount:\n correct = 'OK'\n else:\n correct = 'FAILED'\n \n if firstDayIn == 1:\n FDI = 'considering first day in'\n else:\n FDI = 'not considering first day in'\n \n print('{0}: A notional of {1} between {2:%d-%m-%Y} and {3:%d-%m-%Y} with a rate of {4:.6%} and a DCC of {5} and a BDCC of {6} using the basis {7} and {8} should yield {9} and yields {10}. {11}'.format(correct, \\\n notional, startDate, endDate, rate, dcc, bdcc, basis, FDI, resultingAmount, testAmount, comment))\n \ndef testInterestAmount ():\n calendar = {date(2011,1,1),date(2011,12,25),date(2012,1,1),date(2012,12,25),date(2013,1,1),date(2013,12,25),date(2014,1,1),date(2014,12,25),date(2015,1,1),date(2015,12,25), \\\n date(2016,1,1),date(2016,12,25),date(2017,1,1),date(2017,12,25),date(2018,1,1),date(2018,12,25),date(2019,1,1),date(2019,12,25),date(2020,1,1),date(2020,12,25), \\\n date(2021,1,1),date(2021,12,25)}\n \n print('ACT/365 First Day Out')\n interestAmountAssert(100, 0.1, date(2010, 1, 1), date(2011, 1, 1), 'ACT/365', 'NONE', 'SIMPLE_BASIS', 0, calendar, 10, '')\n interestAmountAssert(100, 0.1, date(2010, 1, 1), date(2010, 7, 1), 'ACT/365', 'NONE', 'SIMPLE_BASIS', 0, calendar, 4.958904109589, '')\n print('--------------------------------------------------------------------')\n print('30/360 First Day Out')\n interestAmountAssert(100, 0.1, date(2010, 1, 1), date(2011, 1, 1), '30/360', 'NONE', 'SIMPLE_BASIS', 0, calendar, 10, '')\n print('--------------------------------------------------------------------')\n \n\n \nif __name__ == '__main__':\n #testInterestAmount()\n #testCalculateCouponData()\n pass","sub_path":"src/Library/interestCalculation.py","file_name":"interestCalculation.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"563799951","text":"import numpy as np\nfrom game_board import GameBoard, merge, justify_left, get_available_from_zeros\nfrom ai import Expectimax, MonteCarlo, get_smoothness\nfrom game_board import GameBoard\nfrom random import randint\nfrom timeit import default_timer as timer\nfrom time import sleep\nfrom collections import Counter\nfrom joblib import Parallel, delayed\nfrom sys import argv\n\n\nDELAY = 0\n\n# first calls for Numba to compile fast versions\ntemp = np.zeros((4, 4))\nmerge(temp)\njustify_left(temp, temp)\nget_available_from_zeros(temp)\nget_smoothness(temp)\nsleep(1)\n\nclass Batch:\n def __init__(self):\n # MEASURES\n self.total_moves_time = 0\n self.total_moves = 0\n self.fastest_move = -1\n self.longest_move = 0\n self.time_to_reach = []\n\n # setup game & ai\n self.board = GameBoard()\n self.ai = Expectimax()\n self.init_game()\n\n # run ai on game\n self.start = timer()\n self.run_game()\n end = timer()\n\n # MEASURES\n self.total_time = end - self.start # total time to run\n self.avg_move_time = self.total_moves_time / self.total_moves # moves done\n self.max_tile = self.board.get_max_tile() # max tile\n self.states_visited = self.ai.states_visited # states visited\n\n def init_game(self):\n self.insert_random_tile()\n self.insert_random_tile()\n\n def run_game(self):\n cur_max_tile = 8\n while True:\n move_start = timer()\n move = self.ai.get_move(self.board)\n move_end = timer()\n \n # save move time\n move_time = move_end - move_start\n self.total_moves_time += move_time\n self.total_moves += 1\n if self.fastest_move == -1 or move_time < self.fastest_move:\n self.fastest_move = move_time\n if move_time > self.longest_move:\n self.longest_move = move_time\n\n # do the actual move + the response\n self.board.move(move)\n self.insert_random_tile()\n\n # check if we got a bigger tile\n if cur_max_tile in self.board.grid:\n reached_end = timer()\n self.time_to_reach.append((cur_max_tile, reached_end - self.start))\n cur_max_tile *= 2\n\n # if no more moves, game over\n if len(self.board.get_available_moves()) == 0:\n break\n\n def insert_random_tile(self):\n if randint(0,99) < 100 * 0.9:\n value = 2\n else:\n value = 4\n\n cells = self.board.get_available_cells()\n pos = cells[randint(0, len(cells) - 1)] if cells else None\n\n if pos is None:\n return None\n else:\n self.board.insert_tile(pos, value)\n return pos\n\ndef log_test(b):\n outputnum = argv[1]\n with open('output' + outputnum + '.log', 'a') as f:\n f.write('-----\\n')\n f.write('Max Tile: %d\\n' % b.max_tile)\n f.write('Total Moves: %d\\n' % b.total_moves)\n f.write('Total States Visited: %d\\n' % b.states_visited)\n f.write('Total Time: %f\\n' % b.total_time)\n f.write('Average Time / Move: %f\\n' % b.avg_move_time)\n f.write('Fastest Move: %f\\n' % b.fastest_move)\n f.write('Longest Move: %f\\n' % b.longest_move)\n f.write('Time To Get Tiles:\\n')\n for tile, time in b.time_to_reach:\n f.write('%d: %f\\n' % (tile, time))\n\ndef parallel_runs():\n return (Batch(),)\n\ndef run_parallel():\n jobs = 10\n tests = 10 / jobs\n return Parallel(n_jobs=jobs, verbose=0)(delayed(parallel_runs)() for i in range(int(tests)))\n\ndef main_parallel():\n open('output.log', 'w').close()\n open('average.log', 'w').close()\n\n b_total = run_parallel()\n print(b_total)\n\ndef main():\n outputnum = argv[1]\n open('output' + outputnum + '.log', 'w').close()\n open('average' + outputnum + '.log', 'w').close()\n tests = 0\n\n max_tile_list = []\n total_moves_sum = 0\n states_visited_sum = 0\n total_time_sum = 0\n avg_move_time_sum = 0\n fastest_move_sum = 0\n longest_move_sum = 0\n time_to_reach_sum = {}\n\n while tests < 10:\n b = Batch()\n \n max_tile_list.append(b.max_tile)\n total_moves_sum += b.total_moves\n states_visited_sum += b.states_visited\n total_time_sum += b.total_time\n avg_move_time_sum += b.avg_move_time\n fastest_move_sum += b.fastest_move\n longest_move_sum += b.longest_move\n for tile, time in b.time_to_reach:\n if tile not in time_to_reach_sum:\n time_to_reach_sum[tile] = (0,0)\n num = time_to_reach_sum[tile][0] + 1\n new_time = time_to_reach_sum[tile][1] + time\n time_to_reach_sum[tile] = (num, new_time)\n\n log_test(b)\n\n tests += 1\n\n avg_max_tile = Counter(max_tile_list).most_common(1)[0][0]\n\n with open('average' + outputnum + '.log', 'w') as f:\n f.write('Average Max Tile: %d\\n' % avg_max_tile)\n f.write('Average Total Moves: %f\\n' % (total_moves_sum / tests))\n f.write('Average Total States Visited: %f\\n' % (states_visited_sum / tests))\n f.write('Average Total Time: %f\\n' % (total_time_sum / tests))\n f.write('Average Time / Move: %f\\n' % (avg_move_time_sum / tests))\n f.write('Average Fastest Move: %f\\n' % (fastest_move_sum / tests))\n f.write('Average Longest Move: %f\\n' % (longest_move_sum / tests))\n f.write('Average Time To Get Tiles:\\n')\n for tile, value in time_to_reach_sum.items():\n num, time = value\n f.write('%d: %f\\n' % (tile, time / num))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main_batch.py","file_name":"main_batch.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"602854040","text":"import sdl2\nimport sdl2.ext\nfrom sdl2 import sdlmixer\n\n\ndef init_sdl():\n initialized = getattr(init_sdl, 'initialized', False)\n if initialized:\n return True\n\n sdl2.SDL_Init(0)\n sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_AUDIO)\n sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_JOYSTICK)\n sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b\"1\")\n\n result = sdlmixer.Mix_OpenAudio(sdlmixer.MIX_DEFAULT_FREQUENCY,\n sdlmixer.MIX_DEFAULT_FORMAT,\n 2, 1024) != -1\n if result:\n setattr(init_sdl, 'initialized', True)\n return result\n","sub_path":"soundboard/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"534300870","text":"import numpy as np\n\nfrom simulate import SimulateData\nfrom maxlike_hmm import MaxLikeHMM\nfrom bayesian_hmm import BayesianHMM\nfrom visualizer import plot, plot_mu, KDEplot\n\nclass CrossValidation:\n\n def __init__(self, bayesian=False, num_states = 6, num_training=1000, num_test=200):\n self.data = SimulateData()\n self.num_states = num_states\n self.bayesian = bayesian\n self.num_training = num_training\n self.num_test = num_test\n self.model = None # will either be a Bayesian or a MaxLike model\n\n\n def train(self, num_iter=10000, num_burnin=1000):\n \"\"\"\n\n :param num_training: size of the training set for cv\n :param num_test: size of the test set for cv\n :param num_iter: for BayesianHMM\n :param num_burnin: for BayesianHMM\n :return:\n \"\"\"\n\n obs, state_path = self.data.simulate_continuous(num_obs=self.num_training+self.num_test)\n\n\n KDEplot(obs)\n training_set = obs[:self.num_training]\n test_set = obs[-self.num_test:]\n training_state_path = state_path[:self.num_training]\n test_state_path = state_path[-self.num_test:]\n\n\n\n if self.bayesian:\n\n self.model = BayesianHMM(observations=training_set, state_path=training_state_path, num_states = self.num_states)\n self.model.generate_priors()\n\n self.model.sample_parameters(num_iter=num_iter, num_burnin=num_burnin)\n\n B = [[mu, np.sqrt(1/self.model.sigma_invsq)] for mu in self.model.mu]\n\n # use viterbi algo because Gibbs sampler not trained on test data\n path, _, _ = self.model.viterbi_robust(training_set, self.model.initial_dist, self.model.A, np.array(B))\n rate = np.sum(path == training_state_path)/len(training_state_path)\n\n plot(training_set, ylabel = \"Simulated Observations\", name = \"Bayes_Original_Observations\", bayesian=True)\n plot(training_state_path, ylabel = \"Simulated Hidden States\", name = \"Bayes_Original_States\",bayesian=True)\n plot(path, ylabel = \"Estimated Hidden States\", name = \"Bayes_Viterbi_Path\", bayesian=True)\n plot_mu(chain=self.model.chain, num_states=self.model.num_states, num_iter=num_iter)\n\n\n else:\n\n self.model = MaxLikeHMM(observations = training_set)\n tran_matrix, emis_matrix, initial = self.model.initial_parameters()\n\n sim_tran, sim_emis, sim_init = self.model.baum_welch_robust(tran_matrix, emis_matrix, initial)\n path, _, _ = self.model.viterbi_robust(training_set, sim_init, sim_tran, sim_emis)\n rate = np.sum(path == training_state_path)/len(training_state_path)\n\n self.sim_tran = sim_tran\n self.sim_emis = sim_emis\n self.sim_init = sim_init\n\n plot(path, ylabel = \"Estimated Hidden States\", name = \"Max_Viterbi_Path\",bayesian=False)\n\n\n return rate, state_path, test_set, test_state_path\n\n def test(self, state_path, test_set, test_state_path):\n\n if self.bayesian:\n\n B = [[mu, np.sqrt(1/self.model.sigma_invsq)] for mu in self.model.mu]\n\n # use viterbi algo because Gibbs sampler not trained on test data\n test_path, _, _ = self.model.viterbi_robust(test_set, self.model.initial_dist, self.model.A, np.array(B))\n rate = np.sum(test_path == state_path[-self.num_test:])/self.num_test\n\n\n plot(test_state_path, ylabel=\"Simulated Hidden States\", name=\"Bayes_Test_States\", bayesian=True)\n plot(test_path, ylabel=\"Estimated Hidden States\", name=\"Bayes_Viterbi_Test_Path\", bayesian=True)\n\n\n else:\n\n test_path, _, _ = self.model.viterbi_robust(test_set, self.sim_init, self.sim_tran, self.sim_emis)\n rate = np.sum(test_path == state_path[-self.num_test])/self.num_test\n\n plot(test_state_path, ylabel=\"Simulated Hidden States\", name=\"Max_Test_States\", bayesian=False)\n plot(test_path, ylabel=\"Estimated Hidden States\", name=\"Max_Viterbi_Test_Path\", bayesian=False)\n\n\n # print(\"Test Rate:\", rate)\n return rate\n\n\n","sub_path":"src/cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"414623761","text":"from scipy.sparse import identity\nfrom scipy.sparse import diags\nimport scipy.sparse as sparse\nimport numpy as np\nfrom numpy import square\nfrom numpy import trace\nfrom numpy import amax\nfrom math import sqrt\nimport math\nfrom utils.utils import log_filter, binary_filter\n\n\ndef InverseMatrix(A, args):\n '''\n use Fast Belief Propagatioin\n CITATION: Danai Koutra, Tai-You Ke, U. Kang, Duen Horng Chau, Hsing-Kuo\n Kenneth Pao, Christos Faloutsos\n Unifying Guilt-by-Association Approaches\n return [I+a*D-c*A]^-1\n '''\n try:\n log_transform = args['log_transform']\n except KeyError:\n log_transform = 0\n I = identity(A.shape[0]) # identity matirx\n D = diags(sum(A).toarray(), [0]) # diagonal degree matrix\n\n c1 = trace(D.toarray()) + 2\n c2 = trace(square(D).toarray()) - 1\n h_h = sqrt((-c1 + sqrt(c1 * c1 + 4 * c2)) / (8 * c2))\n\n a = 4 * h_h * h_h / (1 - 4 * h_h * h_h)\n c = 2 * h_h / (1 - 4 * h_h * h_h)\n\n # M=I-c*A+a*D\n # S=inv(M.toarray())\n '''\n compute the inverse of matrix [I+a*D-c*A]\n use the method propose in Unifying Guilt-by-Association equation 5\n '''\n M = c * A - a * D\n S = I\n mat = M\n power = 1\n while amax(M.toarray()) > 10 ** (-9) and power < 7:\n S = S + mat\n mat = mat * M\n power += 1\n if log_transform == 1:\n return {0: log_filter(sparse.csr_matrix(S))}\n else:\n return {0: S}\n\n\ndef belief_propgation(A, args, logger):\n '''\n use Fast Belief Propagatioin\n CITATION: Danai Koutra, Tai-You Ke, U. Kang, Duen Horng Chau, Hsing-Kuo\n Kenneth Pao, Christos Faloutsos\n Unifying Guilt-by-Association Approaches\n return [I+a*D-c*A]^-1\n '''\n try:\n transform = args[\"prox_params\"]['transform']\n threshold = args[\"prox_params\"]['threshold']\n scale1 = args[\"prox_params\"]['scale1']\n scale2 = args[\"prox_params\"]['scale2']\n except KeyError:\n transform = 0\n scale1 = 1\n scale2 = 1\n I = sparse.identity(A.shape[0]) # identity matirx\n D = sparse.diags(sum(A).toarray(), [0]) # diagonal degree matrix\n\n c1 = np.trace(D.toarray()) + 2\n c2 = np.trace(np.square(D).toarray()) - 1\n h_h = math.sqrt((-c1 + math.sqrt(c1 * c1 + 4 * c2)) / (8 * c2))\n\n a = scale1 * 4 * h_h * h_h / (1 - 4 * h_h * h_h)\n c = scale2 * 2 * h_h / (1 - 4 * h_h * h_h)\n\n # M=I-c*A+a*D\n # S=inv(M.toarray())\n '''\n compute the inverse of matrix [I+a*D-c*A]\n use the method propose in Unifying Guilt-by-Association equation 5\n '''\n M = c * A - a * D\n S = I\n mat = M\n power = 1\n while np.amax(M.toarray()) > 10 ** (-9) and power < 7:\n S = S + mat\n mat = mat * M\n power += 1\n if transform == 1:\n S = log_filter(S, threshold)\n elif transform == 2:\n S = binary_filter(S, logger, threshold)\n return {0: S}\n","sub_path":"src/proxi_methods/FaBP.py","file_name":"FaBP.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605374389","text":"import urllib2\nimport base64\nimport suds\nimport suds.transport\nfrom suds.client import Client\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger('suds.client').setLevel(logging.DEBUG)\nlogging.getLogger('suds.transport').setLevel(logging.DEBUG)\nlogging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)\nlogging.getLogger('suds.wsdl').setLevel(logging.DEBUG)\n\n\nclass HTTPSudsPreprocessor(urllib2.BaseHandler):\n\n def http_request(self, req):\n message = \\\n \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n # user = 'Universal API/uAPI5632685783-282e0d4d'\n # password = 'xS!7K6d%3?'\n # auth = base64.b64encode('Universal API/uAPI2514620686-0edbb8e4:D54HWfck9nRZNPbXmpzCGwc95')\n auth = base64.b64encode(b'Universal API/uAPI5632685783-282e0d4d:xS!7K6d%3?')\n print(auth.decode('utf-8'))\n req.add_header('Accept-Encoding', 'gzip,deflate')\n req.add_header('Content-Type', 'text/xml;charset=UTF-8')\n req.add_header('Cache-Control', 'no-cache')\n req.add_header('Pragma', 'no-cache')\n req.add_header('SOAPAction', \"http://localhost:8080/kestrel/AirService\")\n req.add_header('action', \"http://localhost:8080/kestrel/AirService\")\n # req.add_header('Authorization', 'Basic %s' % (auth.decode('utf-8')))\n req.add_header('Authorization', 'Basic VW5pdmVyc2FsIEFQSS91QVBJNTYzMjY4NTc4My0yODJlMGQ0ZDp4UyE3SzZkJTM/')\n return req\n\n https_request = http_request\n\n\nURL = \"https://americas.universal-api.travelport.com/B2BGateway/connect/uAPI/AirService\"\nhttps = suds.transport.https.HttpTransport()\nopener = urllib2.build_opener(HTTPSudsPreprocessor)\nhttps.urlopener = opener\ntry:\n suds.client.Client(URL, transport=https)\nexcept Exception as e:\n print(e)\n\n# client = suds.client.Client(URL, headers={'Content-Type': 'text/xml;charset=UTF-8', 'Authorization': 'Basic VW5pdmVyc2FsIEFQSS91QVBJNTYzMjY4NTc4My0yODJlMGQ0ZDp4UyE3SzZkJTM/'})\n# client.set_options(headers={'Content-Type': 'text/xml;charset=UTF-8', 'Authorization': 'Basic VW5pdmVyc2FsIEFQSS91QVBJNTYzMjY4NTc4My0yODJlMGQ0ZDp4UyE3SzZkJTM/'})\n","sub_path":"testpy2.py","file_name":"testpy2.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"632730875","text":"import sys\nfrom logging import getLogger\nimport os\nimport urlparse\nfrom abstract_step import AbstractSourceStep\n\nlogger=getLogger(\"uap_logger\")\n\nclass RawUrlSource(AbstractSourceStep):\n\n def __init__(self, pipeline):\n super(RawUrlSource, self).__init__(pipeline)\n\n self.add_connection('out/raw')\n\n self.require_tool('compare_secure_hashes')\n self.require_tool('cp')\n self.require_tool('curl')\n self.require_tool('dd')\n self.require_tool('mkdir')\n self.require_tool('pigz')\n\n self.add_option('filename', str, optional = True,\n description = \"local file name of downloaded file\")\n self.add_option('hashing-algorithm', str, optional=True,\n choices = ['md5', 'sha1', 'sha224', 'sha256',\n 'sha384', 'sha512'],\n description = \"hashing algorithm to use\")\n self.add_option('path', str, optional = False,\n description = \"directory to move downloaded file to\")\n self.add_option('secure-hash', str, optional = True,\n description = \"expected secure hash of downloaded file\")\n self.add_option('uncompress', bool, optional = True, default = False,\n description = 'Shall the file be uncompressed after '\n 'downloading')\n self.add_option('url', str, optional = False,\n description = \"file URL\")\n\n def runs(self, run_ids_connections_files):\n # Get file name of downloaded file\n url_filename = os.path.basename(\n urlparse.urlparse(self.get_option('url')).path)\n\n # Is downloaded file gzipped?\n root, ext = os.path.splitext(url_filename)\n is_gzipped = True if ext in ['.gz', '.gzip'] else False\n if not is_gzipped and self.get_option('uncompress'):\n raise StandardError(\"Uncompression of non-gzipped file %s requested.\"\n % url_filename)\n\n # Handle the filename to have the proper ending\n filename = root if self.get_option('uncompress') and is_gzipped \\\n else url_filename\n\n if self.is_option_set_in_config('filename'):\n conf_filename = self.get_option('filename')\n root, ext = os.path.splitext(\n os.path.basename(conf_filename))\n\n if is_gzipped and self.get_option('uncompress') and \\\n ext in ['.gz', '.gzip']:\n raise StandardError(\"The filename %s should NOT end on '.gz' or \"\n \"'.gzip'.\" % conf_filename)\n filename = conf_filename\n\n # Get directory to move downloaded file to\n path = self.get_option('path')\n # Absolute path to downloaded file\n final_abspath = os.path.join(path, filename)\n\n with self.declare_run('download') as run:\n # Test if path exists\n if os.path.exists(path):\n # Fail if it is not a directory\n if not os.path.isdir(path):\n raise StandardError(\n \"Path %s already exists but is not a directory\" % path)\n else:\n # Create the directory\n with run.new_exec_group() as mkdir_exec_group:\n mkdir = [self.get_tool('mkdir'), '-p', path]\n mkdir_exec_group.add_command(mkdir)\n out_file = run.add_output_file('raw', final_abspath, [] )\n\n temp_filename = run.add_temporary_file(suffix = url_filename)\n with run.new_exec_group() as curl_exec_group:\n # 1. download file\n curl = [self.get_tool('curl'), self.get_option('url')]\n curl_exec_group.add_command(curl, stdout_path = temp_filename)\n\n if self.is_option_set_in_config('hashing-algorithm') and \\\n self.is_option_set_in_config('secure-hash'):\n with run.new_exec_group() as check_exec_group:\n # 2. Compare secure hashes\n compare_secure_hashes = [\n self.get_tool('compare_secure_hashes'),\n '--algorithm',\n self.get_option('hashing-algorithm'),\n '--secure-hash',\n self.get_option('secure-hash'),\n temp_filename\n ]\n check_exec_group.add_command(compare_secure_hashes)\n with run.new_exec_group() as cp_exec_group:\n if self.get_option(\"uncompress\"):\n with cp_exec_group.add_pipeline() as pipe:\n pigz = [self.get_tool('pigz'),\n '--decompress',\n '--stdout',\n '--processes', '1',\n temp_filename]\n # temp_filename = os.path.splitext(temp_filename)[0]\n dd_out = [self.get_tool('dd'),\n 'bs=4M',\n 'of=%s' % out_file]\n pipe.add_command(pigz)\n pipe.add_command(dd_out)\n else:\n cp = [self.get_tool('cp'), '--update', temp_filename,\n out_file]\n cp_exec_group.add_command(cp)\n","sub_path":"include/sources/raw_url_source.py","file_name":"raw_url_source.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"124694861","text":"import re\nfrom datetime import timedelta\n\nfrom django.views.generic import DetailView, CreateView, ListView\nfrom django.http import HttpResponseRedirect\nfrom django.db.models import Q\nfrom django.db import connection\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.timezone import now\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth import get_user_model\n\nfrom braces.views import JSONResponseMixin\n\nfrom med_social.views.base import BaseEditView\nfrom med_social.decorators import member_required\n\nfrom users.tasks import user_invite\nfrom .models import Channel\nfrom .forms import MessageForm, NewChannelForm, UserInviteForm\n\n\nclass ChannelSuggestions(JSONResponseMixin, ListView):\n def get_queryset(self):\n vendors = self.channel.vendors.values_list('id', flat=True)\n restrictions = Q(vendor=None) | Q(vendor__in=vendors)\n\n query = self.request.GET.get('q', '').strip()\n filters = Q(username__icontains=query) \\\n | Q(first_name__icontains=query) | Q(last_name__icontains=query)\n\n return get_user_model().objects.filter(\n restrictions).filter(filters)\n\n def get(self, request, channel_pk):\n self.channel = get_object_or_404(Channel, pk=channel_pk)\n self.results = list(self.get_queryset().values(\n 'id', 'username', 'first_name', 'last_name'))\n return self.render_json_response(self.results)\nsuggestions = ChannelSuggestions.as_view()\n\n\nclass CreateChannel(CreateView):\n model = Channel\n template_name = 'channels/create.html'\n context_object_name = 'channel'\n form_class = NewChannelForm\n\n def dispatch(self, request, content_type_pk, object_pk):\n self.content_type = get_object_or_404(ContentType, pk=content_type_pk)\n self.content_object = get_object_or_404(self.content_type.model_class(),\n pk=object_pk)\n return super(CreateChannel, self).dispatch(request,\n content_type_pk,\n object_pk)\n\n def get_form_kwargs(self):\n kwargs = super(CreateChannel, self).get_form_kwargs()\n kwargs['object_id'] = self.content_object.id\n kwargs['content_type'] = self.content_type\n kwargs['vendor_choices'] = self.content_object\\\n .get_channel_vendor_choices(self.request.user)\n kwargs['request'] = self.request\n return kwargs\n\n def get_template_names(self):\n if self.request.is_ajax():\n return 'channels/partials/create.html'\n else:\n return self.template_name\n\n def get_success_url(self):\n url = self.content_object.get_absolute_url()\n return '{}?active_tab=channel-{}'.format(url, self.object.id)\ncreate_channel = member_required(CreateChannel.as_view())\n\n\nclass ChannelPage(DetailView):\n model = Channel\n template_name = 'channels/details.html'\n context_object_name = 'channel'\n\n def get_object(self):\n kwargs = {'pk': self.kwargs['channel_pk']}\n if self.request.user.is_vendor:\n kwargs['vendors'] = self.request.user.vendor\n return Channel.objects.get(**kwargs)\n\n def get_context_data(self, object):\n ctx = super(ChannelPage, self).get_context_data()\n ctx['message_form'] = MessageForm(request=self.request)\n return ctx\nchannel_page = member_required(ChannelPage.as_view())\n\n\nclass PostComment(BaseEditView):\n model_form = MessageForm\n template_name = 'channels/comments/create.html'\n is_success = False\n\n def get_template_names(self):\n if self.is_success:\n return 'channels/comments/as_field.html'\n else:\n return self.template_name\n\n def get_context_data(self):\n ctx = super(PostComment, self).get_context_data()\n ctx['form'] = MessageForm(request=self.request)\n ctx['channel'] = self.channel\n ctx['success'] = self.is_success\n ctx['object'] = self.object\n emails = re.findall(settings.EMAIL_REGEX, self.object.body)\n existing = set(get_user_model().objects.filter(\n email__in=emails).values_list('email', flat=True))\n emails = set(emails) - existing\n ctx['emails'] = emails\n return ctx\n\n def get(self, request, channel_pk):\n return HttpResponseRedirect(self.response.get_absolute_url())\n\n def dispatch(self, request, channel_pk):\n self.user = self.request.user\n\n kwargs = {'pk': channel_pk}\n if self.user.is_vendor:\n kwargs['vendors'] = self.user.vendor\n self.channel = get_object_or_404(Channel, **kwargs)\n ret_val = super(PostComment, self).dispatch(request, channel_pk)\n if self.request.is_ajax():\n return self.render_to_response(self.get_context_data())\n return ret_val\n\n def get_success_url(self):\n return self.channel.content_object.get_absolute_url()\n\n def pre_save(self, instance):\n instance.channel = self.channel\n instance.posted_by = self.user\n return instance\n\n def post_save(self, instance):\n self.is_success = True\n return instance\npost_comment = member_required(PostComment.as_view())\n\n\nclass InviteUser(CreateView):\n model = get_user_model()\n form_class = UserInviteForm\n template_name = 'channels/partials/invite_user_modal.html'\n ajax_template_name = 'channels/partials/invite_user_form.html'\n ajax_result_template_name = 'channels/partials/invite_result.html'\n\n def get_template_names(self):\n if self.request.method == 'POST':\n if self.object:\n return self.ajax_result_template_name\n else:\n return self.ajax_template_name\n else:\n return self.template_name\n\n def get_context_data(self, form=None):\n ctx = super(InviteUser, self).get_context_data()\n ctx['channel'] = get_object_or_404(\n Channel, id=self.kwargs['channel_pk'])\n if form:ctx['form'] = form\n ctx['object'] = self.object\n return ctx\n\n def get_initial(self):\n initial = super(InviteUser, self).get_initial()\n initial['email'] = self.request.GET.get('email', '')\n return initial\n\n def get_form_kwargs(self):\n kwargs = super(InviteUser, self).get_form_kwargs()\n kwargs['request'] = self.request\n return kwargs\n\n def form_valid(self, form):\n super(InviteUser, self).form_valid(form)\n password = get_user_model().objects.make_random_password()\n tenant = connection.get_tenant()\n self.object.kind = form.cleaned_data['kind']\n self.object.set_password(password)\n self.object.save()\n\n expires_at = now() + timedelta(days=7)\n user_invitation, _ = self.object.invitations.get_or_create(\n sender=self.request.user, receiver=self.object,\n defaults={'expires_at': expires_at})\n\n user_invitation.expires_at = expires_at\n user_invitation.save()\n user_invite.delay(tenant_id=tenant.id,\n invite_id=user_invitation.id,\n password=password)\n\n return self.render_to_response(self.get_context_data(form))\ninvite_user = member_required(InviteUser.as_view())\n","sub_path":"apps/channels/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110290876","text":"import speech_recognition as sr\r\nimport pyaudio\r\n\r\nr = sr.Recognizer()\r\nwith sr.Microphone() as source:\r\n r.adjust_for_ambient_noise(source)\r\n print(\"Say Something\")\r\n audio = r.listen(source)\r\n\r\ntry:\r\n print(\"You said \" + '\"' + r.recognize_google(audio) + '\"')\r\nexcept Exception as e:\r\n print(e)\r\n","sub_path":"SpeechRecognition.py","file_name":"SpeechRecognition.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"132286437","text":"#!/bin/env python3\n\nimport discord\nfrom discord.ext import commands\n\nclass Aesthetic:\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(aliases=['at'])\n async def aesthetify(self, ctx, *, a_text):\n \"\"\" Make your message aesthetic, man \"\"\"\n ascii_to_wide = dict((i, chr(i + 0xfee0)) for i in range(0x21, 0x7f))\n ascii_to_wide.update({0x20: u'\\u3000', 0x2D: u'\\u2212'})\n\n await ctx.message.edit(content=f'{a_text.translate(ascii_to_wide)}')\n \n \ndef setup(bot):\n bot.add_cog(Aesthetic(bot))\n \n","sub_path":"aesthetic.py","file_name":"aesthetic.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"37886144","text":"\"\"\"Module realizes interpreter of basic esoteric language called\n BrainFuck. Also provides with the converter from Spoon esoteric\n language to BF.\n\"\"\"\nimport argparse\nimport sys\n\nINT_MAX = 2147483648\nINT_MIN = -2147483649\n\n\nclass EsotericLanguageConverter:\n \"\"\"\n Converter interface with\n methods to be implemented.\n \"\"\"\n @staticmethod\n def convert_to_brain_fuck(_input):\n \"\"\":param _input: string representing the code in esoteric language\n :return: code in BrainFuck language\n \"\"\"\n raise NotImplementedError\n\n\nclass SpoonConverter(EsotericLanguageConverter):\n \"\"\"\n Converter from Spoon to BrainFuck\n \"\"\"\n @staticmethod\n def convert_to_brain_fuck(_input):\n \"\"\"\n :param _input: code in Spoon\n :return: BrainFuck code\n \"\"\"\n start = 0\n convert_dict = {\n \"1\": \"+\",\n \"000\": \"-\",\n \"010\": \">\",\n \"011\": \"<\",\n \"00100\": \"[\",\n \"0011\": \"]\",\n \"001010\": \".\",\n \"0010110\": \",\"\n }\n brain_fuck_input = ''\n while start < len(_input):\n is_command_found = False\n for key in convert_dict:\n if _input[start: start + len(key)] == key:\n start += len(key)\n brain_fuck_input += convert_dict[key]\n is_command_found = True\n if not is_command_found:\n raise SyntaxError(\"Unexpected commands found\")\n return brain_fuck_input\n\n\nclass EsotericParser:\n \"\"\"\n Parser interface with\n methods to be implemented.\n \"\"\"\n @staticmethod\n def get_command_list(code):\n \"\"\":param code: string representing the code in esoteric language\n :return: list of commands\n \"\"\"\n raise NotImplementedError\n\n\nclass SpoonParser(EsotericParser):\n \"\"\"\n Parser of Spoon code\n \"\"\"\n @staticmethod\n def get_command_list(code):\n possible_commands = [\n \"1\", \"000\", \"010\", \"011\",\n \"00100\", \"0011\", \"001010\", \"0010110\"]\n\n if any(symbol not in ('0', '1', '\\n', ' ') for symbol in code):\n raise SyntaxError(\n \"Spoon code should consist of binary symbols only\")\n spoon_commands = []\n spoon_sub_code = code.split()\n for sub_code in spoon_sub_code:\n start = 0\n while start < len(sub_code):\n is_command_found = False\n for possible_command in possible_commands:\n if sub_code[start: start + len(possible_command)] \\\n == possible_command:\n spoon_commands += possible_command\n start += len(possible_command)\n is_command_found = True\n if not is_command_found:\n raise SyntaxError(\"Unexpected commands found\")\n return spoon_commands\n\n\nclass BrainLuck:\n \"\"\"Implements BrainFuck interpreter\n \"\"\"\n def __init__(self):\n self.cells = [0] * 60000\n self.while_pointers = []\n self.command_index = 0\n self.data_index = 30000\n self.commands = None\n self.last_commands = None\n\n def go_to_next_cell(self):\n \"\"\"increases index of data cell\n :return: None\n \"\"\"\n self.data_index += 1\n\n def go_to_prev_cell(self):\n \"\"\"decreases index of data cell\n :return: None\n \"\"\"\n self.data_index -= 1\n\n def increase_cell(self):\n \"\"\"increases index of data cell\n :return: None\n \"\"\"\n self.cells[self.data_index] = (\n self.cells[self.data_index] + 1) % INT_MAX\n\n def decrease_cell(self):\n \"\"\"decreases index of data cell\n :return: None\n \"\"\"\n self.cells[self.data_index] = (\n self.cells[self.data_index] - 1)\n if self.cells[self.data_index] < 0:\n self.cells[self.data_index] %= INT_MIN\n\n def get_char(self):\n \"\"\"reads one char from stream i/o\n :return: None\n \"\"\"\n _input = sys.stdin.read(1)\n if _input:\n self.cells[self.data_index] = ord(_input)\n else:\n self.cells[self.data_index] = 0\n\n def put_char(self):\n \"\"\"prints current data cell to stream i/o\n :return: None\n \"\"\"\n sys.stdout.write(chr(self.cells[self.data_index]))\n\n def start_cycle(self):\n \"\"\"\n starts cycle from \"[\" if value of current data cell is positive\n else jumps to paired \"]\" according to the nesting\n :return: None\n \"\"\"\n if self.cells[self.data_index] == 0:\n self.command_index = self.while_pointers[self.command_index]\n\n def decrease_cycle(self):\n \"\"\"\n ends cycle started from paired \"] if data cell is 0\n else jumps to paired \"]\" according to the nesting\n :return: None\n \"\"\"\n if self.cells[self.data_index] != 0:\n self.command_index = self.while_pointers[self.command_index]\n\n def interpret(self, commands):\n \"\"\"\n Performs code in BrainFuck. Prints to Stream I/O.\n Reads from Stream I/O.\n :param commands - code in BrainFuck.\n :return: None\n \"\"\"\n if not isinstance(commands, str):\n raise ValueError(\n \"commands argument must be of type str\")\n self.last_commands = self.commands = (\n commands if commands else self.last_commands)\n self.while_pointers = [0] * len(commands)\n\n stack = []\n\n for index, token in enumerate(commands):\n if token == \"[\":\n stack.append(index)\n elif token == \"]\":\n self.while_pointers[stack[-1]] = index\n self.while_pointers[index] = stack.pop()\n\n while self.command_index < len(commands):\n self.command_dict[commands[self.command_index]](self)\n self.command_index += 1\n\n self.commands = None\n self.command_index = 0\n self.data_index = 0\n\n def repeat_last_command(self):\n \"\"\"If someone wants to repeat last command =)\n :return: None\n \"\"\"\n self.interpret(self.last_commands)\n\n command_dict = {\n \">\": go_to_next_cell,\n \"<\": go_to_prev_cell,\n \"+\": increase_cell,\n \"-\": decrease_cell,\n \".\": put_char,\n \",\": get_char,\n \"[\": start_cycle,\n \"]\": decrease_cycle\n }\n\n\ndef main():\n \"\"\"\n Allows using module as script\n python3 spoon.py path_to_spoon_code\n :return: None\n \"\"\"\n file_names_parser = argparse.ArgumentParser(description='''\n Get input and output file's names''')\n file_names_parser.add_argument('spoon_file',\n help='path to spoon_file')\n parser_args = file_names_parser.parse_args()\n\n spoon = BrainLuck()\n _input = open(parser_args.spoon_file).read()\n converted_commands = SpoonConverter.convert_to_brain_fuck(\n ''.join(SpoonParser.get_command_list(_input)))\n spoon.interpret(converted_commands)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"spoon.py","file_name":"spoon.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"200491226","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/4/22 9:51\n# @File : fib.py\n# @author : dfkai\n# @Software: PyCharm\n\ndef fib_recur(n):\n assert n >= 0, \"n > 0\"\n if n <= 1:\n return n\n return fib_recur(n - 1) + fib_recur(n - 2)\n\n\nprint(fib_recur(3))\n\n\ndef fib_two(n):\n a, b = 0, 1\n for i in range(n):\n a, b = b, a + b\n return a\n\n\nprint(fib_two(3))\n\nprint(\"fuckkk\")\nprint(\"helo\")\nprint(\"world\")\n","sub_path":"fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"479663837","text":"# coding=UTF-8\n\"\"\"\nSubclassing of the xigt package to add a few convenience methods.\n\"\"\"\n\n#===============================================================================\n# Logging\n#===============================================================================\n\nimport logging\n\n# Set up logging ---------------------------------------------------------------\nfrom intent.igt.create_tiers import trans_lines, get_raw_tier, generate_clean_tier, add_normal_line_to_tier, generate_normal_tier, morphemes\nfrom intent.utils.string_utils import replace_invalid_xml\nfrom xigt.errors import XigtError\n\nPARSELOG = logging.getLogger(__name__)\nALIGN_LOG = logging.getLogger('GIZA_LN')\nODIN_LOG = logging.getLogger('ODIN_LOOKUP')\nCONVERT_LOG = logging.getLogger('CONVERSION')\n\n# XIGT imports -----------------------------------------------------------------\nfrom xigt.codecs import xigtxml\nfrom xigt.model import XigtCorpus, Igt, Item\n\n# INTERNAL imports -------------------------------------------------------------\n\n\n#===============================================================================\n# IGT Class\n#===============================================================================\n\n\n\nclass RGIgt(Igt):\n\n # • Constructors -----------------------------------------------------------\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n\n\n\n # • Processing of newly created instances ----------------------------------\n\n\n\n\n def add_gloss_lang_alignments(self):\n # Finally, do morpheme-to-morpheme alignment between gloss\n # and language if it's not already done...\n if not glosses(self).alignment:\n morph_align(glosses(self), morphemes(self))\n\n if not gloss(self).alignment:\n word_align(gloss(self), lang(self))\n\n # • Basic Tier Creation ------------------------------------------------------------\n\n def raw_tier(self):\n return get_raw_tier(self)\n\n def clean_tier(self, merge=False, generate=True):\n return generate_clean_tier(self, merge, generate)\n\n\n\n\n\n # • Word Tier Creation -----------------------------------\n\n def add_normal_line(self, tier, tag, func):\n add_normal_line_to_tier(self, tier, tag, func)\n\n def normal_tier(self, clean=True, generate=True):\n return generate_normal_tier(self, clean, generate)\n\n\n\n #===========================================================================\n # ALIGNMENT STUFF\n #===========================================================================\n\n\n def heur_align(self, **kwargs):\n return heur_align_inst(self, **kwargs)\n\n # -------------------------------------------\n # POS TAG MANIPULATION\n # -------------------------------------------\n\n\n\n\n\n\n def project_trans_to_lang(self, aln_method=None, tag_method=None):\n \"\"\"\n Project POS tags from the translation line directly to the language\n line. This assumes that we have a bilingual alignment between\n translation words and language words already.\n\n \"\"\"\n\n # Get the alignment between translation and language lines\n ta_aln = self.get_bilingual_alignment(self.trans.id, self.lang.id, aln_method=aln_method)\n\n # Get the trans tags...\n trans_tags = self.get_pos_tags(self.trans.id, tag_method=tag_method)\n\n if not ta_aln:\n raise ProjectionException(\"No translation-language-line alignment was found for instance \\\"{}\\\". Not projecting.\".format(self.id))\n\n\n # Create the new pos tier...\n pos_id = gen_tier_id(self, POS_TIER_ID, tier_type=POS_TIER_TYPE, alignment=self.lang.id)\n pt = Tier(type=POS_TIER_TYPE, id=pos_id, alignment=self.lang.id)\n\n # Add the metadata about the source of the tags.\n set_intent_method(pt, INTENT_POS_PROJ)\n set_intent_proj_data(pt, trans_tags, ta_aln.type)\n\n for t_i, l_i in ta_aln:\n t_word = self.trans.get_index(t_i)\n t_tag = trans_tags[t_i-1]\n\n l_word = self.lang.get_index(l_i)\n\n pt.add(RGToken(id=ask_item_id(pt), alignment = l_word.id, text = str(t_tag)))\n\n self.append(pt)\n\n\n","sub_path":"intent/igt/rgxigt.py","file_name":"rgxigt.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"496078760","text":"import glob\nimport os\nimport sys\nimport json\n\n\ndef readfilename(self):\n ret = []\n files = glob.glob(self.results + self.height + '/*.json')\n for f in files:\n name = f.split('/')[-1]\n ret.append(name)\n return ret\n\n\ndef crflist(crf):\n ret = []\n for q in crf.split(','):\n ret.append(\"_\" + q + \"_\")\n ret.reverse() \n return ret\n\n\ndef calc_avg_qual(self, crf_list, files):\n psnr_avg = []\n ssim_avg = []\n vmaf_avg = []\n \n height = self.height\n codec = self.codec\n result_path = self.results + height + '/'\n num_seq = int(self.num_seq)\n\n for crf in crf_list: #qp_set\n sum_ssim = 0\n sum_psnr = 0\n sum_vmaf = 0\n for res in files:\n if crf in res:\n with open(result_path + res, \"r\") as f1:\n data = json.load(f1)\n sum_ssim += data['MS-SSIM score']\n sum_psnr += data['PSNR score']\n sum_vmaf += data['VMAF score']\n \n psnr_avg.append(sum_psnr/(num_seq))\n ssim_avg.append(sum_ssim/(num_seq))\n vmaf_avg.append(sum_vmaf/(num_seq))\n\n print('psnr_avg_' + height + '_' + codec + ' = ', psnr_avg)\n print('ssim_avg_' + height + '_' + codec + ' = ', ssim_avg)\n print('vma_avg_' + height + '_' + codec + ' = ', vmaf_avg)\n\n\ndef calc_avg_bpp(self, crf_list, files):\n size_avg = []\n \n height = self.height\n width = self.width\n frames = self.frames\n num_seq = self.num_seq\n codec = self.codec\n \n path = self.bin_out + height + '/'\n\n for crf in crf_list:\n bitsum = 0.0\n for res in files:\n res = res.split('.')[0] + '.mp4'\n if crf in res:\n mp4 = path + res\n size = os.stat(mp4).st_size\n bitsum += (size*8.0)\n size_avg.append(bitsum/(int(num_seq) * int(width) * int(height) * int(frames)))\n \n print('bpp_' + height + '_' + codec + ' = ', size_avg)\n\n\ndef average(self):\n if self.mode == 'crf':\n crf = crflist(self.crf)\n else:\n crf = crflist(self.cbr)\n files = readfilename(self)\n calc_avg_qual(self, crf, files)\n calc_avg_bpp(self, crf, files)\n","sub_path":"scripts/average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"246537391","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Guewen Baconnier, Sébastien Beau\n# Copyright (C) 2011 Akretion Sébastien BEAU \n# Copyright 2013 Camptocamp SA (Guewen Baconnier)\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom phpserialize import serialize, unserialize\nfrom openerp.addons.connector.unit.mapper import (mapping, ImportMapper)\nfrom openerp.addons.magentoerpconnect.sale import (SaleOrderAdapter,MagentoShippingLineBuilder, SaleOrderImport, SaleOrderImportMapper, SaleOrderLineImportMapper,SaleOrderBatchImport)\nfrom openerp.addons.magentoerpconnect.partner import (PartnerImportMapper, AddressImportMapper)\nfrom openerp.addons.connector_ecommerce.unit.sale_order_onchange import (SaleOrderOnChange)\nfrom openerp.addons.magentoerpconnect.unit.import_synchronizer import MagentoImportSynchronizer\nfrom openerp.addons.connector_ecommerce.sale import SpecialOrderLineBuilder\nfrom openerp.addons.magentoerpconnect.unit.backend_adapter import (MAGENTO_DATETIME_FORMAT)\nfrom wf_magento_connector.backend import magento_web_fortune\nfrom openerp.addons.magentoerpconnect.product import(ProductProductAdapter)\nfrom openerp.addons.connector.queue.job import job\n\nimport re\nimport requests\nimport urllib\nimport logging\nfrom datetime import datetime\n_logger = logging.getLogger(__name__)\n\n\n@magento_web_fortune\nclass WF_SaleOrderBatchImport(SaleOrderBatchImport):\n\n def run(self, filters=None):\n \"\"\" Run the synchronization \"\"\"\n if filters is None:\n filters = {}\n filters['status'] = {'nin': ['pending_payment', 'canceled', 'canceled_saferpaycw']}\n from_date = filters.pop('from_date', None)\n to_date = filters.pop('to_date', None)\n magento_storeview_ids = [filters.pop('magento_storeview_id')]\n \n record_ids = self.backend_adapter.search(\n filters,\n from_date=from_date,\n to_date=to_date,\n magento_storeview_ids=magento_storeview_ids)\n _logger.info('search for magento saleorders %s returned %s',\n filters, record_ids)\n for record_id in record_ids:\n self._import_record(record_id)\n #bsbs mark Sales Order as imported \n API = self.get_connector_unit_for_model(SaleOrderAdapter) \n API._call('%s.done' % API._magento_model, [record_id])\n\n@magento_web_fortune\nclass WF_SaleOrderAdapter(SaleOrderAdapter):\n\n def search(self, filters=None, from_date=None, to_date=None,\n magento_storeview_ids=None):\n \"\"\" Search records according to some criteria\n and returns a list of ids\n\n :rtype: list\n \"\"\"\n if filters is None:\n filters = {}\n dt_fmt = MAGENTO_DATETIME_FORMAT\n\n #bsbs removed to get older orders where the state is changed from pending_payment into processing\n # instead we use now the field imported in magento to mark sales order as imported\n \n #if from_date is not None:\n # filters.setdefault('created_at', {})\n # filters['created_at']['from'] = from_date.strftime(dt_fmt)\n \n if to_date is not None:\n filters.setdefault('created_at', {})\n filters['created_at']['to'] = to_date.strftime(dt_fmt)\n if magento_storeview_ids is not None:\n filters['store_id'] = {'in': magento_storeview_ids}\n arguments = {'imported': False,\n # 'limit': 200,\n 'filters': filters,\n }\n return super(SaleOrderAdapter, self).search(arguments)\n\n@magento_web_fortune\nclass VoucherLineBuilder(SpecialOrderLineBuilder):\n \"\"\" Return values for a Voucher line \"\"\"\n _model_name = 'magento.sale.order'\n\n def __init__(self, environment):\n super(VoucherLineBuilder, self).__init__(environment)\n self.sequence = 999\n\n@magento_web_fortune\nclass WF_SaleOrderImport(SaleOrderImport):\n _model_name = ['magento.sale.order']\n\n def _import_addresses(self):\n record = self.magento_record\n sess = self.session\n if sess.context:\n sess.context.update({'wf_mag_import': True})\n else:\n sess.context = {'wf_mag_import': True}\n # Magento allows to create a sale order not registered as a user\n is_guest_order = bool(int(record.get('customer_is_guest', 0) or 0))\n\n # For a guest order or when magento does not provide customer_id\n # on a non-guest order (it happens, Magento inconsistencies are\n # common)\n if (is_guest_order or not record.get('customer_id')):\n website_binder = self.get_binder_for_model('magento.website')\n oe_website_id = website_binder.to_openerp(record['website_id'])\n\n # search an existing partner with the same email\n partner_ids = sess.search(\n 'magento.res.partner',\n [('emailid', '=ilike', record['customer_email']),\n ('website_id', '=', oe_website_id)])\n \n # if we have found one, we \"fix\" the record with the magento\n # customer id\n if partner_ids:\n partner = sess.read('magento.res.partner',\n partner_ids[0],\n ['magento_id'])\n # If there are multiple orders with \"customer_id is\n # null\" and \"customer_is_guest = 0\" which share the same\n # customer_email, then we may get a magento_id that is a\n # marker 'guestorder:...' for a guest order (which is\n # set below). This causes a problem with\n # \"importer.run...\" below where the id is cast to int.\n if str(partner['magento_id']).startswith('guestorder:'):\n is_guest_order = True\n else:\n record['customer_id'] = partner['magento_id']\n\n # no partner matching, it means that we have to consider it\n # as a guest order\n else:\n is_guest_order = True\n\n partner_binder = self.get_binder_for_model('magento.res.partner')\n if is_guest_order:\n # ensure that the flag is correct in the record\n record['customer_is_guest'] = True\n guest_customer_id = 'guestorder:%s' % record['increment_id']\n # \"fix\" the record with a on-purpose built ID so we can found it\n # from the mapper\n record['customer_id'] = guest_customer_id\n\n address = record['billing_address']\n\n customer_group = record.get('customer_group_id')\n if customer_group:\n self._import_customer_group(customer_group)\n\n customer_record = {\n 'email': record.get('customer_email'),\n 'taxvat': record.get('customer_taxvat'),\n 'group_id': customer_group,\n 'gender': record.get('customer_gender'),\n 'store_id': record['store_id'],\n 'created_at': record['created_at'],\n 'updated_at': False,\n 'created_in': False,\n 'dob': record.get('customer_dob'),\n 'website_id': record.get('website_id'),\n }\n \n #bsbs to find existing Openerp Records with Addressdata\n customer_record.update(address)\n\n mapper = self.get_connector_unit_for_model(PartnerImportMapper,\n 'magento.res.partner')\n map_record = mapper.map_record(customer_record)\n map_record.update(guest_customer=True)\n partner_bind_id = sess.create('magento.res.partner',\n map_record.values(for_create=True))\n partner_binder.bind(guest_customer_id,\n partner_bind_id)\n else:\n\n # we always update the customer when importing an order\n importer = self.get_connector_unit_for_model(\n MagentoImportSynchronizer, 'magento.res.partner')\n sess = self.session\n if sess.context:\n sess.context.update({'address': record['billing_address']})\n else:\n sess.context = {'address': record['billing_address']}\n importer.run(record['customer_id'])\n partner_bind_id = partner_binder.to_openerp(record['customer_id'])\n\n partner_id = sess.read(\n 'magento.res.partner',\n partner_bind_id, ['openerp_id'])['openerp_id'][0]\n\n\n addresses_defaults = {\n 'parent_id': partner_id,\n 'magento_partner_id': partner_bind_id,\n 'email': record.get('customer_email', False),\n 'active': True,\n 'is_magento_order_address': True}\n\n addr_mapper = self.get_connector_unit_for_model(AddressImportMapper,\n 'magento.address')\n self.session.context.update({'store_id': record['store_id']})\n def create_address(address_record):\n map_record = addr_mapper.map_record(address_record)\n map_record.update(addresses_defaults)\n address_bind_id = sess.create('magento.address',\n map_record.values(for_create=True))\n return sess.read('magento.address',\n address_bind_id,\n ['openerp_id'])['openerp_id'][0]\n\n\n start = False\n street_no = False\n shipping_id = None\n ship_street_no = False\n ship_shipping_id = None\n \n addresses_defaults.update({'openerp_id': partner_id, 'parent_id': False})\n billing_id = create_address(record['billing_address'])\n if record['shipping_address'] and record['shipping_method'] != 'Lemundo_AwnCustomShippingMethod_Lemundo_AwnCustomShippingMethod':\n country_id = self.session.search('res.country',[('code', '=', record['shipping_address']['country_id'])])\n street_no_position = re.search(\"\\d\", record['shipping_address']['street'])\n if street_no_position:\n if street_no_position.start() == 0: \n street_no_position = re.search(\"\\s\", record['shipping_address']['street']) \n start_street = street_no_position.start()\n ship_street = record['shipping_address']['street'][start_street+1:]\n ship_street_no = record['shipping_address']['street'][:start_street+1]\n if ship_street_no:\n ship_street_no = ship_street_no.strip()\n else:\n start = len(record['shipping_address']['street']) - street_no_position.start()\n ship_street = record['shipping_address']['street'][:start *(-1)]\n ship_street_no = record['shipping_address']['street'][start *(-1):]\n if ship_street_no:\n ship_street_no = ship_street_no.strip()\n else:\n ship_street = record['shipping_address']['street']\n\n street_no_position = False\n street_no_position = re.search(\"\\d\", record['billing_address']['street'])\n if street_no_position:\n if street_no_position.start() == 0: \n street_no_position = re.search(\"\\s\", record['billing_address']['street']) \n start_street = street_no_position.start()\n street = record['billing_address']['street'][start_street+1:]\n street_no = record['billing_address']['street'][:start_street+1]\n else:\n start = len(record['billing_address']['street']) - street_no_position.start()\n street = record['billing_address']['street'][:start *(-1)]\n street_no = record['billing_address']['street'][start *(-1):]\n else:\n street = record['billing_address']['street']\n\n if record['shipping_address'] and record['shipping_address']['lastname']:\n if (record['billing_address']['firstname'].strip() != record['shipping_address']['firstname'].strip() or record['billing_address']['lastname'].strip() != record['shipping_address']['lastname'].strip() \\\n or street != ship_street or ship_street_no != street_no or record['billing_address']['postcode'] != record['shipping_address']['postcode'] \\\n or record['billing_address']['city'] != record['billing_address']['city'] or record['billing_address']['country_id'] != record['shipping_address']['country_id']): \n partner_ids = sess.search('res.partner',\n [ ('last_name', '=ilike', record['shipping_address']['lastname'].strip()),\n ('first_name', '=ilike', record['shipping_address']['firstname'].strip()),\n ('street', '=ilike', ship_street.strip()),\n ('wf_street_no', '=ilike', ship_street_no),\n ('zip', '=ilike', record['shipping_address']['postcode'].strip()),\n ('city', '=ilike', record['shipping_address']['city'].strip()),\n ('country_id', '=', country_id),\n ('customer', '=', True),\n ])\n if partner_ids:\n addresses_defaults.update({'openerp_id': partner_ids[0], 'parent_id': partner_id})\n else:\n addresses_defaults.update({'openerp_id': False, 'parent_id': partner_id})\n shipping_id = create_address(record['shipping_address'])\n else:\n #hotfix for paypal express data where firstname and lastname in firstname field of shipping address\n name = \"%s %s\" %(record['billing_address']['firstname'].strip(), record['billing_address']['lastname'].strip())\n if (name != record['shipping_address']['firstname'].strip() \\\n or street != ship_street or record['billing_address']['postcode'] != record['shipping_address']['postcode'] \\\n or record['billing_address']['city'] != record['billing_address']['city'] or record['billing_address']['country_id'] != record['shipping_address']['country_id']): \n t = record['shipping_address']['firstname'].split(\" \")\n partner_ids = sess.search('res.partner',\n [ ('last_name', '=ilike', t[0].strip()),\n ('first_name', '=ilike', t[1].strip()),\n ('street', '=ilike', ship_street.strip()),\n ('wf_street_no', '=ilike', ship_street_no),\n ('zip', '=ilike', record['shipping_address']['postcode'].strip()),\n ('city', '=ilike', record['shipping_address']['city'].strip()),\n ('country_id', '=', country_id),\n ('customer', '=', True),\n ])\n if partner_ids:\n addresses_defaults.update({'openerp_id': partner_ids[0], 'parent_id': partner_id})\n else:\n addresses_defaults.update({'openerp_id': False, 'parent_id': partner_id})\n shipping_id = create_address(record['shipping_address'])\n\n self.partner_id = partner_id\n self.partner_invoice_id = partner_id\n self.partner_shipping_id = shipping_id or partner_id\n\n@magento_web_fortune\nclass WF_SaleOrderImportMapper(SaleOrderImportMapper):\n _model_name = 'magento.sale.order'\n\n def _add_shipping_line(self, map_record, values):\n record = map_record.source\n amount_incl = float(record.get('base_shipping_incl_tax') or 0.0)\n amount_excl = float(record.get('shipping_amount') or 0.0)\n\n #bsbs Nachnahmegebuehren dazu\n amount_excl += float(record.get('cod_fee') or 0.0)\n amount_incl += float(record.get('cod_tax_amount') or 0.0) + float(record.get('cod_fee') or 0.0)\n\n\n if not (amount_incl or amount_excl):\n return values\n line_builder = self.get_connector_unit_for_model(\n MagentoShippingLineBuilder)\n if self.options.tax_include:\n discount = float(record.get('shipping_discount_amount') or 0.0)\n line_builder.price_unit = (amount_incl - discount)\n else:\n line_builder.price_unit = amount_excl\n\n if values.get('carrier_id'):\n carrier = self.session.browse('delivery.carrier',\n values['carrier_id'])\n line_builder.product_id = carrier.product_id\n\n line = (0, 0, line_builder.get_line())\n\n #bsbs todo get Product Name in correct translation\n if 'name' in line[2] and 'product_id' in line [2]:\n product = self.session.pool['product.product'].browse(self.session.cr, self.session.uid, line [2]['product_id'], self.session.context)\n name = '[%s] %s' % (product.default_code,product.name_template)\n line [2]['name'] = name\n values['order_line'].append(line)\n return values\n\n def _add_voucher_line(self, map_record, values):\n record = map_record.source\n amount = float(record.get('base_discount_amount') or 0.0)\n voucher = record.get('coupon_code')\n company = self.options.storeview.store_id.openerp_id.company_id.id\n if voucher:\n if self.options.storeview.store_id.id == 3:\n voucher = voucher[6:]\n else: \n voucher = voucher[4:]\n wf_voucher_id = self.session.search('wf_voucher.voucher',[('name', '=', voucher), ('company_id', '=', company)])\n values.update({'wf_coupon_code': voucher, 'wf_coupon_value': (amount*(-1))})\n if not amount or not voucher or not wf_voucher_id:\n return values\n\n line_builder = self.get_connector_unit_for_model(\n VoucherLineBuilder)\n \n \n wf_voucher = self.session.browse('wf_voucher.voucher',wf_voucher_id)\n\n line_builder.price_unit = amount\n line_builder.product = wf_voucher[0].wf_product_voucher_id.id\n\n line = (0, 0, line_builder.get_line())\n if len(line) == 3:\n name = \"Gutschein-Nr.: %s \" % ( voucher)\n line[2].update({'name': name, 'wf_voucher_id': wf_voucher[0].id})\n\n values['order_line'].append(line)\n return values\n\n def _add_product_opt_line(self, map_record, values):\n \n line_builder = self.get_connector_unit_for_model(\n MagentoShippingLineBuilder)\n product_options = self.session.context['wf_product_opt']\n product_id = self.session.search('product.product',[('default_code', '=', product_options['sku'])])\n \n line_builder.price_unit = product_options['price']\n line_builder.product = product_id[0]\n\n line = (0, 0, line_builder.get_line())\n\n values['order_line'].append(line)\n\n return values\n\n def finalize(self, map_record, values):\n sess = self.session\n if sess.context:\n sess.context.update({'wf_mag_import': True})\n else:\n sess.context = {'wf_mag_import': True}\n values.setdefault('order_line', [])\n values = self._add_shipping_line(map_record, values)\n #bsbs is combined with shipping_line\n #values = self._add_cash_on_delivery_line(map_record, values)\n\n #add to get product_options in own line\n if 'wf_product_opt' in sess.context:\n values = self._add_product_opt_line(map_record, values)\n\n values = self._add_gift_certificate_line(map_record, values)\n #bsbs\n values = self._add_voucher_line(map_record, values)\n\n partner = self.session.browse('res.partner', self.options.partner_id)\n if partner.cl_accountmanager and partner.cl_accountmanager.wf_shop_id and 'carrier_id' in values and values['carrier_id'] != 6:\n values.update({'shop_id': partner.cl_accountmanager.wf_shop_id.id})\n\n values.update({\n 'partner_id': self.options.partner_id,\n 'partner_invoice_id': self.options.partner_invoice_id,\n 'partner_shipping_id': self.options.partner_shipping_id,\n })\n\n onchange = self.get_connector_unit_for_model(SaleOrderOnChange)\n return onchange.play(values, values['magento_order_line_ids'])\n\n @mapping\n def payment(self, record):\n sess = self.session\n if sess.context:\n sess.context.update({'wf_mag_import': True})\n else:\n sess.context = {'wf_mag_import': True}\n # to get transaction_id out of additional_data\n if record['payment'] and record['payment']['additional_data'] and not record['payment']['last_trans_id']:\n record['payment']['additional_data'] = record['payment']['additional_data'].replace(u'\\xdc', 'Ue')\n additional_data = unserialize(record['payment']['additional_data'])\n if additional_data and 'component_mode' in additional_data and additional_data['component_mode'] == 'amazon':\n record['payment']['last_trans_id'] = additional_data['channel_order_id']\n record_method = 'amazon'\n\n elif additional_data and 'payment_method' in additional_data:\n record_method = additional_data['payment_method']\n \n if additional_data and 'transactions' in additional_data and additional_data['transactions']:\n record['payment']['last_trans_id'] = additional_data['transactions'][0]['transaction_id']\n else:\n record['payment']['last_trans_id'] = 'MANUELL ALS BEZAHLT'\n else:\n record_method = record['payment']['method']\n \n method_ids = sess.search('payment.method',\n [['name', '=', record_method]])\n assert method_ids, (\"method %s should exist because the import fails \"\n \"in SaleOrderImport._before_import when it is \"\n \" missing\" % record_method)\n method_id = method_ids[0] \n payment_obj = sess.pool['payment.method']\n payment = payment_obj.browse(sess.cr, sess.uid,method_id)\n if payment and payment.wf_payment_type:\n wf_payment_type = payment.wf_payment_type.id\n else:\n wf_payment_type = 1\n\n if payment.wf_payment_type.wf_precash_ready and payment.wf_payment_type.id == 3: #Creditcards only reserved in Web\n wf_pay_status = 'RESERVED'\n elif payment.wf_payment_type.wf_precash_ready and payment.wf_payment_type.id in [5,9,20]: # Precash but waiting for payment (Nachnahme, Vorkasse, Barzahlung bei Abhokung)\n wf_pay_status = 'WAITING'\n elif payment.wf_payment_type.wf_precash_ready:\n wf_pay_status = 'Web_Paid'\n else:\n wf_pay_status = False\n\n ppp_date = False\n if 'ppp_pui_payment_due_date' in record['payment'] and record['payment']['ppp_pui_payment_due_date']:\n ppp_date = datetime.strptime(record['payment']['ppp_pui_payment_due_date'], '%d.%m.%Y')\n # Set Payment Type to \"PaypalPlus Rechnung\"\n wf_payment_type = 24\n result = {'wf_pay_status': wf_pay_status, 'payment_method_id': method_id, 'payment_type': wf_payment_type, 'wf_freight_calc': True, 'wf_transactions_id': record['payment']['last_trans_id'], \\\n 'wf_ppp_iban': record['payment']['ppp_pui_international_bank_account_number'], 'wf_ppp_bank': record['payment']['ppp_pui_bank_name'], 'wf_ppp_bic': record['payment']['ppp_pui_bank_identifier_code'], \\\n 'wf_ppp_holder': record['payment']['ppp_pui_account_holder_name'], 'wf_ppp_due_date': ppp_date}\n \n # decrypt the Payment_data with a php script on Magento_Server and write in Partner Record\n if record['payment']['debit_iban'] and record['payment']['debit_swift']:\n server_url = self.backend_record.location\n IBAN = urllib.quote_plus(record['payment']['debit_iban'])\n BIC = urllib.quote_plus(record['payment']['debit_swift'])\n IBAN_DECODE = requests.get(\"%s/ajaxScripts/encryption.php?key=W55BoOvCaI1Xi7q72mpjz43Io&data=%s\" %(server_url,IBAN))\n BIC_DECODE = requests.get(\"%s/ajaxScripts/encryption.php?key=W55BoOvCaI1Xi7q72mpjz43Io&data=%s\" %(server_url,BIC))\n sess.write('res.partner',self.options.partner_id, {'wf_iban': IBAN_DECODE.content, 'wf_bic': BIC_DECODE.content})\n\n # decrypt the saferpay Payment data with a saferpay api on Magento_Server and write in Partner Record\n if 'saferpay' in record['payment']['method'] and record['payment']['last_trans_id']:\n API = self.get_connector_unit_for_model(SaleOrderAdapter)\n cardrefid = False\n cardmask = False\n cardyear = False\n cardmonth = False\n trans_id = re.search(\"-\", record['payment']['last_trans_id'])\n if trans_id:\n trans_id = record['payment']['last_trans_id'][:trans_id.start()]\n else:\n trans_id = record['payment']['last_trans_id']\n call_result = API._call('saferpaycw_transaction.infoByPaymentId', [trans_id])\n\n for saferpay_data in call_result['data']:\n if saferpay_data['key'] == 'cardRefId':\n cardrefid = saferpay_data['value']\n if saferpay_data['key'] == 'PAN':\n cardmask = saferpay_data['value']\n if saferpay_data['key'] == 'EXP':\n\n cardyear = saferpay_data['value'][-2:]\n cardyear = \"20%s\" % cardyear\n cardmonth = saferpay_data['value'][:2]\n\n if '0' in cardmonth and cardmonth != '10':\n cardmonth = cardmonth[-1]\n sess.write('res.partner',self.options.partner_id, {'wf_cc_pan': cardrefid, 'wf_card_mask': cardmask, 'wf_cc_month': cardmonth, 'wf_cc_year': cardyear})\n\n #tempoary Creditcard encoding\n # decrypt the Payment_data with a php script on Magento_Server and write in Partner Record\n if record['payment']['cc_number_enc'] and 'saferpay' not in record['payment']['method']:\n server_url = self.backend_record.location\n CC_ENC = urllib.quote_plus(record['payment']['cc_number_enc'])\n CC_DECODE = requests.get(\"%s/ajaxScripts/encryption.php?key=W55BoOvCaI1Xi7q72mpjz43Io&data=%s\" %(server_url,CC_ENC))\n sess.write('res.partner',self.options.partner_id, {'wf_cc_pan': CC_DECODE.content, 'wf_cc_year': record['payment']['cc_exp_year'], 'wf_cc_month': record['payment']['cc_exp_month'], 'wf_cc_owner': record['payment']['cc_owner']})\n sess.pool['res.partner'].get_pan(sess.cr, sess.uid,[self.options.partner_id], context=None)\n return result\n\n\n @mapping\n def name(self, record):\n name = record['increment_id']\n prefix = self.backend_record.sale_prefix\n if prefix:\n name = prefix + name\n prio = '3'\n name_num = re.sub('[\\D]', '', name)\n section_id = 2\n if 'ebay' in name or 'ama' in name:\n section_id = 31\n prio = '2'\n return {'client_order_ref': name, 'section_id': section_id, 'client_order_ref_num': name_num, 'wf_prio': prio}\n\n @mapping\n def user_id(self, record):\n #CH Webauftraege User CH\n if self.options.storeview.store_id.id == 3:\n res = {'user_id': 1027}\n else:\n res = {'user_id': 1}\n\n return res\n\n @mapping\n def store_id(self, record):\n auto_picking = self.options.storeview.store_id.openerp_id.wf_so_auto_internal_picking\n workflow_process_id = 1\n if self.options.storeview.store_id.id == 3:\n shop_id = self.options.storeview.store_id.openerp_id.id\n own_location = True\n order_policy = 'manual'\n workflow_process_id = False\n \n elif record['shipping_method'] and record['shipping_method'] == 'Lemundo_AwnCustomShippingMethod_Lemundo_AwnCustomShippingMethod':\n shop_id = int(record['shipping_address']['firstname'])\n own_location = True\n order_policy = 'manual'\n auto_picking = True\n else:\n shop_id = self.options.storeview.store_id.openerp_id.id\n own_location = False\n order_policy = 'picking'\n return {'shop_id': shop_id, 'wf_own_location': own_location, 'order_policy': order_policy, 'create_automatic_internal_picking': auto_picking, 'workflow_process_id': workflow_process_id}\n\n @mapping\n def shipping_method(self, record):\n session = self.session\n ifield = record.get('shipping_method')\n if not ifield:\n return\n \n #bsbs matrixrate_1 is DHL Express for the other use one delivery_carrier \n if ('matrixrate_matrixrate' in ifield and ifield != 'matrixrate_matrixrate_1'):\n ifield = 'dhlint_matrixrate'\n if ifield == 'matrixrate_matrixrate_1':\n ifield = 'dhlint_matrixrate_1'\n\n carrier_ids = session.search('delivery.carrier',\n [('magento_code', '=', ifield)])\n if carrier_ids:\n result = {'carrier_id': carrier_ids[0]}\n else:\n #bsbs if no carrier found use default carrier\n carrier_id = 1\n result = {'carrier_id': carrier_id}\n\n if result['carrier_id'] == 6:\n result.update({'wf_shipping_method': 'collect'})\n return result\n\n @mapping\n def fiscal_position(self, record):\n # set fiscal_position in Sale Order\n if 'shipping_address' not in record:\n return\n fiscal_position = False\n if self.options.storeview.store_id.id == 3:\n with self.session.change_user(1027):\n country_id = self.session.search('res.country',[('code', '=', record['shipping_address']['country_id'])])\n country = self.session.browse('res.country', country_id[0])\n if 'billing_address' in record and 'vat_id' in record['billing_address'] and record['billing_address']['vat_id'] and country.wf_company_fiscal_position:\n fiscal_position = country.wf_company_fiscal_position.id\n elif country.property_account_position:\n fiscal_position = country.property_account_position.id\n \n if not fiscal_position and 'shipping_address_id' in record:\n partner = self.session.browse('magento.address', record['shipping_address_id'])\n\n if partner and partner.openerp_id and partner.openerp_id.property_account_position:\n fiscal_position = partner.openerp_id.property_account_position.id\n else: \n country_id = self.session.search('res.country',[('code', '=', record['shipping_address']['country_id'])])\n country = self.session.browse('res.country', country_id[0])\n if 'billing_address' in record and 'vat_id' in record['billing_address'] and record['billing_address']['vat_id'] and country.wf_company_fiscal_position:\n fiscal_position = country.wf_company_fiscal_position.id\n elif country.property_account_position:\n fiscal_position = country.property_account_position.id\n \n if not fiscal_position and 'shipping_address_id' in record:\n partner = self.session.browse('magento.address', record['shipping_address_id'])\n\n if partner and partner.openerp_id and partner.openerp_id.property_account_position:\n fiscal_position = partner.openerp_id.property_account_position.id\n\n return {'fiscal_position': fiscal_position}\n\n\n @mapping\n def pricelist_id(self, record):\n \"\"\" Assign to the sale order the price list used on\n the Magento Website or Backend \"\"\"\n pricelist_ids = self.session.search(\n 'product.pricelist',\n [('web', '=', record['customer_group_id'])])\n \n if pricelist_ids:\n pricelist_id = pricelist_ids[0]\n else:\n website_binder = self.get_binder_for_model('magento.website')\n oe_website_id = website_binder.to_openerp(record['website_id'])\n website = self.session.browse('magento.website', oe_website_id)\n if website.pricelist_id:\n pricelist_id = website.pricelist_id.id\n else:\n pricelist_id = self.backend_record.pricelist_id.id\n return {'pricelist_id': pricelist_id}\n\n\n@magento_web_fortune\nclass WF_SaleOrderLineImportMapper(SaleOrderLineImportMapper):\n _model_name = 'magento.sale.order.line'\n\n @mapping\n def discount_amount(self, record):\n #discount_value = float(record.get('discount_amount', 0))\n #if self.backend_record.catalog_price_tax_included:\n # row_total = float(record.get('row_total_incl_tax', 0))\n #else:\n # row_total = float(record.get('row_total', 0))\n #discount = 0\n #if discount_value > 0 and row_total > 0:\n # discount = 100 * discount_value / row_total\n #result = {'discount': discount}\n return {'discount': 0}\n\n @mapping\n def product_id(self, record):\n if 'product_options' in record:\n product_options = unserialize(record['product_options'].encode(\"utf-8\"))\n if 'options' in product_options:\n opt = False\n option_id = product_options['options'][0]['option_id']\n option_value = product_options['options'][0]['option_value']\n API = self.get_connector_unit_for_model(ProductProductAdapter, model='magento.product.product')\n call_result = API._call('product_custom_option.info', [option_id])\n if call_result and 'additional_fields' in call_result:\n for val in call_result['additional_fields']:\n if val['value_id'] == option_value:\n opt = val\n if opt:\n #todo to use product_options as individual text without own line add some cutomize code here and do not add additional\n # to add poduct_options as own_line\n if self.session.context:\n self.session.context.update({'wf_product_opt': opt})\n else:\n self.session.context = {'wf_product_opt': opt}\n\n binder = self.get_binder_for_model('magento.product.product')\n product_id = binder.to_openerp(record['product_id'], unwrap=True)\n assert product_id is not None, (\n \"product_id %s should have been imported in \"\n \"SaleOrderImport._import_dependencies\" % record['product_id'])\n #bsbs to get correct Tax in sale Order Line with Module wf_sale_order\n binder = self.get_binder_for_model('magento.storeview')\n binding_id = binder.to_openerp(record['store_id'])\n if binding_id:\n storeview = self.session.browse('magento.storeview',\n binding_id)\n if storeview.store_id and storeview.store_id.openerp_id.company_id:\n self.session.context.update({'company': storeview.store_id.openerp_id.company_id.id})\n\n #bsbs todo get Product Name in correct translation\n product = self.session.pool['product.product'].browse(self.session.cr, self.session.uid, product_id, self.session.context)\n name = '[%s] %s' % (product.default_code,product.name_template)\n \n return {'product_id': product_id, 'name': name}","sub_path":"wf_magento_connector/magento_sale_order.py","file_name":"magento_sale_order.py","file_ext":"py","file_size_in_byte":37278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205109037","text":"import numpy as np\r\nimport pandas as pd\r\n\r\n\r\nclass ReadCsv:\r\n\r\n @staticmethod\r\n def load_csv(self: str, encoding='latin1'):\r\n \"\"\"\r\n It load a file using read mode and a latin encoding.\r\n :return: A readed file\r\n \"\"\"\r\n input_file = open(self, 'r', newline='', encoding=encoding)\r\n return input_file\r\n\r\n @staticmethod\r\n def processing_txt_without_header(self, separator=';', nan_val='?', header=False, change_decimal=False):\r\n \"\"\"\r\n It loads a .txt file as a Dataframe and return a processed df without header\r\n \"\"\"\r\n\r\n df = pd.read_csv(self, sep=separator, header=None, encoding='latin1', quotechar='\"')\r\n if header:\r\n df = df[1:]\r\n\r\n if change_decimal:\r\n df = pd.read_csv(self, sep=separator, header=None, encoding='latin1', quotechar='\"', decimal=',')\r\n\r\n df = df.replace(nan_val, np.nan)\r\n\r\n return df\r\n\r\n @staticmethod\r\n def load_blacklist(self):\r\n input_file = open(self, 'r', newline='\\n', encoding = 'latin1')\r\n return input_file\r\n\r\n","sub_path":"resources/fraud_home/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"521493290","text":"__author__ = 'JMartinez'\n__author__ = 'JMartinez'\nimport orca\nfrom urbansim.models import SegmentedRegressionModel\nimport numpy as np\n\nseg_col = 'building_type_id'\nmin_seg_size = 150\ntransform = np.exp\nfilters_fit = ['improvement_value>10000']\ndefault_model = 'np.log1p(unit_price_non_residential) ~ ln_jobs_within_20min+nonres_far+year_built+ln_dist_bus+ln_dist_rail+' \\\n 'ln_avg_land_value_per_sqft_zone+ln_residential_unit_density_zone+ln_non_residential_sqft_zone+' \\\n 'allpurpose_agglosum_floor+county8001+county8005+county8013+county8014+county8019+county8035+county8039+' \\\n 'county8047+county8059+county8123'\n\nrepm = SegmentedRegressionModel(seg_col,fit_filters=filters_fit, predict_filters=filters_fit,\n default_ytransform=transform, min_segment_size=min_seg_size, default_model_expr=default_model)\n\n\nbuildings = orca.get_table('alts_nrepm').to_frame()\nbuildings = buildings[np.in1d(buildings.building_type_id,[5,8,11,16,17,18,21,23,9,22])]\nsample_index = np.random.choice(buildings.index, 10000, replace=False)\nbuildings = buildings.loc[sample_index]\n\n\nresults = repm.fit(buildings)\nrepm.to_yaml('c:/urbansim_new/urbansim/urbansim_drcog/config/nrepm_yaml.yaml')","sub_path":"urbansim_drcog/nres_estimation.py","file_name":"nres_estimation.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"521045755","text":"inventory = [\"shoes, 12, 29.99\", \"shirts, 20, 9.99\", \"sweatpants, 25, 15.00\", \"scarves, 13, 7.75\"]\nfor item in inventory:\n splittedItem = item.split(', ')\n if len(splittedItem) >= 3:\n result = 'The store has {} {}, each for {} USD'.format(splittedItem[1], splittedItem[0], splittedItem[2])\n print(result)\n\n\n\np_phrase = \"was it a car or a cat I saw\"\nr_phrase = p_phrase[::-1]\nif p_phrase == r_phrase:\n print('YES')\nprint(r_phrase)\n\n#$ p_phrase_without_spaces = p_phrase.replace(' ', '').lower()\n\n\nstopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']\nsent = \"The water earth and air are vital\"\nsplittedSent = sent.split()\nacro = ''\nfor word in splittedSent:\n if not(word in stopwords):\n tmp = word[:2].upper() + '. '\n acro += tmp\n\nacro = acro[:-2]\nprint(acro)\n\nstopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', \"The\"]\norg = \"The organization for health, safety, and education\"\nsplittedOrg = org.split()\nacro = ''\nfor word in splittedOrg:\n if not (word in stopwords):\n acro += word[0].upper()\nprint(acro)\n\n\nscores = \"67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100\"\nsplittedScores = scores.split()\na_scores = 0\nfor score in splittedScores:\n if int(score) >= 90:\n a_scores += 1\nprint(a_scores)","sub_path":"Misc/final_assessment.py","file_name":"final_assessment.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"355179536","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n result = [[]]\n for i in nums:\n result += [r + [i] for r in result]\n return result\n\n\nif __name__ == '__main__':\n nums = [5, 4, 0, 3, 1, 6, 2]\n solution = Solution()\n result = solution.subsets(nums=nums)\n print(result)\n","sub_path":"Medium/78. Subsets/78. Subsets.py","file_name":"78. Subsets.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"214355626","text":"import numpy as np\nimport pickle as cPickle\nimport bz2\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve, auc\nfrom scipy.io import loadmat, savemat\n\n######################################################\n#### Process Animal with Attributes (AwA) Dataset ####\n######################################################\n\n'''\nRequired files\n\t* ./classes.txt\n\t* ./numexamples.txt\n\t* ./testclasses.txt\n\t* ./trainclasses.txt\n\t* ./predicate-matrix-{binary}.txt # when predicate_type = 'binary'\n\t* ./CreatedData/train_features_index.txt\n\t* ./CreatedData/test_features_index.txt\n\t* ./CreatedData/train_featuresVGG19.pic.bz2\n\t* ./CreatedData/test_featuresVGG19.pic.bz2\n'''\n\ndef nameonly(x):\n\treturn x.split('\\t')[1]\n\ndef loadstr(filename,converter=str):\n\treturn [converter(c.strip()) for c in open(filename).readlines()]\n\ndef loaddict(filename,converter=str):\n\tD={}\n\tfor line in open(filename).readlines():\n\t\tline = line.split()\n\t\tD[line[0]] = converter(line[1].strip())\n\t\n\treturn D\n\ndef get_full_animals_dict(path):\n\tanimal_dict = {}\n\twith open(path) as f:\n\t\tfor line in f:\n\t\t\t(key, val) = line.split()\n\t\t\tanimal_dict[val] = int(key)\n\treturn animal_dict\n\ndef get_animal_index(path, filename):\n\tclasses = []\n\tanimal_dict = get_full_animals_dict(path + \"classes.txt\")\n\twith open(path+filename) as infile:\n\t\tfor line in infile:\n\t\t\tclasses.append(line[:-1])\n\treturn [animal_dict[animal]-1 for animal in classes]\n\ndef get_attributes():\n\tattributes = []\n\twith open('attributes.txt') as infile:\n\t\tfor line in infile:\n\t\t\tattributes.append(line[:-1])\n\treturn attributes\n\ndef get_class_attributes(path, name='train', predicate_type='binary'):\n\tanimal_index = get_animal_index(path, name+'classes.txt')\n\tclassAttributes = np.loadtxt(path + \"predicate-matrix-\" + predicate_type + \".txt\", comments=\"#\", unpack=False)\n\treturn classAttributes[animal_index]\n\ndef create_data(path, sample_index, attributes):\n \n\tX = bzUnpickle(path)\n\t\n\tnb_animal_samples = [item[1] for item in sample_index]\n\tfor i,nb_samples in enumerate(nb_animal_samples):\n\t\tif i==0:\n\t\t\ty = np.array([attributes[i,:]]*nb_samples)\n\t\telse:\n\t\t\ty = np.concatenate((y,np.array([attributes[i,:]]*nb_samples)), axis=0)\n\t\n\treturn X,y\n\n\ndef autolabel(rects, ax):\n\t\"\"\"\n\tAttach a text label above each bar displaying its height\n\t\"\"\"\n\tfor rect in rects:\n\t\tif np.isnan(rect.get_height()):\n\t\t\tcontinue\n\t\telse:\n\t\t\theight = rect.get_height()\n\t\tax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%0.3f' % height, \n\t\t\tha='center', va='bottom', rotation=90)\n\n\ndef awa_to_dstruct(predicate_type = 'binary'):\n\n\t# Get features index to recover samples\n\ttrain_index = bzUnpickle('./CreatedData/train_features_index.txt')\n\ttest_index = bzUnpickle('./CreatedData/test_features_index.txt')\n\n\t# Get classes-attributes relationship\n\ttrain_attributes = get_class_attributes('./', name='train', predicate_type=predicate_type)\n\ttest_attributes = get_class_attributes('./', name='test', predicate_type=predicate_type)\n\n\t# Create training Dataset\n\tprint ('Creating training dataset...')\n\tX_train, y_train = create_data('./CreatedData/train_featuresVGG19.pic.bz2',train_index, train_attributes)\n\t\n\t# Convert from sparse to dense array\n\tprint ('X_train to dense...')\n\tX_train = X_train.toarray()\n\n\tprint ('Creating test dataset...')\n\tX_test, y_test = create_data('./CreatedData/test_featuresVGG19.pic.bz2',test_index, test_attributes)\n\n\t# Convert from sparse to dense array\n\tprint ('X_test to dense...')\n\tX_test = X_test.toarray() \n\n\tclassnames = loadstr('classes.txt', nameonly)\n\tnumexamples = loaddict('numexamples.txt', int)\n\ttest_classnames=loadstr('testclasses.txt')\n\ttrain_classnames=loadstr('trainclasses.txt')\n\n\ttest_classes = [ classnames.index(c) for c in test_classnames]\n\ttrain_classes = [ classnames.index(c) for c in train_classnames]\n\n\ttest_output = []\n\tfor idx, c in enumerate(test_classes):\n\t\ttest_output.extend( [idx]*numexamples[classnames[c]] )\n\n\ttrain_output = []\n\tfor idx, c in enumerate(train_classes):\n\t\ttrain_output.extend( [idx]*numexamples[classnames[c]] )\n\n\tdata = {}\n\n\tdata['seen_class_ids'] = np.array(train_classes).astype(np.uint8)\n\tdata['unseen_class_ids'] = np.array(test_classes).astype(np.uint8)\n\n\tdata['seen_data_input'] = X_train\n\tdata['seen_data_output'] = np.array(train_output).astype(np.uint8)\n\t\n\tdata['unseen_data_input'] = X_test\n\tdata['unseen_data_output'] = np.array(test_output).astype(np.uint8)\n\t\n\tdata['seen_attr_mat'] = train_attributes\n\tdata['unseen_attr_mat'] = test_attributes\n\n\treturn data\n\n######################################################\n######### Plotting confusion and roc curves ##########\n######################################################\n\ndef plot_confusion(confusion, classes, wpath = ''):\n\tfig=plt.figure()\n\tplt.imshow(confusion,interpolation='nearest',origin='upper')\n\tplt.clim(0,1)\n\tplt.xticks(np.arange(0,len(classes)),[c.replace('+',' ') for c in classes],rotation='vertical',fontsize=24)\n\tplt.yticks(np.arange(0,len(classes)),[c.replace('+',' ') for c in classes],fontsize=24)\n\tplt.axis([-.5, len(classes)-.5, -.5, len(classes)-.5])\n\tplt.setp(plt.gca().xaxis.get_major_ticks(), pad=18)\n\tplt.setp(plt.gca().yaxis.get_major_ticks(), pad=12)\n\tfig.subplots_adjust(left=0.30)\n\tfig.subplots_adjust(top=0.98)\n\tfig.subplots_adjust(right=0.98)\n\tfig.subplots_adjust(bottom=0.22)\n\tplt.gray()\n\tplt.colorbar(shrink=0.79)\n\tif(len(wpath) == 0):\n\t\tplt.show()\n\telse:\n\t\tplt.savefig(wpath)\n\treturn \n\ndef plot_roc(P, GT, classes, wpath = ''):\n\tAUC=[]\n\tCURVE=[]\n\tfor i,c in enumerate(classes):\n\t\tfp, tp, _ = roc_curve(GT == i, P[:,i])\n\t\troc_auc = auc(fp, tp)\n\t\tprint (\"AUC: %s %5.3f\" % (c,roc_auc))\n\t\tAUC.append(roc_auc)\n\t\tCURVE.append(np.array([fp,tp]))\n\n\tprint (\"----------------------------------\")\n\tprint (\"Mean classAUC %g\" % (np.mean(AUC)*100))\n\n\torder = np.argsort(AUC)[::-1]\n\tstyles=['-','-','-','-','-','-','-','--','--','--']\n\tplt.figure(figsize=(9,5))\n\tfor i in order:\n\t\tc = classes[i]\n\t\tplt.plot(CURVE[i][0],CURVE[i][1],label='%s (AUC: %3.2f)' % (c,AUC[i]),linewidth=3,linestyle=styles[i])\n\t\n\tplt.legend(loc='lower right')\n\tplt.xticks([0.0,0.2,0.4,0.6,0.8,1.0], [r'$0$', r'$0.2$',r'$0.4$',r'$0.6$',r'$0.8$',r'$1.0$'],fontsize=18)\n\tplt.yticks([0.0,0.2,0.4,0.6,0.8,1.0], [r'$0$', r'$0.2$',r'$0.4$',r'$0.6$',r'$0.8$',r'$1.0$'],fontsize=18)\n\tplt.xlabel('false positive rate',fontsize=18)\n\tplt.ylabel('true positive rate',fontsize=18)\n\tif(len(wpath) == 0): plt.show()\n\telse: plt.savefig(wpath)\n\treturn AUC, CURVE\n\n\ndef plot_attAUC(P, y_true, wpath, attributes = None):\n\tAUC=[]\n\tif(attributes is None):\n\t\tattributes = map(str, range(y_true.shape[1]))\n\n\tfor i in range(y_true.shape[1]):\n\t\tfp, tp, _ = roc_curve(y_true[:,i], P[:,i])\n\t\troc_auc = auc(fp, tp)\n\t\tAUC.append(roc_auc)\n\tprint (\"Mean attrAUC %g\" % (np.nanmean(AUC)) )\n\n\txs = np.arange(y_true.shape[1])\n\twidth = 0.5\n\n\t# fig = plt.figure(figsize=(15,5))\n\tfig = plt.figure()\n\tax = fig.add_subplot(1,1,1)\n\trects = ax.bar(xs, AUC, width, align='center')\n\tax.set_xticks(xs)\n\tax.set_xticklabels(attributes, rotation=90)\n\tax.set_ylabel(\"area under ROC curve\")\n\tautolabel(rects, ax)\n\tif(len(wpath) == 0): plt.show()\n\telse: plt.savefig(wpath)\n\treturn AUC\n\n######################################################\n################## General functions #################\n######################################################\n\ndef bzPickle(obj,filename):\n\tf = bz2.BZ2File(filename, 'wb')\n\tcPickle.dump(obj, f)\n\tf.close()\n\ndef bzUnpickle(filename):\n\treturn cPickle.load(bz2.BZ2File(filename))\n\ndef print_dict(dict_inst, idx = 1):\n\tfor key, value in dict_inst.items():\n\t\tif(isinstance(value, dict)):\n\t\t\tprint('\\t'*(idx-1), key, ': ')\n\t\t\tprint_dict(value, idx = idx+1)\n\t\telse:\n\t\t\tprint('\\t'*idx, key, ': ', end = '')\n\t\t\tif(isinstance(value, np.ndarray)):\n\t\t\t\tprint(value.shape)\n\t\t\telse: print(value)\n\n######################################################\n####################### Others #######################\n######################################################\n\ndef reformat_dstruct(data_path):\n\t'''\n\t\tDescription:\n\t\t\tConvert the ZSL data file that we have in Windows/Matlab into a\n\t\t\tformat compatible with python DAP codes. \n\t\tInput:\n\t\t\tdata_path: path to the .mat file. This file has a matlab struct variable 'dstruct'\n\t\t\t\tExample: # r'/home/isat-deep/Desktop/Naveen/fg2020/data/raw_feat_data/data_0.11935.mat'\n\t\tOutput: \n\t\t\tdata: dictionary with the following keys\n\t\t\t\t1. seen_data_input: np.ndarray (train_num_instances x feature_size)\n\t\t\t\t2. unseen_data_input: np.ndarray (test_num_instances x feature_size)\n\t\t\t\t3. seen_data_output: np.ndarray (train_num_instances, )\n\t\t\t\t4. unseen_data_output : np.ndarray (test_num_instances, )\n\t\t\t\t5. seen_class_ids: np.ndarray (num_seen_classes, )\n\t\t\t\t6. unseen_class_ids: np.ndarray (num_unseen_classes, )\n\t\t\t\t7. seen_attr_mat: np.ndarray (num_seen_classes, num_attributes)\n\t\t\t\t8. unseen_attr_mat: np.ndarray (num_unseen_classes, num_attributes)\n\n\t'''\n\tx = loadmat(data_path, struct_as_record = False, squeeze_me = True)['dstruct']\n\n\timp_keys = ['unseen_class_ids', 'seen_class_ids', 'seen_data_input', 'unseen_data_input', \\\n\t\t\t\t'seen_data_output', 'unseen_data_output', 'seen_attr_mat', 'unseen_attr_mat']\n\n\tdata = {}\n\tfor key in imp_keys:\n\t\tdata[key] = getattr(x, key)\n\tdel x\n\n\tdata['seen_data_input'] = data['seen_data_input'].astype(np.float)\n\tdata['unseen_data_input'] = data['unseen_data_input'].astype(np.float)\n\n\tdata['seen_data_output'] = data['seen_data_output'].astype(np.uint8) - 1 # Matlab indices start from 1\n\tdata['unseen_data_output'] = data['unseen_data_output'].astype(np.uint8) - 1 # Matlab indices start from 1\n\t\n\tdata['seen_class_ids'] = data['seen_class_ids'].astype(np.uint8) - 1 # Matlab indices start from 1\n\tdata['unseen_class_ids'] = data['unseen_class_ids'].astype(np.uint8) - 1 # Matlab indices start from 1\n\n\treturn data","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"572501034","text":"class TopNList(object):\n\tdef __init__(self,n,reverse=False,value_func=lambda x:x):\n\t\tif n<=0:\n\t\t\traise Exception(\"n must be a postive integer\")\n\t\tself.n=n\n\t\tself.value_func=value_func\n\t\tself.compare_func=(lambda x,y:x>y) if reverse else (lambda x,y:xself.n:\n\t\t\t\t\t\tself._data.pop()\n\t\t\t\t\tbreak\n\t\t\t\tif index==len(self._data)-1:\n\t\t\t\t\tself._data.insert(0,value)\n\t\t\t\t\tif len(self._data)>self.n:\n\t\t\t\t\t\tself._data.pop()\n\t\t\t\t\tbreak\n\t\t\t\n\n\tdef __len__(self):\n\t\treturn len(self._data)\n\n\tdef __iter__(self):\n\t\tself.index=0\n\t\treturn self\n\n\tdef __getitem__(self,index):\n\t\treturn self._data[index]\n\n\tdef next(self):\n\t\tif self.index == len(self):\n\t\t\traise StopIteration\n\t\tres=self._data[self.index]\n\t\tself.index = self.index + 1\n\t\treturn res\n","sub_path":"youlil/api/rec_api/rec/utils/topnlist.py","file_name":"topnlist.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"362821233","text":"#!/usr/bin/python\nimport sys\nimport time\nimport RPi.GPIO as GPIO\nfrom pi_sht1x import SHT1x\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(24, GPIO.OUT)\nGPIO.output(24, 1)\ntry:\n\twhile 1:\n\t\tGPIO.setmode(GPIO.BCM)\n\t\tGPIO.setup(24, GPIO.OUT)\n\t\ttime.sleep(3)\n\t\twith SHT1x(18, 23, gpio_mode=GPIO.BCM) as sensor:\n\t\t temp = sensor.read_temperature()\n\t\t humidity = sensor.read_humidity(temp)\n\t\t sensor.calculate_dew_point(temp, humidity)\n\t\t print(temp)\n\t\t print(humidity)\n\t\t if temp>32:\n\t\t GPIO.output(24, 0)\n\t\t print(\"veca...\")\n\t\t else:\n\t\t print(\"manja...\")\n\t\t GPIO.output(24, 1)\nfinally:\n GPIO.cleanup() # this ensures a clean exit\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406938100","text":"import cv2\nimport ps5\nimport os\nimport numpy as np\nimport multi_filter\n\n\ndef run_kalman_filter(kf, imgs_dir, noise, sensor, save_frames={},\n template_loc=None):\n\n imgs_list = [f for f in os.listdir(imgs_dir)\n if f[0] != '.' and f.endswith('.jpg')]\n imgs_list.sort()\n\n frame_num = 0\n\n if sensor == \"hog\":\n hog = cv2.HOGDescriptor()\n hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\n elif sensor == \"matching\":\n frame = cv2.imread(os.path.join(imgs_dir, imgs_list[0]))\n # template = frame[template_loc['y']:\n # template_loc['y'] + template_loc['h'],\n # template_loc['x']:\n # template_loc['x'] + template_loc['w']]\n template = multi_filter.get_template_3()\n\n else:\n raise ValueError(\"Unknown sensor name. Choose between 'hog' or \"\n \"'matching'\")\n\n for img in imgs_list:\n\n frame = cv2.imread(os.path.join(imgs_dir, img))\n if frame_num < 25:\n frame_num += 1\n continue\n\n # Sensor\n if sensor == \"hog\":\n (rects, weights) = hog.detectMultiScale(frame, winStride=(4, 4),\n padding=(8, 8), scale=1.05)\n\n if len(weights) > 0:\n max_w_id = np.argmax(weights)\n z_x, z_y, z_w, z_h = rects[max_w_id]\n\n z_x += z_w // 2\n z_y += z_h // 2\n\n z_x += np.random.normal(0, noise['x'])\n z_y += np.random.normal(0, noise['y'])\n\n elif sensor == \"matching\":\n corr_map = cv2.matchTemplate(frame, template, cv2.TM_SQDIFF)\n z_y, z_x = np.unravel_index(np.argmin(corr_map), corr_map.shape)\n\n z_w = template.shape[1]\n z_h = template.shape[0]\n\n z_x += z_w // 2 + np.random.normal(0, noise['x'])\n z_y += z_h // 2 + np.random.normal(0, noise['y'])\n\n x, y = kf.process(z_x, z_y)\n if frame_num == 36:\n x_int = int(x) - 15\n y_int = int(y)\n h_2 = int(template.shape[0]/2)\n w_2 = int(template.shape[1]/2) + 20\n template = frame[y_int-h_2:y_int + h_2+1, x_int-w_2:x_int + w_2]\n cv2.imwrite(\"out/new_template.png\", template)\n\n if frame_num == 55:\n x_int = int(x)+5\n y_int = int(y) + 10\n h_2 = int(template.shape[0]/2) + 20\n w_2 = int(template.shape[1]/2)\n template = frame[y_int-h_2:y_int + h_2+1, x_int-w_2:x_int + w_2]\n cv2.imwrite(\"out/new_template.png\", template)\n\n if frame_num == 65:\n x_int = int(x)\n y_int = int(y)\n h_2 = int(template.shape[0]/2)\n w_2 = int(template.shape[1]/2)\n template = frame[y_int-h_2:y_int + h_2+1, x_int-w_2:x_int + w_2]\n cv2.imwrite(\"out/new_template.png\", template)\n\n\n if True: # For debugging, it displays every frame\n out_frame = frame.copy()\n cv2.circle(out_frame, (int(z_x), int(z_y)), 20, (0, 0, 255), 2)\n cv2.circle(out_frame, (int(x), int(y)), 10, (255, 0, 0), 2)\n cv2.rectangle(out_frame, (int(z_x) - z_w // 2, int(z_y) - z_h // 2),\n (int(z_x) + z_w // 2, int(z_y) + z_h // 2),\n (0, 0, 255), 2)\n\n cv2.imshow('Tracking', out_frame)\n cv2.waitKey(1)\n\n # Render and save output, if indicated\n if frame_num in save_frames:\n frame_out = frame.copy()\n cv2.circle(frame_out, (int(x), int(y)), 10, (255, 0, 0), 2)\n cv2.imwrite(save_frames[frame_num], frame_out)\n\n # Update frame number\n frame_num += 1\n if frame_num % 20 == 0:\n print('Working on frame {}'.format(frame_num))\n","sub_path":"object_tracking/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238150262","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport time\nimport math\nimport numpy as np\nfrom random import randrange, uniform\nfrom multiprocessing import Process\n\ndef convert_tga_to_rk(rr,rt,hr,Y=1):\n #[rr]=/s,[rt]=°C,[hr]=K/min, [E]=J/mol, [A]=1/s\n rt=rt+273.15\n hr=hr/60\n E=(math.exp(1)*rr*8.3145*(rt**2))/hr\n A=(math.exp(1)*rr*math.exp(E/(8.3145*rt)))\n return(A,E)\n\ndef reactionrate(A,E,y,T):\n r=A*y*math.exp(-E/8.3145/T)\n return(r)\n\ndef calculate_reaction(A,E,Ys,T0=20,T1=550,HR=5.,dt=5):\n Y=Ys.copy()\n T0,T1=T0+273.15,T1+273.15\n x=np.zeros(((int((T1-T0)*(60./(HR*dt))+1),3)))\n x[:,0]=np.linspace(T0,T1,int((T1-T0)*(60./(HR*dt))+1))\n for i in x:\n k=0\n for c,t in enumerate(Y):\n if Y[c] == 0:\n pass\n else:\n r=reactionrate(A[c],E[c],Y[c],i[0])\n Y[c]=Y[c]-(r*dt)\n k=k+r\n if Y[c]<0:\n r,Y[c]=0,0\n i[2]=sum(Y)\n i[1]=k\n x[:,0]=x[:,0]-273.15\n return(x.T)\n\ndef generate(dataset,nr):\n dataset=np.array(dataset)\n feat=[]\n np.savetxt(\"./labels{}k_5_10_30_40_2r_2ks_{}.csv\".format(int(i/1000),int(nr)), np.copy(dataset.reshape(int((i/cores)*a),18)), delimiter=\",\")\n for ik,each1 in enumerate(np.copy(dataset)):\n each=each1.copy()\n temp1,masslossrate1,massloss1=calculate_reaction(each[3],each[4],each[2],HR=5.,dt=24,T0=Tstart, T1=Tend)\n each=each1.copy()\n temp2,masslossrate2,massloss2=calculate_reaction(each[3],each[4],each[2],HR=10.,dt=12,T0=Tstart, T1=Tend)\n each=each1.copy()\n temp3,masslossrate3,massloss3=calculate_reaction(each[3],each[4],each[2],HR=30., dt=4,T0=Tstart, T1=Tend)\n each=each1.copy()\n temp4,masslossrate4,massloss4=calculate_reaction(each[3],each[4],each[2],HR=40., dt=3,T0=Tstart, T1=Tend)\n feat.append((temp1,temp2,temp3,temp4,masslossrate1,masslossrate2,masslossrate3,masslossrate4,massloss1,massloss2,massloss3,massloss4))\n scale=len(temp1)\n feat=np.array(feat)\n print('{} done'.format(int(nr)))\n np.savetxt(\"./features{}k_5_10_30_40_2r_2ks_{}.csv\".format(int(i/1000),nr), (np.copy(feat[:,4:8])).reshape(int(i/cores),scale*4), delimiter=\",\")\n\n##################################\n### Parameters defined by user ###\n##################################\n\n# i: number of elements that will be generated\n# cores: number of cores \n# rrlimlow: lower boundary of peak reaction rate sampling (in /s)\n# rrlimup: upper boundary of peak reaction rate sampling (in /s)\n# rtlimlow: lower boundary of peak reaction rate sampling (in °C)\n# rtlimup: upper boundary of peak reaction rate sampling (in °C)\n# Tstart: Start temperature of experiment (in °C)\n# Tend: End temperature of experiment (in °C)\n\n# Note: i/cores must be an integer\n\ni=6400000\ncores=128\nrrlimlow=0.001\nrrlimup= 0.01\nrtlimlow= 100\nrtlimup= 500\nTstart=20\nTend=550\n\n# RR/RT for 2 components\na=1\ndataset=[]\nfor each in range(i):\n ia=round(uniform(0,1),4)\n ib=1-ia\n ic=0\n RR,RT=round(uniform(rrlimlow,rrlimup),6),randrange(rtlimlow,rtlimup)\n RR2,RT2=round(uniform(rrlimlow,rrlimup),6),randrange(rtlimlow,rtlimup)\n RR3,RT3=0,0\n E,A=[0,0,0],[0,0,0]\n A[0],E[0]=convert_tga_to_rk(RR,RT,5,ia)\n A[1],E[1]=convert_tga_to_rk(RR2,RT2,5,ib)\n dataset.append(([RR,RR2,RR3],[RT,RT2,RT3],[ia,ib,ic],A,E,[ia,ib,ic]))\n\nstarttime=time.time()\ndataset=np.array(dataset)\nnp.savetxt(\"./labels{}k_5_10_40_2r_2ks.csv\".format(int(i/1000)), np.copy(dataset.reshape(i*a,18)), delimiter=\",\")\n\n# calculate MLR\n\nif __name__ == '__main__':\n processes = []\n for n in range(cores):\n p=Process(target=generate, args=(dataset[int((n*(i/cores))):int(((i/cores)+n*(i/cores)))],n,))\n processes.append(p)\n\n for p in processes:\n p.start()\n for p in processes:\n p.join()\nendtime=time.time()\nduration=endtime-starttime\nprint(duration)\n","sub_path":"generate_db/generate_2c.py","file_name":"generate_2c.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"533236778","text":"import gzip\nimport random\nimport string\nimport time\nimport timeit\n\nimport mock\nimport pytest\n\nfrom elasticapm.transport.base import AsyncTransport, Transport, TransportException, TransportState\nfrom elasticapm.utils import compat\nfrom tests.fixtures import DummyTransport, TempStoreClient\n\n\ndef test_transport_state_should_try_online():\n state = TransportState()\n assert state.should_try() is True\n\n\ndef test_transport_state_should_try_new_error():\n state = TransportState()\n state.status = state.ERROR\n state.last_check = timeit.default_timer()\n state.retry_number = 1\n assert state.should_try() is False\n\n\ndef test_transport_state_should_try_time_passed_error():\n state = TransportState()\n state.status = state.ERROR\n state.last_check = timeit.default_timer() - 10\n state.retry_number = 1\n assert state.should_try() is True\n\n\ndef test_transport_state_set_fail():\n state = TransportState()\n state.set_fail()\n assert state.status == state.ERROR\n assert state.last_check is not None\n assert state.retry_number == 0\n\n\ndef test_transport_state_set_success():\n state = TransportState()\n state.status = state.ERROR\n state.last_check = \"foo\"\n state.retry_number = 5\n state.set_success()\n assert state.status == state.ONLINE\n assert state.last_check is None\n assert state.retry_number == -1\n\n\n@mock.patch(\"elasticapm.transport.base.Transport.send\")\ndef test_empty_queue_flush_is_not_sent(mock_send):\n transport = Transport(metadata={\"x\": \"y\"}, max_flush_time=5)\n try:\n transport.flush()\n assert mock_send.call_count == 0\n finally:\n transport.close()\n\n\n@mock.patch(\"elasticapm.transport.base.Transport.send\")\ndef test_metadata_prepended(mock_send):\n transport = Transport(metadata={\"x\": \"y\"}, max_flush_time=5, compress_level=0)\n transport.queue(\"error\", {}, flush=True)\n transport.close()\n assert mock_send.call_count == 1\n args, kwargs = mock_send.call_args\n if compat.PY2:\n data = gzip.GzipFile(fileobj=compat.StringIO(args[0])).read()\n else:\n data = gzip.decompress(args[0])\n data = data.decode(\"utf-8\").split(\"\\n\")\n assert \"metadata\" in data[0]\n\n\n@mock.patch(\"elasticapm.transport.base.Transport.send\")\ndef test_flush_time(mock_send, caplog):\n with caplog.at_level(\"DEBUG\", \"elasticapm.transport\"):\n transport = Transport(metadata={}, max_flush_time=0.1)\n # let first run finish\n time.sleep(0.2)\n transport.close()\n record = caplog.records[0]\n assert \"0.1\" in record.message\n assert mock_send.call_count == 0\n\n\n@mock.patch(\"elasticapm.transport.base.Transport._flush\")\ndef test_flush_time_size(mock_flush, caplog):\n transport = Transport(metadata={}, max_buffer_size=100, queue_chill_count=1)\n with caplog.at_level(\"DEBUG\", \"elasticapm.transport\"):\n # we need to add lots of uncompressible data to fill up the gzip-internal buffer\n for i in range(12):\n transport.queue(\"error\", \"\".join(random.choice(string.ascii_letters) for i in range(2000)))\n transport._flushed.wait(timeout=0.1)\n assert mock_flush.call_count == 1\n transport.close()\n\n\n@mock.patch(\"elasticapm.transport.base.Transport.send\")\ndef test_forced_flush(mock_send, caplog):\n transport = Transport(metadata={}, max_buffer_size=1000, compress_level=0)\n with caplog.at_level(\"DEBUG\", \"elasticapm.transport\"):\n transport.queue(\"error\", \"x\", flush=True)\n transport.close()\n assert mock_send.call_count == 1\n assert transport._queued_data is None\n\n\n@mock.patch(\"elasticapm.transport.base.Transport.send\")\ndef test_sync_transport_fail_and_recover(mock_send, caplog):\n transport = Transport()\n try:\n mock_send.side_effect = TransportException(\"meh\")\n transport.queue(\"x\", {})\n transport.flush()\n assert transport.state.did_fail()\n # first retry should be allowed immediately\n assert transport.state.should_try()\n\n # recover\n mock_send.side_effect = None\n transport.queue(\"x\", {})\n transport.flush()\n assert not transport.state.did_fail()\n finally:\n transport.close()\n\n\n@pytest.mark.parametrize(\"sending_elasticapm_client\", [{\"api_request_time\": \"2s\"}], indirect=True)\ndef test_send_timer(sending_elasticapm_client, caplog):\n with caplog.at_level(\"DEBUG\", \"elasticapm.transport\"):\n assert sending_elasticapm_client.config.api_request_time == 2000\n sending_elasticapm_client.begin_transaction(\"test_type\")\n sending_elasticapm_client.end_transaction(\"test\")\n\n sending_elasticapm_client._transport.flush()\n\n assert \"Sent request\" in caplog.records[1].message\n\n\n@mock.patch(\"tests.fixtures.DummyTransport._start_event_processor\")\n@mock.patch(\"elasticapm.transport.base.is_master_process\")\ndef test_client_doesnt_start_processor_thread_in_master_process(is_master_process, mock_start_event_processor):\n # when in the master process, the client should not start worker threads\n is_master_process.return_value = True\n before = mock_start_event_processor.call_count\n client = TempStoreClient(server_url=\"http://example.com\", service_name=\"app_name\", secret_token=\"secret\")\n assert mock_start_event_processor.call_count == before\n client.close()\n\n is_master_process.return_value = False\n before = mock_start_event_processor.call_count\n client = TempStoreClient(server_url=\"http://example.com\", service_name=\"app_name\", secret_token=\"secret\")\n assert mock_start_event_processor.call_count == before + 1\n client.close()\n\n\ndef test_compress_level_sanitization():\n assert DummyTransport(compress_level=None, url=\"\")._compress_level == 0\n assert DummyTransport(compress_level=-1, url=\"\")._compress_level == 0\n assert DummyTransport(compress_level=10, url=\"\")._compress_level == 9\n","sub_path":"tests/transports/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"16490655","text":"import sys\nimport os\n\nimport pandas as pd\nimport csv\n\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\n\nimport networkx as nx\n\nimport spaligner_parser\nfrom gfa_parser import gfa_to_G\n\nimport graphs\nimport clustering\n\n\ndef tsv_to_sets(tsv, min_component_size=3):\n clusters = set()\n with open(tsv, 'r') as fin:\n for line in fin:\n path = frozenset(line.strip().split(','))\n if len(path) < min_component_size:\n continue\n clusters.add(path)\n print(tsv + ': {} clusters'.format(len(clusters)))\n return clusters\n\n\ndef write_clustering(clustering, tsv, min_clusters_size=2):\n with open(tsv, 'w') as outfile:\n for cluster in clustering:\n if len(cluster) < min_clusters_size:\n continue\n outfile.write(','.join([str(x) for x in cluster]) + '\\n')\n\n\ndef jaccard_similarity(set1, set2):\n up = len(set1.intersection(set2))\n down = len(set1.union(set2))\n # print('Intersection:')\n # for c in set1.intersection(set2):\n # print(c)\n # print('Ground truth - clustering: ')\n # for c in set2 - set1:\n # print(c)\n print('Exact reconstruction: {}'.format(up))\n print('Clusters in total: {}'.format(down))\n return up / down\n\ndef F1_for_two_clusters(reconstructed_cluster, ground_truth_cluster):\n precision = \\\n len(ground_truth_cluster.intersection(reconstructed_cluster)) / \\\n len(reconstructed_cluster)\n recall = \\\n len(ground_truth_cluster.intersection(reconstructed_cluster)) / \\\n len(ground_truth_cluster)\n if precision + recall != 0:\n F1 = 2 * precision * recall / (precision + recall)\n else:\n F1 = 0\n return F1\n\ndef F1_best_match(r_cluster, ground_truth_set, fout):\n F1_best_match = 0\n cluster_best_match = None\n for gt_cluster in ground_truth_set:\n F1_curr = F1_for_two_clusters(r_cluster, gt_cluster)\n if F1_best_match <= F1_curr:\n F1_best_match = F1_curr\n cluster_best_match = gt_cluster\n if F1_best_match != 1:\n fout.write(' '.join(sorted(r_cluster)) + '\\n' + ' '.join(sorted(cluster_best_match)) + '\\n\\n')\n return F1_best_match\n\ndef F1_for_clustering(reconstructed_set, ground_truth_set, outdir):\n F1 = 0\n not_reconstructed_txt = os.path.join(outdir, 'not_reconstructed.debug')\n with open(not_reconstructed_txt, 'w') as fout:\n for r_cluster in reconstructed_set:\n F1 += F1_best_match(r_cluster, ground_truth_set, fout)\n F1 /= len(reconstructed_set)\n return F1\n\ndef exact_recall(reconstructed_set, ground_truth_set):\n up = len(reconstructed_set.intersection(ground_truth_set))\n down = len(ground_truth_set)\n return up / down\n\ndef evaluate_clustering(reconstructed_clustering_tsv, ground_truth_clustering_tsv, outdir):\n short_report_txt = os.path.join(outdir, 'short_report.txt')\n\n reconstructed_clusters = tsv_to_sets(reconstructed_clustering_tsv)\n ground_truth_clusters = tsv_to_sets(ground_truth_clustering_tsv)\n\n J = jaccard_similarity(reconstructed_clusters, ground_truth_clusters)\n print('Jaccard similarity: %.3f' % J)\n\n recall = exact_recall(reconstructed_clusters, ground_truth_clusters)\n print('Recall: %.3f' % recall)\n\n F1 = F1_for_clustering(reconstructed_clusters, ground_truth_clusters, outdir)\n print('F1 score: %.3f' % F1)\n\n with open(short_report_txt, 'w') as fout:\n fout.write('Jaccard similarity: %.3f\\n' % J)\n fout.write('Recall: %.3f\\n' % recall)\n fout.write('F1 score: %.3f\\n' % F1)\n\ndef get_node_colors(G, c_dict):\n clusters = []\n for node in G.nodes:\n clusters.append(c_dict[node])\n size = len(set(clusters))\n node_colors = [str(cluster * 1.0 / size) for cluster in clusters]\n return node_colors\n\ndef plot_components_clusters(G, c_list, weight, outdir, n=4):\n c_dict = clustering.clusters_list_to_dict(c_list)\n pos = nx.spring_layout(G)\n largest_components = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[:n]\n for i, component in enumerate(largest_components):\n colors = get_node_colors(component, c_dict)\n edge_labels = graphs.truncate_values(nx.get_edge_attributes(G, weight), component.edges)\n nx.draw_networkx_nodes(component, pos=pos, node_color=colors)\n nx.draw_networkx_labels(component, pos, font_size=5)\n nx.draw_networkx_edges(component, pos, alpha=0.5)\n nx.draw_networkx_edge_labels(component, pos=pos, font_size=5, edge_labels=edge_labels)\n plt.savefig(os.path.join(outdir, '{}.{}.png'.format(G.name, i)))\n plt.clf()\n\ndef plot_graph_clusters(G, c_list, outdir):\n size = float(len(c_list))\n pos = nx.spring_layout(G)\n for i, com in enumerate(c_list):\n nx.draw_networkx_nodes(G, pos, com, node_size=20, node_color=str(i / size))\n nx.draw_networkx_edges(G, pos, alpha=0.5)\n plt.savefig(os.path.join(outdir, '{}.png'.format(G.name)))\n plt.clf()\n\n\ndef main():\n clustering_tsv = sys.argv[1]\n spaligner_tsv = sys.argv[2]\n gfa = sys.argv[3]\n k = int(sys.argv[4])\n outdir = os.path.join(sys.argv[5])\n\n spaligner_clustering_tsv = \\\n spaligner_parser.spaligner_to_clustering_tsv(spaligner_tsv,\n os.path.join(outdir, 'spaligner_clustering.tsv'),\n gfa_to_G(gfa, k))\n evaluate_clustering(clustering_tsv, spaligner_clustering_tsv, outdir)\n\n\nif __name__ == '__main__':\n main()","sub_path":"evaluating_clustering.py","file_name":"evaluating_clustering.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"446422200","text":"import json\nimport os\nimport platform\nimport random\nimport shutil\nimport string\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nfrom .helpers import *\n\n\nclass TestCreate:\n\n current_root_prefix = os.environ[\"MAMBA_ROOT_PREFIX\"]\n current_prefix = os.environ[\"CONDA_PREFIX\"]\n cache = os.path.join(current_root_prefix, \"pkgs\")\n\n env_name = random_string()\n root_prefix = os.path.expanduser(os.path.join(\"~\", \"tmproot\" + random_string()))\n prefix = os.path.join(root_prefix, \"envs\", env_name)\n other_prefix = os.path.expanduser(os.path.join(\"~\", \"tmproot\" + random_string()))\n\n @classmethod\n def setup_class(cls):\n os.environ[\"MAMBA_ROOT_PREFIX\"] = TestCreate.root_prefix\n os.environ[\"CONDA_PREFIX\"] = TestCreate.prefix\n\n # speed-up the tests\n os.environ[\"CONDA_PKGS_DIRS\"] = TestCreate.cache\n\n @classmethod\n def setup(cls):\n os.makedirs(TestCreate.root_prefix, exist_ok=False)\n\n @classmethod\n def teardown_class(cls):\n os.environ[\"MAMBA_ROOT_PREFIX\"] = TestCreate.current_root_prefix\n os.environ[\"CONDA_PREFIX\"] = TestCreate.current_prefix\n\n @classmethod\n def teardown(cls):\n os.environ[\"MAMBA_ROOT_PREFIX\"] = TestCreate.root_prefix\n os.environ[\"CONDA_PREFIX\"] = TestCreate.prefix\n shutil.rmtree(TestCreate.root_prefix)\n if Path(TestCreate.other_prefix).exists():\n shutil.rmtree(TestCreate.other_prefix)\n\n @pytest.mark.parametrize(\"root_prefix_env_var\", [False, True])\n @pytest.mark.parametrize(\n \"env_selector,outside_root_prefix\",\n [(\"prefix\", False), (\"prefix\", True), (\"name\", False)],\n )\n def test_create(self, root_prefix_env_var, env_selector, outside_root_prefix):\n if not root_prefix_env_var:\n os.environ.pop(\"MAMBA_ROOT_PREFIX\")\n cmd = (\"-r\", TestCreate.root_prefix, \"xtensor\", \"--json\")\n else:\n cmd = (\"xtensor\", \"--json\")\n\n if outside_root_prefix:\n p = TestCreate.other_prefix\n else:\n p = TestCreate.prefix\n\n if env_selector == \"prefix\":\n res = create(\"-p\", p, *cmd)\n elif env_selector == \"name\":\n res = create(\"-n\", TestCreate.env_name, *cmd)\n\n assert res[\"success\"]\n assert res[\"dry_run\"] == dry_run_tests\n\n keys = {\"success\", \"prefix\", \"actions\", \"dry_run\"}\n assert keys.issubset(set(res.keys()))\n\n action_keys = {\"LINK\", \"PREFIX\"}\n assert action_keys.issubset(set(res[\"actions\"].keys()))\n\n packages = {pkg[\"name\"] for pkg in res[\"actions\"][\"LINK\"]}\n expected_packages = {\"xtensor\", \"xtl\"}\n assert expected_packages.issubset(packages)\n\n if not dry_run_tests:\n pkg_name = get_concrete_pkg(res, \"xtensor\")\n orig_file_path = get_pkg(\n pkg_name, xtensor_hpp, TestCreate.current_root_prefix\n )\n assert orig_file_path.exists()\n\n @pytest.mark.parametrize(\"env_selector\", [\"prefix\", \"name\"])\n @pytest.mark.parametrize(\"root_non_empty\", [False, True])\n def test_create_base(self, root_non_empty, env_selector):\n\n with open(os.path.join(TestCreate.root_prefix, \"some_file\"), \"w\") as f:\n f.write(\"abc\")\n\n with pytest.raises(subprocess.CalledProcessError):\n if env_selector == \"prefix\":\n create(\"-p\", TestCreate.root_prefix, \"xtensor\")\n elif env_selector == \"name\":\n create(\"-n\", \"base\", \"xtensor\")\n\n @pytest.mark.parametrize(\n \"alias\",\n [\n \"\",\n \"https://conda.anaconda.org/\",\n \"https://repo.mamba.pm/\",\n \"https://repo.mamba.pm\",\n ],\n )\n def test_channel_alias(self, alias):\n if alias:\n res = create(\n \"-n\",\n TestCreate.env_name,\n \"xtensor\",\n \"--json\",\n \"--dry-run\",\n \"--channel-alias\",\n alias,\n )\n ca = alias.rstrip(\"/\")\n else:\n res = create(\"-n\", TestCreate.env_name, \"xtensor\", \"--json\", \"--dry-run\")\n ca = \"https://conda.anaconda.org\"\n\n for l in res[\"actions\"][\"LINK\"]:\n assert l[\"channel\"].startswith(f\"{ca}/conda-forge/\")\n assert l[\"url\"].startswith(f\"{ca}/conda-forge/\")\n\n @pytest.mark.parametrize(\n \"channels\", [None, \"both\", \"CLI_only\", \"file_only\", \"file_empty\"]\n )\n @pytest.mark.parametrize(\"env_name\", [None, \"both\", \"CLI_only\", \"file_only\"])\n @pytest.mark.parametrize(\"specs\", [None, \"both\", \"CLI_only\", \"file_only\"])\n def test_yaml_spec_file(self, channels, env_name, specs):\n spec_file_content = []\n if env_name in (\"both\", \"file_only\"):\n spec_file_content += [f\"name: {TestCreate.env_name}\"]\n if channels in (\"both\", \"file_only\"):\n spec_file_content += [\"channels:\", \" - https://repo.mamba.pm/conda-forge\"]\n if specs in (\"both\", \"file_only\"):\n spec_file_content += [\"dependencies:\", \" - xtensor\", \" - xsimd\"]\n if specs == \"file_empty\":\n spec_file_content += [\"dependencies: ~\"]\n\n yaml_spec_file = os.path.join(TestCreate.root_prefix, \"yaml_env.yml\")\n with open(yaml_spec_file, \"w\") as f:\n f.write(\"\\n\".join(spec_file_content))\n\n cmd = []\n\n if specs not in (\"file_only\", None):\n cmd += [\"xframe\"]\n\n if env_name not in (\"file_only\", None):\n cmd += [\"-n\", \"override_name\"]\n\n if channels not in (\"file_only\", None):\n cmd += [\"-c\", \"https://conda.anaconda.org/conda-forge\"]\n\n cmd += [\"-f\", yaml_spec_file, \"--json\"]\n\n if specs is None or env_name is None or specs == \"CLI_only\" or channels is None:\n with pytest.raises(subprocess.CalledProcessError):\n create(*cmd, default_channel=False)\n else:\n res = create(*cmd, default_channel=False)\n\n keys = {\"success\", \"prefix\", \"actions\", \"dry_run\"}\n assert keys.issubset(set(res.keys()))\n assert res[\"success\"]\n assert res[\"dry_run\"] == dry_run_tests\n\n if env_name == \"file_only\":\n assert res[\"prefix\"] == TestCreate.prefix\n else:\n assert res[\"prefix\"] == os.path.join(\n TestCreate.root_prefix, \"envs\", \"override_name\"\n )\n\n action_keys = {\"LINK\", \"PREFIX\"}\n assert action_keys.issubset(set(res[\"actions\"].keys()))\n\n packages = {pkg[\"name\"] for pkg in res[\"actions\"][\"LINK\"]}\n expected_packages = [\"xtensor\", \"xtl\", \"xsimd\"]\n if specs not in (\"file_only\", None):\n expected_packages.append(\"xframe\")\n assert set(expected_packages).issubset(packages)\n\n if channels == \"file_only\":\n expected_channel = \"https://repo.mamba.pm/conda-forge\"\n else:\n expected_channel = \"https://conda.anaconda.org/conda-forge\"\n\n for l in res[\"actions\"][\"LINK\"]:\n assert l[\"channel\"].startswith(expected_channel)\n assert l[\"url\"].startswith(expected_channel)\n\n @pytest.mark.parametrize(\"valid\", [False, True])\n def test_explicit_file(self, valid):\n spec_file_content = [\n \"@EXPLICIT\",\n \"https://conda.anaconda.org/conda-forge/linux-64/xtensor-0.21.5-hc9558a2_0.tar.bz2#d330e02e5ed58330638a24601b7e4887\",\n ]\n if not valid:\n spec_file_content += [\"https://conda.anaconda.org/conda-forge/linux-64/xtl\"]\n\n spec_file = os.path.join(TestCreate.root_prefix, \"explicit_specs.txt\")\n with open(spec_file, \"w\") as f:\n f.write(\"\\n\".join(spec_file_content))\n\n cmd = (\"-p\", TestCreate.prefix, \"-q\", \"-f\", spec_file)\n\n if valid:\n res = create(*cmd, default_channel=False)\n assert res.splitlines() == [\"Linking xtensor-0.21.5-hc9558a2_0\"]\n\n list_res = umamba_list(\"-p\", TestCreate.prefix, \"--json\")\n assert len(list_res) == 1\n pkg = list_res[0]\n assert pkg[\"name\"] == \"xtensor\"\n assert pkg[\"version\"] == \"0.21.5\"\n assert pkg[\"build_string\"] == \"hc9558a2_0\"\n else:\n with pytest.raises(subprocess.CalledProcessError):\n create(*cmd, default_channel=False)\n","sub_path":"test/micromamba/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":8416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"561638227","text":"\"\"\"\n 函数返回结果:\n return 数据 -- 单个\n yield 数据 -- 多个\n\"\"\"\nclass EmployeeModel:\n def __init__(self, eid=0, did=0, name=\"\", money=0.0):\n self.eid = eid\n self.did = did\n self.name = name\n self.money = money\n\nlist_employee = [\n EmployeeModel(1001, 9003, \"林玉玲\", 13000),\n EmployeeModel(1002, 9003, \"王荆轲\", 16000),\n EmployeeModel(1003, 9003, \"刘岳浩\", 11000),\n EmployeeModel(1004, 9003, \"冯舜禹\", 17000),\n EmployeeModel(1005, 9003, \"曹海欧\", 15000),\n EmployeeModel(1006, 9003, \"魏鑫珑\", 12000),\n]\n\n# 1. 定义函数,在list_employee中查找薪资大于等于15000的所有员工\ndef find_employees_gt_15k():\n for emp in list_employee:\n if emp.money >= 15000:\n yield emp\ngeneator_employee = (emp for emp in list_employee if emp.money >= 15000 )\nfor employee in geneator_employee:\n print(employee.__dict__)\n\nprint()\n\n# for item in find_employees_gt_15k():\n# print(item.__dict__)\n\n# 2. 定义函数,在list_employee中查找员工编号为1005的员工\ndef find_employee_at_eid():\n for emp in list_employee:\n if emp.eid == 1005:\n return emp\nemployee = find_employee_at_eid()\nprint(employee.__dict__)\n\n# 3. 定义函数,在list_employee中查找所有员工的姓名\nlist_result = (emp.name for emp in list_employee)\nfor name in list_result:\n print(name)\n\ndef select_names_by_employee():\n for emp in list_employee:\n yield emp.name\n\n# for name in select_names_by_employee():\n# print(name)\n\n# 4. 定义函数,在list_employee中查找薪资最高的员工\n\n\ndef get_max_employee_by_money():\n max_emp = list_employee[0]\n for i in range(1,len(list_employee)):\n if max_emp.money < list_employee[i].money:\n max_emp = list_employee[i]\n return max_emp\n\n# emp = get_max_employee_by_money()\n# print(emp.__dict__)\n","sub_path":"month_01/day_17/exercise09.py","file_name":"exercise09.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"7403050","text":"# Copyright (2016-2017) Hewlett Packard Enterprise Development LP\n# Copyright (2016-2017) Universidade Federal de Campina Grande\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport copy\nimport mock\nimport unittest\n\nfrom ironic_oneviewd import facade\nfrom ironic_oneviewd.node_manager import manage\nfrom ironic_oneviewd.node_manager.manage import NodeManager\n\n\nclass FakeIronicNode(object):\n def __init__(self, id, uuid, chassis_uuid, provision_state, driver,\n ports, driver_info={}, driver_internal_info={},\n name='fake-node', maintenance='False', properties={},\n extra={}):\n\n self.id = id\n self.uuid = uuid\n self.chassis_uuid = chassis_uuid\n self.provision_state = provision_state\n self.driver = driver\n self.ports = ports\n self.driver_info = driver_info\n self.driver_internal_info = driver_internal_info\n self.maintenance = maintenance\n self.properties = properties\n self.extra = extra\n self.name = name\n\n\nclass FakeIronicPort(object):\n def __init__(self, id, uuid, node_uuid, address, extra={},\n local_link_connection='', portgroup_id='',\n pxe_enabled='False'):\n\n self.id = id\n self.uuid = uuid\n self.node_uuid = node_uuid\n self.address = address\n self.extra = extra\n self.local_link_connection = local_link_connection\n self.portgroup_id = portgroup_id\n self.pxe_enabled = pxe_enabled\n\n\nclass FakeServerHardware(object):\n def __init__(self, name, uuid, uri, power_state, port_map,\n server_profile_uri, server_hardware_type_uri,\n enclosure_group_uri, state, enclosure_uri):\n\n self.name = name\n self.uuid = uuid\n self.uri = uri\n self.power_state = power_state\n self.port_map = port_map\n self.server_profile_uri = server_profile_uri\n self.server_hardware_type_uri = server_hardware_type_uri\n self.enclosure_group_uri = enclosure_group_uri\n self.state = state\n self.enclosure_uri = enclosure_uri\n\n\nclass FakeServerProfile(object):\n attribute_map = {\n 'uri': 'uri',\n 'name': 'name',\n 'connections': 'connections',\n }\n\n\nclass FakeConfHelper(object):\n def __init__(self, max_workers):\n self.rpc_thread_pool_size = max_workers\n\n\nclass FakeConfClient(object):\n def __init__(self, max_workers):\n self.DEFAULT = FakeConfHelper(max_workers)\n\n\nPOOL_OF_FAKE_IRONIC_NODES = [\n FakeIronicNode(\n id=123,\n uuid='66666666-7777-8888-9999-000000000000',\n chassis_uuid='aaaaaaaa-1111-bbbb-2222-cccccccccccc',\n maintenance=False,\n provision_state='enroll',\n ports=[\n {'id': 987,\n 'uuid': '11111111-2222-3333-4444-555555555555',\n 'node_uuid': '66666666-7777-8888-9999-000000000000',\n 'address': 'AA:BB:CC:DD:EE:FF',\n 'extra': {}}\n ],\n driver='fake_oneview',\n driver_info={'use_oneview_ml2_driver': True, 'user': 'foo',\n 'password': 'bar',\n 'server_hardware_uri':\n '/rest/server-hardware-types/111112222233333'},\n properties={'num_cpu': 4},\n name='fake-node-1',\n extra={}\n ),\n FakeIronicNode(\n id=123,\n uuid='66666666-7777-8888-9999-000000000000',\n chassis_uuid='aaaaaaaa-1111-bbbb-2222-cccccccccccc',\n maintenance=False,\n provision_state='enroll',\n ports=[\n {'id': 987,\n 'uuid': '11111111-2222-3333-4444-555555555555',\n 'node_uuid': '66666666-7777-8888-9999-000000000000',\n 'address': 'AA:BB:CC:DD:EE:FF',\n 'extra': {}}\n ],\n driver='fake_oneview',\n driver_info={\n 'user': 'foo', 'password': 'bar'\n },\n properties={'num_cpu': 4},\n name='fake-node-2',\n extra={}\n ),\n FakeIronicNode(\n id=123,\n uuid='66666666-7777-8888-9999-000000000000',\n chassis_uuid='aaaaaaaa-1111-bbbb-2222-cccccccccccc',\n maintenance=False,\n provision_state='enroll',\n ports=[\n {'id': 987,\n 'uuid': '11111111-2222-3333-4444-555555555555',\n 'node_uuid': '66666666-7777-8888-9999-000000000000',\n 'address': 'AA:BB:CC:DD:EE:FF',\n 'extra': {}}\n ],\n driver='fake_oneview',\n driver_info={'use_oneview_ml2_driver': False, 'user': 'foo',\n 'password': 'bar',\n 'server_hardware_uri':\n '/rest/server-hardware-types/111112222233333'},\n properties={'num_cpu': 4},\n name='fake-node-3',\n extra={}\n ),\n]\n\nPOOL_OF_FAKE_IRONIC_PORTS = [\n FakeIronicPort(\n id=987,\n uuid='11111111-2222-3333-4444-555555555555',\n local_link_connection=None,\n node_uuid='66666666-7777-8888-9999-000000000000',\n address='AA:BB:CC:DD:EE:FF',\n extra={}\n )\n]\n\nPOOL_OF_FAKE_SERVER_HARDWARE = [\n FakeServerHardware(\n name='AAAAA',\n uuid='11111111-7777-8888-9999-000000000000',\n uri='/rest/server-hardware/11111',\n port_map={'deviceSlots': ''},\n power_state='Off',\n server_profile_uri='',\n server_hardware_type_uri='/rest/server-hardware-types/111112222233333',\n enclosure_group_uri='/rest/enclosure-groups/1111112222233333',\n state='Unknown',\n enclosure_uri='/rest/enclosures/1111112222233333',\n )\n]\n\n\nclass TestIronicOneviewd(unittest.TestCase):\n @mock.patch('ironic_oneviewd.facade.Facade', autospec=True)\n @mock.patch.object(facade.Facade, 'get_ironic_node_list')\n def test_take_node_actions(self, mock_get_ironic_node_list, mock_facade):\n\n mocked_facade = facade.Facade()\n mock_get_ironic_node_list.return_value = POOL_OF_FAKE_IRONIC_NODES\n mocked_facade.get_ironic_node_list = mock_get_ironic_node_list\n mock_facade.return_value = mocked_facade\n node_manager = NodeManager()\n node_manager.pull_ironic_nodes()\n mock_get_ironic_node_list.assert_called_with()\n\n @mock.patch('ironic_oneviewd.facade.Facade', autospec=True)\n @mock.patch.object(manage.NodeManager, 'take_enroll_state_actions')\n def test_manage_node_provision_state_with_node_in_enroll(\n self, mock_take_enroll_state_actions, mock_facade\n ):\n fake_node = copy.deepcopy(POOL_OF_FAKE_IRONIC_NODES[0])\n fake_node.provision_state = 'enroll'\n node_manager = NodeManager()\n node_manager.manage_node_provision_state(fake_node)\n mock_take_enroll_state_actions.assert_called_with(fake_node)\n\n @mock.patch('ironic_oneviewd.facade.Facade', autospec=True)\n @mock.patch.object(manage.NodeManager, 'take_manageable_state_actions')\n def test_manage_node_provision_state_with_node_in_manageable(\n self, mock_take_manageable_state_actions, mock_facade\n ):\n fake_node = copy.deepcopy(POOL_OF_FAKE_IRONIC_NODES[0])\n fake_node.provision_state = 'manageable'\n node_manager = NodeManager()\n node_manager.manage_node_provision_state(fake_node)\n mock_take_manageable_state_actions.assert_called_with(fake_node)\n\n @mock.patch('ironic_oneviewd.conf.CONF.openstack.inspection_enabled')\n @mock.patch('ironic_oneviewd.facade.Facade', new_callable=mock.MagicMock)\n def test_manage_provision_state_inspection_enabled(\n self, mock_facade, mock_inspection_enabled\n ):\n mock_facade = facade.Facade()\n mock_facade.set_node_provision_state = mock.MagicMock()\n mock_inspection_enabled.return_value = True\n fake_node = copy.deepcopy(POOL_OF_FAKE_IRONIC_NODES[1])\n fake_node.provision_state = 'manageable'\n node_manager = NodeManager()\n node_manager.manage_node_provision_state(fake_node)\n mock_facade.set_node_provision_state.assert_called_with(fake_node,\n 'inspect')\n\n @mock.patch('ironic_oneviewd.facade.Facade', new_callable=mock.MagicMock)\n def test_manage_node_provision_state_with_node_in_inspect_failed(\n self, mock_facade\n ):\n mock_facade = facade.Facade()\n mock_facade.set_node_provision_state = mock.MagicMock()\n fake_node = copy.deepcopy(POOL_OF_FAKE_IRONIC_NODES[1])\n fake_node.provision_state = 'inspect failed'\n fake_node.last_error = (\"OneView exception occurred. Error: Node %s is\"\n \" already in use by OneView.\") % fake_node.id\n node_manager = NodeManager()\n node_manager.manage_node_provision_state(fake_node)\n mock_facade.set_node_provision_state.assert_called_with(fake_node,\n 'manage')\n\n @mock.patch('ironic_oneviewd.facade.Facade.set_node_provision_state',\n autospec=True)\n @mock.patch('ironic_oneviewd.facade.Facade', new_callable=mock.MagicMock)\n def test_all_enroll_actions(self, mock_facade,\n mock_facade_set_node_provision_state):\n node_manager = NodeManager()\n\n fake_node = copy.deepcopy(POOL_OF_FAKE_IRONIC_NODES[1])\n fake_node.provision_state = 'enroll'\n\n node_manager.manage_node_provision_state(fake_node)\n mock_facade_set_node_provision_state.assert_called_with(fake_node,\n 'manage')\n","sub_path":"ironic-oneviewd/ironic_oneviewd/tests/functional/test_ironic_oneviewd.py","file_name":"test_ironic_oneviewd.py","file_ext":"py","file_size_in_byte":10110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"254548825","text":"import pandas as pd, numpy, matplotlib\n\n# What would have to be changed to make the code in Figure 3.4 work for finding an approximation to the cube root of both negative and positive numbers? (Hing: think about changing low to ensure that the answer lies within the region being searched.)\n\nx = -27\nepsilon = 0.01\nnumGuesses = 0\nlow = 0.0\nhigh = max(1.0, abs(x))\nans = (high + low)/2.0\nwhile abs(ans**3 - abs(x)) >= epsilon:\n print ('low =', low, 'high =', high, 'ans =', ans)\n numGuesses += 1\n if ans**3 < abs(x):\n low = ans\n else:\n high = ans\n ans = (high + low)/2.0\nif x < 0:\n ans *= -1\n print('x is negative') \nprint('numGuesses =', numGuesses)\nprint(ans, 'is close to the square root of', x)","sub_path":"finger_exercises/finger_exercises3c.py","file_name":"finger_exercises3c.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"565205126","text":"\"\"\"\n深度遍历有重要的三种方法。这三种方式常被用于访问树的节点,它们之间的不同在于访问每个节点的次序不同。这三种遍历分别叫做\n先序遍历(preorder),中序遍历(inorder)和后序遍历(postorder)。我们来给出它们的详细定义,然后举例看看它们的应用。\n\"\"\"\ndef preorder(root):\n \"\"\"\n preorder:根节点-》左-》右\n :param root:\n :return:\n \"\"\"\n if root==None:\n return\n print(root.elem)\n preorder(root.lchild)\n preorder(root.rchild)\n\ndef inorder(root):\n \"\"\"\n inorder:左-》根节点-》右\n :param root:\n :return:\n \"\"\"\n if root==None:\n return root\n inorder(root.lchild)\n print(root.elem)\n inorder(root.rchild)\ndef posorder(root):\n if root==None:\n return root\n posorder(root.lchild)\n posorder(root.rchild)\n print(root.elem)","sub_path":"leetCode/binary_tree/Depth_First_Search.py","file_name":"Depth_First_Search.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"74095640","text":"from naive_bayes import NaiveBayesClassifier\n\ntraining_data = [\n \"Kyoto is the former capital of Japan\",\n \"Bejing is the current capital of China\",\n \"New Delhi is the current capital of India\",\n \"Tokyo is the Japanese capital\",\n \"Prime minister Narendra Modi hangs out with Bear Grylls\",\n \"Wen Jiabao was a former Premier of China\",\n \"Shinzo Abe is the Japanese prime minister\",\n \"Hyderabad is becoming a global tech hub\"\n]\n\nlabels = [\n \"Japan\",\n \"China\",\n \"India\",\n \"Japan\",\n \"India\",\n \"China\",\n \"Japan\",\n \"India\"\n]\n\ntesting_data = [\n \"Premier Wen Jiabao visits Kyoto Japan\",\n \"Kyoto Animations opens new headquaters in Tokyo\",\n \"Bear Grylls looks to go hiking with Shinzo Abe\",\n \"Shinzo Abe visits New Delhi to meet with Narendra Modi\",\n \"Narendra Modi goes to Tokyo to talk with Shinzo Abe\"\n]\n\nclassifier = NaiveBayesClassifier()\nclassifier.train(training_data, labels)\n\nfor test_document in testing_data:\n print(test_document)\n print(\"Result: {}\\n\".format(classifier.classify(test_document, verbose=True), test_document))","sub_path":"Code/Naive Bayes/naive_bayes/multiclass_naive_bayes_demo.py","file_name":"multiclass_naive_bayes_demo.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"417732439","text":"from django.contrib import admin\nfrom django.urls import path\nfrom myapp import views\n\nurlpatterns = [\n path('',views.index,name='index'),\n #path('',views.signup),\n path('profile/',views.profile,name='profile'),\n path('updatestudent/',views.updatestudent),\n path('deleteprofile/',views.deleteprofile),\n path('student/',views.student,name='student'),\n path('studentdata',views.studentdata),\n path('updateprofile/',views.updateprofile),\n path('user_logout',views.user_logout),\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"239126968","text":"from google.appengine.ext import db\nimport entry\n\nclass Tag(db.Model):\n\n tag = db.StringProperty(multiline=False)\n tagcount = db.IntegerProperty(default=0)\n\n @property\n def posts(self):\n return entry.Entry.all('entrytype =', 'post').filter('tags =', self)\n \n @property\n def tagclass(self):\n if self.tagcount < 10:\n return self.tagcount\n else:\n return 10\n\n @classmethod\n def add(cls, value):\n if value:\n value = value.strip()\n tag = Tag.get_by_key_name(value)\n if not tag:\n tag = Tag(key_name=value)\n tag.tag = value\n\n tag.tagcount += 1\n tag.put()\n return tag\n else:\n return None\n\n @classmethod\n def remove(cls, value):\n if value:\n value = value.strip()\n tag = Tag.get_by_key_name(value)\n if tag:\n if tag.tagcount > 1:\n tag.tagcount -= 1\n else:\n tag.delete()\n","sub_path":"models/tag.py","file_name":"tag.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"573585701","text":"import re\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom Converter.models import Converter\n\n\nclass ConverterForm(forms.ModelForm):\n class Meta:\n model = Converter\n fields = ['number', 'result']\n widgets = {\n 'number': forms.TextInput(attrs={'placeholder': 'Number'}),\n 'result': forms.TextInput(attrs={'placeholder': 'Result', 'readonly': 'True'})\n }\n\n def clean_number(self):\n number = self.cleaned_data['number']\n\n invalid_input = (\n 'IIII', 'VV', 'XXXX', 'LL', 'CCCC', 'DD',\n 'MMMM', 'IM', 'VM', 'XM', 'LM', 'DM', 'ID', 'VD',\n 'XD', 'LD', 'IC', 'VC', 'LC', 'IL', 'VL', 'VX'\n )\n\n if number.isdigit():\n if int(number) == 0:\n raise ValidationError(\"There is no zero in Roman numerals\")\n elif int(number) > 3999:\n raise ValidationError(\"Number should be less than 3999\")\n elif bool(re.match(\"^(?=.*[a-zA-Zа-яА-Я])(?=.*[0-9])|(?=.*\\W)\", number)):\n raise ValidationError(\"Type either arabic or roman number in field\")\n elif number.isalpha():\n if any(i not in ['M', 'D', 'C', 'L', 'X', 'V', 'I'] for i in number.upper()) or \\\n any(i in number.upper() for i in invalid_input):\n raise ValidationError(\"Input is not a valid roman numeral\")\n\n return number\n\n\n","sub_path":"Converter/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"114468937","text":"# GENERAL\nAPP_NAME = 'GreeterApp'\nSERVER_NAME = 'localhost'\nSECRET_KEY = 'SomeSecretKey'\nDEBUG = True\n\n# FILE UPLOADS\nUPLOAD_FOLDER = 'uploads/'\nMAX_CONTENT_LENGTH = 16*1024*1024\n\n# MAIL\nMAIL_SERVER = 'your.smtpserver.com'\nMAIL_PORT = 465\nMAIL_USE_TLS = False\nMAIL_USE_SSL = True\nMAIL_DEBUG = True\nMAIL_USERNAME = 'yourusername'\nMAIL_PASSWORD = 'yourpassword'\nMAIL_DEFAULT_SENDER = 'noreply@yourdomain.com'\nMAIL_MAX_EMAILS = None\nMAIL_SUPPRESS_SEND = False\nMAIL_ASCII_ATTACHMENTS = False\n\n# BACKGROUND TASKS\nCELERY_BROKER_URL = 'amqp://rabbit'\nCELERY_RESULT_BACKEND = 'redis://redis'\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\n","sub_path":"appconfig_develop.example.py","file_name":"appconfig_develop.example.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"617806727","text":"from __future__ import division\n\nimport math\nfrom picraft import World, Vector, O, X, Y, Z, lines\n\ndef polygon(sides, center=O, radius=5):\n angle = 2 * math.pi / sides\n for side in range(sides):\n yield Vector(\n center.x + radius * math.cos(side * angle),\n center.y + radius * math.sin(side * angle))\n\ndef shapes():\n for sides in range(3, 9):\n yield lines(polygon(sides, center=3*Y))\n\nw = World()\nfor shape in shapes():\n # Draw the shape\n with w.connection.batch_start():\n for p in shape:\n w.blocks[p] = Block('stone')\n sleep(0.5)\n # Wipe the shape\n with w.connection.batch_start():\n for p in shape:\n w.blocks[p] = Block('air')\n","sub_path":"docs/recipe_shapes2.py","file_name":"recipe_shapes2.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"370052503","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nimport Lib_LinkedList\nfrom Lib_LinkedList import LinkedList\n\nclass Solution:\n # @param {ListNode} head\n # @return {ListNode}\n def reverseList_iterative(self, head):\n newHead = None #head of the reversed linked list\n while(head!=None): #each iteration, move the first node of the list of Head to the first node of the list of newHead\n tmpNode = head.next #use tmpNode to preserve the location of the second node, this node will be used as head of the non-reversed node in the second iteration\n head.next=newHead #insert the node pointed to by head as the first node of the reversed linked list \n newHead=head #move newHead to point to the newly added node\n head = tmpNode #move head to the previously second node of the non-reversed list to prepare for the next iteration\n return newHead\n \n def reverseList_iterativeII(self, head):\n newhead=None\n while(head!=None):\n currNode = head\n head = head.next\n currNode.next = newhead\n newhead = currNode\n return newhead\n \n def reverseList_recur_wrapper(self, head):\n return Solution.reverseList_recur(self, head, None)\n def reverseList_recur(self, head, newHead): #each recursive call is an insert-at-head to the reversedLinkedList\n if head==None:\n return newHead\n else:\n tmp = head\n head=head.next\n \n tmp.next=newHead\n newHead=tmp\n return Solution.reverseList_recur(self, head, newHead)\n\n \n \nsol = Solution()\nmyList = LinkedList()\nmyHead = myList.buildList([1,2,3,4,5,6])\nmyList.printList(myHead)\n\nreversedHead = Solution().reverseList_recur_wrapper(myHead)\nmyList.printList(reversedHead)\n\n\nsol2 = Solution()\nmyList2 = LinkedList()\nmyHead2 = myList2.buildList([1,2,3,4,5,6])\nmyList.printList(myHead2)\nreversedHead2 = sol2.reverseList_iterativeII(myHead2)\nmyList2.printList(reversedHead2)","sub_path":"Python/206-ReverseLinkedList.py","file_name":"206-ReverseLinkedList.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"56299646","text":"# Ejemplo de clasificacion\n# Predecir los ingresos de una persona en funcion de sus caracteristicas\nimport tensorflow as tf\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\n# importar archivo\ndata = pd.read_csv('original.csv')\n#print(data)\n\n#seleccionar una columna\ningresos = data['income'].unique()\n\n# cambiar los valores de income a 0 o 1\ndef cambio_valor(valor):\n if valor == '<=50K':\n return 0\n else:\n return 1\n#aplicar valores\ndata['income'] = data['income'].apply(cambio_valor)\n\n#eliminar columna income\ndatos_x = data.drop('income', axis=1)\n\n#seleccionar datos de la columna income\ndatos_y = data['income']\n\n#dividir datos de Entrenamiento y test\nx_train, x_test, y_train , y_test = train_test_split(datos_x, datos_y,test_size=0.3)\n\n# obtner datos de las columnas\ngender = tf.feature_column.categorical_column_with_vocabulary_list(\"gender\",['Female, Male'])\noccupation = tf.feature_column.categorical_column_with_hash_bucket(\"occupation\",hash_bucket_size=1000)\nmarital_status = tf.feature_column.categorical_column_with_hash_bucket(\"marital-status\",hash_bucket_size=1000)\nrelationship = tf.feature_column.categorical_column_with_hash_bucket(\"relationship\",hash_bucket_size=1000)\neducation = tf.feature_column.categorical_column_with_hash_bucket(\"education\",hash_bucket_size=1000)\nnative_country = tf.feature_column.categorical_column_with_hash_bucket(\"native-country\",hash_bucket_size=1000)\nworkclass = tf.feature_column.categorical_column_with_hash_bucket(\"workclass\",hash_bucket_size=1000)\n\nage = tf.feature_column.numeric_column(\"age\")\nfnlwgt = tf.feature_column.numeric_column(\"fnlwgt\")\neducational_num = tf.feature_column.numeric_column(\"educational-num\")\ncapital_gain = tf.feature_column.numeric_column(\"capital-gain\")\ncapital_loss = tf.feature_column.numeric_column(\"capital-loss\")\nhours_per_week = tf.feature_column.numeric_column(\"hours-per-week\")\n\n# crear lista\ncolumnas_categorias = [gender, occupation, marital_status, relationship, education, native_country, workclass, age, fnlwgt, educational_num, capital_gain, capital_loss, hours_per_week ]\n\n#funcion de entrada para estimar\nfuncion_entrada = tf.estimator.inputs.pandas_input_fn(x=x_train, y=y_train, batch_size=100, num_epochs=None, shuffle=True)\nmodelo = tf.estimator.LinearClassifier(feature_columns=columnas_categorias)\n#entrenar modelo\nmodelo.train(input_fn=funcion_entrada, steps=8000)\nfuncion_pred = tf.estimator.inputs.pandas_input_fn(x=x_test, batch_size=len(x_test), shuffle=False)\n#generador de predicciones\ngenerador_pred = modelo.predict(input_fn = funcion_pred)\n#lista de predicciones\npredicciones = list(generador_pred)\npredict_fin = [prediccion['class_ids'][0] for prediccion in predicciones]\nprint(classification_report(y_test, predict_fin))\n","sub_path":"clasificacion.py","file_name":"clasificacion.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184052586","text":"import sys\nsys.path.insert(0, '../')\n\nfrom ast import literal_eval\nfrom glove_one_vs_many.model import Classifier\nfrom sklearn.metrics import f1_score, accuracy_score, recall_score, precision_score\n\nimport numpy as np\nimport os, csv\nimport global_config as cfg\n\nverbose = False\n\nclassifier = Classifier(cfg.TOPICS)\nprint(\"Training\")\nclassifier.train()\n\nsummaries = []\ntargets = []\n\nprint(\"Evaluating on test data\")\nwith open(cfg.TEST_DATA_PATH, 'r') as dataFile:\n reader = csv.reader(dataFile)\n\n for summary,cats in reader:\n summaries.append(summary)\n targets.append(tuple(literal_eval(cats)))\n\ntargets = classifier.mlb.transform(targets) \npredicted = classifier.predict(summaries)\n\nif verbose:\n for i,p in enumerate(predicted.tolist()):\n if len(predicted) - i < 20:\n \tprint(\"%s : Predicted %s, Actual %s)\" % (i, p, targets[i]))\n\nprint(\"GloVe OneVsMany Accuracy: %f\" % accuracy_score(predicted, targets))\nprint(\"GloVe OneVsMany Precision Score (global): %f\" % precision_score(predicted, targets, average='micro'))\nprint(\"GloVe OneVsMany Precision Score (weighted per label): %f\" % precision_score(predicted, targets, average='weighted'))\nprint(\"GloVe OneVsMany Recall Score (global): %f\" % recall_score(predicted, targets, average='micro'))\nprint(\"GloVe OneVsMany Recall Score (weighted per label): %f\" % recall_score(predicted, targets, average='weighted'))\nprint(\"GloVe OneVsMany F1 Score (global): %f\" % f1_score(predicted, targets, average='micro'))\nprint(\"GloVe OneVsMany F1 Score (weighted per label): %f\" % f1_score(predicted, targets, average='weighted'))\n","sub_path":"glove_one_vs_many/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"161228493","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\n\nfrom app.models import Category, Bookmark\nfrom app.helpers import *\n\n@login_required(login_url='/b/login')\ndef edit_category(request):\n\t_id = request.POST['ID']\n\tcategory_name = request.POST['category_name']\n\tcolor = request.POST['color']\n\trow_number = int(request.POST['row_number'])-1\n\tcolumn_number = int(request.POST['column_number'])-1\n\t# print(_id, category_name, color, row_number, column_number)\n\tcategory = Category.objects.get(id=_id)\n\tcategory.name = category_name\n\tcategory.progress_bar_color = color\n\tcategory.row_number = row_number\n\tcategory.column_number = column_number\n\tcategory.save()\n\treturn HttpResponseRedirect('/b/edit/')\n\n@login_required(login_url='/b/login')\ndef edit_bookmark(request):\n\t_id = request.POST['ID']\n\tbookmark_name = request.POST['bookmark_name']\n\tlink = request.POST['link']\n\tcategory_name = request.POST['category']\n\tglyphicon = request.POST['glyphicon']\n\trow_number = max(int(request.POST['row_number'])-1, 0)\n\n\tbookmark = Bookmark.objects.get(id=_id)\n\tbookmark.name = bookmark_name\n\tbookmark.link = link\n\tbookmark.glyphicon = glyphicon\n\n\ttry:\n\t\tcategory = Category.objects.get(name=category_name)\n\t\tif category == bookmark.category:\n\t\t\tif bookmark.row_number == row_number:\n\t\t\t\tbookmark.save()\n\t\t\telse:\n\t\t\t\tbookmarks = Bookmark.objects.filter(category=category)\n\t\t\t\tfill_gap(bookmarks, bookmark.row_number)\n\t\t\t\tinsert_object(bookmarks, bookmark, row_number)\n\t\telse:\n\t\t\tbookmarks = Bookmark.objects.filter(category=bookmark.category)\n\t\t\tfill_gap(bookmarks, bookmark.row_number)\n\t\t\tbookmarks = Bookmark.objects.filter(category=category)\n\t\t\tinsert_object(bookmarks, bookmark, row_number)\n\t\t\tbookmark.category = category\n\t\t\tbookmark.save()\n\texcept:\n\t\t# Handle new categories\n\t\tpass\n\treturn HttpResponseRedirect('/b/edit')\n","sub_path":"bm/app/edit_form_handlers.py","file_name":"edit_form_handlers.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"3145299","text":"#!/apollo/sbin/envroot \"$ENVROOT/python3.6/bin/python3.6\"\n\nimport argparse\nimport os\nimport sys\nimport logging\nfrom dxd_tools_dev.modules import cm_creator, device_list_generator, colours\n\nCM_TYPES = ['ibgp']\n\ndef create_args_parser():\n parser = argparse.ArgumentParser()\n cm_args = parser.add_argument_group()\n cm_args.add_argument('--cm_type', required=True, help='CM type to create')\n cm_args.add_argument('--new_devices', required=True, \n help='List of new devices to add. EG. iad2-vc-car-r1:1.1.1.1,iad2-vc-car-r2:2.2.2.2')\n cm_args.add_argument('--region', required=True, help='Region.')\n cm_args.add_argument('--mcm', required=True, help='CM number')\n parser.add_argument('-v', '--verbose', action='store_true', help='Increase display output')\n \n return parser\n\ndef get_devices(query_type, region):\n return device_list_generator.main(query_type, region)\n \ndef validation(args):\n if args.cm_type not in CM_TYPES:\n print(colours.FAIL + 'The following list of cm types are supported: {}.'.format(CM_TYPES) + colours.ENDC )\n return False\n if not all('vc-car' in device for device in args.new_devices.split(',')):\n print(colours.FAIL + 'Currently only vc-car devices are supported.' + colours.ENDC)\n return False\n if not all(':' in device for device in args.new_devices.split(',')):\n print(colours.FAIL + 'Incorrect device syntax.' + colours.ENDC)\n return False\n\n return True\n\ndef main():\n parser = create_args_parser()\n args = parser.parse_args()\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n logging.debug('Validating user arguments')\n proceed = validation(args)\n logging.debug('User args validated. Continue: {}'.format(proceed))\n if args.cm_type == 'ibgp':\n if proceed:\n logging.debug('Getting list of devices')\n devices = get_devices('ibgp_query', args.region)\n logging.debug('Retrieved devices')\n cm_creator_obj = cm_creator.CmCreator(args.new_devices, \n args.region,\n args.mcm)\n car_mesh = cm_creator_obj.get_ibgp_mesh_for_cars(devices)\n logging.debug('Creating variable file')\n cm_creator_obj.create_ibgp_mesh_var(car_mesh)\n print(colours.OKGREEN + 'Adding the following devices to the mesh: \\n' + colours.ENDC)\n for device in car_mesh:\n print(device)\n else:\n sys.exit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"aws/cm_builder.py","file_name":"cm_builder.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486375665","text":"\"\"\"\r\nPredict.py contains the functions and post/get requests nessecary for\r\nthe API to take inputs and return outputs relevant to the data being searched.\r\n\"\"\"\r\n\r\nimport logging\r\nimport random\r\n\r\nfrom fastapi import APIRouter\r\nimport pandas as pd\r\nfrom pydantic import BaseModel, Field, validator\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.neighbors import NearestNeighbors\r\nimport spacy\r\nfrom spacy.tokenizer import Tokenizer\r\nfrom spacy.lang.en import English\r\n\r\nlog = logging.getLogger(__name__)\r\nrouter = APIRouter()\r\n\r\ndf = pd.read_csv('toking.csv')\r\n\r\n\r\ndef search_func(user_input, num_results=10):\r\n \"\"\"\r\n Flexible function that searches for cannabis strains.\r\n\r\n ### Request Body\r\n - user_input str\r\n - num_results int: default 10\r\n ### Response\r\n - `strain_recommendation`: dictionary of strain recommendations\r\n \"\"\"\r\n\r\n user_input = [user_input]\r\n nlp = English()\r\n tokenizer = Tokenizer(nlp.vocab)\r\n tf = TfidfVectorizer(stop_words='english')\r\n dtm = tf.fit_transform(df['search'])\r\n dtm = pd.DataFrame(dtm.todense(), columns=tf.get_feature_names())\r\n\r\n nr = num_results\r\n nn = NearestNeighbors(n_neighbors=nr, algorithm='ball_tree')\r\n nn.fit(dtm)\r\n dtf = tf.transform(user_input)\r\n _, output = nn.kneighbors(dtf.todense())\r\n\r\n recommendations = []\r\n for n in output:\r\n for row in n:\r\n recommendations.append(row)\r\n\r\n result = []\r\n for i in recommendations:\r\n data = (df.loc[i, :])\r\n result.append(data)\r\n return {'strain_recommendations': result}\r\n\r\n\r\nclass Item(BaseModel):\r\n \"\"\"Use this data model to parse the request body JSON.\"\"\"\r\n\r\n symptoms: str = Field(..., example='insomnia')\r\n# results: int = Field(..., example=5)\r\n\r\n def to_df(self):\r\n \"\"\"Convert pydantic object to pandas dataframe with 1 row.\"\"\"\r\n return pd.DataFrame([dict(self)])\r\n\r\n\r\n@router.post('/predict')\r\nasync def predict(item: Item):\r\n \"\"\"\r\n Make a baseline strain recommendation.\r\n ### Request Body\r\n - `symptoms`: string\r\n - `results`: int\r\n ### Response\r\n - `strain_recommendation`: dictionary of strain names\r\n \"\"\"\r\n X_new = item.to_df()\r\n log.info(X_new)\r\n return {'recommendations': search_func(item.symptoms, 10)}\r\n","sub_path":"API_Template/app/api/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"622890332","text":"import os, glob\nimport numpy as np\nfrom tqdm import tqdm\nimport librosa\nfrom tensorflow.keras.models import Model, load_model\n\n\n# config.\nSAMPLING_RATE = 16000\nSEGMENT_LENGTH = 3\nTOTAL_AUDIO_LENGTH_SEC = 60\nBATCH_SIZE = 10\n\n# constants.\nFRAME_SAMPLES = SAMPLING_RATE * SEGMENT_LENGTH\nFIX_TOTAL_AUDIO_SAMPLE = SAMPLING_RATE * TOTAL_AUDIO_LENGTH_SEC\n\n\n\nassert (FIX_TOTAL_AUDIO_SAMPLE / FRAME_SAMPLES) % BATCH_SIZE == 0, \"Total audio sample should be divisible by frame samples.\"\n\n\n\n\ndef load_audio_track(file_path):\n track, _= librosa.load(file_path, sr=SAMPLING_RATE, mono=True, res_type='kaiser_fast')\n if len(track) < FIX_TOTAL_AUDIO_SAMPLE:\n pad_len = FIX_TOTAL_AUDIO_SAMPLE - len(track)\n track = np.concatenate([track, np.zeros(pad_len)])\n else:\n track = track[:FIX_TOTAL_AUDIO_SAMPLE]\n\n return track\n\n\n\ndef encode_template(template_track):\n # pre-encode template track to [20, 60, 9, 192]\n template_track = template_track.reshape((-1, BATCH_SIZE, FRAME_SAMPLES))\n\n template_feats = []\n for b in template_track:\n template_feats.append(track1_encoder.predict(b))\n return np.stack(template_feats)\n\n\ndef compare(template_feats, target_audio):\n target_audio = target_audio.reshape((-1, BATCH_SIZE, FRAME_SAMPLES))\n\n result = []\n for tem, tar in zip(template_feats, target_audio):\n result.append(model.predict([tem, tar]))\n\n return np.average(result)\n\n\n\n\n\n\nTEMPLATE_PATH = \"data\\\\anchor\\\\anchor.mp3\"\nDONATE_AUDIOS = \"data\\\\production\\\\*.mp3\"\n# DONATE_AUDIOS = \"data\\\\production\\\\f85e803c-09fb-4ccc-a86b-0085eff83e04.mp3\"\n\n\n\n# load models.\ntrack1_encoder = load_model(\"models\\\\siam_sim_track1_encode_b10.h5\")\nmodel = load_model(\"models\\\\siam_sim_b10_deploy.h5\")\n\n\n\nif __name__ == '__main__':\n\n\n # load template track.\n template_track = load_audio_track(TEMPLATE_PATH)\n template_feats = encode_template(template_track)\n\n\n # donate files.\n donate_files = glob.glob(DONATE_AUDIOS)\n\n\n for target_file in tqdm(donate_files):\n\n target_audio = load_audio_track(target_file)\n \n score = compare(template_feats, target_audio)\n\n if score < 0.72 : \n file_name = os.path.split(target_file)[-1]\n target_location = os.path.join(\"data\", \"trash\", file_name)\n os.rename(target_file, target_location)\n\n # target_audio = load_audio_track(DONATE_AUDIOS)\n \n # score = compare(template_feats, target_audio)\n\n # print('Score: ', score)\n\n\n","sub_path":"donate_trash_filter.py","file_name":"donate_trash_filter.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"586592368","text":"import urllib.request\nimport os\nimport pandas as pd\nimport json\nimport numpy as np\nimport csv\nfrom collections import OrderedDict\n\n#########################\n# Functions\n#########################\n\n# retrieve file from url\ndef get_url(url, fname):\n \"\"\" Retrieves file from url and returns path to file \"\"\"\n path_to_file = urllib.request.urlretrieve(url, fname)\n return path_to_file\n\n\ndef create_path(path, create_path=True):\n if not os.path.exists(path) & create_path:\n os.mkdir(path)\n else:\n NameError(\"Path not Found\")\n\n\ndef read_subject_data(path_csv):\n subs_df = pd.read_csv(path_csv)\n # subject ids / urls / metadata\n subject_ids = subs_df['subject_id']\n subject_urls = [json.loads(x) for x in subs_df['locations']]\n subject_meta = [json.loads(x) for x in subs_df['metadata']]\n # fill dictionary\n subs_dir = dict()\n for i in range(0, len(subject_ids)):\n subs_dir[subject_ids[i]] = {'url': [x for x in subject_urls[i].values()],\n 'metadata': subject_meta[i]}\n return subs_dir\n\n\ndef read_subject_data1(path_csv):\n subs_df = pd.read_csv(path_csv)\n # subject ids / urls / metadata\n subject_ids = subs_df['subject_id']\n subject_urls = [json.loads(x)['0'] for x in subs_df['locations']]\n subject_meta = [json.loads(x) for x in subs_df['metadata']]\n # fill dictionary\n subs_dir = dict()\n for i in range(0, len(subject_ids)):\n subs_dir[subject_ids[i]] = {'url': subject_urls[i],\n 'metadata': subject_meta[i]}\n return subs_dir\n\n\ndef read_subject_data2(path_csv):\n subs_df = pd.read_csv(path_csv)\n # subject ids / urls / metadata\n subject_ids = subs_df['subject_id']\n subject_urls = [json.loads(x)['0'] for x in subs_df['locations']]\n subject_meta = [json.loads(x) for x in subs_df['metadata']]\n subject_workflow_ids = subs_df['workflow_id']\n # fill dictionary\n subs_dir = dict()\n for i in range(0, len(subject_ids)):\n subs_dir[subject_ids[i]] = {'url': subject_urls[i],\n 'metadata': subject_meta[i],\n 'workflow_id': subject_workflow_ids[i]}\n return subs_dir\n\n\ndef read_subject_data_camcat(path_csv):\n subs_df_dict = OrderedDict()\n counter = 0\n with open(path_csv, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in reader:\n if counter == 0:\n counter += 1\n continue\n else:\n subject_id = str(row[0])\n workflow_id = row[2]\n subject_urls = json.loads(row[5])['0']\n subject_meta = json.loads(row[4])\n subs_df_dict[subject_id] = {'url': subject_urls,\n 'metadata': subject_meta,\n 'workflow_id': workflow_id}\n counter += 1\n if (counter % 100000) == 0:\n print(\"Processed %s\" % counter)\n return subs_df_dict\n\n\ndef read_classification_data(path_csv):\n # read csv\n cls_df = pd.read_csv(path_csv)\n return cls_df\n\n\ndef read_classification_data_camcat(path_csv):\n cls_dict = OrderedDict()\n counter = 0\n with open(path_csv, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in reader:\n if counter == 0:\n header = row\n counter += 1\n continue\n else:\n row_dict = {k: v for k, v in zip(header, row)}\n cls_dict[counter] = row_dict\n counter += 1\n if (counter % 100000) == 0:\n print(\"Processed %s\" % counter)\n return cls_dict\n\n\ndef calc_pielu(votes, blank_classes):\n \"\"\" calculate pielous evenness \"\"\"\n\n # result\n res = dict()\n\n # remove blanks\n votes = [x for x in votes if x not in blank_classes]\n\n # total number of votes\n n = len(votes)\n\n if n == 0:\n return 0\n\n # calculate proportions\n for v in votes:\n if v not in res:\n res[v] = 1.0\n else:\n res[v] += 1\n\n # n different species\n n_species = len(res.keys())\n\n if n_species == 1:\n return 0\n\n # calculate proportions\n for r, v in res.items():\n res[r] = v / n\n\n # calculate pielou\n pp = 0\n for r, v in res.items():\n pp += (v * np.log(v))\n\n return -(pp) / np.log(n_species)\n","sub_path":"transfer_learning/db/data_prep_functions.py","file_name":"data_prep_functions.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"277092101","text":"# 思路:用while迴圈,遇到9999就break,每次輸入就存數字進去list變成一個元素\n# 參考答案跟我的思路一模模一樣樣\n\nnumbers = [] # 宣告list\n\nwhile True:\n number = int(input(\"請輸入數字(輸入9999即退出程序計算最小值): \"))\n numbers.append(number)\n\n if number == 9999: # 判斷是否退出迴圈去計算最小值\n break\n\nmin_value = min(numbers)\nprint(\"在您輸入的所有數字中,最小值為 \" + str(min_value))\n","sub_path":"_4_control_procedure/402/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"71791777","text":"# -*- coding: utf-8 -*-\n\nfrom os.path import join\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, pi, zeros\n\nfrom pyleecan.Classes.Frame import Frame\nfrom pyleecan.Classes.LamSlotWind import LamSlotWind\nfrom pyleecan.Classes.LamSquirrelCage import LamSquirrelCage\nfrom pyleecan.Classes.MachineDFIM import MachineDFIM\nfrom pyleecan.Classes.Shaft import Shaft\nfrom pyleecan.Classes.VentilationCirc import VentilationCirc\nfrom pyleecan.Classes.VentilationPolar import VentilationPolar\nfrom pyleecan.Classes.VentilationTrap import VentilationTrap\nfrom pyleecan.Classes.Winding import Winding\nfrom pyleecan.Classes.WindingUD import WindingUD\nfrom pyleecan.Classes.SlotW10 import SlotW10\nfrom pyleecan.Classes.SurfLine import SurfLine\n\nfrom pyleecan.Methods import ParentMissingError, NotImplementedYetError\n\nfrom Tests import save_plot_path as save_path\nfrom Tests.Plot.LamWind import wind_mat\n\nimport pytest\n\n\n\"\"\"pytest for Lamination with winding plot\"\"\"\n\n\nclass Test_Slot_10_plot(object):\n def test_Lam_Wind_10_wind_22(self):\n \"\"\"Test machine plot with Slot 10 and winding rad=2, tan=2\"\"\"\n print(\"\\nTest plot Slot 10\")\n plt.close(\"all\")\n test_obj = MachineDFIM()\n test_obj.rotor = LamSlotWind(\n Rint=0.2,\n Rext=0.5,\n is_internal=True,\n is_stator=False,\n L1=0.95,\n Nrvd=1,\n Wrvd=0.05,\n )\n test_obj.rotor.slot = SlotW10(\n Zs=6,\n W0=50e-3,\n W1=90e-3,\n W2=100e-3,\n H0=20e-3,\n H1=35e-3,\n H2=130e-3,\n H1_is_rad=False,\n )\n test_obj.rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n test_obj.shaft = Shaft(Drsh=test_obj.rotor.Rint * 2, Lshaft=1)\n\n test_obj.stator = LamSlotWind(\n Rint=0.51,\n Rext=0.8,\n is_internal=False,\n is_stator=True,\n L1=0.95,\n Nrvd=1,\n Wrvd=0.05,\n )\n test_obj.stator.slot = SlotW10(\n Zs=6,\n W0=50e-3,\n W1=80e-3,\n W2=50e-3,\n H0=15e-3,\n H1=25e-3,\n H2=140e-3,\n H1_is_rad=False,\n )\n test_obj.stator.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n\n test_obj.frame = Frame(Rint=0.8, Rext=0.9, Lfra=1)\n test_obj.frame.mat_type.name = \"M330_35A\"\n\n test_obj.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_1-Machine.png\"))\n # Rotor + Stator + 2 for frame + 1 for Shaft\n assert len(fig.axes[0].patches) == 59\n\n test_obj.rotor.plot(is_show_fig=False)\n fig = plt.gcf()\n assert len(fig.axes[0].patches) == 28\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_2-Rotor.png\"))\n # 2 for lam + Zs*4 for wind\n assert len(fig.axes[0].patches) == 28\n # Don't display the plot\n assert len(test_obj.rotor.plot(is_display=False, is_show_fig=False)) == 28\n\n test_obj.stator.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_3-Stator.png\"))\n # 2 for lam + Zs*4 for wind\n assert len(fig.axes[0].patches) == 28\n\n lines = test_obj.stator.slot.build_geometry_half_tooth(is_top=False)\n surf = SurfLine(line_list=lines)\n surf.plot_lines(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_bottom_out.png\"))\n\n lines = test_obj.stator.slot.build_geometry_half_tooth(is_top=True)\n surf = SurfLine(line_list=lines)\n surf.plot_lines(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_top_out.png\"))\n\n lines = test_obj.rotor.slot.build_geometry_half_tooth(is_top=False)\n surf = SurfLine(line_list=lines)\n surf.plot_lines(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_bottom_in.png\"))\n\n lines = test_obj.rotor.slot.build_geometry_half_tooth(is_top=True)\n surf = SurfLine(line_list=lines)\n surf.plot_lines(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_top_in.png\"))\n\n tooth = test_obj.rotor.slot.get_surface_tooth()\n tooth.plot(color=\"r\", is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_in.png\"))\n\n tooth = test_obj.stator.slot.get_surface_tooth()\n tooth.plot(color=\"r\", is_show_fig=False)\n fig = plt.gcf()\n mesh_dict = tooth.comp_mesh_dict(5e-3)\n for ii, line in enumerate(tooth.get_lines()):\n mid = line.get_middle()\n plt.text(mid.real, mid.imag, str(mesh_dict[str(ii)]))\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Tooth_out.png\"))\n\n slot = SlotW10(\n Zs=6,\n W0=50e-3,\n W1=80e-3,\n W2=50e-3,\n H0=15e-3,\n H1=25e-3,\n H2=140e-3,\n H1_is_rad=False,\n )\n\n with pytest.raises(ParentMissingError) as context:\n slot.get_surface_tooth()\n\n test_obj.rotor.comp_wind_function(alpha_mmf0=1)\n\n test_obj.stator.slot = SlotW10(\n Zs=6,\n W0=50e-1,\n W1=80e-1,\n W2=50e-1,\n H0=15e-1,\n H1=25e-1,\n H2=140e-1,\n H1_is_rad=False,\n )\n\n lines = test_obj.stator.slot.build_geometry_half_tooth(is_top=False)\n assert len(lines) == 7\n\n # Testing comp_angle_d_axis\n test_obj.stator.winding = None\n assert test_obj.stator.comp_angle_d_axis() == 0\n\n def test_plot_stator_true(self):\n \"\"\"Test if the plot is right with a stator LamSlotWind\"\"\"\n plt.close(\"all\")\n test_obj = MachineDFIM()\n\n test_obj.stator = LamSlotWind(\n Rint=0.51,\n Rext=0.8,\n is_internal=False,\n is_stator=True,\n L1=0.95,\n Nrvd=1,\n Wrvd=0.05,\n )\n test_obj.stator.slot = SlotW10(\n Zs=6,\n W0=50e-3,\n W1=80e-3,\n W2=50e-3,\n H0=15e-3,\n H1=25e-3,\n H2=140e-3,\n H1_is_rad=False,\n )\n test_obj.stator.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n\n test_obj.frame = Frame(Rint=0.8, Rext=0.9, Lfra=1)\n test_obj.frame.mat_type.name = \"M330_35A\"\n\n test_obj.stator.plot(is_show_fig=False)\n\n # The rotor will be blue\n\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s10_Stator.png\"))\n\n result = test_obj.stator.plot(is_display=False)\n assert len(result) == 28\n","sub_path":"Tests/Plot/LamWind/test_Slot_10_plot.py","file_name":"test_Slot_10_plot.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"397419073","text":"import keyboard\r\n\r\nfrom bot_utils.picture_in_picture.picture_in_picture import PictureInPicture\r\n\r\nfrom examples.albion_online.images import Images\r\n\r\n\r\npip = PictureInPicture()\r\n\r\n\r\nasync def take_journal():\r\n await pip.click_asap(Images.take_all)\r\n\r\n\r\nasync def give_journal(journal_img):\r\n keyboard.press('shift')\r\n try:\r\n await pip.click_asap(journal_img)\r\n except Exception as exception:\r\n raise exception\r\n finally:\r\n keyboard.release('shift')\r\n\r\n await pip.click_asap(Images.accept)\r\n\r\n\r\nif __name__ == '__main__':\r\n import asyncio\r\n loop = asyncio.get_event_loop()\r\n\r\n async def start():\r\n await take_journal()\r\n await give_journal(Images.t6_fletcher_journal)\r\n\r\n loop.run_until_complete(start())\r\n","sub_path":"examples/albion_online/laborer_manager.py","file_name":"laborer_manager.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84696096","text":"class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n n=len(code)\n res=[0]*n\n if k==0: return res\n start, end, sum=1, k, 0\n if k<0:\n k=-k\n start, end=n-k, n-1\n for i in range(start, end+1): sum+=code[i]\n for i in range(n):\n res[i]=sum\n sum-=code[start]\n start=(start+1)%n\n end=(end+1)%n\n sum+=code[end]\n return res\n\n","sub_path":"python/defuse-the-bomb.py","file_name":"defuse-the-bomb.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"76264199","text":"#Summations: Tasks\n#1+2+3....+98+99\n\nsum = 0\nfor i in range(1, 100, 1) :\n sum = sum + i\nprint(sum)\n\n\n#2+4+6+.....+48+50\ns = 0\nfor i in range(2, 51, 2) :\n s = s + i\nprint(s)\n\n# 3(1)^2 + 3(2)^2 +.....+3(500)^2\nsumsq = 0\nfor i in range(1, 501) :\n sumsq += i**2\n\nprint(3*sumsq)\n\n#(3k-2) for k in (-50, 100)\nnewSum = 0\nfor i in range(-50, 100, 1) :\n newSum += 3*i-2\nprint(newSum)\n\n#100(j+1)^2 for j in (-50, 100)\nnSum = 0\nfor i in range(-50, 100) :\n nSum += 100*(i+1)**2\nprint(nSum)\n\n#Calculate sum of the areas of circles whose radii are 1, 2, 3, ….. 100 cm. \nsumArea = 0\nfor radii in range(1, 101) :\n sumArea += 3.14*radii**2\nprint(sumArea)\n\n#Calculate sum of the areas of a rectangle whose sides are (1,0.5), (2,1), (3,1.5) ….. (100,50) cm. \nsumRect = 0\nfor i in range(1, 101) :\n b = 0.5*i\n sumRect += i*b\nprint(sumRect)\n\n#I change the question: calculate sum of the areas of a rectangle whose sides are (1,0.001), (2,0.001),(3,0.00.1) ….. (100,0.001) cm. \nsumrec = 0\nfor i in range(1, 101) :\n sumrec += i*0.001\nprint(sumrec)\n#Once you finish these code: write a code in such a way that it should ask you to enter ranges of a series summation. You can use any of these series for example. \nbegin = int(input('Enter the first term: '))\nend = int(input('Enter the last term: '))\n\n#Series: (3k - 2)\nkSum = 0\nfor k in range(begin, end+1) :\n kSum += 3*k - 2\nprint(kSum)\n\n\n\n\n\n\n\n","sub_path":"another.py","file_name":"another.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"225427577","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 20 14:19:16 2017\r\n\r\n@author: Michael\r\n\"\"\"\r\n\r\nfrom pylab import * \r\n\r\nt0 = 0.0 \r\ntf = 30.0\r\ndt = 0.5\r\n\r\nt = arange(t0 , tf , dt)\r\nv = zeros(len(t))\r\nv0 = 0\r\nv[0] = v0\r\n\r\nb = 0.1\r\ng = 10\r\nm = 1.0 \r\n\r\nfor i in arange(1 , len(t)):\r\n dv = (-b/m*v[i - 1]-g)*dt\r\n v[i] = v[i - 1] + dv \r\n \r\nfigure(1)\r\nclf()\r\nplot(t , v , 'b-o')\r\nvt = -m*g/b\r\nplot(t , vt*(1-exp(-b*t/m)),'k')\r\ntext(10, -40, r'$v(t) = v_T(e^{-\\frac{bt}{m}}-1)$', size = 20, color='Blue')\r\nplot(t , 0*t+vt , 'k--')\r\nplot(t , -g*t , 'c--')\r\nylim(-120,0)\r\n\r\n","sub_path":"Skydiver 2.0.py","file_name":"Skydiver 2.0.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"547832691","text":"import tensorflow as tf\r\nfrom tensorflow.python.ops import variable_scope as vs\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport numpy as np\r\nfrom utils import printoptions\r\n\r\n\r\nclass DynamicMaxPooling(object):\r\n def __init__(self, dim=2, shape=None):\r\n self.conv_dim = dim\r\n self.shape = shape\r\n\r\n\r\n def __call__(self, x, dpool_index, pool_size, strides, padding, name=None):\r\n x_expand = tf.gather_nd(x, dpool_index)\r\n if self.conv_dim == 1:\r\n size = [self.shape[0] / pool_size[0]]\r\n if size[0] != 1:\r\n x_pool = tf.layers.max_pooling1d(x_expand, pool_size=size, strides=size, padding=padding, name=name)\r\n else:\r\n x_pool = x_expand\r\n elif self.conv_dim == 2:\r\n size = [self.shape[0] / pool_size[0], self.shape[1] / pool_size[1]]\r\n if size[0] != 1 or size[1] != 1:\r\n x_pool = tf.layers.max_pooling2d(x_expand, pool_size=size, strides=size, padding=padding, name=name)\r\n else:\r\n x_pool = x_expand\r\n return x_pool\r\n\r\n\r\n @staticmethod\r\n def dynamic_pooling_index_1d(leng, max_len, compress_ratio=1):\r\n bs = tf.shape(leng)[0]\r\n dpool_bias = 0\r\n if max_len % compress_ratio != 0:\r\n dpool_bias = 1\r\n cur_max_len = max_len // compress_ratio + dpool_bias\r\n leng = leng // compress_ratio\r\n bidx = tf.ones([bs, cur_max_len], dtype=tf.int32) * tf.expand_dims(tf.range(bs), axis=-1)\r\n leng = tf.maximum(1, leng)\r\n stride = tf.cast(cur_max_len / leng, dtype=tf.float32)\r\n lidx = tf.cast(tf.cast(tf.expand_dims(tf.range(cur_max_len), axis=0), dtype=tf.float32) / \r\n tf.expand_dims(stride, axis=-1), dtype=tf.int32)\r\n return tf.stack([bidx, lidx], axis=-1)\r\n\r\n\r\n @staticmethod\r\n def dynamic_pooling_index_1d_np(leng, max_len, compress_ratio=1):\r\n def dpool_index_(batch_idx, leng, max_len):\r\n if leng == 0:\r\n stride = max_len\r\n else:\r\n stride = 1.0 * max_len / leng\r\n idx = [int(i / stride) for i in range(max_len)]\r\n index = np.stack([np.ones_like(idx) * batch_idx, idx], axis=-1)\r\n return index\r\n index = []\r\n dpool_bias = 0\r\n if max_len % compress_ratio != 0:\r\n dpool_bias = 1\r\n cur_max_len = max_len // compress_ratio + dpool_bias\r\n for i in range(len(leng)):\r\n index.append(dpool_index_(i, leng[i] // compress_ratio, cur_max_len))\r\n return np.array(index)\r\n\r\n @staticmethod\r\n def dynamic_pooling_index_2d(len1, len2, max_len1, max_len2, compress_ratio1=1, compress_ratio=1):\r\n # TODO: don't support compress_ratio\r\n batch_size = tf.shape(len1)[0]\r\n # convert zeros to ones\r\n len1 = len1 + (len1 == 0)\r\n len2 = len2 + (len2 == 0)\r\n # compute stride\r\n stride1 = max_len1 / len1\r\n stride2 = max_len2 / len2\r\n # compute index\r\n idx1 = tf.cast(tf.expand_dims(tf.range(max_len1), dim=0), dtype=tf.float64) / tf.expand_dims(stride1, dim=1)\r\n idx2 = tf.cast(tf.expand_dims(tf.range(max_len2), dim=0), dtype=tf.float64) / tf.expand_dims(stride2, dim=1)\r\n idx1 = tf.cast(idx1, dtype=tf.int32)\r\n idx2 = tf.cast(idx2, dtype=tf.int32)\r\n # mesh\r\n mesh1 = tf.tile(tf.expand_dims(idx1, 2), [1, 1, max_len2])\r\n mesh2 = tf.tile(tf.expand_dims(idx2, 1), [1, max_len1, 1])\r\n # construct index\r\n bidx = tf.ones_like(mesh1) * tf.reshape(tf.range(batch_size), [batch_size, 1, 1])\r\n return tf.stack([bidx, mesh1, mesh2], axis=3)\r\n\r\n @staticmethod\r\n def dynamic_pooling_index_2d_np(len1, len2, max_len1, max_len2, compress_ratio1=1, compress_ratio2=1):\r\n def dpool_index_(batch_idx, len1_one, len2_one, max_len1, max_len2):\r\n if len1_one == 0:\r\n stride1 = max_len1\r\n else:\r\n stride1 = 1.0 * max_len1 / len1_one\r\n\r\n if len2_one == 0:\r\n stride2 = max_len2\r\n else:\r\n stride2 = 1.0 * max_len2 / len2_one\r\n idx1_one = [int(i / stride1) for i in range(max_len1)]\r\n idx2_one = [int(i / stride2) for i in range(max_len2)]\r\n mesh2, mesh1 = np.meshgrid(idx2_one, idx1_one)\r\n index_one = np.stack([np.ones(mesh1.shape) * batch_idx, mesh1, mesh2], axis=-1)\r\n return index_one\r\n index = []\r\n dpool_bias1 = dpool_bias2 = 0\r\n if max_len1 % compress_ratio1 != 0:\r\n dpool_bias1 = 1\r\n if max_len2 % compress_ratio2 != 0:\r\n dpool_bias2 = 1\r\n cur_max_len1 = max_len1 // compress_ratio1 + dpool_bias1\r\n cur_max_len2 = max_len2 // compress_ratio2 + dpool_bias2\r\n for i in range(len(len1)):\r\n index.append(dpool_index_(i, len1[i] // compress_ratio1, \r\n len2[i] // compress_ratio2, cur_max_len1, cur_max_len2))\r\n return np.array(index)\r\n\r\n\r\ndef cnn(x, architecture=[(3, 3, 1, 16), (1, 2, 2, 1)], activation='relu', dpool_index=None):\r\n if activation not in {None, 'relu', 'tanh'}:\r\n raise Exception('not supported activation')\r\n if len(architecture) <= 0 or len(architecture) % 2 != 0:\r\n raise Exception('cnn architecture bug')\r\n if len(architecture[0]) == 3:\r\n conv_dim = 1\r\n elif len(architecture[0]) == 4:\r\n conv_dim = 2\r\n else:\r\n raise Exception('architecture not correct')\r\n if conv_dim == 1:\r\n shape = x.get_shape().as_list()[1:2]\r\n elif conv_dim == 2:\r\n shape = x.get_shape().as_list()[1:3]\r\n last = x\r\n for i in range(len(architecture) // 2):\r\n layer = i + 1\r\n conv_size = architecture[i*2]\r\n pool_size = architecture[i*2+1]\r\n with vs.variable_scope('conv{}'.format(layer)):\r\n #kernel = tf.Variable(tf.truncated_normal(conv_size, dtype=tf.float32, stddev=1e-1), name='weights')\r\n kernel = tf.get_variable('weights', shape=conv_size, dtype=tf.float32, initializer=\\\r\n tf.truncated_normal_initializer(mean=0.0, stddev=1e-1, dtype=tf.float32))\r\n tf.add_to_collection('conv_kernel', kernel)\r\n if conv_dim == 1:\r\n conv = tf.nn.conv1d(last, kernel, 1, padding='SAME')\r\n elif conv_dim == 2:\r\n conv = tf.nn.conv2d(last, kernel, [1, 1, 1, 1], padding='SAME')\r\n #biases = tf.Variable(tf.constant(0.0, shape=[conv_size[-1]], dtype=tf.float32),\r\n # trainable=True, name='biases')\r\n biases = tf.get_variable('biases', shape=[conv_size[-1]], dtype=tf.float32, initializer=\\\r\n tf.zeros_initializer())\r\n out = tf.nn.bias_add(conv, biases)\r\n if activation == 'relu':\r\n out = tf.nn.relu(out)\r\n elif activation == 'tanh':\r\n out = tf.nn.tanh(out)\r\n tf.add_to_collection('feature_map', out)\r\n with vs.variable_scope('pool{}'.format(layer)):\r\n if dpool_index is not None and layer == 1: # dynamic pooling\r\n dynamic_max_pool = DynamicMaxPooling(dim=conv_dim, shape=shape)\r\n out = dynamic_max_pool(out, dpool_index, pool_size=pool_size, strides=pool_size, \r\n padding='SAME', name='pool')\r\n else: # conventional pooling\r\n if conv_dim == 1 and pool_size[0] != 1:\r\n out = tf.layers.max_pooling1d(out, pool_size=pool_size, strides=pool_size, \r\n padding='SAME', name='pool')\r\n elif conv_dim == 2 and (pool_size[0] != 1 or pool_size[1] != 1):\r\n out = tf.layers.max_pooling2d(out, pool_size=pool_size, strides=pool_size, \r\n padding='SAME', name='pool')\r\n last = out\r\n return last\r\n\r\n\r\nclass CNNVis(object):\r\n SALIENCY_MAX_ROW = 9\r\n SALIENCY_MAX_COL = 3\r\n\r\n def __init__(self):\r\n pass\r\n\r\n\r\n def set_max_min(self, vmax, vmin):\r\n self.vmax = vmax\r\n self.vmin = vmin\r\n\r\n\r\n def plot_conv_kernel(self, kernel, name):\r\n in_c = kernel.shape[2]\r\n out_c = kernel.shape[3]\r\n print('vis kernel: {} with size: {}'.format(name, kernel.shape))\r\n fig, axes = plt.subplots(out_c, in_c, figsize=(10, 7))\r\n axes = axes.reshape([out_c, in_c])\r\n for o in range(out_c):\r\n for i in range(in_c):\r\n ax = axes[o, i]\r\n print(o, i)\r\n print(kernel[:, :, i, o])\r\n ax.imshow(kernel[:, :, i, o], vmin=self.vmin, vmax=self.vmax,\r\n interpolation='none', cmap='gray')\r\n ax.set_xticks([])\r\n ax.set_yticks([])\r\n try:\r\n plt.show()\r\n except KeyboardInterrupt:\r\n print('plot show interrupted')\r\n pass\r\n\r\n\r\n def plot_saliency_map(self, image, saliency_map):\r\n bs, h, w, c = saliency_map.shape\r\n print('vis saliency map with size: {}'.format(saliency_map.shape))\r\n saliency_map = np.max(np.abs(saliency_map), axis=3)\r\n smax = np.max(saliency_map)\r\n imax = np.max(image)\r\n imin = np.min(image)\r\n print('saliency max: {}'.format(smax))\r\n fig, axes = plt.subplots(CNNVis.SALIENCY_MAX_ROW, 2 * CNNVis.SALIENCY_MAX_COL, figsize=(10, 7))\r\n axes = axes.reshape([CNNVis.SALIENCY_MAX_ROW, 2 * CNNVis.SALIENCY_MAX_COL])\r\n for b in range(math.ceil(bs / (CNNVis.SALIENCY_MAX_ROW * CNNVis.SALIENCY_MAX_COL))):\r\n for i in range(CNNVis.SALIENCY_MAX_ROW * CNNVis.SALIENCY_MAX_COL):\r\n ni = i + b * (CNNVis.SALIENCY_MAX_ROW * CNNVis.SALIENCY_MAX_COL)\r\n if ni >= bs:\r\n break\r\n r = i // CNNVis.SALIENCY_MAX_COL\r\n c_img = (i % CNNVis.SALIENCY_MAX_COL) * 2\r\n c_s = (i % CNNVis.SALIENCY_MAX_COL) * 2 + 1\r\n ax_img = axes[r, c_img]\r\n ax_s = axes[r, c_s]\r\n if c == 1:\r\n ax_img.imshow(image[ni, :, :, 0], vmin=imin, vmax=imax,\r\n interpolation='none', cmap='gray')\r\n elif c == 3:\r\n ax_img.imshow(image[ni, :, :, :], vmin=imin, vmax=imax,\r\n interpolation='none', cmap='gray')\r\n ax_img.set_xticks([])\r\n ax_img.set_yticks([])\r\n ax_s.imshow(saliency_map[ni, :, :], vmin=0, vmax=np.max(saliency_map[ni, :, :]),\r\n interpolation='none', cmap='gray')\r\n ax_s.set_xticks([])\r\n ax_s.set_yticks([])\r\n #with printoptions(precision=2, suppress=True):\r\n #print(np.rint(np.abs(image[ni, :, :, 0] * w)).astype(int))\r\n #print(saliency_map[i, :, :])\r\n try:\r\n plt.show()\r\n except KeyboardInterrupt:\r\n print('plot show interrupted')\r\n pass\r\n cont = input('press \"c\" to continue')\r\n if cont != 'c':\r\n break","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":11305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"596784192","text":"import sys\nfrom server import *\nfrom server import databaseManager\nimport cgi\nimport json\nfrom utils import apiUtil\nimport os\nimport pymysql\n\nprint(\"Content-Type: text/html\\n\")\n\n\ndef returnErrorMessage(text, code):\n response = {'type': 'error', \"code\": code, 'message': text}\n print(json.dumps(response))\n exit(0)\n\n\ndef returnSuccesMessage():\n response = {'type': 'success', \"code\": 200, 'message': \"Joke updated successfully\"}\n print(json.dumps(response))\n exit(0)\n\n\narguments = cgi.FieldStorage()\n\nif 'json' not in arguments.keys():\n returnErrorMessage(\"No JSON found.\", 422) # unprocessable entity\n\njsonObj = json.loads(arguments['json'].value)\n\nif 'joke_id' not in jsonObj.keys():\n returnErrorMessage(\"No id specified\", 400) # bad request\n\nif 'joke_text' not in jsonObj.keys():\n returnErrorMessage(\"No id specified\", 400) # bad request\n\n\nif os.environ['REQUEST_METHOD'] == 'PUT':\n try:\n jsonObj = json.loads(arguments['json'].value.encode('utf-8'))\n if databaseManager.getJoke(jsonObj[\"joke_id\"]) != \"\":\n databaseManager.updateJoke(jsonObj[\"joke_id\"], jsonObj[\"joke_text\"])\n returnSuccesMessage()\n else:\n returnErrorMessage(\"Joke Not found\", 204) # no content\n except pymysql.DatabaseError:\n returnErrorMessage(\"Internal server error\", 500)\n except pymysql.InterfaceError:\n returnErrorMessage(\"Internal server error\", 500)\nelse:\n returnErrorMessage(\"Method not allowed\", 405) # method not allowed","sub_path":"Cloud Computing/Homework 02/assets/cgi-bin/updateJoke.py","file_name":"updateJoke.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228590649","text":"import distutils.spawn\nimport glob\nimport os\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom pbr.forms import executable_form_map\nfrom pbr.models import ExecutableOutput\nfrom pbr.settings import SERVER_URL\nfrom subprocess import Popen\n\n# static template for condor submit file\nsubmit_file_template = \"\"\"\nuniverse = local\nexecutable = {executable_path}\narguments = {arguments}\ngetenv = True\nlog = {file_dir}/{file_slug}.log\nerror = {file_dir}/{file_slug}.err\noutput = {file_dir}/{file_slug}.out\nnotification = never\nrequirements = ( OpSys == \"LINUX\" )\nqueue 1\n\"\"\"\n\ndef submit_condor_job(file_dir, file_slug, executable_path, arguments):\n ''' This function submits a job to a condor scheduler.\n '''\n\n # path to condor submit file that will be written\n sub_path = file_dir + '/' + file_slug + '.sub'\n\n # arugments to fill into condor submit file template\n content = {'executable_path' : executable_path,\n 'file_slug' : file_slug,\n 'arguments' : arguments,\n 'file_dir' : file_dir}\n\n # write condor submit file\n with open(sub_path, 'w') as fp:\n fp.write(submit_file_template.format(**content))\n\n # submit condor job\n Popen(['condor_submit', sub_path])\n\ndef ExecutableView(request, executable_slug):\n ''' This view renders the inputs to run an executable and the user can\n then submit the job to the condor scheduler.\n '''\n\n # initializations\n output_url = None\n\n # figure out what form to use\n FormClass = executable_form_map[executable_slug]\n\n # get executable path\n executable_path = distutils.spawn.find_executable(executable_slug)\n\n # check if HTTP POST request\n if request.method == 'POST':\n\n # get data\n form = FormClass(request.POST)\n\n # check if user posted a valid form\n if form.is_valid():\n\n # get inputs that are used to contruct filenames\n gps_start_time = form.cleaned_data['gps_start_time']\n gps_end_time = form.cleaned_data['gps_end_time']\n duration = gps_end_time - gps_start_time\n channel_name = form.cleaned_data['channel_name']\n\n # get IFO from channel name\n ifo = channel_name[:2]\n\n # get output path and url\n file_dir = 'static/output'\n file_extention = form.output_file_extension\n file_slug = ifo + '-' + os.path.basename(executable_path.upper()) + '-' + str(gps_start_time) + '-' + str(duration)\n output_dir = 'output'\n output_path = output_dir + '/' + file_slug\n output_url = server_url + '/' + output_path\n\n # construct arguments\n arguments = ''\n for key,value in form.cleaned_data.iteritems():\n arguments += ' --'+key.lower().replace('_', '-')+' '+str(value)\n\n # if output directory does not exist make it\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n\n # run executable using condor\n submit_condor_job(file_dir, file_slug, executable_path, arguments)\n\n # make an entry in the database\n entry = ExecutableOutput(output_url=output_url)\n entry.save()\n\n # get empty form if not HTTP POST request\n else:\n form = FormClass()\n\n # render\n context = {\n 'executable_path' : executable_path,\n 'form' : form,\n 'output_url' : output_url,\n }\n return render_to_response('executable.html', context,\n context_instance=RequestContext(request))\n\nclass Output():\n ''' This class handles rendering files in the templates.\n '''\n\n def __init__(self, path):\n self.path = path\n self.image_flag = path.split('.')[-1] in ['png'] \n self.text_flag = path.split('.')[-1] in ['err', 'log', 'out', 'sub']\n\n def text_read(self):\n ''' This function reads a text file.\n '''\n\n return open(self.path, 'r').read()\n\ndef OutputView(request, output_slug):\n ''' This view renders all the output files for an executable.\n '''\n\n # get all output files\n output_list = glob.glob('static/output/'+output_slug+'*')\n output_list = [Output(path) for path in output_list]\n\n # render\n context = {\n 'output_list' : output_list,\n }\n return render_to_response('output.html', context,\n context_instance=RequestContext(request))\n\ndef HomeView(request):\n ''' This view renders the home page.\n '''\n\n # list of all executables\n executable_list = executable_form_map.keys()\n\n # render\n context = {\n 'executable_list' : executable_list,\n }\n return render_to_response('home.html', context,\n context_instance=RequestContext(request))\n\ndef AllOutputView(request):\n ''' This view renders a list of all the output files.\n '''\n\n # get all entries in datbase for output files\n outputs = ExecutableOutput.objects.all().order_by('id').reverse()\n\n # render\n context = {\n 'outputs' : outputs,\n }\n return render_to_response('all_output.html', context,\n context_instance=RequestContext(request))\n","sub_path":"pbr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130406386","text":"from api import app\nfrom db.cache import get_cache\nfrom pysolarized import solr, from_solr_date\nfrom flask import request\nimport settings\n\ncache = get_cache()\n\n\n@app.route(\"/v1/news/related/\")\ndef get_related():\n news_id = request.args.get(u\"id\", None)\n if not news_id:\n return {\"error\": \"missing id parameter\"}\n return get_related_id(news_id)\n\n\n@app.route(\"/v1/news/related//\")\ndef get_related_id(news_id):\n return build_related(news_id)\n\n@cache.cache_on_arguments()\ndef build_related(id):\n solr_int = solr.Solr(settings.SOLR_ENDPOINT_URLS, settings.SOLR_DEFAULT_ENDPOINT)\n results = solr_int.more_like_this(\"id:%s\" % id, [\"title\", \"content\"], [\"id\",\n \"title\",\n \"published\",\n \"source\",\n \"source_url\",\n \"author\",\n \"score\"])\n\n if results is None:\n return {u\"error\": u\"Failed to connect to news search server.\"}\n\n documents = []\n for doc in results.documents:\n if \"score\" in doc and float(doc[\"score\"]) < 0.1:\n continue\n\n document = {u\"id\": doc[\"id\"],\n u\"published\": str(from_solr_date(doc[\"published\"]).isoformat()) + \"Z\",\n u\"link\": doc[\"source_url\"],\n u\"source\": doc[\"source\"]}\n\n if u\"author\" in doc and doc[u\"author\"] is not None:\n document[u\"author\"] = doc[\"author\"]\n document[u\"title\"] = doc[\"title\"]\n\n if u\"score\" in doc:\n document[u\"score\"] = doc[\"score\"]\n\n documents.append(document)\n\n r = {u\"results\": documents}\n return r","sub_path":"news_buddy/api/v1/related.py","file_name":"related.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285560775","text":"# -*- coding: UTF-8 -*-\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport numpy as np\r\n\r\n\r\ndef function(File_name, Dict): # 第一个参数表示传递文件名,第二个参数表示生成的新字典\r\n with open(File_name, 'r') as f:\r\n for line in f:\r\n temp = line.replace('\\n', '').split(',')\r\n task_id = temp[0] + ',' + temp[1] # 给新字典赋予键值\r\n if task_id not in Dict:\r\n Dict[task_id] = float(float(temp[3]) / 1000000) # 转换成s\r\n f.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n duration = [0] * 500 # 初始化一个空列表\r\n dict = {} # 初始化一个空字典\r\n all_task = 0 # 计数变量初始化为0\r\n function('G:/实习文件夹/task_schedule_time_with_timestamp.txt', dict) # 调用函数获得新字典\r\n with open('all.txt', 'w') as f: # 打开文件进行写入操作\r\n for key in dict:\r\n f.write(key + ',' + str(dict[key]) + '\\n')\r\n f.close()\r\n with open('all.txt', 'r') as f: # 再次打开刚才写入的文件,读取文件\r\n for line in f:\r\n temp = line.replace('\\n', '').split(',')\r\n all_task += 1\r\n if float(temp[2]) < 1000: # 判断是否在1000s内\r\n duration[math.floor(float(temp[2]) / float(2))] += 1 # 用整除将0-1000分为500段\r\n duration = np.cumsum(duration) # 求累加\r\n plt.plot([math.log10(i+1) for i in range(0, 1000, 2)], [math.log10(j) for j in duration]) # 将0-1000切分成500段并求出每一段的值不断进行叠加\r\n plt.xlabel('Scheduling time(x=lg(time))')\r\n plt.ylabel('Number of tasks(y=lg(number_of_tasks))')\r\n plt.show()","sub_path":"schedule-time_task-class.py","file_name":"schedule-time_task-class.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250185978","text":"from multiprocessing import Process\nfrom threading import Thread\n\nimport twint\nimport schedule\nimport time\n\nhashtags = ['#COVID19',\n '#C19',\n 'Corona',\n 'CORONA',\n 'corona',\n '#Corona',\n '#CORONA',\n '#corona',\n 'Coronavirus',\n 'CoronaVirus',\n 'CORONAVIRUS',\n '#Coronavirus',\n '#CoronaVirus',\n '#CORONAVIRUS'\n ]\n\n\ndef job(hashtag):\n c = twint.Config()\n c.Search = hashtag\n c.Since = \"2019-12-01\"\n c.Until = \"2020-05-01\"\n c.Lang = \"en\"\n c.Near = \"US\"\n c.Database = 'new_tweets.db'\n twint.run.Search(c)\n\n\ndef fetch_hashtags():\n for hashtag in hashtags:\n job(hashtag)\n\n\n# fetch_hashtags()\n\n# while True:\n# thread = Thread(target=fetch_hashtags)\n# thread.start()\n# time.sleep(1)\n\ndef job():\n c = twint.Config()\n c.Search = '#COVID19'\n c.Since = \"2019-12-01\"\n c.Until = \"2020-04-15\"\n c.Lang = \"en\"\n c.Near = \"US\"\n c.Database = 'tweets'\n twint.run.Search(c)\n\n\njob()\n\n# schedule.every().second.do(job)\n\n# while True:\n# # schedule.run_pending()\n# thread = Thread(target=job)\n# thread.start()\n# time.sleep(0.05)\n\n","sub_path":"automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"399327850","text":"import os\n\n# all base settings for Django\nfrom .base import *\n\nfrom .installed import *\n\nALLOWED_HOSTS = ['mahindarama-jv5lt5t3va-uw.a.run.app']\nDEBUG = False\n\nSECRET_KEY = os.environ.get(\n \"SECRET_KEY\", 'trp)7+j_n5^%a(%@itwn242@eq0d#m=ybtdl7_6j!%cg(is6e$')\n\n\nprint(\"Using production\")\n\n# Database\n\nHOME_PAGE_MESSAGE = f\"Hello World Testing 6. This Is Production.\"\n\nDB_USER_UN = os.environ.get(\"DB_USER_UN\", '')\nDB_USER_PW = os.environ.get(\"DB_USER_PW\", 'abc')\nDB_NAME = os.environ.get(\"DB_NAME\", \"production\")\nINSTANCE_CONNECTION_NAME = os.environ.get(\"INSTANCE_CONNECTION_NAME\")\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': DB_NAME,\n 'USER': DB_USER_UN,\n 'PASSWORD': DB_USER_PW,\n 'HOST': f'/cloudsql/{INSTANCE_CONNECTION_NAME}',\n }\n}\n","sub_path":"mahindarama/mahindarama/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"114761110","text":"#!/usr/bin/env python\n# encoding: utf-8\n# @Time:2020/9/15 15:09\n# @Author:JiahangGu\nfrom typing import List\n\n\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n \"\"\"\n 分析题意,首先对s串的操作是选定子区间升序排序,也就意味着大的数字会到后面,如果target某个位置发现数字小的在数字大的后面,且\n 后面都比较完成,则这个数组不能转换。\n 可以从后往前遍历,对于不相等的s[i], t[i],如果t[i] < s[i]则不可以转换,如果t[i]>s[i]则从s[i]向前查找到第一个t[i]的位置\n 和邻点两两交换(如果逆序的话),如果非逆序则无法交换。如果可以遍历到0得到相同字符串,则可以交换得到\n :param s:\n :param t:\n :return:\n \"\"\"\n # s_list = [c for c in s]\n # ptr_t, ptr_s = len(t)-1, len(s)-1\n # if ptr_s != ptr_t:\n # return False\n # while ptr_t >= 0 and ptr_s >= 0:\n # if s_list[ptr_s] == t[ptr_t]:\n # pass\n # elif s_list[ptr_s] > t[ptr_t]:\n # return False\n # else:\n # idx = ptr_s - 1\n # while idx >= 0 and s_list[idx] != t[ptr_t]:\n # idx -= 1\n # if idx < 0:\n # return False\n # for i in range(idx, ptr_s):\n # if s_list[i] < s_list[i+1]:\n # return False\n # s_list[i], s_list[i+1] = s_list[i+1], s_list[i]\n # ptr_t -= 1\n # ptr_s -= 1\n # return True\n \"\"\"\n 解法超时,通过样例129/131,但至少证明了思路是正确的。寻找一下可以优化的空间。首先就看到寻找s中出现的\n 第一个t[i],这里使用了两个循环一个查找另一个交换,但其实需要的信息是判断在找到的s对应字符的位置到t的位置\n 之间是否有大于该数字的字符出现,因为一旦出现之后就无法交换。所以可以使用一个字典来记录每个数字出现的位置,\n 如果该数字最右边的位置到t当前位置之间有大于的存在,则无法交换。而且,这里的邻点交换只是模拟,并不需要真的交换\n ,因为交换前后的子序列中的数字的相对位置不变。\n \"\"\"\n from collections import defaultdict\n pos = defaultdict(list)\n p_t, p_s = len(t)-1, len(s)-1\n if p_t != p_s:\n return False\n for i, c in enumerate(s):\n pos[int(c)].append(i)\n while p_t >= 0:\n # 判断s中最右边的t[p_t]换到p_s的位置的途中是否存在大于t[p_t]的值\n if not pos[int(t[p_t])]:\n return False\n left_pos = pos[int(t[p_t])].pop(-1)\n for i in range(int(t[p_t])+1, 10):\n if pos[i] and pos[i][-1] > left_pos:\n return False\n p_t -= 1\n return True\n\n\nss = Solution()\ns = \"12345\"\nt = \"12435\"\nprint(ss.isTransformable(s, t))\n","sub_path":"All Problems/1585-check-if-string-is-transformable-with-substring-sort-operations.py","file_name":"1585-check-if-string-is-transformable-with-substring-sort-operations.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"482141209","text":"#! python3.6\r\n\r\n\r\nimport tkinter as tk\r\n\r\n# Create main window\r\nwin = tk.Tk()\r\n# Setting the title\r\nwin.title(\"responsive GUI Label\")\r\n# set minimum size for window resizing\r\nwin.minsize(300,100)\r\n# set background color\r\nwin.config(bg=\"#9b9\")\r\n\r\n# Create Label widget\r\nL = tk.Label(win)\r\n\r\n# method 1 to configure label\r\nL[\"text\"] = \"blue label\".capitalize()\r\n\r\n# dict for style options [ bg, fg, bd, ... etc]\r\nstyleoptions = {'relief':'groove', 'fg':\"white\", 'bd':3, 'bg':\"#39f\"}\r\n# dict for font options ...\r\nfontoptions = {'font':(\"calibri\", 12, \"italic\",\"bold\",\"underline\")}\r\n\r\n# method 2 to configure label\r\nL.config(styleoptions) # ex 1: style [colors, relief .. etc]\r\nL.config(fontoptions) # ex 2: font [type, size, mode .. etc]\r\n\r\n# place manager ,, options . as a dict\r\nplaceoptions = {'relx':0.5, 'rely':0.5, 'relwidth':0.8, 'relheight':0.3, 'anchor':'center'}\r\n\r\n# configure place options ..\r\nL.place_configure(placeoptions)\r\n\r\n\r\n# FLOOTING MENU TESTing\r\ndef MSG():\r\n '''toplevel window'''\r\n win2 = tk.Toplevel()\r\n win2.minsize(180,140)\r\n win2.geometry(\"50x50\")\r\n msg = tk.Message(win2, bg=\"#afa\", font=(\"Console\", 10, \"bold\"))\r\n txt = '''hi, top level window\r\ninherite from main win\r\nexecuted from floating menu\r\nthat can be only accessed from The Blue Label'''\r\n msg.config(text=txt)\r\n msg.place(relx=0.5,rely=0.5, relwidth=1, relheight=0.9, anchor='center')\r\n\r\n# Menu settings\r\nfm = tk.Menu(win, tearoff=0)\r\nfm.config(bg=\"#aaf\",font=(\"courier\",10,\"bold\"))\r\nfm.add_command(label=\"about\", command=MSG)\r\n\r\ndef fm_popup(menu, ev):\r\n menu.post(ev.x_root+5, ev.y_root)\r\n \r\n\r\nL.bind(\"\", lambda ev: fm_popup(fm, ev))\r\n\r\n# start mainloop ...\r\nwin.mainloop()\r\n","sub_path":"tk_tutorial/widget_label_configuration.py","file_name":"widget_label_configuration.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472315620","text":"# bayesian_neural_network.py\n# zhoudoao@gmail.com\n# 2018.8.21\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport time\nimport json\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport edward as ed\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as plb\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom edward.models import Normal, Categorical\n\ndef main():\n \"\"\" Parameters \"\"\"\n params = {\n 'input_dim': 784,\n 'output_dim': 10,\n 'train_size': 50000,\n 'test_size': 1000,\n 'batch_size': 128,\n # 'n_epochs': int(n_epochs),\n # 'learning_rate': float(learning_rate),\n 'hidden_size': [400, 400]\n }\n\n \"\"\" log_file_name = 'logfile.txt'\n log_file = open(log_file_name, 'a+')\n llog_file.write(time.strftime('%a, %d %b %Y %H:%M:%S +0800\\n', time.localtime()))\n log_file.write(json.dumps(params)) \"\"\"\n\n \"\"\" Data \"\"\"\n # path to data\n path = './data/mnist'\n if not os.path.exists(path):\n os.makedirs(path)\n # mnist data\n mnist = input_data.read_data_sets(path, one_hot=True)\n\n \"\"\" Variables \"\"\"\n # weights and biases of neural networks\n with tf.name_scope('model'):\n x = tf.placeholder(tf.float32, [None, params['input_dim']])\n w1 = Normal(loc=tf.zeros([params['input_dim'], params['hidden_size'][0]]), \n scale=tf.ones([params['input_dim'], params['hidden_size'][0]]))\n b1 = Normal(loc=tf.zeros(params['hidden_size'][0]),\n scale=tf.ones(params['hidden_size'][0]))\n w2 = Normal(loc=tf.zeros([params['hidden_size'][0], params['hidden_size'][1]]),\n scale=tf.ones([params['hidden_size'][0], params['hidden_size'][1]]))\n b2 = Normal(loc=tf.zeros(params['hidden_size'][1]),\n scale=tf.ones(params['hidden_size'][1]))\n w3 = Normal(loc=tf.zeros([params['hidden_size'][1], params['output_dim']]),\n scale=tf.ones(params['output_dim']))\n b3 = Normal(loc=tf.zeros(params['output_dim']),\n scale=tf.ones(params['output_dim']))\n \n # define the neural networks\n def nn(x, w1, b1, w2, b2, w3, b3):\n a1 = tf.tanh(tf.matmul(x, w1)+b1)\n a2 = tf.tanh(tf.matmul(a1, w2)+b2)\n y = tf.matmul(a2, w3)+b3\n return y\n y = Categorical(nn(x, w1, b1, w2, b2, w3, b3))\n\n \"\"\" Inference \"\"\"\n qw1 = Normal(loc=tf.Variable(tf.random_normal([params['input_dim'], params['hidden_size'][0]])), \n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['input_dim'], params['hidden_size'][0]]))))\n qb1 = Normal(loc=tf.Variable(tf.random_normal([params['hidden_size'][0]])),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['hidden_size'][0]]))))\n\n qw2 = Normal(loc=tf.Variable(tf.random_normal([params['hidden_size'][0], params['hidden_size'][1]])),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['hidden_size'][0], params['hidden_size'][1]]))))\n qb2 = Normal(loc= tf.Variable(tf.random_normal([params['hidden_size'][1]])),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['hidden_size'][1]]))))\n\n qw3 = Normal(loc=tf.Variable(tf.random_normal([params['hidden_size'][1], params['output_dim']])), \n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['hidden_size'][1], params['output_dim']]))))\n qb3 = Normal(loc=tf.Variable(tf.random_normal([params['output_dim']])),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([params['output_dim']]))))\n\n y_ph = tf.placeholder(tf.int32, [params['batch_size']])\n inference = ed.KLqp(\n {w1: qw1, b1: qb1,\n w2: qw2, b2: qb2,\n w3: qw3, b3: qb3},\n data={y: y_ph}\n )\n inference.initialize(n_iter=50000, n_print=100, scale={y: float(mnist.train.num_examples)/params['batch_size']})\n sess = tf.InteractiveSession()\n tf.global_variables_initializer().run()\n for _ in range(inference.n_iter):\n x_batch, y_batch = mnist.train.next_batch(params['batch_size'])\n y_batch = np.argmax(y_batch, axis=1)\n info_dict = inference.update(feed_dict={x: x_batch, y_ph: y_batch})\n inference.print_progress(info_dict) \n\n \"\"\" Test \"\"\"\n x_test = mnist.test.images\n y_test = np.argmax(mnist.test.labels, axis=1)\n\n \"\"\" Samples from posterior \"\"\"\n n_samples = 10\n prob_lst = []\n samples = []\n w1_samples, w2_samples, w3_samples = [], [], []\n b1_samples, b2_samples, b3_samples = [], [], []\n\n for i in range(n_samples):\n w1_sample = qw1.sample()\n w2_sample = qw2.sample()\n w3_sample = qw3.sample()\n b1_sample = qb1.sample()\n b2_sample = qb2.sample()\n b3_sample = qb3.sample()\n w1_samples.append(w1_sample)\n w2_samples.append(w2_sample)\n w3_samples.append(w3_sample) \n b1_samples.append(b1_sample)\n b2_samples.append(b2_sample)\n b3_samples.append(b3_sample)\n prob = tf.nn.softmax(nn(x_test, w1_sample, b1_sample, w2_sample, b2_sample, w3_sample, b3_sample))\n prob_lst.append(prob.eval())\n print('Sample : {}'.format(i))\n\n acc_test = []\n for prob in prob_lst:\n y_trn_prd = np.argmax(prob, axis=1).astype(np.float32)\n acc = (y_trn_prd==y_test).mean()*100\n acc_test.append(acc)\n \n plt.hist(acc_test)\n plt.title('Historgram of prediction accuracies in the MNIST test data')\n plt.xlabel('Accuracy')\n plt.ylabel('Frequency')\n plt.show()\n\n y_pred = np.argmax(np.mean(prob_lst, axis=0), axis=1)\n print('Accuracy in predicting the test data = ', (y_pred == y_test).mean()*100)\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"bayesian_neural_network.py","file_name":"bayesian_neural_network.py","file_ext":"py","file_size_in_byte":5854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449866705","text":"from django.urls import path\n\nfrom . import views\nfrom .controllers import tools\n\napp_name = 'bioseq'\nurlpatterns = [\n path('about', views.AboutView.as_view(), name='index'),\n path('tax/', views.TaxView.as_view(), name='tax_view'),\n path('seq/', views.sequence_view, name='seq_view'),\n path('assembly/', views.assembly_view, name='assembly_view'),\n path('seq/', views.sequence_lt_view, name='sequence_lt_view'),\n\n path('geneproducts', views.gene_product_list_view, name='gene_product_list'),\n path('proteins/', views.protein_list_view, name='protein_list'),\n\n\n path('variant/', views.TaxView.as_view(), name='variant_view'),\n\n path('blast', tools.blast, name='blast_view'),\n path('blast_result', tools.blast_result, name='blast_result_view'),\n path('msa/', views.AboutView.as_view(), name='msa_view'),\n path('primer/', views.AboutView.as_view(), name='primer_view'),\n\n\n\n path('analysis/', views.TaxView.as_view(), name='analysis_view'), # tree / msa / blast\n\n\n\n # path('pathway/', views.TaxView.as_view(), name='tax_view'),\n\n # path('publications', views.FilteredPersonListView.as_view(), name='publications'),\n # path('search/', views.BioSearchView.as_view(), name='search_view'),\n\n\n]","sub_path":"bioseq/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10690833","text":"from sys import stdout\nimport numpy as np\nnp.set_printoptions(threshold=np.nan)\nimport vrep as VREP\nimport time\nimport math\nimport array\nimport cv2\n\nfrom PIL import Image\nfrom utility import *\n\n\nclass State:\n def init():\n return \"initialized\"\n\n def drive_to_object():\n return \"driving_to_object\"\n\n def follow_obstacle():\n return \"following_obstacle\"\n\n def grab_object():\n return \"grabbing_object\"\n\n def drop_object():\n return \"dropping_object\"\n\n def goal_reached():\n return \"goal_reached\"\n\nclass ArmState:\n def rest():\n return \"rest_pose\"\n\n def grasping():\n return \"grasping_pose\"\n\n def drop():\n return \"dropping_pose\"\n\n\nclass YouBot:\n class ConnectionError(RuntimeError):\n def __init__(self):\n RuntimeError.__init__(self)\n\n def scope_from_diameter(diameter):\n return math.pi * diameter\n\n WHEEL_DIAMETER = 100 # mm\n WHEEL_SCOPE = scope_from_diameter(WHEEL_DIAMETER)\n\n INNER_WHEEL_DIAMETER = 28 # mm\n INNER_WHEEL_SCOPE = scope_from_diameter(INNER_WHEEL_DIAMETER)\n\n WHEEL_DISTANCE = 471 # mm\n AXIS_DISTANCE = 300.46 # mm\n ROTATION_DIAMETER = math.sqrt(math.pow(WHEEL_DISTANCE, 2) + math.pow(AXIS_DISTANCE, 2)) # mm\n ROTATION_SCOPE = scope_from_diameter(ROTATION_DIAMETER)\n\n def __init__(self, ip, port, wait=True, reconnect=False, timeout=2000, thread_cycle=5):\n self.ip = ip\n self.port = port\n self.wait = wait\n self.reconnect = reconnect\n self.timeout = timeout\n self.thread_cycle = thread_cycle\n self.wheel_joints = [-1] * 4\n self.arm_joints = [-1] * 5\n self.position = Point(0.0, 0.0)\n self.pose = 0\n self.sensor_right = None\n self.sensor_left = None\n self.camera = None\n self.state = State.init()\n self.arm_state = ArmState.rest()\n self.initial_arm_poses = [0.0] * 5\n\n def update_arm_state(self, state):\n self.arm_state = state\n return self.arm_state\n\n def arm_state_transition(self, to_state):\n print('\\ttransition: ', self.arm_state, '->', to_state)\n return self.update_arm_state(to_state)\n\n def update_state(self, state):\n self.state = state\n return self.state\n\n def transition(self, to_state):\n print('\\ttransition: ', self.state, '->', to_state)\n return self.update_state(to_state)\n\n def connect(self):\n self.client_id = VREP.simxStart(self.ip, self.port, self.wait, not self.reconnect, self.timeout, self.thread_cycle)\n if self.client_id == -1:\n raise ConnectionError('Failed connecting to remote API server.')\n\n self.update_pose()\n self.update_position()\n\n _, self.wheel_joints[0] = VREP.simxGetObjectHandle(self.client_id, 'rollingJoint_fl', VREP.simx_opmode_oneshot_wait)\n _, self.wheel_joints[1] = VREP.simxGetObjectHandle(self.client_id, 'rollingJoint_rl', VREP.simx_opmode_oneshot_wait)\n _, self.wheel_joints[2] = VREP.simxGetObjectHandle(self.client_id, 'rollingJoint_rr', VREP.simx_opmode_oneshot_wait)\n _, self.wheel_joints[3] = VREP.simxGetObjectHandle(self.client_id, 'rollingJoint_fr', VREP.simx_opmode_oneshot_wait)\n\n for i in range(len(self.arm_joints)):\n res, self.arm_joints[i] = VREP.simxGetObjectHandle(self.client_id, 'youBotArmJoint%d' % i, VREP.simx_opmode_oneshot_wait)\n\n res, self.arm_base = VREP.simxGetObjectHandle(self.client_id, 'youBotArmJoint0', VREP.simx_opmode_oneshot_wait)\n self.initial_arm_poses = self.arm_poses()\n\n print('ROBOT_STATE:')\n print('\\t', self.state)\n print('ARM_STATE:')\n print('\\t', self.arm_state)\n\n _, self.sensor_right = VREP.simxGetObjectHandle(self.client_id, 'fastHokuyo_sensor1', VREP.simx_opmode_oneshot_wait)\n _, self.sensor_left = VREP.simxGetObjectHandle(self.client_id, 'fastHokuyo_sensor2', VREP.simx_opmode_oneshot_wait)\n\n # start sensors\n VREP.simxSetIntegerSignal(self.client_id, 'handle_xy_sensor', 2, VREP.simx_opmode_streaming)\n VREP.simxSetIntegerSignal(self.client_id, 'displaylasers', 1, VREP.simx_opmode_oneshot)\n VREP.simxReadVisionSensor(self.client_id, self.sensor_right, VREP.simx_opmode_streaming)\n VREP.simxReadVisionSensor(self.client_id, self.sensor_left, VREP.simx_opmode_streaming)\n\n def disconnect(self):\n if not self.client_id == -1:\n VREP.simxFinish(self.client_id)\n self.client_id = -1\n\n def start_simulation(self):\n VREP.simxStartSimulation(self.client_id, VREP.simx_opmode_oneshot_wait)\n\n for i in range(len(self.wheel_joints)):\n VREP.simxSetJointTargetVelocity(self.client_id, self.wheel_joints[i], 0, VREP.simx_opmode_oneshot_wait)\n\n def stop_simulation(self):\n VREP.simxStopSimulation(self.client_id, VREP.simx_opmode_oneshot_wait)\n\n @classmethod\n def wheel_vel(self, forw_back, left_right, rotation):\n # velocities in rad/s\n return [\n (-forw_back) + (-left_right) + (rotation),\n (-forw_back) + (+left_right) + (rotation),\n (-forw_back) + (-left_right) + (-rotation),\n (-forw_back) + (+left_right) + (-rotation),\n ]\n\n @classmethod\n def forward_distance_by_speed_and_time(self, speed, time):\n radius = self.WHEEL_DIAMETER / 2\n return radius * speed * time # mm\n\n @classmethod\n def rotation_by_speed_and_time(self, speed, time):\n return speed * time # rad\n\n def base(self):\n _, base = VREP.simxGetObjectHandle(self.client_id, 'youBot_center', VREP.simx_opmode_oneshot_wait)\n return base\n\n def vrep_orientation(self, object_handle):\n _, orientation = VREP.simxGetObjectOrientation(self.client_id, object_handle, -1, VREP.simx_opmode_oneshot_wait)\n return orientation\n\n def vrep_object(self, object_name):\n _, goal = VREP.simxGetObjectHandle(self.client_id, object_name, VREP.simx_opmode_blocking)\n return goal\n\n def vrep_self_position(self):\n res, position = VREP.simxGetObjectPosition(self.client_id, self.base(), -1, VREP.simx_opmode_oneshot_wait)\n return position\n\n def vrep_position(self, objectHandle):\n _, position = VREP.simxGetObjectPosition(self.client_id, objectHandle, -1, VREP.simx_opmode_oneshot_wait)\n x = position[0]\n y = position[1]\n return Point(x, y)\n\n def vrep_reset(self):\n VREP.simxSetObjectOrientation(self.client_id, self.base(), -1, [0, 0, 0], VREP.simx_opmode_oneshot_wait)\n\n def update_odometry_pose(self, angle):\n new_pose_in_deg = self.pose + math.degrees(angle)\n\n if new_pose_in_deg >= 0:\n new_pose_in_deg %= 360\n else:\n new_pose_in_deg %= -360\n\n self.pose = new_pose_in_deg\n\n def update_odometry_position(self, forward_distance, sideward_distance):\n f_x = forward_distance * math.cos(math.radians(self.pose))\n f_y = forward_distance * math.sin(math.radians(self.pose))\n\n s_x = sideward_distance * -math.sin(math.radians(self.pose))\n s_y = sideward_distance * math.cos(math.radians(self.pose))\n\n self.position.x += f_x + s_x\n self.position.y += f_y + s_y\n\n def update_position(self):\n _, position = VREP.simxGetObjectPosition(self.client_id, self.base(), -1, VREP.simx_opmode_oneshot_wait)\n self.position.x = position[0]\n self.position.y = position[1]\n return position\n\n def update_pose(self):\n self.pose = (360 + math.degrees(self.vrep_orientation(self.base())[2])) % 360\n return self.pose\n\n def update_arm_base(self):\n _, self.arm_base = VREP.simxGetObjectHandle(self.client_id, 'youBotArmJoint0', VREP.simx_opmode_oneshot_wait)\n return self.arm_base\n\n def set_wheel_velocities(self, wheel_velocities):\n VREP.simxPauseCommunication(self.client_id, True)\n\n for i in range(len(self.wheel_joints)):\n VREP.simxSetJointTargetVelocity(self.client_id, self.wheel_joints[i], wheel_velocities[i], VREP.simx_opmode_oneshot)\n\n VREP.simxPauseCommunication(self.client_id, False)\n\n def drive(self, forw_back, left_right, rotation, duration):\n self.set_wheel_velocities(self.wheel_vel(-forw_back, left_right, rotation))\n time.sleep(duration)\n self.update_position()\n self.update_pose()\n\n def brake(self):\n VREP.simxPauseCommunication(self.client_id, True)\n for wheel_joint in self.wheel_joints:\n VREP.simxSetJointTargetVelocity(self.client_id, wheel_joint, 0, VREP.simx_opmode_oneshot)\n\n VREP.simxPauseCommunication(self.client_id, False)\n\n def parse_sensor_data(self, data):\n _, (count, _, *measurements) = data\n\n return list(map(\n lambda i: {\n 'x': measurements[i * 4 + 0],\n 'y': measurements[i * 4 + 1],\n 'z': measurements[i * 4 + 2],\n 'd': measurements[i * 4 + 3],\n },\n range(0, int(count))\n ))\n\n def parse_sensors(self, aux_d1, aux_d2):\n # get all distance values for both sensors\n distances1 = list(map(lambda d: d['d'], self.parse_sensor_data(aux_d1))) # left\n distances2 = list(map(lambda d: d['d'], self.parse_sensor_data(aux_d2))) # right\n\n split_central = np.array_split(distances1[:130] + distances2[-130:], 10)\n distances_central = list(map(np.mean, split_central))\n\n # split list in 3 parts and get the average of every part\n split_left = np.array_split(distances1[-200:], 10)\n distances_left = list(map(np.mean, split_left))\n\n split_right = np.array_split(distances2[70:200], 10)\n distances_right = list(map(np.mean, split_right))\n\n return [distances_left, distances_central, distances_right]\n\n def read_sensors(self):\n res1, _, aux_d1 = VREP.simxReadVisionSensor(self.client_id, self.sensor_left, VREP.simx_opmode_oneshot_wait)\n res2, _, aux_d2 = VREP.simxReadVisionSensor(self.client_id, self.sensor_right, VREP.simx_opmode_oneshot_wait)\n obstacle = [False, False, False, False]\n\n if res1 == VREP.simx_return_ok and res2 == VREP.simx_return_ok:\n [left, center, right] = self.parse_sensors(aux_d1, aux_d2)\n\n if any(d < 0.35 for d in left):\n obstacle[0] = True\n\n if any(d < 0.35 for d in center):\n obstacle[1] = True\n\n if any(d < 0.35 for d in right):\n obstacle[2] = True\n\n if any(d < 0.5 for d in left):\n obstacle[3] = True\n\n return obstacle\n\n def get_goal_direction(self, goal_handle):\n robot_pos_wrt_goal = VREP.simxGetObjectPosition(self.client_id, self.base(), goal_handle, VREP.simx_opmode_oneshot_wait)\n dx = robot_pos_wrt_goal[1][0]\n dy = robot_pos_wrt_goal[1][1]\n theta = math.atan2(-dx, dy)\n\n return math.degrees(theta)\n\n def in_range(self, value, lower, upper):\n return (lower <= value <= upper)\n\n def rotate(self, to_degree, speed=1):\n self.update_pose()\n if (to_degree < self.pose):\n if (math.fabs(to_degree - self.pose) >= 180):\n while (not self.in_range(self.pose, to_degree - 3, to_degree + 3)):\n self.drive(0, 0, speed, 0.001)\n else:\n while (not self.in_range(self.pose, to_degree - 3, to_degree + 3)):\n self.drive(0, 0, -speed, 0.001)\n else:\n if (math.fabs(to_degree - self.pose) <= 180):\n while (not self.in_range(self.pose, to_degree - 3, to_degree + 3)):\n self.drive(0, 0, speed, 0.001)\n else:\n while (not self.in_range(self.pose, to_degree - 3, to_degree + 3)):\n self.drive(0, 0, -speed, 0.001)\n self.update_pose()\n\n def rotate_by_degree(self, degree, iteration=0, speed=1):\n init_pose = self.pose\n to_degree = init_pose + degree\n\n if(to_degree < 0):\n to_degree + 360\n\n self.rotate_to_degree(to_degree)\n\n def rotate_to_goal(self, theta):\n if (theta > 180):\n theta = -(360 - theta)\n\n self.rotate_to_degree(theta)\n\n def rotate_to_degree(self, degree):\n if (degree < 0):\n degree += 360\n\n self.rotate(degree)\n\n def check_free_space(self, goal):\n _, _, aux_d1 = VREP.simxReadVisionSensor(self.client_id, self.sensor_left, VREP.simx_opmode_oneshot_wait)\n _, _, aux_d2 = VREP.simxReadVisionSensor(self.client_id, self.sensor_right, VREP.simx_opmode_oneshot_wait)\n left, center, right = self.parse_sensors(aux_d1, aux_d2)\n\n return np.mean(right) > 0.25 and np.mean(center) > 0.25\n\n def check_direction_to_goal(self, goalObject):\n theta = self.get_goal_direction(goalObject)\n if (theta < 0):\n theta = -theta\n\n return (self.pose + theta) % 360 <= 20\n\n def drive_until_obstacle(self, speed, goal, min_dist_to_goal=0.65):\n should_be_state = State.drive_to_object()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n\n while(True):\n distance_to_goal = self.position.distance(goal)\n stdout.write(\"\\rDistance to goal %f m \" % distance_to_goal)\n stdout.flush()\n\n if distance_to_goal <= min_dist_to_goal:\n stdout.write(\"\\n\")\n return True\n\n left, center, right, _ = self.read_sensors()\n\n if left or center or right:\n break\n\n self.drive(speed, 0, 0, 0.5)\n stdout.write(\"\\n\")\n\n def dist_bug(self, goalObject, speed, min_dist_to_goal=0.65):\n self.update_position()\n self.update_pose()\n theta = self.get_goal_direction(goalObject)\n self.rotate_to_goal(theta)\n\n goal = self.vrep_position(goalObject)\n goal_reached = False\n\n while (True):\n if(self.drive_until_obstacle(speed, goal, min_dist_to_goal)):\n goal_reached = True\n should_be_state = State.goal_reached()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n break\n\n if (self.follow_obstacle_boundary(speed, goalObject)):\n break\n\n theta = self.get_goal_direction(goalObject)\n self.rotate_to_goal(theta)\n\n if (not goal_reached):\n self.update_position()\n self.update_pose()\n theta = self.get_goal_direction(goalObject)\n self.rotate_to_goal(theta)\n self.drive_until_obstacle(speed, goal, min_dist_to_goal)\n\n self.brake()\n\n def follow_obstacle_boundary(self, speed, goalObject):\n should_be_state = State.follow_obstacle()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n\n goal = self.vrep_position(goalObject)\n\n while (True):\n [left, center, right, far_left] = self.read_sensors()\n if (not center and not right and left):\n goal = self.vrep_position(goalObject)\n a = self.check_free_space(goal)\n b = self.check_direction_to_goal(goalObject)\n\n if (a and b):\n break\n\n if center or left:\n self.drive(0, 0, -1, 0.05)\n elif not center and not left and not far_left:\n self.drive(0, 0, 1, 0.05)\n else:\n self.drive(speed, 0, 0, 0.05)\n\n if (self.check_free_space(goal) and self.check_direction_to_goal(goalObject)):\n break\n\n def start_camera(self, angle=math.pi / 4):\n # Change the angle of the camera view. (default: pi / 4)\n VREP.simxSetFloatSignal(self.client_id, 'rgbd_sensor_scan_angle', angle, VREP.simx_opmode_oneshot_wait)\n\n # Turn on camera.\n VREP.simxSetIntegerSignal(self.client_id, 'handle_rgb_sensor', 2, VREP.simx_opmode_oneshot_wait)\n\n # Get camera object handle.\n _, self.camera = VREP.simxGetObjectHandle(self.client_id, 'rgbSensor', VREP.simx_opmode_oneshot_wait)\n\n # Get first image.\n _, resolution, image = VREP.simxGetVisionSensorImage(self.client_id, self.camera, 0, VREP.simx_opmode_oneshot_wait)\n\n return [resolution, image]\n\n @classmethod\n def vrep_to_opencv(self, image, resolution):\n image_bytes = bytes(array.array('b', image))\n image_buffer = Image.frombytes(\"RGB\", (resolution[0], resolution[1]), np.asarray(image_bytes), \"raw\", \"RGB\", 0, 1)\n image = np.asarray(image_buffer)\n return cv2.cvtColor(cv2.flip(image, 0), cv2.COLOR_BGR2RGB)\n\n @classmethod\n def opencv_to_vrep(self, image):\n image = cv2.cvtColor(cv2.flip(image, 0), cv2.COLOR_RGB2BGR)\n return image.ravel()\n\n def get_image(self):\n res, resolution, image = VREP.simxGetVisionSensorImage(self.client_id, self.camera, 0, VREP.simx_opmode_oneshot_wait)\n\n if res == VREP.simx_return_ok:\n # Convert VREP image to OpenCV image.\n return self.vrep_to_opencv(image, resolution)\n\n return None\n\n def show_image(self, image):\n # Send OpenCV image back to VREP.\n vrep_image = self.opencv_to_vrep(image)\n VREP.simxSetVisionSensorImage(self.client_id, self.camera, vrep_image, 0, VREP.simx_opmode_oneshot)\n\n # Display image in external window.\n cv2.imshow(\"camera\", image)\n cv2.waitKey(5)\n\n def drive_without_braking(self, forw_back, left_right, rotation):\n should_be_state = State.driving()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n\n self.set_wheel_velocities(self.wheel_vel(forw_back, left_right, rotation))\n\n def gripper_status(self):\n _, status = VREP.simxGetIntegerSignal(self.client_id, 'gripper_open', VREP.simx_opmode_oneshot_wait)\n return status\n\n def gripper_open(self, sleep=None):\n self.gripper_action(1, sleep)\n\n def gripper_close(self, sleep=None):\n self.gripper_action(0, sleep)\n\n def gripper_action(self, action, sleep=None):\n if sleep is None:\n sleep = True if self.gripper_status() is not action else False\n\n res = VREP.simxSetIntegerSignal(self.client_id, 'gripper_open', action, VREP.simx_opmode_oneshot_wait)\n\n if sleep:\n time.sleep(1)\n\n def arm_poses(self):\n arm_poses = [None] * len(self.arm_joints)\n\n for i in range(len(self.arm_joints)):\n arm_poses[i] = round(VREP.simxGetJointPosition(self.client_id, self.arm_joints[i], VREP.simx_opmode_oneshot_wait)[1], 3)\n\n return arm_poses\n\n def print_arm_poses(self):\n stdout.write(\"\\t[\")\n i = 0\n while(i < len(self.arm_poses()) - 1):\n stdout.write(\"%.2f°, \" % math.degrees(self.arm_poses()[i]))\n i += 1\n stdout.write(\"%.2f°]\\n\" % math.degrees(self.arm_poses()[i]))\n\n def move_arm(self, angles, sleep=True):\n VREP.simxPauseCommunication(self.client_id, True)\n\n max_angle = 0\n\n for i in range(len(self.arm_joints)):\n if angles[i] is not None:\n res = VREP.simxSetJointTargetPosition(self.client_id, self.arm_joints[i], angles[i], VREP.simx_opmode_oneshot)\n if max_angle < math.fabs(angles[i]):\n max_angle = math.fabs(angles[i])\n\n VREP.simxPauseCommunication(self.client_id, False)\n\n if sleep is True:\n time.sleep(2 * (math.degrees(max_angle) / 90))\n elif sleep is not False:\n time.sleep(sleep)\n\n def rotate_arm_to_target(self, target, sleep=True, opposite_side=False):\n res, (x, y, z) = VREP.simxGetObjectPosition(self.client_id, self.arm_base, -1, VREP.simx_opmode_oneshot_wait)\n\n arm_base_position = Point(x, y)\n\n target_point = self.vrep_position(target)\n rotation = target_point.rotation(arm_base_position) - self.vrep_orientation(self.arm_base)[2] - math.radians(90)\n\n if opposite_side is True:\n rotation += math.radians(180)\n\n self.move_arm([\n rotation,\n None,\n None,\n None,\n None,\n ], sleep)\n\n def prepare_arm(self):\n self.gripper_open(False)\n\n self.move_arm([\n math.radians(90),\n math.radians(45),\n math.radians(-150),\n math.radians(102.5),\n math.radians(0)\n ], False)\n\n def grab_object(self, target):\n # robot\n should_be_state = State.grab_object()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n\n # arm\n should_be_state = ArmState.grasping()\n if self.arm_state != should_be_state:\n print('ARM_STATE: ')\n print('\\tcurrent: ', self.arm_state_transition(should_be_state))\n self.print_arm_poses()\n\n self.rotate_arm_to_target(target, 1)\n\n self.move_arm([\n None, # ground rotation\n math.radians(-71), # R1 / L1\n math.radians(-150), # R2 / L2\n math.radians(102.5), # R3 / tool frame\n math.radians(0) # tool frame rotation\n ], 1)\n\n self.move_arm([\n None,\n math.radians(-75),\n math.radians(-120),\n math.radians(80),\n math.radians(0)\n ], 1)\n\n self.move_arm([\n None,\n math.radians(-80),\n math.radians(-95),\n math.radians(70),\n math.radians(0)\n ], 0.5)\n\n self.move_arm([\n None,\n math.radians(-85),\n math.radians(-80),\n math.radians(70),\n math.radians(0)\n ], 0.5)\n\n self.move_arm([\n None,\n math.radians(-90),\n math.radians(-75),\n math.radians(65),\n math.radians(0)\n ])\n\n target_point = self.vrep_position(target)\n while (self.vrep_position(self.arm_base).distance(target_point) > 0.42):\n self.drive(0, 1, 0, 0.01)\n self.brake()\n\n self.gripper_close()\n\n # after grabbing raise up the object\n self.move_arm([\n math.radians(-180), # ground rotation\n math.radians(-10), # R1 / L1\n math.radians(-60), # R2 / L2\n math.radians(-20), # R3 / tool frame\n math.radians(0) # tool frame rotation\n ], 4)\n\n should_be_state = ArmState.rest()\n if self.arm_state != should_be_state:\n print('ARM_STATE: ')\n print('\\tcurrent: ', self.arm_state_transition(should_be_state))\n self.print_arm_poses()\n\n def drop_object_into_target(self, target):\n # robot\n should_be_state = State.drop_object()\n if self.state != should_be_state:\n print('ROBOT_STATE:')\n print(\"\\tcurrent: \", self.transition(should_be_state))\n\n # arm\n should_be_state = ArmState.drop()\n if self.arm_state != should_be_state:\n print('ARM_STATE:')\n print('\\tcurrent: ', self.arm_state_transition(should_be_state))\n self.print_arm_poses()\n\n self.rotate_arm_to_target(target, 1.5)\n\n # drop object into basket\n self.move_arm([\n None, # ground rotation\n math.radians(-40), # R1 / L1\n math.radians(-40), # R2 / L2\n math.radians(-10), # R3 / tool frame\n math.radians(0) # tool frame rotation\n ], 4)\n\n self.gripper_open()\n\n # after the object is dropped, bring arm to a initial arm position while driving\n self.move_arm(self.initial_arm_poses, 1.5)\n\n should_be_state = ArmState.rest()\n if self.arm_state != should_be_state:\n print('ARM_STATE: ')\n print('\\tcurrent: ', self.arm_state_transition(should_be_state))\n self.print_arm_poses()\n","sub_path":"includes/youbot.py","file_name":"youbot.py","file_ext":"py","file_size_in_byte":22248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"141587345","text":"# -*- coding:utf8 -*-\n\nimport platform\nimport subprocess\n\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QApplication\n\nfrom base.logger import LOG\n\n\nclass ControllerApi(object):\n \"\"\"暴露给plugin或者其他外部模块的接口和数据\n \"\"\"\n notify_widget = None\n lyric_widget = None\n desktop_mini = None\n current_playlist_widget = None\n player = None\n network_manager = None\n api = None\n\n state = {\"is_login\": False,\n \"current_mid\": 0,\n \"current_pid\": 0,\n \"platform\": \"\",\n \"other_mode\": False}\n\n @classmethod\n def set_login(cls):\n cls.state['is_login'] = True\n cls.view.ui.LOVE_SONG_BTN.show()\n cls.view.ui.LOGIN_BTN.hide()\n\n @classmethod\n def play_mv_by_mvid(cls, mvid):\n mv_model = ControllerApi.api.get_mv_detail(mvid)\n if not ControllerApi.api.is_response_ok(mv_model):\n return\n\n url_high = mv_model['url_high']\n clipboard = QApplication.clipboard()\n clipboard.setText(url_high)\n\n if platform.system() == \"Linux\":\n ControllerApi.player.pause()\n ControllerApi.notify_widget.show_message(\"通知\", \"正在尝试调用VLC视频播放器播放MV\")\n subprocess.Popen(['vlc', url_high, '--play-and-exit', '-f'])\n elif platform.system().lower() == 'Darwin'.lower():\n ControllerApi.player.pause()\n cls.view.ui.STATUS_BAR.showMessage(u\"准备调用 QuickTime Player 播放mv\", 4000)\n subprocess.Popen(['open', '-a', 'QuickTime Player', url_high])\n else:\n cls.view.ui.STATUS_BAR.showMessage(u\"程序已经将视频的播放地址复制到剪切板\", 5000)\n\n @classmethod\n def toggle_lyric_widget(cls):\n if ControllerApi.lyric_widget.isVisible():\n ControllerApi.lyric_widget.close()\n else:\n ControllerApi.lyric_widget.show()\n\n @classmethod\n def toggle_desktop_mini(cls):\n if ControllerApi.desktop_mini.isVisible():\n ControllerApi.desktop_mini.close()\n else:\n ControllerApi.desktop_mini.show()\n ControllerApi.notify_widget.show_message(\"Tips\", \"按ESC可以退出mini模式哦 ~\")\n\n @classmethod\n @pyqtSlot(int)\n def seek(cls, seconds):\n cls.player.setPosition(seconds * 1000)\n\n @classmethod\n def play_specific_song_by_mid(cls, mid):\n songs = ControllerApi.api.get_song_detail(mid)\n if not ControllerApi.api.is_response_ok(songs):\n return False\n\n if len(songs) == 0:\n LOG.info(\"music id %d is unavailable\" % mid)\n return False\n ControllerApi.player.play(songs[0])\n return True\n","sub_path":"src/controller_api.py","file_name":"controller_api.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226106069","text":"import requests,re\nfrom bs4 import BeautifulSoup\n\n# Get the data\ndata = requests.get('http://www.mesghal.com')\n\n# Load data into bs4\nsoup = BeautifulSoup(data.text, 'html.parser')\n\n# get data simply by looking for td and putting into a list\ndata_l = []\nfor tr in soup.find_all('tr'):\n data_l.append(tr.text)\n\n# chopping dollar section into small pieces\ndata_usd = data_l[-13]\ndata_re = re.compile(r'\\w+')\ndata_pieces = data_re.findall(data_usd)\n\n# taking last piece as dollar price\nprint(data_pieces[-1])\n\n","sub_path":"mesghal_USD.py","file_name":"mesghal_USD.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638862421","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n#保存模型\r\nfrom sklearn.externals import joblib\r\njoblib.dump(lgb,'lgb.pkl')\r\n\r\ntrain0 = train[train['acc_now_delinq'] == 0]\r\ntrain1 = train[train['acc_now_delinq'] == 1]\r\n#样本个数:709903;正样本占99.54%;负样本占0.46%\r\n\"\"\"\r\n### 导入模块\r\nimport time\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom dateutil.parser import parse\r\nfrom sklearn.cross_validation import KFold\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn import cross_validation,metrics\r\n\r\n# 忽略弹出的warnings\r\nimport warnings\r\nwarnings.filterwarnings('ignore') \r\n\r\n# 01 读取数据\r\nstart_time=time.time()\r\ndf = pd.read_csv('data/train.csv')\r\ntrain = df.drop(['grade','verification_status_joint','addr_state','desc','emp_title','earliest_cr_line','issue_d','member_id', \\\r\n 'purpose','title','zip_code'], axis = 1)\r\n\r\n# 02 缺失值处理(利用均值填补)\r\nprint(\"train 缺失值处理\\n\")\r\ntrain = train.fillna(0)\r\n\r\n# 03 字符串的替换--映射\r\nprint(\"map替换\\n\")\r\n#删除grade因为sub_grade与之重复\r\ntrain['term']=train['term'].map({' 36 months':1,' 60 months':0.8}).astype(float)\r\n#train['grade'] = train['grade'].map( {'D':0.4, 'A':1, 'E':0.2, 'B':0.8, 'C':0.6, 'F':0.1, 'G':0.05} ).astype(float)\r\ntrain['sub_grade']=train['sub_grade'].map({'A1':1,'A2':1.2,'A3':1.3,'A4':1.4,'A5':1.5,\\\r\n 'B1':2,'B2':2.2,'B3':2.3,'B4':2.4,'B5':2.5,\\\r\n 'C1':3,'C2':3.2,'C3':3.3,'C4':3.4,'C5':3.5,\\\r\n 'D1':4,'D2':4.2,'D3':4.3,'D4':4.4,'D5':4.5,\\\r\n 'E1':5,'E2':5.2,'E3':5.3,'E4':5.4,'E5':5.5,\\\r\n 'F1':6,'F2':6.2,'F3':6.3,'F4':6.4,'F5':6.5,\\\r\n 'G1':7,'G2':7.2,'G3':7.3,'G4':7.4,'G5':7.5,'0':10}).astype(float)\r\ntrain['application_type']=train['application_type'].map({'JOINT':1.0,'INDIVIDUAL':0.5}).astype(float)\r\ntrain['initial_list_status']=train['initial_list_status'].map({'f':0.5,'w':1}).astype(float)\r\ntrain['pymnt_plan']=train['pymnt_plan'].map({'y':1,'n':0}).astype(int)\r\ntrain['loan_status']=train['loan_status'].map({'Charged Off':1,'Fully Paid':1,'Current':0.6,'In Grace Period':0.8,\\\r\n 'Late (31-120 days)':0.3,'Late (16-30 days)':0.5,'Default':0.1, \\\r\n 'Does not meet the credit policy. Status:Fully Paid':0, \\\r\n 'Does not meet the credit policy. Status:Charged Off':0,'Issued':0}).astype(float)\r\ntrain['verification_status']=train['verification_status'].map({'Verified':1.0,'Source Verified':0.5,'Not Verified':0.0}).astype(float)\r\ntrain['home_ownership']=train['home_ownership'].map({'NONE':0,'ANY':0.2,'OTHER':0.1,'OWN':1,'RENT':0.4,'MORTGAGE':0.8}).astype(float)\r\ntrain['emp_length']=train['emp_length'].map({'< 1 year':0,'1 year':1,'2 years':2,'3 years':3,'4 years':4,'5 years':5, \\\r\n '6 years':6,'7 years':7,'8 years':8,'9 years':9,'10+ years':10,'n/a':0}).astype(float)\r\nfrom sklearn.feature_selection import RFE\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\nprint(\"首次剔除一些特征\\n\")\r\nx_val = train.drop(['acc_now_delinq'], axis = 1)\r\ny_val = train['acc_now_delinq']\r\n\r\n'''\r\n# 建立逻辑回归分类器\r\nmodel = LogisticRegression()\r\n# 建立递归特征消除筛选器\r\nrfe = RFE(model, 30) #通过递归选择特征,选择30个特征\r\nrfe = rfe.fit(x_val, y_val)\r\n# 打印筛选结果\r\nprint(\"rfe.support_:\\n\",rfe.support_)\r\nprint(\"rfe.ranking_:\\n\",rfe.ranking_) #ranking 为 1代表被选中,其他则未被代表未被选中\r\ncol_filter = x_val.columns[rfe.support_] #通过布尔值筛选首次降维后的变量\r\nprint(col_filter) # 查看通过递归特征消除法筛选的变量\r\n'''\r\n\r\n#新舍弃21个特征\r\nx_val_new = x_val.drop(['funded_amnt','annual_inc','verification_status','pymnt_plan', \\\r\n 'pub_rec','pub_rec','total_rec_prncp','total_rec_int','recoveries',\\\r\n 'collection_recovery_fee', 'collections_12_mths_ex_med',\\\r\n 'annual_inc_joint', 'dti_joint','tot_coll_amt', 'tot_cur_bal' ,\\\r\n 'open_il_12m','total_bal_il','max_bal_bc', 'all_util', \\\r\n 'total_rev_hi_lim', 'inq_fi', 'total_cu_tl'],axis = 1)\r\n\r\n# 正负样本的不平衡 / 导入SMOTE算法模块 / 处理过采样的方法 增加反例的比例\r\nprint('通过SMOTE方法平衡正负样本后\\n')\r\nX = x_val_new\r\ny = y_val\r\nfrom imblearn.over_sampling import SMOTE\r\nsm = SMOTE(random_state=42) \r\nX, y = sm.fit_sample(X, y)\r\nn_sample = y.shape[0]\r\nn_pos_sample = y[y == 0].shape[0]#正样本\r\nn_neg_sample = y[y == 1].shape[0]#负样本\r\nprint('样本个数:{}; 正样本占{:.2%}; 负样本占{:.2%}'.format(n_sample,\r\n n_pos_sample / n_sample,\r\n n_neg_sample / n_sample))\r\nprint('特征维数:',X.shape[1])\r\n#通过SMOTE方法平衡正负样本后\r\n#样本个数:1413220; 正样本占50.00%; 负样本占50.00%\r\nfrom sklearn.linear_model import LogisticRegression\r\nclf = LogisticRegression() # 构建逻辑回归分类器\r\nclf.fit(X, y)\r\npredicted1 = clf.predict(X) # 通过分类器产生预测结果\r\n\r\n#基本精确度\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Test set accuracy score: {:.5f}\".format(accuracy_score(predicted1, y,)))\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\nm = confusion_matrix(y, predicted1)\r\nprint(\"混淆矩阵:\\n\",m)\r\n\r\nfrom sklearn.metrics import roc_auc_score\r\nroc_auc1 = roc_auc_score(y, predicted1)\r\nprint(\"Area under the ROC curve : %f\" % roc_auc1)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # random_state = 0 每次切分的数据都一样\r\n# 构建参数组合\r\nparam_grid = {'C': [0.01,0.1, 1, 10, 100, 1000,],\r\n 'penalty': [ 'l1', 'l2']}\r\ngrid_search = GridSearchCV(LogisticRegression(), param_grid, cv=10) # 确定模型LogisticRegression,和参数组合param_grid ,cv指定5折\r\ngrid_search.fit(X_train, y_train) # 使用训练集学习算法\r\nfrom sklearn.metrics import roc_auc_score\r\nroc_auc1 = roc_auc_score(y, predicted1)\r\nprint(\"Area under the ROC curve : %f\" % roc_auc1)\r\n\r\n#模型性能评估\r\nprint(\"Best parameters: {}\".format(grid_search.best_params_))\r\nprint(\"Best cross-validation score: {:.5f}\".format(grid_search.best_score_))\r\n\r\nend_time=time.time()\r\nprint(\"用时{%d}秒\".format(end_time-start_time))","sub_path":"SMOTElogisticloss.py","file_name":"SMOTElogisticloss.py","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"598452248","text":"import mimetypes\n\nimport nbconvert.exporters.html\nfrom jinja2 import contextfilter\nfrom nbconvert.filters.markdown_mistune import IPythonRenderer, MarkdownWithMath\n\n\nclass VoilaMarkdownRenderer(IPythonRenderer):\n \"\"\"Custom markdown renderer that inlines images\"\"\"\n def image(self, src, title, text):\n contents_manager = self.options['contents_manager']\n if contents_manager.file_exists(src):\n content = contents_manager.get(src, format='base64')\n data = content['content'].replace('\\n', '') # remove the newline\n mime_type, encoding = mimetypes.guess_type(src)\n src = 'data:{mime_type};base64,{data}'.format(mime_type=mime_type, data=data)\n return super(VoilaMarkdownRenderer, self).image(src, title, text)\n\n\nclass HTMLExporter(nbconvert.exporters.html.HTMLExporter):\n \"\"\"Custom HTMLExporter that inlines the images using VoilaMarkdownRenderer\"\"\"\n @contextfilter\n def markdown2html(self, context, source):\n cell = context['cell']\n attachments = cell.get('attachments', {})\n renderer = VoilaMarkdownRenderer(escape=False, attachments=attachments,\n contents_manager=self.contents_manager,\n anchor_link_text=self.anchor_link_text)\n return MarkdownWithMath(renderer=renderer).render(source)\n","sub_path":"voila/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"477269364","text":"# Tool to convert color values, developed as study for object oriented programming\n\n\nclass Color:\n # Contructor receiving integer values\n def __init__(self, red: int, green: int, blue=0):\n # Validate arguments\n assert red >= 0 and red <= 255, f'Red value is invalid ({red} not in 0 ~ 255 range)'\n assert green >= 0 and green <= 255, f'Green value is invalid ({green} not in 0 ~ 255 range)'\n assert blue >= 0 and blue <= 255, f'Blue value is invalid ({blue} not in 0 ~ 255 range)'\n\n # Assign values\n self.red = red\n self.green = green\n self.blue = blue\n self.hexColor = self.convertHex(\n self.red)+self.convertHex(self.green)+self.convertHex(self.blue)\n\n # Method to describe color parameters\n def description(self):\n return(f'The color values are {self.red} red, {self.green} green and {self.blue} blue. '\n f'The Hexadecimal color is {self.hexColor}.')\n\n # Method to convert integer value to hexadecimal\n def convertHex(self, intColor):\n hexadecimalColor = hex(intColor).lstrip(\"0x\")\n if len(hexadecimalColor) == 0:\n hexadecimalColor = \"00\"\n elif len(hexadecimalColor) == 1:\n hexadecimalColor = \"0\" + hexadecimalColor\n return hexadecimalColor\n\n # Method to validate hexadecimal value\n def validateHex(self, hexValue):\n error = False\n if len(hexValue) != 6: # Validate lenght\n error = True\n else:\n # Validate values\n dicHex = ['0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F']\n for i in hexValue:\n if i.upper() not in dicHex:\n error = True\n if error:\n return False\n else:\n return True\n\n # Method to convert hexadecimal value to integer (used on child class)\n def convertInt(self, hexColor):\n if self.validateHex(hexColor):\n self.red = int(hexColor[0:2], 16)\n self.green = int(hexColor[2:4], 16)\n self.blue = int(hexColor[4:6], 16)\n else:\n print(\n f'{hexColor} is invalid hexadecimal color, setting values to black')\n self.hexColor = '000000'\n self.red = 0\n self.green = 0\n self.blue = 0\n\n # Getters and Setters\n def setRed(self, red):\n self.red = red\n self.hexColor = self.convertHex(\n self.red)+self.convertHex(self.green)+self.convertHex(self.blue)\n\n def setGreen(self, green):\n self.green = green\n self.hexColor = self.convertHex(\n self.red)+self.convertHex(self.green)+self.convertHex(self.blue)\n\n def setBlue(self, blue):\n self.blue = blue\n self.hexColor = self.convertHex(\n self.red)+self.convertHex(self.green)+self.convertHex(self.blue)\n\n def setHex(self, hexColor):\n self.hexColor = hexColor\n self.convertInt(self.hexColor)\n\n def getRed(self):\n return self.red\n\n def getGreen(self):\n return self.green\n\n def getBlue(self):\n return self.blue\n\n def getHex(self):\n return self.hexColor\n\n\nclass ColorHex(Color):\n # Contructor receiving hexadecimal value\n def __init__(self, hexColor: str):\n self.hexColor = hexColor\n self.convertInt(hexColor)\n\n\n# Main program\nblack = Color(0, 0, 0)\nprint(f'Black: {black.description()}')\n\nwhite = ColorHex('ffffff')\nprint(f'White: {white.description()}')\n\ngrey = Color(0, 0, 0)\ngrey.setRed(128)\ngrey.setGreen(128)\ngrey.setBlue(128)\nprint(f'Grey: {grey.description()}')\n\nyellow = Color(0, 0, 0)\nyellow.setHex('ffff00')\nprint(f'Yellow: {yellow.description()}')\n\nprint('\\nInvalid color 1:')\ninvalidColor1 = ColorHex('gfffff')\nprint(f'Invalid: {invalidColor1.description()}')\n\nprint('\\nInvalid color 2:')\ninvalidColor2 = ColorHex('g')\nprint(f'Invalid: {invalidColor2.description()}')\n\n# print('\\nInvalid color 3:')\n# invalidColor3 = Color(255, 256, -1)\n# print(f'Invalid: {invalidColor3.description()}')\n","sub_path":"colorConverter.py","file_name":"colorConverter.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"528462017","text":"\"\"\"Define the normal perceptron class.\"\"\"\n\nimport numpy\n\n\nclass Perceptron():\n \"\"\"Class of normal perceptron.\"\"\"\n\n def __init__(self, act_funct):\n self.__act_funct = act_funct\n self.sw = None # synaptic weight\n self.__input_data = None\n self.result = None\n\n @property\n def data(self):\n \"\"\"Return current input data.\"\"\"\n return self.__input_data\n\n @data.setter\n def data(self, data):\n \"\"\"Set one data (coordinates) to adjust the perceptron and calculate result.\n And also initialize members that is None at the __init__.\n \"\"\"\n if self.__input_data is None:\n self.__input_data = numpy.array(data)\n self.__input_data = numpy.insert(self.__input_data, 0, -1)\n else:\n self.__input_data[1:] = data\n if self.sw is None:\n self.sw = numpy.random.uniform(-1, 1, len(self.__input_data))\n\n self.result = self.__act_funct(numpy.dot(self.sw, self.__input_data))\n\n def adjust_sw(self, learn_rate, dsr_out, obj_out):\n \"\"\"Adjust the synaptic weight for next training cycle. The synaptic weight of the\n perceptron object will be updated by the learn_rate, dsr_out, obj_out parameters.\n - learn_rate: The current learning rate while training\n - dsr_out: The desire output (kth group)\n - obj_out: The distinguishing objective (kth group),\n if dsr_out is not equal to obj_out, the\n result should be -1, and vice versa.\n \"\"\"\n if self.result == 1 and dsr_out != obj_out:\n self.sw -= learn_rate * self.__input_data\n elif self.result == -1 and dsr_out == obj_out:\n self.sw += learn_rate * self.__input_data\n\n\nif __name__ == '__main__':\n print(\"Error: This file can only be imported. Try to execute 'simple_perceptron.py.'\")\n","sub_path":"simple_perceptron/backend/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343537084","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated by Matthew A. Bennett (%(date)s)\n\nMatthew.Bennett@glasgow.ac.uk\n\"\"\"\n\n#%%% =======================================================================================\n# imports\nimport os, glob\nfrom my_functions.misc import bash\n\n#%%% =======================================================================================\n# paths and definitions\n\nbase_dir = '/analyse/Project0256/'\n\nsub_folders = ['20190816_PFB06', '20190817_EPA14', '20190817_SLW06', '20190818_FUH13',\n '20190819_LDH12', '20190820_ULA08', '20190901_ALL21', '20190902_MZA30',\n '20190903_CGE02', '20190909_LLN21']\n\nsub_folders = sub_folders[1:]\n\nnifti_ext = '.nii.gz'\n# format and store anatomical names\n\n#%% =============================================================================\n# register anatomical to functional epi:\n# 1) map mp2rage to T2w in itksnap\n# 2) map from T2w to epi in itksnap\n# 3) nonlinear map from T2w to average epi in using ANTs\n# 4) apply above transforms in one step to e.g. mp2rage/segmentation/ROIs\n\nsubs_processed_correctly = []\n\nfor sub_fold in sub_folders:\n\n try:\n sub_id = sub_fold[9:]\n print(f'Processing {sub_id}...')\n print('')\n\n nifti_dir = f'{base_dir}{sub_fold}/sub-{sub_id}/func/'\n os.chdir(f'{nifti_dir}')\n\n nifti_dir_anat = f'{base_dir}{sub_fold}/sub-{sub_id}/anat/'\n os.chdir(f'{nifti_dir}')\n\n UNI_name = f'sub-{sub_id}_UNI'\n T2w_name = f'sub-{sub_id}_T2w'\n\n st_im = f'{nifti_dir}sub-{sub_id}_run-01_bold_mean'\n mv_im = f'{nifti_dir_anat}{T2w_name}_skullstrip_upsample0p4'\n\n # do the alignments\n bash(f\"itksnap -g {st_im}{nifti_ext} -o {mv_im}{nifti_ext}\")\n bash(f'itksnap -g {mv_im}{nifti_ext} -o {nifti_dir_anat}dnoised_{UNI_name}_skullstrip_inhom_corr_upsample0p4{nifti_ext}')\n\n # use ANTs to add a nonlinear algignment of the anatomical to the functional\n\n T2w_to_func_init = f'{nifti_dir}T2w_to_func_CC_Affine.txt'\n UNI_to_T2w = f'{nifti_dir_anat}UNI_to_T2w.txt'\n #mask=f'{nifti_dir}/alignment_mask{nifti_ext}'\n\n # put this after the --output flag if using mask\n #--masks [$mask, $mask] \\\n\n call_to_ANTs = f'antsRegistration \\\n --verbose 1 \\\n --dimensionality 3 \\\n --float 0 \\\n --output [ANTs_, ANTs_Warped{nifti_ext},ANTs_InverseWarped{nifti_ext}] \\\n --interpolation Linear \\\n --use-histogram-matching 0 \\\n --winsorize-image-intensities [0.005,0.995] \\\n --initial-moving-transform {T2w_to_func_init} \\\n --transform Rigid[0.05] \\\n --metric MI[{st_im}{nifti_ext},{mv_im}{nifti_ext},0.7,32,Regular,0.1] \\\n --convergence [1000x500,1e-6,10] \\\n --shrink-factors 2x1 \\\n --smoothing-sigmas 1x0vox \\\n --transform Affine[0.1] \\\n --metric MI[{st_im}{nifti_ext},{mv_im}{nifti_ext},0.7,32,Regular,0.1] \\\n --convergence [1000x500,1e-6,10] \\\n --shrink-factors 2x1 \\\n --smoothing-sigmas 1x0vox \\\n --transform SyN[0.1,3,0] \\\n --metric CC[{st_im}{nifti_ext},{mv_im}{nifti_ext},1,4] \\\n --convergence [100x70x50x20,1e-6,10] \\\n --shrink-factors 4x4x2x1 \\\n --smoothing-sigmas 3x2x1x0vox'\n\n bash(f'{call_to_ANTs}')\n\n #%%% =============================================================================\n # move mp2rage into epi space, using above transform\n\n# mv_im=f'{nifti_dir_anat}dnoised_{UNI_name}_skullstrip_inhom_corr_upsample0p4'\n mv_im=f'{nifti_dir_anat}test_native_upscale'\n\n #mask=f'{nifti_dir}/alignment_mask{nifti_ext}'\n\n # put this after the --output flag if using mask\n #--masks [$mask, $mask] \\\n\n\n call_to_ANTs = f'antsApplyTransforms \\\n --interpolation Linear \\\n --dimensionality 3 \\\n --input {mv_im}{nifti_ext} \\\n --reference-image {st_im}{nifti_ext} \\\n --transform ANTs_1Warp{nifti_ext} \\\n --transform ANTs_0GenericAffine.mat \\\n --transform {UNI_to_T2w} \\\n --output ANTs_WM_to_func_Warped3{nifti_ext}'\n\n bash(f'{call_to_ANTs}')\n\n\n subs_processed_correctly.append(sub_id)\n except:\n continue\n\n#%%% =======================================================================================\n#\n\n#%%% =======================================================================================\n#\n\n\n\n","sub_path":"7T-fMRI_pipeline/anatomical_to_functional_registration.py","file_name":"anatomical_to_functional_registration.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"539113849","text":"import heapq\nimport random\nimport time\n\ndef heapSort(v):\n heapq.heapify(v)\n t= [heapq.heappop(v) for _ in range(len(v))]\n return t\n\nn=int(input(\"n 입력 : \"))\nv= [random.randint(1,1000000) for _ in range(n)]\nts =time.time()\n\nv= heapSort(v)\n\net=int((time.time()-ts)*1000)\nprint(\"경과 시간 (Elapsed time) : %dms\"%et)","sub_path":"heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"504652935","text":"\n\n#calss header\nclass _REFRACTORY():\n\tdef __init__(self,): \n\t\tself.name = \"REFRACTORY\"\n\t\tself.definitions = [u'not affected by a treatment, change, or process: ', u'difficult to control; unwilling to obey: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_refractory.py","file_name":"_refractory.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"269861727","text":"from django.shortcuts import render, redirect\nfrom django.utils import timezone\nfrom .models import Brand, Presentation, Product\nfrom django.shortcuts import render, get_object_or_404\nfrom .forms import BrandForm, PresentationForm, ProductForm\n###33 Brand Functions\ndef brand_list(request):\n brands = Brand.objects.order_by('name')\n return render(request, 'brand/brand_list.html', {'brands':brands})\n##33\ndef brand_detail(request,pk):\n\tbrands=get_object_or_404(Brand,pk=pk)\n\treturn render(request,'brand/brand_detail.html',{'brands':brands})\n#333\ndef brand_new(request):\n if request.method == \"POST\":\n form = BrandForm(request.POST)\n if form.is_valid():\n brand = form.save(commit=False)\n brand.save()\n return redirect('/', pk=brand.pk)\n else:\n form = BrandForm()\n return render(request, 'brand/brand_edit.html', {'form': form})\n###33\ndef brand_edit(request, pk):\n brand = get_object_or_404(Brand, pk=pk)\n if request.method == \"POST\":\n form = BrandForm(request.POST, instance=brand)\n if form.is_valid():\n brand = form.save(commit=False)\n brand.save()\n return redirect('/', pk=brand.pk)\n else:\n form = BrandForm(instance=brand)\n return render(request, 'brand/brand_edit.html', {'form': form})\n#3333\ndef brand_destroy(request, id):\n brand = Brand.objects.get(id=id)\n brand.delete()\n return redirect(\"/\")\n######33333333333\n###333 Presentation functions\ndef presentation_list(request):\n presentations = Presentation.objects.order_by('name')\n return render(request, 'presentation/presentation_list.html', {'presentations':presentations})\n##33\ndef presentation_detail(request,pk):\n\tpresentations=get_object_or_404(Presentation,pk=pk)\n\treturn render(request,'presentation/presentation_detail.html',{'presentations':presentations})\n#333\ndef presentation_new(request):\n if request.method == \"POST\":\n form = PresentationForm(request.POST)\n if form.is_valid():\n presentation = form.save(commit=False)\n presentation.save()\n return redirect('/presentation', pk=presentation.pk)\n else:\n form = PresentationForm()\n return render(request, 'presentation/presentation_edit.html', {'form': form})\n###33\ndef presentation_edit(request, pk):\n presentation = get_object_or_404(Presentation, pk=pk)\n if request.method == \"POST\":\n form = PresentationForm(request.POST, instance=presentation)\n if form.is_valid():\n presentation = form.save(commit=False)\n presentation.save()\n return redirect('/presentation', pk=presentation.pk)\n else:\n form = PresentationForm(instance=presentation)\n return render(request, 'presentation/presentation_edit.html', {'form': form})\n#3333\ndef presentation_destroy(request, id):\n presentation = Presentation.objects.get(id=id)\n presentation.delete()\n return redirect(\"/\")\n######3333333333#############################################################\ndef product_list(request):\n products = Product.objects.order_by('name')\n return render(request, 'product/product_list.html', {'products':products})\n##33\ndef product_detail(request,pk):\n\tproducts=get_object_or_404(Product,pk=pk)\n\treturn render(request,'product/product_detail.html',{'products':products})\n#333\ndef product_new(request):\n if request.method == \"POST\":\n form = ProductForm(request.POST)\n if form.is_valid():\n product = form.save(commit=False)\n product.save()\n return redirect('/product', pk=product.pk)\n else:\n form = ProductForm()\n return render(request, 'product/product_edit.html', {'form': form})\n###33\ndef product_edit(request, pk):\n product = get_object_or_404(Product, pk=pk)\n if request.method == \"POST\":\n form = ProductForm(request.POST, instance=product)\n if form.is_valid():\n product = form.save(commit=False)\n product.save()\n return redirect('/product', pk=product.pk)\n else:\n form = ProductForm(instance=product)\n return render(request, 'product/product_edit.html', {'form': form})\n#3333\ndef product_destroy(request, id):\n product = Product.objects.get(id=id)\n product.delete()\n return redirect(\"/\")\n","sub_path":"brand/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"276968998","text":"# -*- coding: utf-8 -*-\n\n#--------------------------------------------------------------------#\n# #\n# Copyright (C) 2018 HOLOEYE Photonics AG. All rights reserved. #\n# Contact: https://holoeye.com/contact/ #\n# #\n# This file is part of HOLOEYE SLM Display SDK. #\n# #\n# You may use this file under the terms and conditions of the #\n# \"HOLOEYE SLM Display SDK Standard License v1.0\" license agreement. #\n# #\n#--------------------------------------------------------------------#\n\n\n# Plays a slideshow on the SLM with pre-calculated 2d phase fields consisting of vertical blazed gratings with different periods.\n# The data fields are pre-calculated and uploaded to the GPU once, and then each frame is shown on the SLM by selecting the\n# appropriate phase values field on the GPU directly to reach higher performance.\n\nimport sys, time, math\n\n# Import the SLM Display SDK:\nimport detect_heds_module_path\nfrom holoeye import slmdisplaysdk\n\n# Import helper function to print timing statistics of the display duration of the handles:\nfrom slideshow_preload_print_stats import printStat\n\nif not slmdisplaysdk.supportNumPy:\n print(\"Please install numpy to make this example work on your system.\")\n sys.exit()\n\n# Import numpy:\nimport numpy as np\n\n# Make some enumerations available locally to avoid too much code:\nErrorCode = slmdisplaysdk.SLMDisplay.ErrorCode\nShowFlags = slmdisplaysdk.SLMDisplay.ShowFlags\nState = slmdisplaysdk.SLMDisplay.State\n\n# Detect SLMs and open a window on the selected SLM:\nslm = slmdisplaysdk.SLMDisplay()\n\n# Open the SLM preview window (might have an impact on performance):\nslm.utilsSLMPreviewShow()\n\n# Configure slideshow (steer the laser beam from left to right and back):\ngratingPeriodMin = 8\ngratingPeriodMax = 64\ngratingPeriodStepSize = 4\ndataDisplayDurationMilliSec = 100 # duration of each data frame in ms\nrepeatSlideshow = 3 # <= 0 (e. g. -1) repeats until Python process gets killed\n\ngratingPeriodList = np.arange(-gratingPeriodMin, -(gratingPeriodMax+1), -gratingPeriodStepSize)\ngratingPeriodList = np.concatenate((gratingPeriodList, np.arange(gratingPeriodMax, gratingPeriodMin-1, -gratingPeriodStepSize)))\ngratingPeriodList = np.concatenate((gratingPeriodList, np.arange(gratingPeriodMin, gratingPeriodMax+1, gratingPeriodStepSize)))\ngratingPeriodList = np.concatenate((gratingPeriodList, np.arange(-gratingPeriodMax, -(gratingPeriodMin-1), gratingPeriodStepSize)))\n\nprint(\"gratingPeriodList = \" + str(gratingPeriodList))\nprint(\"len(gratingPeriodList) = \" + str(len(gratingPeriodList)))\n\n\n# Calculate the data we want to show:\nprint(\"Calculating data ...\")\nstart_time = time.time()\n\n# Pre-calculate the phase fields in full SLM size:\nphaseModulation = 2.0*math.pi # radian\ndataWidth = slm.width_px\ndataHeight = slm.height_px # Can be set to 1 to have a faster calculation in case of vertical blazed gratings.\nprint(\"dataWidth = \" + str(dataWidth))\nprint(\"dataHeight = \" + str(dataHeight))\n\ndurationInFrames = int((float(dataDisplayDurationMilliSec)/1000.0) * slm.refreshrate_hz)\nif durationInFrames <= 0:\n durationInFrames = 1 # The minimum duration is one video frame of the SLM\n\nprint(\"slm.refreshrate_hz = \" + str(slm.refreshrate_hz))\nprint(\"durationInFrames = \" + str(durationInFrames))\n\n\ndataHandles = []\ncalcPercent = -1\n\nnHandles = 0 # total number of images loaded to GPU\nfor blazePeriod in gratingPeriodList:\n\n # Print progress:\n percent = int(float(nHandles) / len(gratingPeriodList) * 100)\n if int(percent / 5) > calcPercent:\n calcPercent = int(percent / 5)\n print(str(percent) + \"%\")\n\n # Calculate next phase field:\n\n row = np.matrix(np.zeros([1, dataWidth], dtype=np.float32))\n for x in range(dataWidth):\n row[0, x] = float(phaseModulation * (x - dataWidth / 2) / blazePeriod)\n\n phaseData = np.array(np.matrix(np.ones([dataHeight, 1], dtype=np.float32)) * row, dtype=np.float32)\n\n# Slow, but general version:\n# phaseData = holoeye.createFieldSingle(dataWidth, dataHeight)\n# for y in range(dataHeight):\n# row = phaseData[y]\n# for x in range(dataWidth):\n# row[x] = float(phaseModulation * (x - dataWidth / 2) / blazePeriod)\n\n # Load data to GPU using automatic wrapping and values in radian:\n error, handle = slm.loadPhasevalues(phaseData)\n\n if error == ErrorCode.OutOfVideoMemory:\n print(\"No video memory left at \" + str(nHandles) + \". Skipping the rest\")\n break\n\n slm.datahandleSetDuration(handle, durationInFrames)\n\n assert error == ErrorCode.NoError, slm.errorString(error)\n\n nHandles += 1\n dataHandles.append(handle)\n\nprint(\"100%\")\nend_time = time.time()\nprint(\"Calculation took \"+ str(\"%0.3f\" % (end_time - start_time)) +\" seconds\\n\")\n\n# Show the pre-calculated data:\nprint(\"Showing data...\")\n\n# Play complete slideshow:\nn = 0\nwhile (n < repeatSlideshow) or (repeatSlideshow <= 0):\n n += 1\n\n print(\"Show data for the \" + str(n) + \". time ...\")\n\n # Play slideshow once:\n for handle in dataHandles:\n error = slm.showDatahandle(handle, ShowFlags.PresentAutomatic)\n assert error == ErrorCode.NoError, slm.errorString(error)\n\n # Update the handles to the latest state:\n for handle in dataHandles:\n error = slm.updateDatahandle(handle)\n assert error == ErrorCode.NoError, slm.errorString(error)\n\n # Print the actual statistics (last data handle has wrong visible time before any other data was shown):\n print(\"Showing timing statistics...\")\n printStat(\"loadingTimeMs\", dataHandles[0:-1])\n printStat(\"conversionTimeMs\", dataHandles[0:-1])\n printStat(\"processingTimeMs\", dataHandles[0:-1])\n printStat(\"transferTimeMs\", dataHandles[0:-1])\n printStat(\"renderTimeMs\", dataHandles[0:-1])\n printStat(\"visibleTimeMs\", dataHandles[0:-1])\n\n# One last image to clear the SLM screen after the slideshow playback:\n# (Also possible by just calling slm.showBlankscreen(128))\ndata = slmdisplaysdk.createFieldUChar(1, 1)\ndata[0, 0] = 128\nerror, dh = slm.loadData(data)\nassert error == ErrorCode.NoError, slm.errorString(error)\n\nerror = slm.showDatahandle(dh, ShowFlags.PresentAutomatic)\nassert error == ErrorCode.NoError, slm.errorString(error)\n\n# Release handles and their data to free up video memory:\ndataHandles = None\n\n# Wait a few seconds after the slideshow has finished:\ntime.sleep(4)\n\n# Unloading the SDK may or may not be required depending on your IDE:\nslm.release()","sub_path":"SLM/slideshow_data_preload.py","file_name":"slideshow_data_preload.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"349648244","text":"'''\r\n문자열 포멧팅 테스트\r\n숫자대입 : %d\r\n문자열대입 : %s\r\n%대입 : (%d or %s ..) 뒤에 %를 붙일경우 '%%'\r\n'''\r\n\r\n\"예제 1 (숫자대입)\"\r\n\"나는 %d시에 학교에 갑니다.\" % 9\r\n\r\n\"예제 2 (문자열대입 )\"\r\n\"나는 %s시에 학교에 갑니다.\" % '9'\r\n\r\n\"예제 3 (문자열대입, %s는 %뒤에 나오는 값을 자동으로 문자열로 변환)\"\r\n\"나는 %s시에 학교에 갑니다.\" % 9\r\n\"나는 %s시에 학교에 갑니다.\" % 3.14\r\n\r\n\"예제 4 (변수대입)\"\r\nhour = 9\r\n\"나는 %d시에 학교에 갑니다.\" % hour\r\n\r\n\"예제 5 (여러 개 대입)\"\r\nhour = 9\r\nminute = \"20\"\r\n\"나는 %d시 %s분에 학교에 갑니다.\" % (hour,minute) \r\n\r\n\"예제 6 (여러 개 대입)\"\r\nhour = 9\r\n\"나는 %d시 %s분에 학교에 갑니다.\" % (hour,\"20\") \r\n\r\n\"예제 7 (%문자를 출력)\"\r\n\"나는 상위 %d%% 이다.\" % 10\r\n\r\n\r\n\"예제 8 (공백과 정렬, 소수점 표현)\"\r\n\"%5s\" % \"SWH\"\r\n\"%-5s\" % \"SWH\"\r\n\"%0.2f\" % 3.141592\r\n\"%10.2f\" % 3.141592","sub_path":"src/com/github/tobby48/python/scene1/StringType_Format.py","file_name":"StringType_Format.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"337383750","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 18 23:20:14 2020\n\n@author: Piyush\n\"\"\"\n\n\ndef compound_interest(amount, interest, num_times_int, time_period, time_period_in):\n amount = float(amount)\n interest = float(interest) / 100\n time_period = float(time_period)\n \n \n time_convert_dict = {'Days' : 365, 'Months' : 12, 'Years' : 1}\n interest_convert_dict = {'Yearly' : 1, \n 'Quarterly' : 4,\n 'Monthly' : 12,\n 'Continuous' : 12}\n \n n = interest_convert_dict[num_times_int]\n \n \n time_period_years = time_period / time_convert_dict[time_period_in]\n \n print(n)\n print('Effective n is %i' % (n * time_period_years))\n total_investment = amount * (1 + (interest / n)) ** (n * time_period_years)\n if total_investment >= 1000000000:\n total_investment = int(total_investment)\n return total_investment\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scripts/compound_interest.py","file_name":"compound_interest.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174665576","text":"from setuptools import setup\nfrom codecs import open as _open\nfrom os import path\nimport re\n\n\ndef readme():\n # Get the long description from the README file\n readme_file = path.join(path.abspath(path.dirname(__file__)), \"README.rst\")\n with _open(readme_file, \"rb\", encoding='utf-8') as opened_file:\n return opened_file.read()\n\n\ndef version(name):\n with open(name, 'rb') as opened:\n search_refind = b'__version__ = [\"\\'](\\d+\\.\\d+\\.\\d+)[\"\\']'\n verdata = re.search(search_refind, opened.read())\n if verdata:\n data = verdata.group(1)\n return data.decode()\n else:\n raise RuntimeError(\"Unable to extract version number\")\n\n\nsetup(name='htmlement',\n version=version('htmlement.py'),\n description='Pure-Python HTML parser with ElementTree support.',\n long_description=readme(),\n keywords='html html5 parsehtml htmlparser elementtree dom',\n classifiers=['Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Text Processing :: Markup :: HTML',\n 'Topic :: Software Development :: Libraries :: Python Modules'],\n url='https://github.com/willforde/python-htmlement',\n platforms=['OS Independent'],\n author='William Forde',\n author_email='willforde@gmail.com',\n license='MIT License',\n py_modules=['htmlement'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"293349137","text":"import array as arr #array of numeric values are supported in Python by the array module\n\nsortedList= arr.array('i', [1, 2,3,4,5])\nunsorted = arr.array('i', [4, 8, 2,5,7,1,3,6])\n\ncount = 0\n\n\n\n# #List example to show difference\n## strings = ['a', 'b', 'c'] # # Simple list type array\n## for x in strings:\n## print (x)\n#\n## #print with while loop\n#def printW(count):\n# while count < len(sortedList):\n# print(sortedList[count])\n# count = count +1\n#\n#\n## Print items in arrays with forloop\n#def printFor():\n# for item in sortedList:\n# print (item)\n## printFor()\n## #-------------------------------------\n# \n## \n#def reversefn():\n# # #reverse items in array using reverse iteration\n# \n# sortedList.reverse()\n# \n# \n# # #Reversing a list in-place with the list.reverse() method\n# for i in sortedList:\n# print(\"Reverse() iter :\", i )\n# \n# print(\"...\\n\")\n# \n# # #Using the “[::-1]” list slicing trick to create a reversed copy\n# \n# sortedList[::-1]\n# for x in sortedList:\n# print(\"Reverse [::-1] slicing :\", x )\n# \n# print(\"...\\n\")\n# \n# # #Creating a reverse iterator with the reversed() built-in function\n# \n# for xy in reversed(unsorted):\n# print(\"reversed(): \", xy)\n# \n# print(\"...\\n\")\n# \n#reversefn()\n\n\n# # #append items to array\ndef add1(x, sortedList):\n newList = arr.array('i',[x])\n sortedList += newList\n for y in sortedList: \n print(y, end=\" \"),\n\n#add1(10, sortedList)\n \ndef clone(sortedList, *num):\n sortedList = num[:]\n for c in sortedList:\n print(c, end=\" \")\n return sortedList\n\nprint(clone(1,2))\n\n# ##add to list with built in methods\n\n# #append takes only one arguement\ndef appendx(x):\n sortedList.append(x)\n print(sortedList)\n \n#appendx(13)\n\n# #add items to list using extend([])\ndef extendY(*args):\n sortedList.extend([*args])\n print(\"\\n___extend____\\n\")\n for y in sortedList: \n print( y, end=\" \")\n#extendY(10,7,6,8,9)\n\n\n\n#add at x or y location in list\n\ndef insert_at():\n sortedList.insert(0,-123)\n sortedList.insert(len(sortedList),103) #equivalent to append\n for y in sortedList: \n print( y, end=\" \")\n\ninsert_at()\n\n# # #prepend items to array\n# def prepend():\n# pass\n\n# # #delete items from array\n# def remove():\n# pass\n\n\n","sub_path":"arrays_ds.py","file_name":"arrays_ds.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"265428714","text":"import pylab as p\n\n# Setup parameters\nmu = 0.1; sigma = 0.26; S0 = 39;\nn_path = 1000; n = n_partitions = 1000;\n# Create Brownian paths\nt = p.linspace (0,3,n+1);\ndB = p.randn (n_path, n+1) / p.sqrt(n/3); dB[:,0] = 0;\nB = dB.cumsum(axis=1);\n\n#Calculate stock prices\nnu = mu - sigma*sigma/2.0\nS = p.zeros_like(B); S[:,0] = S0\nS[:,1:] = S0*p.exp(nu*t[1:]+sigma*B[:,1:])\nS1 = S[0:5]\np.xlabel('t');p.ylabel('X(t)');\np.title('Geometric Brownian Motion');\np.plot(t,S1.transpose());p.show();\n\n#Calculate E[S(3)]\nS3 = S[:,-1]\nExpected_s3= S3.sum()/n_path\nmsg= 'The expected value of S(3) is %.13f' %Expected_s3\nprint(msg)\n\n#Calculate Var[S(3)]\nVar = (S3-Expected_s3)**2\nSum_v = Var.sum()/(n_path-1)\nmsg= 'The variance of S(3) is %.13f' %Sum_v\nprint(msg)\n\n# Calculate P[S(3)> 39] & E[S(3)|S(3) > 39]\ncount=0; total=0;\nfor i in range(n_path): #means 0,1,2,3,4\n if S3[i]>39:\n count = count+1\n total = total+S3[i]\nP = count/n_path\nmsg= 'P[S(3)> 39] is %.13f' %P\nprint (msg)\n\nCond_E = total/count\nmsg= 'E[S(3)|S(3) > 39] is %.13f' %Cond_E\nprint (msg)","sub_path":"gbm.py","file_name":"gbm.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"380866725","text":"# from keras import models\n# from keras import layers\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.linear_model import perceptron\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\n\n\"\"\"\n@attribute having_IP_Address { -1,1 }\n@attribute URL_Length { 1,0,-1 }\n@attribute Shortining_Service { 1,-1 }\n@attribute having_At_Symbol { 1,-1 }\n@attribute double_slash_redirecting { -1,1 }\n@attribute Prefix_Suffix { -1,1 }\n@attribute having_Sub_Domain { -1,0,1 }\n@attribute SSLfinal_State { -1,1,0 }\n@attribute Domain_registeration_length { -1,1 }\n@attribute Favicon { 1,-1 }\n@attribute port { 1,-1 }\n@attribute HTTPS_token { -1,1 }\n@attribute Request_URL { 1,-1 }\n@attribute URL_of_Anchor { -1,0,1 }\n@attribute Links_in_tags { 1,-1,0 }\n@attribute SFH { -1,1,0 }\n@attribute Submitting_to_email { -1,1 }\n@attribute Abnormal_URL { -1,1 }\n@attribute Redirect { 0,1 }\n@attribute on_mouseover { 1,-1 }\n@attribute RightClick { 1,-1 }\n@attribute popUpWidnow { 1,-1 }\n@attribute Iframe { 1,-1 }\n@attribute age_of_domain { -1,1 }\n@attribute DNSRecord { -1,1 }\n@attribute web_traffic { -1,0,1 }\n@attribute Page_Rank { -1,1 }\n@attribute Google_Index { 1,-1 }\n@attribute Links_pointing_to_page { 1,0,-1 }\n@attribute Statistical_report { -1,1 }\n@attribute Result { -1,1 }\n\"\"\"\n\ndf = pd.read_csv(\"phishing_websites.txt\")\n# print(df.head())\n\n# Create the perceptron object (net)\nnet = perceptron.Perceptron(max_iter=100, verbose=0, random_state=None, fit_intercept=True, eta0=0.002)\n\n# Train the perceptron object (net)\nnet.fit(df[['having_IP_Address', 'URL_Length', 'Shortining_Service', 'having_At_Symbol', 'double_slash_redirecting',\n 'Prefix_Suffix', 'having_Sub_Domain', 'SSLfinal_State', 'Domain_registeration_length', 'Favicon',\n 'port', 'HTTPS_token', 'Request_URL', 'URL_of_Anchor', 'Links_in_tags', 'SFH', 'Submitting_to_email',\n 'Abnormal_URL', 'Redirect', 'on_mouseover', 'RightClick', 'popUpWidnow', 'Iframe', 'age_of_domain',\n 'DNSRecord', 'web_traffic', 'Page_Rank', 'Google_Index', 'Links_pointing_to_page', 'Statistical_report']\n ], df['Result'])\n\n# Output the coefficints\nprint(\"Coefficient 0 \" + str(net.coef_[0,0]))\nprint(\"Coefficient 1 \" + str(net.coef_[0,1]))\nprint(\"Bias \" + str(net.intercept_))\n\n# Do a prediction\npred = net.predict(df[['having_IP_Address', 'URL_Length', 'Shortining_Service', 'having_At_Symbol',\n 'double_slash_redirecting', 'Prefix_Suffix', 'having_Sub_Domain', 'SSLfinal_State',\n 'Domain_registeration_length', 'Favicon', 'port', 'HTTPS_token', 'Request_URL',\n 'URL_of_Anchor', 'Links_in_tags', 'SFH', 'Submitting_to_email', 'Abnormal_URL', 'Redirect',\n 'on_mouseover', 'RightClick', 'popUpWidnow', 'Iframe', 'age_of_domain', 'DNSRecord',\n 'web_traffic', 'Page_Rank', 'Google_Index', 'Links_pointing_to_page', 'Statistical_report']])\n#prediction\nprint(pred)\n\n# Confusion Matrix\nconfusion_matrix(pred, df['Result'])\n\n\"\"\"\nmodel = models.Sequential()\nmodel.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\nmodel.add(layers.Dense(16, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\"\"\"\n","sub_path":"3/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"431330632","text":"# -*- coding: utf-8 -*-\nfrom app import app\nimport requests\nfrom flask import render_template\n\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n posts = []\n new_article = requests.get('https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty')\n article_list = new_article.json()[:20]\n for article in article_list:\n data = requests.get('https://hacker-news.firebaseio.com/v0/item/' + str(article) + '.json?print=pretty')\n if 'url' in data.json():\n context = {}\n context['url'] = data.json()['url']\n context['title'] = data.json()['title']\n posts.append(context)\n return render_template('index.html', posts=posts)","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"329336935","text":"#coding:utf-8\nimport os\n# import numpy as np\n# import pandas as pd\n\n\n# data = pd.read_excel('point.xlsx','seat')\n# \n#读取csv文件\nimport csv\nimport matplotlib.pyplot as plt\n\n#出口\nEXIT_X = [16420,34720,6565,43875]\nEXIT_Y = [30852,6587,18720,18720]\n\n#读取座位\nx_zw = []\ny_zw = []\nlabel_zw = []\nwith open('point_zw.csv', 'rb') as f: # 采用b的方式处理可以省去很多问题\n reader = csv.reader(f)\n # print(type(reader))\n for row in reader:\n # do something with row, such as row[0],row[1]\n if row[1] != 'x':\n \tx_zw.append(row[1])\n \ty_zw.append(row[2])\n \tlabel_zw.append(row[0])\n \t# plt.text(row[1],row[2],str(row[0]), family='serif', style='italic', ha='right', wrap=True)\n \t# print(row[1],row[2])\n \t# \n##读取通道\nx_td = []\ny_td = []\nlabel_td = []\nwith open('point_td.csv', 'rb') as f: # 采用b的方式处理可以省去很多问题\n reader = csv.reader(f)\n # print(type(reader))\n for row in reader:\n # do something with row, such as row[0],row[1]\n if row[1] != 'x':\n \tx_td.append(row[1])\n \ty_td.append(row[2])\n \tlabel_td.append(row[0])\n \t# plt.text(row[1],row[2],str(row[0]), family='serif', style='italic', ha='right', wrap=True)\n \t# print(row[1],row[2])\n##读取楼梯\nx_lt = []\ny_lt = []\nlabel_lt = []\nwith open('point_lt.csv', 'rb') as f: # 采用b的方式处理可以省去很多问题\n reader = csv.reader(f)\n # print(type(reader))\n for row in reader:\n # do something with row, such as row[0],row[1]\n if row[1] != 'x':\n \tx_lt.append(row[1])\n \ty_lt.append(row[2])\n \tlabel_lt.append(row[0])\n \t# plt.text(row[1],row[2],str(row[0]), family='serif', style='italic', ha='right', wrap=True)\n \t# print(row[1],row[2])\n##读取辅助点\nx_fz = []\ny_fz = []\nlabel_fz = []\nwith open('point_fz.csv', 'rb') as f: # 采用b的方式处理可以省去很多问题\n reader = csv.reader(f)\n # print(type(reader))\n for row in reader:\n # do something with row, such as row[0],row[1]\n if row[1] != 'x':\n \tx_fz.append(row[1])\n \ty_fz.append(row[2])\n \tlabel_fz.append(row[0])\n \t# plt.text(row[1],row[2],str(row[0]), family='serif', style='italic', ha='right', wrap=True)\n \t# print(row[1],row[2])\n \t# \n \t\nfig = plt.figure(figsize=(80, 56), dpi=50)\n\n\nplt.plot(x_zw,y_zw,'ro',color='blue',label='xujing')\nplt.plot(EXIT_X,EXIT_Y,'ro',color='green',label='xujing')\n\nplt.plot(x_lt,y_lt,'ro',color='red',label='xujing')\nplt.plot(x_fz,y_fz,'ro',color='red',label='xujing')\n\nfor i in range(len(x_zw)):\n\tplt.text(x_zw[i],y_zw[i],str((x_zw[i],y_zw[i])))\nfor i in range(len(x_td)):\n\tplt.text(x_td[i],y_td[i],str((x_td[i],y_td[i])))\nfor i in range(len(x_lt)):\n\tplt.text(x_lt[i],y_lt[i],str((x_lt[i],y_lt[i])))\nfor i in range(len(x_fz)):\n\tplt.text(x_fz[i],y_fz[i],str((x_fz[i],y_fz[i])))\n\n# window = fig.add_subplot(111)\n\n# plt.scatter(x_zw, y_zw, s=200, c='blue')\n# plt.scatter(x_lt, y_lt, s=200, c='red')\n# plt.scatter(x_td, y_td, s=200, c='green')\n# plt.scatter(select_right_x, select_right_y, s=20, c='red')\n# print(len(select_right_x),len(select_right_y))\n# plt.plot(x, y, 'ro')\nplt.xlim(0, 50000)\nplt.ylim(0, 40000)\nplt.xlabel('x 49000')\nplt.ylabel('y 35000')\nplt.title('evacuation')\nplt.grid(True)\nplt.savefig('image_init.png')\nplt.show()\n\n\n# import csv\n# with open('some.csv', 'wb') as f: # 采用b的方式处理可以省去很多问题\n# writer = csv.writer(f)\n# writer.writerows(someiterable)","sub_path":"cg.py","file_name":"cg.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29368094","text":"import pickle\nimport tensorflow as tf\n\n# from models import model_a_conv1d\n\n# assigning the pickle files\n# with open('./Data_Array_Storage/X_train.pkl', 'rb') as f:\n# X_train = pickle.load(f)\n\nwith open('./Data_Array_Storage/X_test.pkl', 'rb') as f:\n X_test = pickle.load(f)\n\n# with open('./Data_Array_Storage/y_train.pkl', 'rb') as f:\n# y_train = pickle.load(f)\n\nwith open('./Data_Array_Storage/y_test.pkl', 'rb') as f:\n y_test = pickle.load(f)\n\n# loading model with just h5\n# Recreate the exact same model, including its weights and the optimizer\nmodel_from_h5 = tf.keras.models.load_model('./models_saved/model_a_conv1d.h5')\n\n# Show the model architecture\nmodel_from_h5.summary()\n\n# We need to define its optimizer and loss function again since the h5 file\n# only need to compile if continuing training\n# if just predictions, then no need for compile\n# does not contain those information :(\n# model_from_h5.compile(optimizer='Adam',\n# loss='sparse_categorical_crossentropy',\n# metrics=['accuracy'])\n\n# Re-evaluate the model\nloss, acc = model_from_h5.evaluate(X_test, y_test)\nprint(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))","sub_path":"predict_model_a_conv1d.py","file_name":"predict_model_a_conv1d.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440172388","text":"import os\nimport argparse\nfrom flask import current_app\nfrom alembic import __version__ as __alembic_version__\nfrom alembic.config import Config as AlembicConfig\nfrom alembic import command\n\nfrom flex.utils.local import proxy\n\n@proxy\ndef migrations():\n\treturn current_app.extensions['migrate']\n\n\nalembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]])\n\n\nclass _MigrateConfig(object):\n\tdef __init__(self, migrate, db, **kwargs):\n\t\tself.migrate = migrate\n\t\tself.db = db\n\t\tself.directory = migrate.directory\n\t\tself.configure_args = kwargs\n\n\t# @property\n\t# def metadata(self):\n\t# \t\"\"\"\n\t# \tBackwards compatibility, in old releases app.extensions['migrate']\n\t# \twas set to db, and env.py accessed app.extensions['migrate'].metadata\n\t# \t\"\"\"\n\t# \treturn self.db.metadata\n\n\nclass Config(AlembicConfig):\n\tdef get_template_directory(self):\n\t\tpackage_dir = os.path.abspath(os.path.dirname(__file__))\n\t\treturn os.path.join(package_dir, 'templates')\n\n\nclass Migrate(object):\n\tdef __init__(self, app=None, db=None, directory='.migrations', **kwargs):\n\t\tself.configure_callbacks = []\n\t\tself.db = db\n\t\tself.directory = directory\n\t\tself.alembic_ctx_kwargs = kwargs\n\t\tif app is not None and db is not None:\n\t\t\t\tself.init_app(app, db, directory)\n\n\tdef init_app(self, app, db=None, directory=None, **kwargs):\n\t\tself.db = db or self.db\n\t\tself.directory = directory or self.directory\n\t\tself.alembic_ctx_kwargs.update(kwargs)\n\t\tapp.extensions['migrate'] = _MigrateConfig(self, self.db,\n\t\t\t**self.alembic_ctx_kwargs)\n\n\tdef configure(self, f):\n\t\tself.configure_callbacks.append(f)\n\t\treturn f\n\n\tdef call_configure_callbacks(self, config):\n\t\tfor f in self.configure_callbacks:\n\t\t\tconfig = f(config)\n\t\treturn config\n\n\tdef get_config(self, directory, x_arg=None, opts=None):\n\t\tif directory is None:\n\t\t\tdirectory = self.directory\n\t\tconfig = Config(os.path.join(directory, 'alembic.ini'))\n\t\tconfig.set_main_option('script_location', directory)\n\t\tif config.cmd_opts is None:\n\t\t\tconfig.cmd_opts = argparse.Namespace()\n\t\tfor opt in opts or []:\n\t\t\tsetattr(config.cmd_opts, opt, True)\n\t\tif not hasattr(config.cmd_opts, 'x'):\n\t\t\tif x_arg is not None:\n\t\t\t\tsetattr(config.cmd_opts, 'x', [])\n\t\t\t\tif isinstance(x_arg, list) or isinstance(x_arg, tuple):\n\t\t\t\t\tfor x in x_arg:\n\t\t\t\t\t\tconfig.cmd_opts.x.append(x)\n\t\t\t\telse:\n\t\t\t\t\tconfig.cmd_opts.x.append(x_arg)\n\t\t\telse:\n\t\t\t\tsetattr(config.cmd_opts, 'x', None)\n\t\treturn self.call_configure_callbacks(config)\n\n\n","sub_path":"flex/db/migrations/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"610158960","text":"#!/usr/bin/python\n\nfrom optparse import OptionParser\n\ndef parse_cli():\n ''' CLI parser using OptionParser'''\n\n parser = OptionParser()\n parser.add_option('-d', '--debug',\n dest='debug',\n default=False,\n help='Enable debug output',\n action='store_true')\n parser.add_option('-F', '--filename',\n dest='FILE',\n default=\"word10k.txt\",\n help='File to use as dictionary file',\n type='string',\n action='store')\n parser.add_option('-P', '--pattern',\n dest='pattern',\n default=\"\",\n help='Pattern of word characters',\n type='string',\n action='store')\n\n return parser.parse_args()\n\n(options, args) = parse_cli()\ndef check_word_length(word,pattern):\n if len(word) == int(len(pattern)):\n return True\n else:\n return False\n\ndef check_repeating_chars(word,pattern):\n #repeats = False (default) then skip any words with repeating chars\n #pattern = true and repeats = True, then look for only words which match the repetition pattern\n match_score = 0\n for i in range(len(word)):\n for j in range(len(word)): \n if i != j :\n if word[i] == word[j]:\n if pattern[i] != pattern[j]:\n match_score = match_score + 1\n else:\n if pattern[i] == pattern[j]:\n match_score = match_score + 1\n if match_score == 0:\n return True \n else:\n return False\n\nwith open(options.FILE) as f:\n for line in f:\n WORD = line.rstrip('\\n').strip()\n if check_word_length(WORD,options.pattern) == True :\n if check_repeating_chars(WORD,options.pattern):\n print(WORD)\n","sub_path":"python_word.py","file_name":"python_word.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"594160740","text":"from src.core import Basic\nimport numpy as np\nfrom src.model.simpleMlpModel.simpleMlpModel import SimpleMlpModel\nfrom src.config.config import Config\nfrom conf.key import CONFIG_KEY\nimport tensorflow as tf\nfrom src.util.sampler.sampler import Sampler\nfrom src.util.sampler.sampler import SamplerData\nfrom src.util.sampler.intelligentSampler import IntelligentSampler\nfrom copy import deepcopy\n\n\nclass FakeSampler(Sampler):\n key_list = Config.load_json(file_path=CONFIG_KEY + '/fakeSamplerKey.json')\n\n def __init__(self, config, cost_fn, reference_trainer_env):\n super().__init__(config=config, cost_fn=cost_fn)\n self.reference_trainer_env = reference_trainer_env\n\n def sample(self, env, agent, sample_count, store_flag=False, agent_print_log_flag=False, reset_Flag=True):\n if agent.status == agent.status_key['TEST'] or agent.env_status == agent.config.config_dict[\n 'CYBER_ENVIRONMENT_STATUS']:\n res = super().sample(agent=agent,\n env=env,\n sample_count=sample_count,\n store_flag=store_flag,\n agent_print_log_flag=agent_print_log_flag,\n reset_Flag=reset_Flag)\n return res\n\n if agent.env_status == agent.config.config_dict['REAL_ENVIRONMENT_STATUS']:\n sample_data, enough_flag = self.reference_trainer_env.target_agent.model.return_most_recent_sample(\n sample_count=sample_count,\n env_status=self.reference_trainer_env.target_agent.config.config_dict['REAL_ENVIRONMENT_STATUS'])\n if enough_flag is False:\n raise ValueError('Real env data is not enough')\n\n sample_record = SamplerData()\n for i in range(sample_count):\n state, new_state, action, re, done = self._return_index_sample(sample_data=sample_data, index=i)\n if not isinstance(done, bool):\n if done[0] == 1.0:\n done = True\n else:\n done = False\n if self.cost_fn:\n reward = self.cost_fn(state=state, action=action, next_state=new_state)\n else:\n reward = re\n from src.agent.targetAgent.targetAgent import TargetAgent\n if isinstance(agent, TargetAgent):\n if agent.env_status == agent.config.config_dict['REAL_ENVIRONMENT_STATUS']:\n pass\n else:\n re = reward\n re = float(re)\n self.step_count_per_episode += 1\n agent.env_sample_count += 1\n if store_flag is True:\n agent.store_one_sample(state=state,\n action=action,\n next_state=new_state,\n reward=re,\n done=done)\n\n self.data.append(state=state,\n action=action,\n new_state=new_state,\n done=done,\n reward=re)\n\n sample_record.append(state=state,\n action=action,\n reward=re,\n new_state=new_state,\n done=done)\n\n self.log_every_step(agent=agent,\n reward=re)\n if done is True:\n tmp_state_set = self.state_set + [self.new_state_set[-1]]\n self.log_every_episode(agent=agent,\n average_reward=self.cumulative_reward / self.step_count_per_episode,\n reward=self.cumulative_reward,\n state_set=tmp_state_set,\n action_set=self.action_set,\n agent_print_log_flag=agent_print_log_flag)\n agent.log_queue.queue.clear()\n\n return sample_record\n\n else:\n raise ValueError('Environment status wrong')\n\n def train(self, *args, **kwargs):\n pass\n\n def print_log_queue(self, status):\n pass\n\n def _return_index_sample(self, sample_data, index):\n return (sample_data.state_set[index],\n sample_data.new_state_set[index],\n sample_data.action_set[index],\n sample_data.reward_set[index],\n sample_data.done_set[index])\n","sub_path":"src/util/sampler/fakeSampler.py","file_name":"fakeSampler.py","file_ext":"py","file_size_in_byte":4797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"287968837","text":"# coding=utf-8\nfrom __future__ import print_function\n\nimport collections\nimport datetime\nimport json\nimport os\nfrom copy import deepcopy\n\nfrom utils.dateutils import get_today_as_str\nimport utils.structured_data_utils\nfrom utils.filter import filter_remove_not_equals, filter_remove_equals\nfrom utils.printutils import print_profits\nfrom utils.profit import get_average_balance, get_start_date, get_stock_profit, \\\n get_annual_interest_rate\nfrom utils.sortutils import sort_by\nfrom utils.safeutils import safe_int\n\n\ndef num2column(column_num):\n return chr(ord('A') + column_num)\n\n\ndef get_label(col, row):\n return \"{}{}\".format(num2column(col), row)\n\n\ndef array_lstrip(arr, target=''):\n ret = []\n\n idx = 0\n while True:\n if arr[idx] != target:\n break\n idx += 1\n for curr_idx in range(idx, len(arr)):\n ret.append(arr[curr_idx])\n\n return ret\n\n\ndef encode(target):\n return target.encode('utf-8')\n\n\ndef encode_arr(arr):\n ret = []\n for each in arr:\n ret.append(each.encode('utf-8'))\n\n return ret\n\n\ndef encode_arr2d(arr2d):\n ret = []\n for each_row in arr2d:\n ret.append(encode_arr(each_row))\n\n return ret\n\n\ndef remove_empty_row(data):\n ret = []\n\n for row_idx in range(len(data)):\n empty = True\n for col_idx in range(len(data[row_idx])):\n if data[row_idx][col_idx]:\n empty = False\n break\n if not empty:\n ret.append(deepcopy(data[row_idx]))\n\n return ret\n\n\ndef get_label_idx(label, label_target):\n ret = -1\n for idx, each in enumerate(label):\n if each == label_target:\n ret = idx\n break\n if ret == -1:\n raise Exception(\"invalid target\")\n return ret\n\n\ndef date_minus(date1, date2):\n parsed_date1 = datetime.datetime.strptime(date1, \"%Y-%m-%d\").date()\n parsed_date2 = datetime.datetime.strptime(date2, \"%Y-%m-%d\").date()\n return (parsed_date1 - parsed_date2).days\n\n\ndef get_total_amount_by_date(structured_data):\n diff_by_date = collections.OrderedDict()\n\n data = structured_data.data\n date_idx = get_label_idx(label=structured_data.label, label_target=\"날짜\")\n price_idx = get_label_idx(label=structured_data.label, label_target=\"가격\")\n quantity_idx = get_label_idx(label=structured_data.label, label_target=\"수량\")\n\n accumulated_amount = 0\n for each_row in data:\n curr_date = each_row[date_idx]\n\n curr_amount = float(each_row[price_idx]) * float(each_row[quantity_idx])\n\n accumulated_amount += curr_amount\n diff_by_date[curr_date] = accumulated_amount\n\n prev_date = None\n accumulated_balance = 0.0\n accumulated_days = 0\n for key, val in diff_by_date.items():\n if prev_date is None:\n prev_date = key\n continue\n date_diff = date_minus(key, prev_date)\n accumulated_balance += val * date_diff\n accumulated_days += date_diff\n # print(\"[{}: {}] \".format(\"accumulated_days\", accumulated_days))\n # print(\"[{}: {}] \".format(\"accumulated_balance\", accumulated_balance))\n prev_date = key\n\n average_balance = accumulated_balance / accumulated_days\n ## 190520 0155\n # By gsheet https://docs.google.com/spreadsheets/d/1WuIknjqU5Rnb9owBAyTksTI8L-WoeKkn30oRc3djOJ4/edit#gid=1407017979\n ACCUMULATED_PROFIT = 111823\n # By banksalad\n CURRENT_VALUE_DIFF = 5625 - 29000 - 1827 + 11000 - 6075 - 10400\n current_profit = ACCUMULATED_PROFIT + CURRENT_VALUE_DIFF\n annual_interest_rate = current_profit / average_balance / accumulated_days * 365\n print(\"{:0.2f}%\".format(annual_interest_rate * 100))\n\n\ndef main():\n target_date = get_today_as_str()\n\n result = utils.structured_data_utils.get_structed_data_from_date(target_date)\n\n result = sort_by(result, \"날짜\")\n\n result = filter_remove_not_equals(result, \"종류\", \"주식\")\n # result = filter_remove_not_equals(result, \"종목\", \"NAVER\")\n # result = filter_remove_not_equals(result, \"종목\", \"SK텔레콤\")\n # result = filter_remove_not_equals(result, \"종목\", \"tiger 200 it\")\n # result = filter_remove_not_equals(result, \"종목\", \"카카오\")\n # result = filter_remove_equals(result, \"가격\", \"\")\n\n for idx, each_row in enumerate(result.data):\n each_price = safe_int(result.get_value_with_label(idx, \"가격\"))\n quantity = safe_int(result.get_value_with_label(idx, \"수량\"))\n\n result.data[idx][result.get_label_idx(\"총가격\")] = each_price * quantity\n print(result.data[idx][result.get_label_idx(\"총가격\")])\n\n average_balance = get_average_balance(result, target_date)\n # print(average_balance)\n\n start_date_as_string = get_start_date(result)\n days = date_minus(target_date, start_date_as_string)\n current_profit = get_stock_profit(result, target_date)\n\n annual_interest_rate = get_annual_interest_rate(current_profit, average_balance, days)\n print_profits(\n average_balance=average_balance,\n current_profit=current_profit,\n start_date=start_date_as_string,\n target_date=target_date,\n days=days,\n annual_interest_rate=annual_interest_rate\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"profit_rate_stock_190520.py","file_name":"profit_rate_stock_190520.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"612192452","text":"from flask import Flask, render_template, request, flash, redirect, jsonify\nfrom flask_cors import CORS\nimport config, csv, datetime\nfrom binance.client import Client\nfrom binance.enums import *\n\napp = Flask(__name__)\nCORS(app)\nclient = Client(config.API_KEY, config.API_SECRET, tld='us')\n#app.config['CORS_HEADERS'] = 'Content-Type'\n\n@app.route('/')\ndef index():\n title = 'CryptoCompare'\n\n info = client.get_account()\n\n balances = info['balances']\n\n #print(balances)\n\n\n return render_template('index.html', title=title, my_balances=balances)\n\n@app.route('/buy')\ndef buy():\n return 'buy'\n\n@app.route('/sell')\ndef sell():\n return 'sell'\n\n@app.route('/settings')\ndef settings():\n return 'settings'\n\n\n@app.route('/history')\ndef history():\n #candlesticks = client.get_all_tickers()\n candlesticks = client.get_historical_klines(\"BTCUSDT\", Client.KLINE_INTERVAL_15MINUTE, \"1 May, 2021\", \"21 May, 2021\")\n \n processed_candlesticks = []\n\n for data in candlesticks:\n candlestick = {\n \"time\": data[0] / 1000,\n \"open\": data[1],\n \"high\": data[2],\n \"low\": data[3],\n \"close\": data[4]\n }\n \n processed_candlesticks.append(candlestick)\n \n return jsonify(processed_candlesticks)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"604178484","text":"import os \nimport smtplib\nimport ssl\nimport imaplib\nfrom email.mime.text import MIMEText\nfrom django.core.files import File\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nimport quopri\nfrom email import encoders\nimport email\nfrom messaging.models import Email, EmailAddress, UserProfile\nimport datetime\nimport parse\nfrom email.parser import HeaderParser\nimport logging\nfrom latrom.settings import MEDIA_ROOT\nimport mailparser\n\nlogger =logging.getLogger(__name__)\n\n\nclass EmailBaseClass():\n def send_plaintext_email(self, to, message):\n '''sends plain text email over tls.\n Args\n ======\n to - list of strings email addresses\n message - plain text string \n '''\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(\n self.SMTP_SERVER, \n self.SMTP_PORT, \n context=context) as server:\n server.login(\n self.profile.email_address, \n self.profile.get_plaintext_password)\n try:\n resp = server.sendmail(self.profile.email_address, to, message)\n except smtplib.SMTPException:\n logger.error(f'Email to {to.split(\", \")} not sent')\n else:\n if len(resp) == 0:\n pass\n else:\n logger.error(f'Email to {\", \".join(resp.keys())} not sent')\n\n finally:\n server.quit()\n\n def send_html_email(self, \n subject, \n to, cc, bcc, \n html_message, \n hook=None, \n **hook_kwargs):\n '''Used to send multipart emails with HTML content.\n calls the send plaintext email method to actually send emails\n applies headers and adds an html part to the message.\n Args\n =======\n subject - string describes message\n to - string, email address of recepient\n cc - list of strings, carbon copy of message\n bcc - list of strings, blind carbon copy\n hook - func - used to attach additional mime parts\n hook_kwargs - variable length kwargs passed on to hook function '''\n\n mime_message = MIMEMultipart('alternative')\n mime_message['Subject'] = subject\n mime_message['From'] = self.profile.email_address\n mime_message['To'] = to\n mime_message['Cc'] = ','.join(cc)\n mime_message.attach(MIMEText(html_message, 'html'))\n \n\n if hook:\n parts = hook(**hook_kwargs)\n for part in parts:\n mime_message.attach(part)\n\n self.send_plaintext_email([to] + cc + bcc, mime_message.as_string())\n\n def send_email_with_attachment(self,\n subject,\n to, cc, bcc,\n message,\n attachment,\n html=False):\n\n def add_attachment_hook(a=None):#meta\n '''Used to add files to emails. returns a one element list\n with the mime-part of the encoded attachment'''\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(a.read())\n\n # encoded into ASCII string\n encoders.encode_base64(part)\n part.add_header(\n 'Content-Disposition',\n f'attachment; filename={a.name}',\n )\n return [part]\n\n self.send_html_email(subject, \n to, cc, bcc, \n message, \n hook=add_attachment_hook,\n a=attachment)\n\n def fetch_mailbox(self):\n '''Used to retrieve an instance of the mailbox'''\n return self.profile.login_incoming()\n\n def process_email(self, mail, id):\n '''Used to retrieve a complete email from the server, and decode it in UTF-8. Logs any errors. \n\n Args\n ==========\n mail - object mailbox\n id - string -represents the index of the email in the folder.\n\n Returns\n ==========\n the decoded string\n '''\n\n typ, data = mail.fetch(id, '(RFC822)')\n raw = data[0][1]\n\n try:\n as_string = raw.decode('utf-8', errors=\"ignore\")\n except Exception as e:\n logger.error(\n f'Error encountered decoding message {id} with error {e}')\n return\n \n return as_string\n\n def save_email_to_local_database(self, \n msg, \n id,\n folder):\n '''Iterates over the message parts and combines the text sections together while decoding them as well.'''\n\n msg_string = \"\"\n html_string = \"\"\n file= None\n\n #multipart vs singular message\n charset = msg.get_content_charset()\n charset = charset if charset else 'utf-8'\n if msg.is_multipart():\n \n for part in msg.walk():\n content_type = part.get_content_type()\n try:\n payload = part.get_payload(decode=True) \n except:\n payload = part.get_payload()\n\n if payload and isinstance(payload, bytes):\n payload = payload.decode(charset, errors=\"ignore\")\n \n if content_type == 'text/plain':\n msg_string += payload\n\n if content_type == 'text/html':\n html_string += payload\n\n file, file_name = self.download_email_attachment(msg, \n os.path.join(MEDIA_ROOT, 'temp'))\n if file:\n file_rb = open(file, 'rb')\n django_file = File(file_rb,\n os.path.join('messaging', file_name))\n \n else:\n payload = msg.get_payload(decode=True)\n if payload and isinstance(payload, bytes):\n payload = payload.decode(charset, errors=\"ignore\")\n msg_string = payload\n\n headers = dict(HeaderParser().parsestr(msg.as_string()).items())\n better_headers = mailparser.parse_from_string(msg.as_string())\n \n to = EmailAddress.get_address(better_headers.to[0][1])\n from_ = EmailAddress.get_address(better_headers.from_[0][1])\n \n\n email_msg = Email.objects.create(\n created_timestamp=better_headers.date,\n subject=better_headers.subject,\n owner=self.profile.user,\n to=to,\n sent_from=from_,\n server_id=id,\n folder=folder,\n )\n \n email_msg.write_body(html_string.strip() + msg_string)\n\n if file:\n try:\n email_msg.attachment.save(file_name, django_file)\n except Exception as e:\n print(f'file related exception {e}')\n\n file_rb.close()\n os.remove(file)\n\n if headers.get('Cc'):\n for address in headers['Cc'].split(', '):\n addr = EmailAddress.get_address(address)\n email_msg.copy.add(addr)\n\n if headers.get('Bcc'):\n for address in headers['Bcc'].split(', '):\n addr = EmailAddress.get_address(address)\n email_msg.blind_copy.add(addr)\n\n email_msg.save()\n\n def download_email_attachment(self, msg_string, path):\n #TODO save the file temporarily and then add it to the filefield in the \n #attachment folder\n fileName =None\n for part in msg_string.walk():\n if part.get_content_maintype() == 'multipart':\n continue\n if part.get('Content-Disposition') is None:\n continue\n fileName = part.get_filename()\n if bool(fileName):\n filePath = os.path.join(path, fileName)\n if not os.path.isfile(filePath) :\n fp = open(filePath, 'wb')\n payload = part.get_payload(decode=True) \n if payload:\n fp.write(payload)\n fp.close()\n\n return filePath, fileName\n return (None, fileName)\n\n def fetch_messages(self, \n mail,\n mail_ids,\n latest, \n folder):\n skipped = 0\n errors = 0\n queryset = self.profile.emails\n \n\n for id in reversed(mail_ids):\n if isinstance(id, bytes):\n id = id.decode('utf-8')\n \n \n if queryset.filter(server_id=id, folder=folder).exists():\n print(f'Email skipped: {id}')\n continue\n\n as_string = self.process_email(mail, id)\n \n #returns email.Message object\n \n email_message = email.message_from_string(as_string)\n try:\n self.save_email_to_local_database(\n email_message, \n id, \n folder)\n\n except UnicodeDecodeError:\n errors += 1\n logger.error(f'Failed to decode email {id}')\n except Exception as e:\n errors += 1\n logger.error(f'An unexpected error occurred: {e}')\n\n logger.warn(f'{skipped} emails skipped')\n logger.warn(f'{errors} errors handled')\n\n def fetch_all_folders(self):\n mail = self.fetch_mailbox()\n for folder in self.profile.folders:\n mail.select(folder.label)\n try:\n type, data = mail.search(None, 'ALL')\n except imaplib.IMAP4.error:\n continue\n mail_ids = data[0].split()\n latest = folder.latest\n self.fetch_messages(mail, mail_ids, latest, folder)\n \n\n\nclass EmailSMTP(EmailBaseClass):\n\n def __init__(self, profile):\n self.profile = profile\n self.SMTP_PORT = self.profile.outgoing_port\n self.SMTP_SERVER = self.profile.outgoing_server\n\n\nif __name__ == \"__main__\":\n profile = UserProfile.objects.first()\n client = EmailSMTP(profile)\n client.fetch_all_folders()","sub_path":"messaging/email_api/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":10459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"395035409","text":"from confluent_kafka import Consumer,TopicPartition\nimport time\nimport datetime\nimport json\nopts={}\nt=time.time()*1000\nt=t-1*60*1000\nt1=datetime.datetime.fromtimestamp(t/1000.0)\nmodifiedoffset=None\n\ndef my_on_assign(consumer, partitions):\n\n for p in partitions:\n p.offset = modifiedoffset\n print('offset set {}'.format(modifiedoffset))\n consumer.assign(partitions)\n time.sleep(10)\n print('complete assignment')\nkafka_brokers_sasl= [\n \"kafka01-prod02.messagehub.services.us-south.bluemix.net:9093\",\n \"kafka02-prod02.messagehub.services.us-south.bluemix.net:9093\",\n \"kafka03-prod02.messagehub.services.us-south.bluemix.net:9093\",\n \"kafka04-prod02.messagehub.services.us-south.bluemix.net:9093\",\n \"kafka05-prod02.messagehub.services.us-south.bluemix.net:9093\"\n ]\nopts['brokers']=','.join(kafka_brokers_sasl)\nopts['ca_location'] = '/etc/ssl/certs'\nopts['api_key']=\"yPVRhDBAFD2zYY3x0kyHAqxiBKneiRQBDS5mOPuHu82KMR64\"\n\ndriver_options = {\n 'bootstrap.servers': opts['brokers'],\n 'security.protocol': 'SASL_SSL',\n 'ssl.ca.location': opts['ca_location'],\n 'sasl.mechanisms': 'PLAIN',\n 'sasl.username': 'token',\n 'sasl.password': opts['api_key'],\n 'api.version.request': True,\n 'broker.version.fallback': '0.10.2.1',\n 'log.connection.close' : False\n }\nconsumer_opts = {\n 'group.id': 'event-enrichment-group1'\n }\nfor key in driver_options:\n consumer_opts[key] = driver_options[key]\nconsumer = Consumer(consumer_opts)\nconsumer.subscribe(['1411848d-2bf7-4309-8fc4-0bc6cd204d80'], on_assign=my_on_assign)\nk=consumer.position([TopicPartition('1411848d-2bf7-4309-8fc4-0bc6cd204d80', 0)])\np = consumer.get_watermark_offsets(TopicPartition('1411848d-2bf7-4309-8fc4-0bc6cd204d80', 0))\ntime.sleep(10)\ntopic_partitons_to_search = list(\n map(lambda p: TopicPartition('1411848d-2bf7-4309-8fc4-0bc6cd204d80', p, int(t)), range(0, 1)))\noffsets = consumer.offsets_for_times(topic_partitons_to_search, timeout=1.0)\nprint(p,k,offsets)\nfor k in offsets:\n modifiedoffset = k.offset\n\ntime.sleep(10)\n#consumer.subscribe(['1411848d-2bf7-4309-8fc4-0bc6cd204d80'])\nmsg_list = consumer.consume(num_messages=100, timeout=1)\n\nprint(msg_list)\nif(len(msg_list) > 0):\n offset_list = [msg.offset() for msg in msg_list]\n print(offset_list)\n# while True:\n# msg_list=consumer.consume(num_messages=10, timeout=1)\n# for msgg in msg_list:\n# msg_key = json.loads(msgg.key().decode('utf-8'))\n# msg_value = json.loads(msgg.value().decode('utf-8'))\n# if(len(msg_list) > 0):\n# print(msgg.topic(),msgg.partition(),msgg.offset())\n# p = consumer.get_watermark_offsets(TopicPartition('iotp_device_events', 0))\n\n\n\n\n","sub_path":"kafkaReplay.py","file_name":"kafkaReplay.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84502323","text":"from flask_wtf import FlaskForm\nfrom wtforms import TextAreaField, FileField\nfrom wtforms.validators import DataRequired\nfrom flask_wtf.file import FileRequired, FileAllowed\n\nnullmsg = \"This field is required\"\n\nclass UploadForm(FlaskForm):\n \"\"\" Form for file upload \"\"\"\n photo = FileField(\n label=\"Upload Picture\", \n validators=[ \n FileRequired(),\n FileAllowed(\n ['jpg', 'png', 'jpeg'], \n message=\"Image Files Only\"\n ) \n ]\n )\n\n description = TextAreaField(\n label=\"Description\", \n validators=[\n DataRequired(message=nullmsg),\n ]\n )\n\n ","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"604692850","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nimport sys\nimport os\n\nif __name__ == \"__main__\":\n\n nproc = len(os.listdir('OUT/'))\n nsamples = 1021\n\n nfeat = -1\n nc = -1\n nloc = -1\n myloc = -1\n\n fdata = None\n counter = None\n centers = None\n clustId = np.zeros(nsamples)\n\n file_string = \"./OUT/FinalOutId\"\n\n for p_id in range(nproc):\n current_file = file_string + str(p_id)\n f = open(current_file)\n f.readline()\n params = f.readline().split()\n myloc = int(params[3])\n if p_id == 0:\n\n nc = int(params[1][:-1])\n nfeat = int(params[5][:-1])\n nloc = myloc\n\n fdata = np.zeros((nsamples, nfeat))\n counter = np.zeros(nc)\n centers = np.zeros((nc, nfeat))\n\n\n f.readline()\n for line_idx in range(nc):\n counts = f.readline().split()\n counter[line_idx] = int(counts[3])\n\n for line_idx in range(myloc):\n clustId[p_id * nloc + line_idx] = int(f.readline())\n\n f.readline()\n\n for line_idx in range(myloc):\n data_pt = f.readline().split()\n data_pt = list(map(float, data_pt))\n fdata[p_id * nloc + line_idx] = np.array(data_pt)\n\n f.close()\n\n\n\n for i in range(nc):\n cluster_data = fdata[clustId == i]\n centers[i] = np.mean(cluster_data, axis=0)\n\n\n tol = 1e-10\n n_init=1\n kmeans = KMeans(n_clusters=nc,tol=tol, n_init=n_init, init=centers)\n kmeans.fit(fdata)\n\n correct_labels = np.sum(clustId == kmeans.labels_)\n print(\"number of correct labels = \",correct_labels, \"/\", nsamples)\n","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"137975216","text":"from django.urls import path, include\n\n# Создаем router и регистрируем наш ViewSet\nfrom rest_framework import routers\n\nfrom .views import ComicsView, LikeView, UserView, UserComicsClass, CommentView\n\nrouter = routers.DefaultRouter()\n# router.register(r'register', UserCreate, basename='register')\nrouter.register(r'usercomics', UserComicsClass, basename='comicss')\n\nurlpatterns = [\n # path('registration/', CreateUser.as_view())\n path('comics/', ComicsView.as_view()),\n path('like/', LikeView.as_view()),\n path('users/', UserView.as_view()),\n path('comment/', CommentView.as_view())\n]\nurlpatterns += router.urls\n","sub_path":"marvel_v2/comics/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"445582379","text":"\"\"\"\nTeX Lookup module driver of the SCRiPTeX Application.\n\"\"\"\n\n\nimport os\nimport filecmp\n\nfrom modules.texlookup import texlookup\n\n\nTEMPFILE = 'texlookup_temp'\n\n\ndef run_texlookup(infile, outfile):\n\n \"\"\"\n Runs the tex lookup module on the passed input file, writing the tex markup to the\n passed output file\n\n Assumes that the input file exists and is valid.\n \"\"\"\n\n # List for indices\n indices = []\n\n # Read input file\n with open(infile, 'r') as file:\n # Get number of symbols\n numsymbols = int(file.readline())\n # Append each index to list\n for _ in range(numsymbols):\n indices.append(file.readline())\n\n\n # Open output file\n with open(outfile, 'w+') as file:\n # Write numsymbols to output file\n file.write(repr(numsymbols) + '\\n')\n # For each index\n for i in range(numsymbols):\n # Write the corresponding tex markup\n file.write(texlookup.get_tex(int(indices[i])) + '\\n')\n\n\ndef test_texlookup(infile, expectedoutfile):\n\n \"\"\"\n Runs the TeX lookup module on the passed input file and returns if the output\n matches the passed expected output file.\n\n Assumes that input file exists and is valid.\n \"\"\"\n\n # Run TeX Lookup\n run_texlookup(infile, TEMPFILE + '.txt')\n\n # Compare files\n match = filecmp.cmp(expectedoutfile, TEMPFILE + '.txt')\n\n # Delete temporary file\n os.remove(TEMPFILE + '.txt')\n\n return match\n","sub_path":"prototype/texlookup.py","file_name":"texlookup.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"40798448","text":"from kalc.cli import run\nimport click\nfrom click.testing import CliRunner\nimport pytest\nimport yaml\nfrom kalc.model.scenario import Scenario\nfrom tests.test_util import print_objects\nfrom kalc.model.kubernetes import KubernetesCluster\nfrom kalc.model.kinds.Service import Service\nfrom kalc.model.search import mark_excluded\n\nTEST_CLUSTER_FOLDER = \"./tests/daemonset_eviction/cluster_dump\"\nTEST_DAEMONET = \"./tests/daemonset_eviction/daemonset_create.yaml\"\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_assert_ServUce():\n # try:\n # run([\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n # \"-t\", \"150\", \"-e\", \"Service:redis-master-evict,ServUc1e:redis-master\"])\n # except AssertionError as e:\n # print(str(e))\n # assert str(e) == \"Error: no such type 'Servic1e'\"\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master-evict,ServUce:redis-master\"])\n assert result.__str__() == \"\"\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_assert_mUster():\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master-evict,Service:redis-mUster\"])\n assert result.__str__() == \"\"\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_ignore_check_mUster():\n # run([\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n # \"-t\", \"150\", \"-e\", \"Service:redis-master-evict,ServUc1e:redis-mUster\",\"--ignore-nonexistent-exclusions\"])\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master-evict,Service:redis-mUster\",\"--ignore-nonexistent-exclusions\"])\n assert result.exit_code == 0\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_excluded_search():\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master-evict,Service:redis-master\", \"--pipe\"])\n assert result.exit_code == 0\n yaml.load(result.output)\n assert not(\"redis-master\\n\" in result.output[-200:])\n assert not(\"redis-master-evict\\n\" in result.output[-200:])\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_exclude_all_services():\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master,Service:redis-master-evict,Service:default-http-backend,Service:redis-slave\", \"--pipe\"])\n # run( [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n # \"-t\", \"150\", \"-e\", \"Service:redis-master,Service:redis-master-evict,Service:default-http-backend,Service:redis-slave\", \"--pipe\"])\n assert result.exit_code == 0\n assert \"Empty scenario\" in result.output\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_exclude_all_services_except_redis_slave():\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n \"-t\", \"650\", \"-e\", \"Service:redis-master,Service:redis-master-evict,Service:default-http-backend\", \"--pipe\"])\n # run( [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\", \\\n # \"-t\", \"150\", \"-e\", \"Service:redis-master,Service:redis-master-evict,Service:default-http-backend,Service:redis-slave\", \"--pipe\"])\n assert result.exit_code == 0\n print(result.output)\n assert \"name: redis-slave\" in result.output\n\n# @pytest.mark.skip(reason=\"temporary skip\")\ndef test_exclude_regexp():\n result = CliRunner().invoke(run, [\"--from-dir\", TEST_CLUSTER_FOLDER, \"-f\", TEST_DAEMONET, \"-o\", \"yaml\",\"-e\", \"Service:redis-master*\", \"--pipe\"])\n assert result.exit_code == 0\n\n@pytest.mark.skip(reason=\"broken issue #108 \")\ndef test_exclude_regexp_unit():\n k = KubernetesCluster()\n k.load_dir(TEST_CLUSTER_FOLDER)\n k.create_resource(open(TEST_DAEMONET).read())\n k._build_state()\n mark_excluded(k.state_objects, \"Service:front*\", skip_check=False)\n for p in filter(lambda x: isinstance(x, Service), k.state_objects):\n if str(p.metadata_name) == \"frontend\":\n if p.searchable:\n raise ValueError(\"exclude doesn't work\")","sub_path":"tests/test_x_exclude.py","file_name":"test_x_exclude.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"433063306","text":"from django.conf.urls import url, include\nfrom . import views \n\napp_name = 'myauth'\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^login/$', views.user_login, name='login'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^register/$', views.register, name='register'),\n]","sub_path":"myauth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"615037178","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 20 21:27:17 2013\n\n@author: acesimbrote\n\"\"\"\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\na=[]\nb=[]\ng = 9.81\nc = 1.0\nA = 0.93\nr = 1.2\nm = 250.0\nh = (c*A*r)/(2.0*m) #unidades [Kg^2 / m]\nTe = eval(raw_input('Ángulo: '))\nt = eval(raw_input('t = '))\n\n\n#Al = \nVo = 67 \nVox = Vo * math.cos(Te) \nVoy = Vo * math.sin(Te) \n#t = - (1/h) math.log((1-Al))\n\ni=0\n\nwhile i pot.purse:\n print(\"That bet is too high, please bet again.\")\n\n elif bet < 0:\n print(\"Please enter only positive numbers\")\n\n else:\n break\n\n\ndef player_choice(player):\n\n \"\"\"Takes player input on whether they would like to hit or stay, and calls\n hit function if they hit\"\"\"\n\n move = input(\"What would you like to do? [H]it or [S]tay\").upper()\n if move not in \"HS\":\n print(\"Please enter H or S\")\n return player_choice(player)\n\n if move == \"H\":\n player.hit(new_deck)\n print(\"You now have: \\n\")\n player.view_cards()\n\n if player.get_value() < 21:\n player_choice(player)\n else:\n player.view_cards()\n\n\ndef win_game(pot):\n \"\"\"Gives player their bet back and prints a win statement\"\"\"\n print(\"You Win!\")\n pot.return_bet()\n print(\"Your pot is now {}\".format(pot.purse))\n\n\ndef lose_game(pot):\n \"\"\"Prints a lose statement, and players pot.\"\"\"\n print(\"You Lose!!!\")\n pot.subtract_bet()\n print(\"Your pot is now {}\".format(pot.purse))\n\n\ndef game_logic(dealer, player, pot, deck):\n \"\"\"Compares values of player and dealer, and determines winner\"\"\"\n if dealer.get_value() < 17:\n dealer.hit(deck)\n print(\"The dealer hits\")\n\n print(\"Dealer has {}\".format(dealer.get_value()))\n print(\"You have {}\".format(player.get_value()))\n\n if player.get_value() > 21:\n lose_game(pot)\n elif dealer.get_value() > 21:\n win_game(pot)\n\n elif abs(player.get_value()-21) < abs(dealer.get_value()-21):\n win_game(pot)\n\n elif abs(player.get_value()-21) > abs(dealer.get_value()-21):\n lose_game(pot)\n\n else:\n print(\"Tie!\")\n\n\ndef deck_type():\n\n while True:\n d_type = input(\"Would you like to play with a\"\n \"[S]hoe or a [D]eck\").upper()\n if d_type not in \"SD\":\n continue\n elif d_type == \"D\":\n return \"D\"\n elif d_type == \"S\":\n return \"S\"\n\n\nif __name__ == '__main__':\n\n counter = 1\n pot = Pot(100)\n\n if deck_type() == \"D\":\n new_deck = Deck()\n else:\n new_deck = Shoe()\n\n print(\"Welcome to Blackjack! \\n\")\n while True:\n\n player = Player(new_deck)\n dealer = Dealer(new_deck)\n bet_logic(pot)\n\n dealer.get_hand()\n player.get_hand()\n print(\"Round {} \\n\".format(counter))\n print(\"Your hand: \\n\")\n player.view_cards()\n print(\"Dealer's hand: \\n\")\n dealer.view_cards()\n\n player_choice(player)\n\n game_logic(dealer, player, pot, new_deck)\n\n counter += 1\n\n if len(new_deck) <= 26:\n new_deck.refill()\n\n if pot.purse <= 0:\n print(\"You're out of money. Game over.\")\n play_again = input(\"Would you like to play again?\",\n \"[Y]es, or [N]o\").upper()\n\n if play_again == \"Y\":\n counter = 0\n pot = Pot(100)\n continue\n else:\n break\n","sub_path":"game_loop.py","file_name":"game_loop.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"379857834","text":"from object_net import object_net_components\nfrom object_net import object_net_writer\nfrom object_net import padder\nfrom object_net import types\nimport numpy as np\nimport tensorflow as tf\nimport tf_utils\n\n\ndef train(args, data: np.array, layer_size: int, num_layers: int):\n state_output_pairs_data = map(sequence_type.get_state_output_pairs, data)\n padded_data = padder.PaddedData.from_unpadded(state_output_pairs_data)\n object_net_data_placeholder = padder.PlaceholderPaddedData()\n data_holder = tf_utils.data_holder.DataHolder(args, lambda i: padded_data[i], len(padded_data))\n model_input = tf.zeros([object_net_data_placeholder.batch_size, 1])\n\n # Set up object_net model\n def get_model(training: bool) -> object_net_writer.ObjectNetWriter:\n return object_net_writer.ObjectNetWriter(\n truth_padded_data=object_net_data_placeholder,\n initial_hidden_vector_input=model_input,\n object_type=sequence_type,\n training=training,\n hidden_vector_network=object_net_components.LstmHiddenVectorNetwork(\n layer_size, num_layers, object_net_components.AdditionHiddenVectorCombiner()))\n\n model = get_model(True)\n model_test = get_model(False)\n optimizer = tf.train.AdamOptimizer().minimize(model.cost)\n summary = tf.summary.scalar(\"cost\", model.cost)\n\n # Run training\n def train_step(session, step, training_input, _, summary_writer):\n _, _, summaries = session.run(\n [optimizer, model.cost, summary],\n object_net_data_placeholder.get_feed_dict(training_input))\n\n summary_writer.add_summary(summaries, step)\n\n def test_step(session, step, testing_input, _, summary_writer):\n cost_result, all_summaries = session.run(\n [model.cost, summary],\n object_net_data_placeholder.get_feed_dict(testing_input))\n\n summary_writer.add_summary(all_summaries, step)\n\n print(\"Test cost at step %d: %f\" % (step, cost_result))\n\n show_examples(session, testing_input)\n\n def show_examples(session, model_input):\n # Limit to 10 inputs\n model_input = [x[:10] for x in model_input]\n\n generated_states_padded, \\\n generated_outputs_padded, \\\n generated_outputs_counts_padded, \\\n generated_step_counts = session.run(\n [\n model_test.generated_states_padded,\n model_test.generated_outputs_padded,\n model_test.generated_outputs_counts_padded,\n model_test.generated_step_counts],\n object_net_data_placeholder.get_feed_dict(model_input))\n\n copied_testing_input = padder.PaddedData(\n generated_step_counts, generated_outputs_counts_padded, generated_states_padded, generated_outputs_padded)\n unpadded = padder.unpad(copied_testing_input)\n\n def try_array_to_value(_array):\n try:\n return list(sequence_type.get_value_from_state_output_pairs(_array))\n except StopIteration:\n return [-1]\n\n generated_sequences = [try_array_to_value(array) for array in unpadded]\n\n [print(s) for s in generated_sequences]\n\n runner = tf_utils.generic_runner.GenericRunner.from_args(args, \"rnn_object_net_comparison\")\n runner.set_data_holder(data_holder)\n runner.set_train_step(train_step)\n runner.set_test_step(test_step)\n runner.run()\n\n\ndef __get_rnn_model(layer_size: int, num_layers: int, model_input: tf.Tensor) -> tf.Tensor:\n def get_cell(index: int):\n with tf.variable_scope(\"rnn_cell_%d\" % index):\n return tf.nn.rnn_cell.LSTMCell(layer_size, state_is_tuple=False)\n\n batch_size = tf.shape(model_input)[0]\n num_steps = tf.shape(model_input)[1]\n cells = [get_cell(i) for i in range(num_layers)]\n\n def body(step: int, current_input: tf.Tensor, previous_states: tf.Tensor, outputs: tf.TensorArray):\n current_states_list = []\n\n for i, cell in enumerate(cells):\n with tf.variable_scope(\"rnn_cell_%d\" % i):\n cell_previous_hidden_vector = tf.squeeze(tf.slice(previous_states, [0, i, 0], [-1, 1, -1]), axis=[1])\n output, state = cell(current_input, cell_previous_hidden_vector)\n\n # Set current_input to output for next cell iteration\n current_input = output\n\n current_states_list.append(state)\n\n current_states = tf.concat([tf.expand_dims(state, axis=1) for state in current_states_list], axis=1)\n\n with tf.variable_scope(\"fully_connected_output\"):\n final_output = tf.contrib.layers.fully_connected(current_input, num_outputs=1, activation_fn=tf.nn.sigmoid)\n\n outputs.write(step, final_output)\n\n return step + 1, current_input, current_states, outputs\n\n def cond(step: int, *_):\n return step < num_steps\n\n *_, outputs_result_ta = tf.while_loop(\n cond=cond,\n body=body,\n loop_vars=[\n 0,\n tf.zeros([batch_size, layer_size]),\n tf.zeros([batch_size, num_layers, layer_size * 2]),\n tf.TensorArray(dtype=tf.float32, size=num_steps)],\n shape_invariants=[\n tf.TensorShape([]),\n tf.TensorShape([None, layer_size]),\n tf.TensorShape([None, num_layers, layer_size * 2]),\n tf.TensorShape([])])\n\n return outputs_result_ta.stack()\n\n\nsequence_type = types.create_from_json(\"\"\"\n{\n \"types\": [\n {\n \"base\": \"list\",\n \"type\": \"float\"\n }\n ]\n}\n\"\"\")[0]\n","sub_path":"object_net_trainer.py","file_name":"object_net_trainer.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"575391292","text":"from django.conf.urls import url\n\nfrom .rest_views import HostAliasRest, HostKeyRest, HostLinkRest, HostDetail, KeyListRest\nfrom .rest_views import HostQuery, HostList, KeyDetail, KValDetail, AliasList\n\nhostspec = r'((?P[0-9]+?)|(?P\\S+?))'\naliasspec = r'((?P[0-9]+?)|(?P\\S*?))'\nkvalspec = r'((?P[0-9]+?)|(?P\\S*?))'\nakeyspec = r'((?P[0-9]+?)|(?P\\S*?))'\nlinkspec = r'((?P[0-9]+?)|(?P\\S*?))'\n\nurlpatterns = [\n url(r'^alias/?$', AliasList),\n url(r'^host/%s/alias/%s/?$' % (hostspec, aliasspec), HostAliasRest, name='hostaliasrest'),\n url(r'^host/%s/alias/?$' % hostspec, HostAliasRest, name='hostaliasrest'),\n url(r'^host/%s/key/%s/(?P.*)/?$' % (hostspec, kvalspec), HostKeyRest, name='hostkeyrest'),\n url(r'^host/%s/key/%s/?$' % (hostspec, kvalspec), HostKeyRest, name='hostkeyrest'),\n url(r'^host/%s/link/%s/(?P.*)/?$' % (hostspec, linkspec), HostLinkRest, name='hostlinkrest'),\n url(r'^host/%s/link/%s/?$' % (hostspec, linkspec), HostLinkRest, name='hostlinkrest'),\n url(r'^host/%s/?$' % hostspec, HostDetail, name='resthost'),\n url(r'^host/$', HostList),\n url(r'^key/%s/?$' % akeyspec, KeyDetail, name='restakey'),\n url(r'^kval/(?P[0-9]+?)/$', KValDetail, name='restkval'),\n url(r'^query/(?P\\S+?)/$', HostQuery),\n url(r'^keylist/%s/(?P\\S+?)?/?$' % akeyspec, KeyListRest),\n]\n\n# EOF\n","sub_path":"hostinfo/host/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"363393701","text":"\nimport requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\nshort = input('Short name of company(e.g CCC or LPP): ')\nsource = 'https://www.bankier.pl/inwestowanie/profile/quote.html?symbol='\n\nwhile True:\n data = requests.get(source+short)\n data.encoding = 'utf-8'\n soup = BeautifulSoup(data.text, 'html.parser')\n latestprice = soup.find('div', {'class': 'profilLast'}).text.strip()\n print(latestprice, end='\\r')\n sleep(30)\n data = None\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"376525498","text":"\n\nfrom xai.brain.wordbase.verbs._nettle import _NETTLE\n\n#calss header\nclass _NETTLES(_NETTLE, ):\n\tdef __init__(self,): \n\t\t_NETTLE.__init__(self)\n\t\tself.name = \"NETTLES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"nettle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_nettles.py","file_name":"_nettles.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"129667300","text":"def criptography():\n keys = 'abcdefghijklmnopqrstuvwxyz !'\n # auto generating the vaules of strings and last to first\n \n values = keys[-1] + keys[0:-1]\n\n # creating two dictionaries\n Dict1 = dict(zip(keys, values))\n Dict2 = dict(zip(values, keys))\n\n # user input\n message = input(\"Enter your secret message: \")\n mode = input(\"Enter Mode : Encode(E) OR Decode(D): \")\n\n #encode and decode\n if mode.upper() == 'E':\n newMessage = ''.join([Dict1[letter]\n for letter in message.lower()])\n elif mode.upper() == 'D':\n newMessage = ''.join([Dict2[letter]\n for letter in message.lower()])\n else:\n print(\"Please enter Right Mode ! \")\n\n return newMessage.capitalize()\n\n\nprint(criptography())\n","sub_path":"Criptography.py","file_name":"Criptography.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272634357","text":"# 뒤집기\n\n# 풀이 방법\n\n'''\n그리디는 한번 시행한 결과를 다시 하지 않는다.\n감으로 푸는 경우가 많다.\n규칙성 찾기\n'''\nstr =input()\ncount=0\nfor i in range(len(str)-1):\n if str[i]!=str[i+1]:\n count+=1\n\nprint((count+1)//2) ","sub_path":"패스트캠퍼스 강의/그리디/1439.py","file_name":"1439.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365639192","text":"\"\"\"\nTimer is a subclass of Thread\n- Action should be run after a certain amount of time has passed\n- Could be cancelled if its waiting\n\nclass threading.Timer(interval, function, args=None, kwargs=None)\n\"\"\"\nfrom threading import Timer\n\ndef task():\n print(\"Thread is running...\")\n\nt = Timer(3.0, task)\nt.start()\nt.cancel()\n","sub_path":"OperatingSystem/Python/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"489362184","text":"from django.utils.translation import ugettext as _\nfrom django.conf import settings\nfrom django.forms.models import inlineformset_factory\n\nimport floppyforms as forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.bootstrap import FormActions\nfrom crispy_forms.layout import Layout, Submit, HTML, Div, Fieldset\nfrom mapentity.widgets import SelectMultipleWithPop\n\nfrom geotrek.core.forms import TopologyForm\nfrom geotrek.core.widgets import LineTopologyWidget, PointTopologyWidget\nfrom .models import Trek, POI, WebLink\n\n\nclass TrekRelationshipForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(TrekRelationshipForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout('id',\n 'trek_a',\n 'trek_b',\n 'has_common_departure',\n 'has_common_edge',\n 'is_circuit_step',\n 'DELETE')\n\nTrekRelationshipFormSet = inlineformset_factory(Trek, Trek.related_treks.through, form=TrekRelationshipForm, fk_name='trek_a', extra=1)\n\n\nclass TrekForm(TopologyForm):\n fieldslayout = [\n Div(\n HTML(\"\"\"\n \"\"\" % (unicode(_(\"Main\")), unicode(_(\"Advanced\")))),\n Div(\n Div('name',\n 'published',\n 'is_park_centered',\n 'departure',\n 'arrival',\n 'duration',\n 'difficulty',\n 'route',\n 'ambiance',\n 'access',\n 'description_teaser',\n 'description',\n\n 'pk',\n 'model',\n\n css_id=\"main\",\n css_class=\"tab-pane active\"\n ),\n Div(\n 'disabled_infrastructure',\n 'advised_parking',\n 'parking_location',\n 'public_transport',\n 'advice',\n 'themes',\n 'networks',\n 'usages',\n 'web_links',\n 'information_desk',\n Fieldset(_(\"Related treks\"),),\n css_id=\"advanced\", # used in Javascript for activating tab if error\n css_class=\"tab-pane\"\n ),\n css_class=\"tab-content\"\n ),\n css_class=\"tabbable\"\n ),\n ]\n\n def __init__(self, *args, **kwargs):\n super(TrekForm, self).__init__(*args, **kwargs)\n self.fields['topology'].widget = LineTopologyWidget()\n self.fields['web_links'].widget = SelectMultipleWithPop(choices=self.fields['web_links'].choices,\n add_url=WebLink.get_add_url())\n # Make sure (force) that name is required, in default language only\n self.fields['name_%s' % settings.LANGUAGE_CODE].required = True\n\n class Meta(TopologyForm.Meta):\n model = Trek\n fields = TopologyForm.Meta.fields + \\\n ['name', 'published', 'is_park_centered', 'departure', 'arrival', 'duration', 'difficulty',\n 'route', 'ambiance', 'access', 'description_teaser', 'description',\n 'disabled_infrastructure', 'advised_parking', 'parking_location', 'public_transport', 'advice',\n 'themes', 'networks', 'usages', 'web_links', 'information_desk']\n\n\nclass POIForm(TopologyForm):\n fieldslayout = [\n Div('pk',\n 'model',\n\n 'type',\n 'name',\n 'description',\n\n css_class=\"tab-content\"\n )\n ]\n\n def __init__(self, *args, **kwargs):\n super(POIForm, self).__init__(*args, **kwargs)\n self.fields['topology'].widget = PointTopologyWidget()\n\n class Meta(TopologyForm.Meta):\n model = POI\n fields = TopologyForm.Meta.fields + ['name', 'description', 'type']\n\n\nclass WebLinkCreateFormPopup(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(WebLinkCreateFormPopup, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_action = self.instance.get_add_url()\n # Main form layout\n # Adds every name field explicitly (name_fr, name_en, ...)\n self.helper.form_class = 'form-horizontal'\n arg_list = ['name_{0}'.format(l[0]) for l in settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']]\n arg_list += ['url', 'category', FormActions(\n HTML('%s' % _(\"Cancel\")),\n Submit('save_changes', _('Create'), css_class=\"btn-primary\"),\n css_class=\"form-actions\",\n )]\n self.helper.layout = Layout(*arg_list)\n\n class Meta:\n model = WebLink\n fields = ['name_{0}'.format(l[0]) for l in settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']] + \\\n ['url', 'category']\n","sub_path":"geotrek/trekking/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"91926729","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 ('growlerdeals', '0031_user_added_deal'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user_added_deal',\n name='Sunday',\n field=models.DecimalField(null=True, max_digits=4, decimal_places=2, validators=[django.core.validators.MinValueValidator(0)]),\n ),\n ]\n","sub_path":"growlerdeals/migrations/0032_user_added_deal_sunday.py","file_name":"0032_user_added_deal_sunday.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"435574957","text":"import datetime\nimport io\nimport os\nimport sys\nimport textwrap\nimport traceback\nimport subprocess\nimport pymysql\nfrom prettytable import PrettyTable\nfrom contextlib import redirect_stdout\n\nimport discord\nfrom discord.ext import commands\n\nimport config\n\n\ndef is_owner(ctx):\n return ctx.author.id in config.owners\n\n\nclass Owner:\n def __init__(self, bot):\n self.bot = bot\n self.last_result = None\n\n @commands.command(name=\"eval\", aliases=[\"ev\", \"debug\"])\n @commands.check(is_owner)\n async def _eval(self, ctx, *, code):\n \"\"\"Evaluate code. (Bot Owner Only)\"\"\"\n env = {\n 'self': self,\n 'bot': self.bot,\n 'client': self.bot,\n 'ctx': ctx,\n 'message': ctx.message,\n 'guild': ctx.guild,\n 'channel': ctx.channel,\n 'author': ctx.author,\n 'me': ctx.me,\n 'that': self.last_result\n }\n env.update(globals())\n\n stdout = io.StringIO()\n\n to_compile = f'async def func():\\n{textwrap.indent(code, \" \")}'\n\n try:\n exec(to_compile, env)\n except Exception as e:\n err = \"; \".join(str(e).split(\"\\n\"))\n return await ctx.send(f\"Error while executing: `{e.__class__.__name__}: {err}`\")\n\n before = datetime.datetime.utcnow()\n func = env['func']\n try:\n with redirect_stdout(stdout):\n ret = await func()\n except Exception as e:\n err = \"; \".join(str(e).split(\"\\n\"))\n return await ctx.send(f\"Error while executing: `{e.__class__.__name__}: {err}`\")\n else:\n value = stdout.getvalue()\n if ret is None:\n if value:\n if isinstance(value, str):\n value = \"'\" + value.replace(\"'\", \"\\\\'\") + \"'\"\n content = f\"{value}\"\n self.last_result = value\n else:\n content = None\n else:\n y = ret if not isinstance(ret, str) else \"'\" + ret.replace(\"'\", \"\\\\'\") + \"'\"\n content = f\"{value}{y}\"\n self.last_result = ret\n try:\n await ctx.send(f\"*Executed in {((datetime.datetime.utcnow() - before) * 1000).total_seconds()}ms\" + (\n f\".* ```py\\n{content}```\" if content else \" with no returns.*\"))\n except discord.HTTPException:\n await ctx.send(\"*Executed in {}ms and returned:*\\nContent too long. Haste: \".format(\n ((datetime.datetime.utcnow() - before) * 1000).total_seconds()) + self.bot.post_to_haste(content))\n\n @commands.command(name=\"exec\")\n @commands.check(is_owner)\n async def _exec(self, ctx, *, code: str):\n \"\"\"Execute code in a command shell. (Bot Owner Only)\"\"\"\n sp = subprocess.Popen(code, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = sp.communicate()\n msg = \"Executing...\\n\"\n if out:\n msg += 'Success! ```\\n{}```\\n'.format(out.decode())\n if err:\n msg += 'Error/Info/Warn! ```\\n{}```\\n'.format(err.decode())\n msg += \"Returncode: {}\".format(sp.returncode)\n await ctx.send(msg)\n\n @commands.command(aliases=[\"die\", \"reboot\"])\n @commands.check(is_owner)\n async def shutdown(self, ctx):\n \"\"\"Shutdown the bot. Thanks to PM2, this also reboots it. (Bot Owner Only)\"\"\"\n await ctx.send(\":wave: Shutting down...\")\n self.bot.logout()\n sys.exit(0)\n\n @commands.command(aliases=['db', 'dbquery'])\n @commands.check(is_owner)\n async def query(self, ctx, *, query: str):\n \"\"\"Query the MySQL database. (Bot Owner Only)\"\"\"\n try:\n db = pymysql.connect(config.db_ip, config.db_user, config.db_pass, config.db_name, charset='utf8mb4')\n cur = db.cursor()\n cur.execute(query)\n table = \":x: Nothing was returned in this query.\"\n if cur.description:\n desc = list(cur.description)\n x = []\n for it in desc:\n l = list(it)\n x.append(l[0])\n table = PrettyTable(x)\n for row in cur.fetchall():\n table.add_row(list(row))\n db.commit()\n cur.close()\n db.close()\n try:\n await ctx.send(f\"```\\n{table}```\")\n except discord.HTTPException:\n await ctx.send(f'Content too long. Hastepaste: ' + await self.bot.post_to_haste(table))\n except pymysql.err.ProgrammingError as e:\n err_msg = str(e).split(',')[1].replace(')', '').replace('\"', '')\n await ctx.send(f\":x: {err_msg}\")\n\n @commands.command()\n @commands.check(is_owner)\n async def reload(self, ctx, *, extension: str):\n \"\"\"Reload an extension (Bot Owner Only)\"\"\"\n if extension != \"all\":\n try:\n self.bot.unload_extension('cogs.' + extension)\n self.bot.load_extension('cogs.' + extension)\n await ctx.send(f\":ok_hand: Reloaded /cogs/{extension}.py\")\n except Exception:\n await ctx.send(f\":sob: I-I'm sorry, I couldn't reload the `{extension}` extensions >w< \"\n + f\"```py\\n{traceback.format_exc()}```\")\n else:\n extensions = [f for f in os.listdir('./cogs') if f.endswith('.py')]\n for ext in extensions:\n try:\n self.bot.unload_extension('cogs.' + ext[:-3])\n self.bot.load_extension('cogs.' + ext[:-3])\n except:\n await ctx.send(\n f'I ran into an error reloading the {ext[:-3]} extension. ```py\\n{traceback.format_exc()}```')\n continue\n await ctx.send(':white_check_mark: Reloaded all extensions.')\n\n @commands.command()\n @commands.check(is_owner)\n async def unload(self, ctx, *, extension: str):\n \"\"\"Unload an extension (Bot Owner Only)\"\"\"\n self.bot.unload_extension(\"cogs.\" + extension)\n await ctx.send(f\":ok_hand: Unloaded /cogs/{extension}.py\")\n\n @commands.command()\n @commands.check(is_owner)\n async def load(self, ctx, *, extension: str):\n \"\"\"Load an extension (Bot Owner Only)\"\"\"\n try:\n self.bot.load_extension(\"cogs.\" + extension)\n await ctx.send(f\":ok_hand: Loaded /cogs/{extension}.py\")\n except Exception:\n await ctx.send(f\":sob: I-I'm sorry, I couldn't load the `{extension}` module >w< \"\n + f\"```py\\n{traceback.format_exc()}```\")\n\n\ndef setup(bot):\n bot.add_cog(Owner(bot))\n","sub_path":"cogs/owner.py","file_name":"owner.py","file_ext":"py","file_size_in_byte":6744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115326727","text":"#Jinesh authored this initially. check.py file is needed to see if every image file is properly associated with a text annotation file. The script finally copies only those image files for which it has a corresponding text annotation. Multiple annotation in a single image file and the corresponding image files are moved into a separate folder to keep it clean.\n\nimport os\nfrom shutil import copyfile\nlabelFolder = \"/Labels/004/\"\nimagesFolder = \"/Images/004/\"\narr = os.listdir('./Images/004/')\noutputFolder = \"/Result/\"\nmultipleResultsFolder = \"/multiple-result/\"\nprint (arr)\noutputDirectory = os.path.join(os.getcwd(), outputFolder)\nmultipleResultsDirectory = os.path.join(os.getcwd(), multipleResultsFolder)\nfor file in arr:\n # compose JPEG file name \n textFile = file.replace(\".JPEG\",\".txt\") \n jpegFile = os.path.join(os.getcwd() +imagesFolder, file)\n filePath = os.path.join(os.getcwd() +labelFolder, textFile)\n print ('Hello World!')\n print ('JPEG file exists: ' + str(os.path.isfile(jpegFile)))\n print ('Text file exists: ' + str(os.path.isfile(filePath)))\n if (os.path.isfile(jpegFile) and os.path.isfile(filePath)):\n print ('Both files exists')\n try:\n f = open(filePath, \"r\")\n #num_lines = sum(1 for line in f)\n print (\"File contents: \")\n print (f)\n length = len(f.readlines())\n f.close()\n print(length)\n if (length <= 1 ):\n print(\"Less in length\")\n #delete image and text file\n #os.remove(jpegFile)\n #f.close()\n #os.remove(filePath)\n #continue\n elif(length > 2):\n print(\"Moving this File to multiple result directory\")\n #os.rename(jpegFile, os.path.join(os.getcwd(), imagesFolder) + \"/\" + \"multiple/\" + file)\n #os.rename(filePath, os.path.join(os.getcwd(), labelFolder) + \"/\" + \"multiple/\" + textFile)\n copyfile (jpegFile, os.path.join(os.getcwd() + multipleResultsFolder + \"/images/\", file))\n copyfile (filePath, os.path.join(os.getcwd() + multipleResultsFolder + \"/labels/\", textFile))\n else:\n print(\"Moving this File to result directory\")\n copyfile (jpegFile, os.path.join(os.getcwd() + outputFolder + \"/images/\", file))\n copyfile (filePath, os.path.join(os.getcwd() + outputFolder + \"/labels/\", textFile))\n except Exception as e:\n print(e)\n #delete file\n #os.remove(jpegFile)\n else:\n print (\"Image and text counterpart not found!\")\n print (\"JPEG File: \" + jpegFile)\n print (\"Text File: \" + filePath)\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"299535274","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n\n#Makes a list of top 10 champions by tier based on role data.\ndef tierlist_list(data):\n\ttierlist_list_out = []\n\tfor champ in data.find_all('div', class_='champion-index-table__name'):\n\t\tif len(tierlist_list_out) >= 5: break\n\t\ttierlist_list_out.append(champ.text.replace(' ','').replace(\"'\",\"\").replace(\".\",\"\").replace(\" & Willump\", \"\"))\n\n\treturn tierlist_list_out\n\n\n#Makes a list of the winrates of champions by tier based on role data.\ndef winrate_list(data):\n\twinrate_list_out = []\n\tvalue_count = 2\n\tfor champ_winrate in data.find_all('td', class_='champion-index-table__cell champion-index-table__cell--value'):\n\t\tif value_count == 30: break\n\t\tvalue_count += 1\n\t\tif value_count % 3 == 0:\n\t\t\twinrate_list_out.append(champ_winrate.text)\n\n\treturn winrate_list_out\n\n#Makes a list of the pickrates of champions by tier based on role data.\ndef pickrate_list(data):\n\twinrate_list_out = []\n\tvalue_count = 1\n\tfor champ_winrate in data.find_all('td', class_='champion-index-table__cell champion-index-table__cell--value'):\n\t\tif value_count == 30: break\n\t\tvalue_count += 1\n\t\tif value_count % 3 == 0:\n\t\t\twinrate_list_out.append(champ_winrate.text)\n\n\treturn winrate_list_out\n\n#https://opgg-static.akamaized.net/images/lol/champion/Zac.png?image=q_auto,w_140&v=1581511032\ndef make_tierlist(champ_list, winrate_list, pickrate_list):\n\ttierlist_out = {}\n\tfor i in range(len(champ_list)):\n\t\ttierlist_out[champ_list[i]] = [winrate_list[i]] \n\t\ttierlist_out[champ_list[i]].append(\"https://opgg-static.akamaized.net/images/lol/champion/{}.png?image=q_auto,w_140&v=1581511032\".format(champ_list[i]))\n\t\ttierlist_out[champ_list[i]].append(pickrate_list[i])\n\n\treturn tierlist_out\n\n\n\nsource = requests.get('https://na.op.gg/champion/statistics').text\n\nsoup = BeautifulSoup(source, 'lxml')\n\n#HTML Parsing for roles\ntop_data = soup.find('tbody', class_='tabItem champion-trend-tier-TOP')\njungle_data = soup.find('tbody', class_='tabItem champion-trend-tier-JUNGLE')\nmid_data = soup.find('tbody', class_='tabItem champion-trend-tier-MID')\nadc_data = soup.find('tbody', class_='tabItem champion-trend-tier-ADC')\nsupport_data = soup.find('tbody', class_='tabItem champion-trend-tier-SUPPORT')\n\n#Top 10 chmapions in each role by tier in order\ntop_tierlist_champion = tierlist_list(top_data)\njungle_tierlist_champion = tierlist_list(jungle_data)\nmid_tierlist_champion = tierlist_list(mid_data)\nadc_tierlist_champion = tierlist_list(adc_data)\nsupport_tierlist_champion = tierlist_list(support_data)\n\n#Winrates of the top 10 champions in each role by tier in order\ntop_tierlist_winrate = winrate_list(top_data)\njungle_tierlist_winrate = winrate_list(jungle_data)\nmid_tierlist_winrate = winrate_list(mid_data)\nadc_tierlist_winrate = winrate_list(adc_data)\nsupport_tierlist_winrate = winrate_list(support_data)\n\n#Pickrates of the top 10 champions in each role by tier in order\ntop_tierlist_pickrate = pickrate_list(top_data)\njungle_tierlist_pickrate = pickrate_list(jungle_data)\nmid_tierlist_pickrate = pickrate_list(mid_data)\nadc_tierlist_pickrate = pickrate_list(adc_data)\nsupport_tierlist_pickrate = pickrate_list(support_data)\n\n#Combining top 10 champions with their corresponsing winrates.\ntop_tierlist = make_tierlist(top_tierlist_champion, top_tierlist_winrate, top_tierlist_pickrate)\njungle_tierlist = make_tierlist(jungle_tierlist_champion, jungle_tierlist_winrate, jungle_tierlist_pickrate)\nmid_tierlist = make_tierlist(mid_tierlist_champion, mid_tierlist_winrate, mid_tierlist_pickrate)\nadc_tierlist = make_tierlist(adc_tierlist_champion, adc_tierlist_winrate, adc_tierlist_pickrate)\nsupport_tierlist = make_tierlist(support_tierlist_champion, support_tierlist_winrate, support_tierlist_pickrate)\n\n","sub_path":"build/exe.win-amd64-3.6/lol_winrates/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"406794378","text":"import datetime\nimport json\nimport math\nimport random\nfrom itertools import chain\n\nimport pandas as pd\nimport pytz\nfrom django.db.models import IntegerField, Max, Min, Q\nfrom django.db.models.functions import Cast, Substr\nfrom django.http import JsonResponse\nfrom django.shortcuts import redirect, render\n\nfrom bts.models import (Card, Place, Route, ScheduleTime, ServiceInterval,\n Station)\n\n\ndef index(request):\n bts_station = Station.objects.all().order_by('name')\n\n context = {\n 'bts_station': bts_station,\n \"cssversion\": random.randint(1, 1000)\n }\n\n return render(request, 'index.html', context=context)\n\ndef trip(request):\n if request.method == 'GET' and 'from' in request.GET and 'to' in request.GET:\n sfrom = request.GET['from'].upper()\n sto = request.GET['to'].upper()\n\n if sfrom and sto:\n sfq = Station.objects.filter(id__exact=sfrom)\n stq = Station.objects.filter(id__exact=sto)\n\n if sfq.count() and stq.count():\n sfq = sfq.get()\n stq = stq.get()\n \n sfq_route = Route.objects.filter(name__exact=sfq.route_id).get()\n stq_route = Route.objects.filter(name__exact=stq.route_id).get()\n\n card_query = Card.objects.all()\n\n data = getStationsInfo(sfrom, sto)\n\n context = {\n \"stationFrom\": data['station'][0],\n \"stationTo\": data['station'][-1],\n \"stationOther\": data['station'][1:-1],\n \"cardPrice\": [{\"cat\": i.category, \"name\": i.name, \"price\": data[\"price\"][i.category]} for i in card_query],\n \"interchange\": data['interchange'],\n \"loadTime\": (datetime.datetime.now() + datetime.timedelta(minutes=2)).strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"cssversion\": random.randint(1, 1000)\n }\n\n place_query = Place.objects.filter(station_id_id__exact=sto)\n place_category = list(set([i.category for i in place_query]))\n\n context[\"place\"] = []\n for place in place_query:\n res = {\n \"category\": place.category,\n \"id\": place.id,\n \"name\": place.name\n }\n\n context[\"place\"].append(res)\n\n pcat = {\n 1: \"Restaurant\",\n 2: \"Traveling\",\n 3: \"Hotel\",\n 4: \"Shopping\"\n }\n\n context['placeCatId'] = place_category\n\n route_color_hex = {\n 'green': '#32cd32',\n 'viridian': '#00807c'\n }\n\n if sfq.route_inter and (sfq.route_id_id == stq.route_id_id or sfq.route_inter_id == stq.route_id_id):\n context['stationFrom']['route_name'] = stq_route.name\n context['stationFrom']['route_id'] = stq_route.id\n context['stationFrom']['route_color'] = route_color_hex[stq_route.color]\n else:\n context['stationFrom']['route_name'] = sfq_route.name\n context['stationFrom']['route_id'] = sfq_route.id\n context['stationFrom']['route_color'] = route_color_hex[sfq_route.color]\n\n if stq.route_inter and (stq.route_id_id == sfq.route_id_id or stq.route_inter_id == sfq.route_id_id):\n context['stationTo']['route_name'] = sfq_route.name\n context['stationTo']['route_id'] = sfq_route.id\n context['stationTo']['route_color'] = route_color_hex[sfq_route.color]\n else:\n context['stationTo']['route_name'] = stq_route.name\n context['stationTo']['route_id'] = stq_route.id\n context['stationTo']['route_color'] = route_color_hex[stq_route.color]\n\n a = ScheduleTime.objects.filter(station_id_id__exact=sfrom)\n b = Station.objects.filter(route_id_id__exact=context['stationFrom']['route_id'])\n \n #####################################\n ##### Get line terminal station #####\n route_sub_from_id = context['stationFrom']['route_id']\n route_sub_query = Station.objects.filter(Q(route_id_id__exact=route_sub_from_id) | Q(route_inter_id__exact=route_sub_from_id)).values(sub_id=Substr('id', 1, 1)).distinct()\n\n route_station_terminal = []\n for i in route_sub_query:\n sub_id = i['sub_id']\n if sub_id != 'C':\n sub_id_station_q = Station.objects.filter((Q(route_id_id__exact=route_sub_from_id) | Q(route_inter_id__exact=route_sub_from_id)) & Q(id__istartswith=sub_id)).values(id_num=Cast(Substr('id', 2), IntegerField()))\n smax = sub_id_station_q.aggregate(Max('id_num'))\n if len(route_sub_query) == 1:\n smin = sub_id_station_q.aggregate(Min('id_num'))\n route_station_terminal.append(f\"{sub_id}{smin['id_num__min']}\")\n route_station_terminal.append(f\"{sub_id}{smax['id_num__max']}\")\n elif len(route_sub_query) == 2:\n route_station_terminal.append(f\"{sub_id}{smax['id_num__max']}\")\n route_station_terminal.append('CEN')\n else:\n route_station_terminal.append(f\"{sub_id}{smax['id_num__max']}\")\n \n result = getStationsInfo(route_station_terminal[0], route_station_terminal[1])['station']\n pos = build_dict(result, \"id\")\n station_trip_to = sto\n\n if data['interchange']:\n station_trip_to = data['interchange'][0]\n \n from_index = pos.get(sfrom)['index']\n to_index = pos.get(station_trip_to)['index']\n \n if from_index > to_index:\n result = result[::-1]\n \n terminal = result[-1]\n\n if route_sub_from_id == 'SMS':\n if terminal['id'] == 'N8':\n line_trip = 'IN'\n else:\n line_trip = 'OUT'\n elif route_sub_from_id == 'SSK':\n if terminal['id'] == 'E15':\n line_trip = 'IN'\n else:\n line_trip = 'OUT'\n elif route_sub_from_id == 'SIL':\n if terminal['id'] == 'W1':\n line_trip = 'IN'\n else:\n line_trip = 'OUT'\n\n prev = None\n cur = None\n diff_set = [0]\n for i in range(len(result)):\n if i > 0:\n prev = ScheduleTime.objects.filter(Q(station_id_id__exact=result[i - 1]['id']) & Q(trip__exact=line_trip) & Q(route_id_id__exact=route_sub_from_id)).values('time_first', 'time_last')\n cur = ScheduleTime.objects.filter(Q(station_id_id__exact=result[i]['id']) & Q(trip__exact=line_trip) & Q(route_id_id__exact=route_sub_from_id)).values('time_first', 'time_last')\n if not cur.count():\n if line_trip == 'IN':\n line_trip_n = 'OUT'\n else:\n line_trip_n = 'IN'\n prev = ScheduleTime.objects.filter(Q(station_id_id__exact=result[i - 1]['id']) & Q(trip__exact=line_trip_n) & Q(route_id_id__exact=route_sub_from_id)).values('time_first', 'time_last')\n cur = ScheduleTime.objects.filter(Q(station_id_id__exact=result[i]['id']) & Q(trip__exact=line_trip_n) & Q(route_id_id__exact=route_sub_from_id)).values('time_first', 'time_last')\n \n prev_n = prev.get()['time_first']\n cur_n = cur.get()['time_first']\n diff = abs((datetime.datetime.combine(datetime.date.today(), prev_n) - datetime.datetime.combine(datetime.date.today(), cur_n)).total_seconds())\n diff_set.append(diff)\n\n context['lineTerminalStation'] = terminal['name']\n #####################################\n\n open_service_time = datetime.datetime.today().replace(hour=6, minute=0, second=0, microsecond=0) + datetime.timedelta(seconds=sum(diff_set[:from_index + 1]))\n time_current = datetime.datetime.now()\n hol_df = pd.read_csv(f\"https://www.myhora.com/calendar/ical/holiday.aspx?{int(time_current.strftime('%Y')) + 543}.csv\", parse_dates=['Start Date'], encoding='utf8', usecols=['Start Date'])\n hol_df = hol_df[hol_df['Start Date'] == time_current.strftime(\"%Y-%m-%d\")]\n if time_current.strftime(\"%a\") in (\"Sat\", \"Sun\") or not hol_df.empty:\n event = 'HOL'\n serv_int_query = ServiceInterval.objects.filter(event__exact=event, route_id_id__exact=route_sub_from_id).order_by('time_from')\n else:\n if sfrom == 'E15' and route_sub_from_id == 'SMS':\n # event = 'NSM'\n serv_int_query1 = ServiceInterval.objects.filter(Q(event__exact='NOR') & Q(route_id_id__exact=route_sub_from_id) & (Q(time_from__exact='06:00:00') | Q(time_from__range=('09:00:00', '16:00:00')) | Q(time_from__gte='20:00:00'))).order_by('time_from')\n serv_int_query2 = ServiceInterval.objects.filter(event__exact='NSM', route_id_id__exact=route_sub_from_id).order_by('time_from')\n serv_int_query = sorted(chain(serv_int_query1, serv_int_query2), key=lambda instance: instance.time_from)\n print(serv_int_query)\n else:\n event = 'NOR'\n serv_int_query = ServiceInterval.objects.filter(event__exact=event, route_id_id__exact=route_sub_from_id).order_by('time_from')\n midnight = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1)\n time_last = ScheduleTime.objects.filter(station_id_id__exact=sfrom, trip__exact=line_trip, route_id_id__exact=route_sub_from_id).values('time_last').get()['time_last']\n\n list_num = 10\n\n time_set = [open_service_time]\n check = True\n for serv_int in serv_int_query:\n time_wait = serv_int.time_wait\n time_to = datetime.datetime.combine(datetime.date.today(), serv_int.time_to)\n if time_to + datetime.timedelta(days=1) == midnight:\n time_to = midnight\n while time_set[-1] < time_to or time_set[-1] + time_wait <= datetime.datetime.combine(midnight, time_last):\n if (time_set[-1] >= time_current or time_set[-1] >= time_current - datetime.timedelta(minutes=1)) and check:\n time_set = time_set[len(time_set) - 1:]\n check = False\n time_set.append(time_set[-1] + time_wait)\n if len(time_set) == list_num and not check:\n break\n if len(time_set) == list_num and not check:\n break\n context['loadTime'] = list(map(lambda x: {\"long\": x.strftime(\"%Y-%m-%d %H:%M:%S\"), \"short\": x.strftime(\"%H:%M\")}, time_set))\n print(context['loadTime'])\n\n return render(request, 'trip.html', context=context)\n \n return redirect('/bts/')\n\ndef build_dict(seq, key):\n return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))\n\ndef getStationByKeyword(request):\n # if request.is_ajax():\n if request.method == 'GET' and 'kw' in request.GET:\n kw = request.GET['kw'].lower()\n if kw:\n kw_query_name = Station.objects.filter(name__istartswith=kw).order_by('name')\n kw_query_id = Station.objects.filter(id__istartswith=kw)\n \n try:\n kw_query_numid = Station.objects.filter(id__icontains=kw)\n except TypeError:\n pass\n\n if kw_query_name.count() or kw_query_id.count() or kw_query_numid.count():\n data = []\n for station in kw_query_numid:\n data.append([station.id, station.name])\n for station in kw_query_id:\n if [station.id, station.name] not in data:\n data.append([station.id, station.name])\n for station in kw_query_name:\n if [station.id, station.name] not in data:\n data.append([station.id, station.name])\n return JsonResponse({\"data\": data})\n else:\n return JsonResponse({\"data\": []})\n else:\n kw_query_name = Station.objects.all().order_by('name')\n data = []\n for station in kw_query_name:\n data.append([station.id, station.name])\n return JsonResponse({\"data\": data})\n else:\n return JsonResponse({\"data\": []})\n # else:\n # return JsonResponse({})\n\n # return JsonResponse({\"status\": \"success\"})\n\ndef getStationsInfo(station_from_id, station_to_id):\n stationFrom = Station.objects.filter(id__exact=station_from_id)\n stationTo = Station.objects.filter(id__exact=station_to_id)\n route_sub_from_id = station_from_id[0]\n route_sub_to_id = station_to_id[0]\n \n if stationFrom.count() > 0 and stationTo.count() > 0:\n if route_sub_from_id == route_sub_to_id:\n station_from_num = int(station_from_id[1:])\n station_to_num = int(station_to_id[1:])\n if station_from_num > station_to_num:\n routeStation = [f\"{route_sub_from_id}{i}\" for i in range(station_from_num, station_to_num - 1, -1)]\n else:\n routeStation = [f\"{route_sub_from_id}{i}\" for i in range(station_from_num, station_to_num + 1)]\n else:\n if station_from_id != \"CEN\" and station_to_id != \"CEN\":\n station_from_num = int(station_from_id[1:])\n station_to_num = int(station_to_id[1:])\n routeStation = [f\"{route_sub_from_id}{i}\" for i in range(station_from_num, 0, -1)]\n routeStation += [\"CEN\"]\n routeStation += [f\"{route_sub_to_id}{i}\" for i in range(1, station_to_num + 1)]\n elif station_from_id == 'CEN':\n station_to_num = int(station_to_id[1:])\n routeStation = [\"CEN\"]\n routeStation += [f\"{route_sub_to_id}{i}\" for i in range(1, station_to_num + 1)]\n elif station_to_id == 'CEN':\n station_from_num = int(station_from_id[1:])\n routeStation = [f\"{route_sub_from_id}{i}\" for i in range(station_from_num, 0, -1)]\n routeStation += [\"CEN\"]\n\n data = {}\n data['status'] = 'success'\n data['station'] = []\n data['interchange'] = []\n mainStation = len(routeStation) - 1\n containExtension = False\n newRoute = True\n\n for n, res in enumerate(routeStation):\n for e in Station.objects.filter(id__exact=res):\n if e.isExtension:\n containExtension = True\n mainStation -= 1\n \n if n > 0 and newRoute and e.route_id_id != 'SSK' and e.route_inter_id != 'SSK':\n newRoute = False\n \n temp = {\n 'route_id': e.route_id.id,\n 'id': e.id,\n 'name': e.name,\n 'lat': e.lat,\n 'long': e.long\n }\n\n temp['route_inter'] = e.route_inter_id\n \n if 0 < n < len(routeStation) - 1:\n prevStation = findStaion(routeStation, n - 1, -1).get()\n nextStation = findStaion(routeStation, n + 1, 1).get()\n\n if (e.route_id == prevStation.route_id and e.route_inter == nextStation.route_id) \\\n or (e.route_inter == prevStation.route_id and e.route_id == nextStation.route_id):\n data['interchange'].append(e.id)\n\n data['station'].append(temp)\n\n if n > 0:\n prevStation = Station\n\n data['price'] = {\n i.category: ticketPrice(mainStation, containExtension, i.category, newRoute) for i in Card.objects.all()\n }\n\n return data\n return {}\n\ndef findStaion(stationsList, position, direction):\n \"\"\"\n stationsList: list\n\n position: int\n\n direction: int (1 or -1)\n \"\"\"\n\n res = Station.objects.filter(id__exact=stationsList[position])\n n = direction\n while not res.count():\n res = Station.objects.filter(id__exact=stationsList[position + n])\n n = n + 1 * direction\n return res\n\ndef getStationByLocation(request):\n if request.method == 'GET' and 'lat' in request.GET and 'long' in request.GET and 'radius' in request.GET:\n lat = request.GET['lat']\n long = request.GET['long']\n radius = request.GET['radius']\n\n if lat and long and radius:\n lat = float(lat)\n long = float(long)\n radius = int(radius)\n\n stations_query = Station.objects.all()\n \n latlon = list(filter(lambda x: x[\"distance\"] <= radius, [{\"id\": e.id, \"name\": e.name, \"distance\": latlong2distance(lat, long, float(e.lat), float(e.long))} for e in stations_query]))\n\n if latlon:\n nearest_station = sorted(latlon, key=lambda x: x[\"distance\"])[:1]\n return JsonResponse({\"status\": \"success\", \"data\": nearest_station})\n else:\n return JsonResponse({\"status\": \"success\", \"data\": []})\n else:\n return JsonResponse({\"status\": \"error\", \"msg\": \"Invalid request values.\"})\n return JsonResponse({\"status\": \"error\", \"msg\": \"error\"})\n\ndef latlong2distance(lat1, long1, lat2, long2):\n \"\"\"\n Find the distance between 2 locations by using Haversine formula\n \n return distance in meter unit\n \"\"\"\n\n earth_radius = 6378.137 # kilometers\n\n # convert lats and longs to radians\n phi1 = lat1 * math.pi / 180\n phi2 = lat2 * math.pi / 180\n lambda1 = long1 * math.pi / 180\n lambda2 = long2 * math.pi / 180\n\n dphi = phi2 - phi1\n dlambda = lambda2 - lambda1\n\n hav = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2\n central_angel = 2 * math.atan2(math.sqrt(hav), math.sqrt(1 - hav))\n distance = earth_radius * central_angel\n \n return distance * 1000 # meters\n\ndef getStationBetween(request):\n if request.method == 'GET' and 'stationFromId' in request.GET and 'stationToId' in request.GET:\n station_from_id = request.GET['stationFromId']\n station_to_id = request.GET['stationToId']\n\n if station_from_id and station_from_id:\n stationFrom = Station.objects.filter(id__exact=station_from_id)\n stationTo = Station.objects.filter(id__exact=station_to_id)\n route_sub_from_id = station_from_id[0]\n route_sub_to_id = station_to_id[0]\n \n if stationFrom.count() > 0 and stationTo.count() > 0:\n return JsonResponse({\n \"status\": \"success\"\n })\n \n return JsonResponse({\n \"status\": \"error\",\n \"routeSubFromId\": route_sub_from_id,\n \"routeSubToId\": route_sub_to_id\n })\n \n return JsonResponse({})\n\ndef ticketPriceInit(cardType, containExt):\n res = 0\n if cardType == 1:\n res = 16\n if containExt:\n res += 15\n elif cardType == 2:\n res = 15\n if containExt:\n res += 15\n elif cardType == 3:\n res = 15\n if containExt:\n res += 10\n else:\n res = 8\n if containExt:\n res += 7\n return res\n\ndef ticketPrice(numberOfStation, containExtension=False, cardType=1, newRoute=False):\n res = 0\n if numberOfStation > 0:\n res = ticketPriceInit(cardType, containExtension)\n for i in range(1, numberOfStation):\n if cardType != 4:\n if i == 1:\n res += 7\n elif i < 8:\n if i % 2 == 0:\n res += 3\n else:\n res += 4\n else:\n break\n else:\n if i == 1:\n res += 4\n elif i == 2 or i == 6:\n res += 1\n elif 2 < i < 6 or i == 7:\n res += 2\n else:\n break\n return res\n elif newRoute:\n return 0\n elif containExtension:\n if cardType == 1 or cardType == 2:\n res = 15\n elif cardType == 3:\n res = 10\n else:\n res = 7\n return res\n else:\n return None\n","sub_path":"bts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"172940330","text":"#! /usr/bin/env python3\n\n\"\"\"This script captures F1 2019 telemetry packets (sent over UDP) and stores them into SQLite3 database files.\n\nOne database file will contain all packets from one session.\n\nFrom UDP packet to database entry\n---------------------------------\n\nThe data flow of UDP packets into the database is managed by 2 threads.\n\nPacketReceiver thread:\n\n (1) The PacketReceiver thread does a select() to wait on incoming packets in the UDP socket.\n (2) When woken up with the notification that a UDP packet is available for reading, it is actually read from the socket.\n (3) The receiver thread calls the recorder_thread.record_packet() method with a TimedPacket containing\n the reception timestamp and the packet just read.\n (4) The recorder_thread.record_packet() method locks its packet queue, inserts the packet there,\n then unlocks the queue. Note that this method is only called from within the receiver thread!\n (5) repeat from (1).\n\nPacketRecorder thread:\n\n (1) The PacketRecorder thread sleeps for a given period, then wakes up.\n (2) It locks its packet queue, moves the queue's packets to a local variable, empties the packet queue,\n then unlocks the packet queue.\n (3) The packets just moved out of the queue are passed to the 'process_incoming_packets' method.\n (4) The 'process_incoming_packets' method inspects the packet headers, and converts the packet data\n into SessionPacket instances that are suitable for inserting into the database.\n In the process, it collects packets from the same session. After collecting all\n available packets from the same session, it passed them on to the\n 'process_incoming_same_session_packets' method.\n (5) The 'process_incoming_same_session_packets' method makes sure that the appropriate SQLite database file\n is opened (i.e., the one with matching sessionUID), then writes the packets into the 'packets' table.\n\nBy decoupling the packet capture and database writing in different threads, we minimize the risk of\ndropping UDP packets. This risk is real because SQLite3 database commits can take a considerable time.\n\"\"\"\n\nimport argparse\nimport sys\nimport time\nimport socket\nimport sqlite3\nimport threading\nimport logging\nimport ctypes\nimport selectors\n\nfrom collections import namedtuple\n\nfrom .threading_utils import WaitConsoleThread, Barrier\nfrom ..packets import PacketHeader, PacketID, HeaderFieldsToPacketType, unpack_udp_packet\n\n# The type used by the PacketReceiverThread to represent incoming telemetry packets, with timestamp.\nTimestampedPacket = namedtuple('TimestampedPacket', 'timestamp, packet')\n\n# The type used by the PacketRecorderThread to represent incoming telemetry packets for storage in the SQLite3 database.\nSessionPacket = namedtuple('SessionPacket', 'timestamp, packetFormat, gameMajorVersion, gameMinorVersion, packetVersion, packetId, sessionUID, sessionTime, frameIdentifier, playerCarIndex, packet')\n\n\nclass PacketRecorder:\n \"\"\"The PacketRecorder records incoming packets to SQLite3 database files.\n\n A single SQLite3 file stores packets from a single session.\n Whenever a new session starts, any open file is closed, and a new database file is created.\n \"\"\"\n\n # The SQLite3 query that creates the 'packets' table in the database file.\n _create_packets_table_query = \"\"\"\n CREATE TABLE packets (\n pkt_id INTEGER PRIMARY KEY, -- Alias for SQLite3's 'rowid'.\n timestamp REAL NOT NULL, -- The POSIX time right after capturing the telemetry packet.\n packetFormat INTEGER NOT NULL, -- Header field: packet format.\n gameMajorVersion INTEGER NOT NULL, -- Header field: game major version.\n gameMinorVersion INTEGER NOT NULL, -- Header field: game minor version.\n packetVersion INTEGER NOT NULL, -- Header field: packet version.\n packetId INTEGER NOT NULL, -- Header field: packet type ('packetId' is a bit of a misnomer).\n sessionUID CHAR(16) NOT NULL, -- Header field: unique session id as hex string.\n sessionTime REAL NOT NULL, -- Header field: session time.\n frameIdentifier INTEGER NOT NULL, -- Header field: frame identifier.\n playerCarIndex INTEGER NOT NULL, -- Header field: player car index.\n packet BLOB NOT NULL -- The packet itself\n );\n \"\"\"\n\n # The SQLite3 query that inserts packet data into the 'packets' table of an open database file.\n _insert_packets_query = \"\"\"\n INSERT INTO packets(\n timestamp,\n packetFormat, gameMajorVersion, gameMinorVersion, packetVersion, packetId, sessionUID,\n sessionTime, frameIdentifier, playerCarIndex,\n packet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\n \"\"\"\n\n def __init__(self):\n self._conn = None\n self._cursor = None\n self._filename = None\n self._sessionUID = None\n\n def close(self):\n \"\"\"Make sure that no database remains open.\"\"\"\n if self._conn is not None:\n self._close_database()\n\n def _open_database(self, sessionUID: str):\n \"\"\"Open SQLite3 database file and make sure it has the correct schema.\"\"\"\n assert self._conn is None\n filename = \"F1_2019_{:s}.sqlite3\".format(sessionUID)\n logging.info(\"Opening file {!r}.\".format(filename))\n conn = sqlite3.connect(filename)\n cursor = conn.cursor()\n\n # Get rid of indentation and superfluous newlines in the 'CREATE TABLE' command.\n query = \"\".join(line[8:] + \"\\n\" for line in PacketRecorder._create_packets_table_query.split(\"\\n\")[1:-1])\n\n # Try to execute the 'CREATE TABLE' statement. If it already exists, this will raise an exception.\n try:\n cursor.execute(query)\n except sqlite3.OperationalError:\n logging.info(\" (Appending to existing file.)\")\n else:\n logging.info(\" (Created new file.)\")\n\n self._conn = conn\n self._cursor = cursor\n self._filename = filename\n self._sessionUID = sessionUID\n\n def _close_database(self):\n \"\"\"Close SQLite3 database file.\"\"\"\n assert self._conn is not None\n logging.info(\"Closing file {!r}.\".format(self._filename))\n self._cursor.close()\n self._cursor = None\n self._conn.close()\n self._conn = None\n self._filename = None\n self._sessionUID = None\n\n def _insert_and_commit_same_session_packets(self, same_session_packets):\n \"\"\"Insert session packets to database and commit.\"\"\"\n assert self._conn is not None\n self._cursor.executemany(PacketRecorder._insert_packets_query, same_session_packets)\n self._conn.commit()\n\n def _process_same_session_packets(self, same_session_packets):\n \"\"\"Insert packets from the same session into the 'packets' table of the appropriate database file.\n\n Precondition: all packets in 'same_session_packets' are from the same session (identical 'sessionUID' field).\n\n We need to handle four different cases:\n\n (1) 'same_session_packets' is empty:\n\n --> return (no-op).\n\n (2) A database file is currently open, but it stores packets with a different session UID:\n\n --> Close database;\n --> Open database with correct session UID;\n --> Insert 'same_session_packets'.\n\n (3) No database file is currently open:\n\n --> Open database with correct session UID;\n --> Insert 'same_session_packets'.\n\n (4) A database is currently open, with correct session UID:\n\n --> Insert 'same_session_packets'.\n \"\"\"\n\n if not same_session_packets:\n # Nothing to insert.\n return\n\n if self._conn is not None and self._sessionUID != same_session_packets[0].sessionUID:\n # Close database if it's recording a different session.\n self._close_database()\n\n if self._conn is None:\n # Open database with the correct sessionID.\n self._open_database(same_session_packets[0].sessionUID)\n\n # Write packets.\n self._insert_and_commit_same_session_packets(same_session_packets)\n\n def process_incoming_packets(self, timestamped_packets):\n \"\"\"Process incoming packets by recording them into the correct database file.\n\n The incoming 'timestamped_packets' is a list of timestamped raw UDP packets.\n\n We process them to a variable 'same_session_packets', which is a list of consecutive\n packets having the same 'sessionUID' field. In this list, each packet is a 11-element tuple\n that can be inserted into the 'packets' table of the database.\n\n The 'same_session_packets' are then passed on to the '_process_same_session_packets'\n method that writes them into the appropriate database file.\n \"\"\"\n\n t1 = time.monotonic()\n\n # Invariant to be guaranteed: all packets in 'same_session_packets' have the same 'sessionUID' field.\n same_session_packets = []\n\n for (timestamp, packet) in timestamped_packets:\n\n if len(packet) < ctypes.sizeof(PacketHeader):\n logging.error(\"Dropped bad packet of size {} (too short).\".format(len(packet)))\n continue\n\n header = PacketHeader.from_buffer_copy(packet)\n\n packet_type_tuple = (header.packetFormat, header.packetVersion, header.packetId)\n\n packet_type = HeaderFieldsToPacketType.get(packet_type_tuple)\n if packet_type is None:\n logging.error(\"Dropped unrecognized packet (format, version, id) = {!r}.\".format(packet_type_tuple))\n continue\n\n if len(packet) != ctypes.sizeof(packet_type):\n logging.error(\"Dropped packet with unexpected size; \"\n \"(format, version, id) = {!r} packet, size = {}, expected {}.\".format(\n packet_type_tuple, len(packet), ctypes.sizeof(packet_type)))\n continue\n\n if header.packetId == PacketID.EVENT: # Log Event packets\n event_packet = unpack_udp_packet(packet)\n logging.info(\"Recording event packet: {}\".format(event_packet.eventStringCode.decode()))\n\n # NOTE: the sessionUID is not reliable at the start of a session (in F1 2018, need to check for F1 2019).\n # See: http://forums.codemasters.com/discussion/138130/bug-f1-2018-pc-v1-0-4-udp-telemetry-bad-session-uid-in-first-few-packets-of-a-session\n\n # Create an INSERT-able tuple for the data in this packet.\n #\n # Note that we convert the sessionUID to a 16-digit hex string here.\n # SQLite3 can store 64-bit numbers, but only signed ones.\n # To prevent any issues, we represent the sessionUID as a 16-digit hex string instead.\n\n session_packet = SessionPacket(\n timestamp,\n header.packetFormat, header.gameMajorVersion, header.gameMinorVersion,\n header.packetVersion, header.packetId, \"{:016x}\".format(header.sessionUID),\n header.sessionTime, header.frameIdentifier, header.playerCarIndex,\n packet\n )\n\n if len(same_session_packets) > 0 and same_session_packets[0].sessionUID != session_packet.sessionUID:\n # Write 'same_session_packets' collected so far to the correct session database, then forget about them.\n self._process_same_session_packets(same_session_packets)\n same_session_packets.clear()\n\n same_session_packets.append(session_packet)\n\n # Write 'same_session_packets' to the correct session database, then forget about them.\n # The 'same_session_packets.clear()' is not strictly necessary here, because 'same_session_packets' is about to\n # go out of scope; but we make it explicit for clarity.\n\n self._process_same_session_packets(same_session_packets)\n same_session_packets.clear()\n\n t2 = time.monotonic()\n\n duration = (t2 - t1)\n\n logging.info(\"Recorded {} packets in {:.3f} ms.\".format(len(timestamped_packets), duration * 1000.0))\n\n def no_packets_received(self, age: float) -> None:\n \"\"\"No packets were received for a considerable time. If a database file is open, close it.\"\"\"\n if self._conn is None:\n logging.info(\"No packets to record for {:.3f} seconds.\".format(age))\n else:\n logging.info(\"No packets to record for {:.3f} seconds; closing file due to inactivity.\".format(age))\n self._close_database()\n\n\nclass PacketRecorderThread(threading.Thread):\n \"\"\"The PacketRecorderThread writes telemetry data to SQLite3 files.\"\"\"\n\n def __init__(self, record_interval):\n super().__init__(name='recorder')\n self._record_interval = record_interval\n self._packets = []\n self._packets_lock = threading.Lock()\n self._socketpair = socket.socketpair()\n\n def close(self):\n for sock in self._socketpair:\n sock.close()\n\n def run(self):\n \"\"\"Receive incoming packets and hand them over the the PacketRecorder.\n\n This method runs in its own thread.\n \"\"\"\n\n selector = selectors.DefaultSelector()\n key_socketpair = selector.register(self._socketpair[0], selectors.EVENT_READ)\n\n recorder = PacketRecorder()\n\n packets = []\n\n logging.info(\"Recorder thread started.\")\n\n quitflag = False\n inactivity_timer = time.time()\n while not quitflag:\n\n # Calculate the timeout value that will bring us in sync with the next period.\n timeout = (-time.time()) % self._record_interval\n # If the timeout interval is too short, increase its length by 1 period.\n if timeout < 0.5 * self._record_interval:\n timeout += self._record_interval\n\n for (key, events) in selector.select(timeout):\n if key == key_socketpair:\n quitflag = True\n\n # Swap packets, so the 'record_packet' method can be called uninhibited as soon as possible.\n with self._packets_lock:\n (packets, self._packets) = (self._packets, packets)\n\n if len(packets) != 0:\n inactivity_timer = packets[-1].timestamp\n recorder.process_incoming_packets(packets)\n packets.clear()\n else:\n t_now = time.time()\n age = t_now - inactivity_timer\n recorder.no_packets_received(age)\n inactivity_timer = t_now\n\n recorder.close()\n\n selector.close()\n\n logging.info(\"Recorder thread stopped.\")\n\n def request_quit(self):\n \"\"\"Request termination of the PacketRecorderThread.\n\n Called from the main thread to request that we quit.\n \"\"\"\n self._socketpair[1].send(b'\\x00')\n\n def record_packet(self, timestamped_packet):\n \"\"\"Called from the receiver thread for every UDP packet received.\"\"\"\n with self._packets_lock:\n self._packets.append(timestamped_packet)\n\n\nclass PacketReceiverThread(threading.Thread):\n \"\"\"The PacketReceiverThread receives incoming telemetry packets via the network and passes them to the PacketRecorderThread for storage.\"\"\"\n\n def __init__(self, udp_port, recorder_thread):\n super().__init__(name='receiver')\n self._udp_port = udp_port\n self._recorder_thread = recorder_thread\n self._socketpair = socket.socketpair()\n\n def close(self):\n for sock in self._socketpair:\n sock.close()\n\n def run(self):\n \"\"\"Receive incoming packets and hand them over to the PacketRecorderThread.\n\n This method runs in its own thread.\n \"\"\"\n\n udp_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n\n # Allow multiple receiving endpoints.\n if sys.platform in ['darwin']:\n udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n elif sys.platform in ['linux', 'win32']:\n udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # Accept UDP packets from any host.\n address = ('', self._udp_port)\n udp_socket.bind(address)\n\n selector = selectors.DefaultSelector()\n\n key_udp_socket = selector.register(udp_socket, selectors.EVENT_READ)\n key_socketpair = selector.register(self._socketpair[0], selectors.EVENT_READ)\n\n logging.info(\"Receiver thread started, reading UDP packets from port {}.\".format(self._udp_port))\n\n quitflag = False\n while not quitflag:\n for (key, events) in selector.select():\n timestamp = time.time()\n if key == key_udp_socket:\n # All telemetry UDP packets fit in 2048 bytes with room to spare.\n packet = udp_socket.recv(2048)\n timestamped_packet = TimestampedPacket(timestamp, packet)\n self._recorder_thread.record_packet(timestamped_packet)\n elif key == key_socketpair:\n quitflag = True\n\n selector.close()\n udp_socket.close()\n for sock in self._socketpair:\n sock.close()\n\n logging.info(\"Receiver thread stopped.\")\n\n def request_quit(self):\n \"\"\"Request termination of the PacketReceiverThread.\n\n Called from the main thread to request that we quit.\n \"\"\"\n self._socketpair[1].send(b'\\x00')\n\n\ndef main():\n \"\"\"Record incoming telemetry data until the user presses enter.\"\"\"\n\n # Configure logging.\n\n logging.basicConfig(level=logging.DEBUG, format=\"%(asctime)-23s | %(threadName)-10s | %(levelname)-5s | %(message)s\")\n logging.Formatter.default_msec_format = '%s.%03d'\n\n # Parse command line arguments.\n\n parser = argparse.ArgumentParser(description=\"Record F1 2019 telemetry data to SQLite3 files.\")\n\n parser.add_argument(\"-p\", \"--port\", default=20777, type=int, help=\"UDP port to listen to (default: 20777)\", dest='port')\n parser.add_argument(\"-i\", \"--interval\", default=1.0, type=float, help=\"interval for writing incoming data to SQLite3 file, in seconds (default: 1.0)\", dest='interval')\n\n args = parser.parse_args()\n\n # Start recorder thread first, then receiver thread.\n\n quit_barrier = Barrier()\n\n recorder_thread = PacketRecorderThread(args.interval)\n recorder_thread.start()\n\n receiver_thread = PacketReceiverThread(args.port, recorder_thread)\n receiver_thread.start()\n\n wait_console_thread = WaitConsoleThread(quit_barrier)\n wait_console_thread.start()\n\n # Recorder, receiver, and wait_console threads are now active. Run until we're asked to quit.\n\n quit_barrier.wait()\n\n # Stop threads.\n\n wait_console_thread.request_quit()\n wait_console_thread.join()\n wait_console_thread.close()\n\n receiver_thread.request_quit()\n receiver_thread.join()\n receiver_thread.close()\n\n recorder_thread.request_quit()\n recorder_thread.join()\n recorder_thread.close()\n\n # All done.\n\n logging.info(\"All done.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"f1_2019_telemetry/cli/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":19366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"91307745","text":"# gradient descent gif\nimport numpy as np\nfrom matplotlib.animation import FuncAnimation\nfrom IPython import display\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmpl.rcParams['animation.html'] = 'jshtml'\nFigure = plt.figure(figsize=(12, 4))\nax = Figure.add_subplot(111)\n\nax.plot(X1, ysd, 'bx')\n\n# gd\ndef animfunc(k):\n ax.clear()\n ax.set_ylim(-3, 3)\n ax.set_xlabel(r\"$x$\")\n ax.set_ylabel(r\"$y$\")\n ax.plot(X1, ysd, 'bx')\n # lobf\n xl = np.linspace(-2, 2, 5)\n ax.plot(xl, gd_bias[k] + gd_theta[k] * xl, color='k')\n\nanim_create = FuncAnimation(Figure, animfunc, frames=30, interval=100)\nvideo = anim_create.to_html5_video()\nhtml = display.HTML(video)\ndisplay.display(html)\n\nanim_create.save(\"gd.gif\")\n\nplt.close()","sub_path":"05-Learning/scripts/gd.py","file_name":"gd.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"80142490","text":"from django.conf.urls import patterns, include, url\nfrom projects.views import *\nfrom django.contrib import admin\nimport os\n\n\nsite_media = os.path.abspath(os.path.join(os.path.dirname(__file__),\"../site_media\"))\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Site nav\n url(r'^today/$', today),\n url(r'^$', today),\n url(r'^main_page/', today),\n url(r'^login/', 'django.contrib.auth.views.login'),\n url(r'^alltasks', alltasks),\n url(r'^allprojects', allprojects),\n\n #ajax urls for use in some wizardy\n url(r'^tasks/(\\d+)/complete/$', mark_complete),\n url(r'^tasks/(\\d+)/incomplete/$', mark_complete),\n url(r'^quickadd/(.*)$', quick_add_task),\n\n #task management URLs\n url(r'^tasks/(\\d+)/$', task_edit),\n url(r'^tasks/edit/(\\d+)/$', task_edit),\n url(r'^tasks/add/$', task_add),\n url(r'^tasks/delete/(\\d+)/$', task_delete),\n url(r'^tasks/complete/(\\d+)/$', task_complete),\n\n #project management URLS\n url(r'^projects/(\\d+)/$', project),\n url(r'^projects/edit/(\\d+)/$', project_edit),\n url(r'^projects/add/$', project_add),\n url(r'^projects/delete/(\\d+)/$', project_delete),\n url(r'^projects/add_task/(\\d+)$', project_add_task),\n\n #user logging and management\n url(r'^accounts/login/', 'django.contrib.auth.views.login'), \n url(r'^accounts/logout/', logout_page),\n\n #some random management stuff\n #Admin stuff\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n\n # Site Media\n (r'^site_media/(?P.*)$', 'django.views.static.serve',\n {'document_root': site_media}),\n)\n","sub_path":"brnstm/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"427731671","text":"import json\nimport urllib.request, urllib.parse, urllib.error\nimport ssl\n\nctx=ssl.create_default_context()\nctx.check_hostname=False\nctx.verife_mode=ssl.CERT_NONE\n\nurl=input('Enter location:')\nprint(\"Retrieving:\",url)\nuh=urllib.request.urlopen(url,context=ctx)\n\ndata=uh.read()\ninfo = json.loads(data)\nprint('Retrieved',len(data),'characters')\n\n\nctr=0\nsum=0\nfor item in info['comments']:\n\n\n sum+=int(item['count'])\n\nprint('Count:', len(info['comments']))\n\nprint('Sum',sum)\n","sub_path":"HelloPython12.py","file_name":"HelloPython12.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57562383","text":"#!/usr/bin/env python36\n\n# TITLE : 2b-auto.py\n# DESCRIPTION : PLus ou moins automatique\n# DATE : 06/11/18\n# NAME : Blanchet Noémie\n\nimport signal\nimport random\nimport re\nimport time\n\n#Fonction pour quitter le programme\ndef quitter(sig, frame):\n print('\\nC\\'est propre moyen c\\'que tu fais')\n exit()\n\n\nsignal.signal(signal.SIGINT, quitter)\n\n\n#Fonction fin\n\n\ndef bisousbisous():\n print(\"j'ai trouver \"+str(rep)+\" en \"+str(count))\n\n\n\n#Fonction pour lire dans le fichier\ndef lectureFichier():\n file = open(\"plusoumoins.txt\", \"r\")\n msg = file.read()\n file.close()\n return msg\n\n\n#Fonction pour éditer un fichier\n\ndef editFichier(msg):\n file = open(\"plusoumoins.txt\", \"w\")\n file.write(msg)\n file.close()\n\n\nsolution = random.randint(0, 100)\nend = False\ncount = 0\nborneSup = 100\nborneInf = 0\nrep = 0\n\n\n#boucle principale plus ou moins\n\nwhile end is False:\n\n print(\"au dessus : \" + str(borneSup) + \" en dessous : \" + str(borneInf))\n\n rep = round((borneSup + borneInf) / 2)\n editFichier(str(rep))\n count += 1\n print(rep)\n time.sleep(2)\n data = lectureFichier()\n print(\"data : \" + data)\n\n if data == 'Bien ouèj, on rigole on rigole mais on vois pas le fond du bol':\n end = True\n print(\"gg\")\n\n elif data == 'C\\'est trop grand':\n borneSup = rep\n print(\"trop grand\")\n\n elif data == 'C\\'est trop petit':\n borneInf = rep\n print(\"trop petit\")\n\nbisousbisous()\n\n","sub_path":"scripts/2b-auto.py","file_name":"2b-auto.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"6465622","text":"# -*- encoding: utf-8 -*-\nfrom smac.tae.execute_ta_run import StatusType\n\nfrom autosklearn.evaluation.abstract_evaluator import AbstractEvaluator\nfrom autosklearn.evaluation.util import calculate_score\n\n\n__all__ = [\n 'eval_t',\n 'TestEvaluator'\n]\n\n\nclass TestEvaluator(AbstractEvaluator):\n\n def __init__(self, Datamanager, backend,\n configuration=None,\n with_predictions=False,\n all_scoring_functions=False,\n seed=1):\n super(TestEvaluator, self).__init__(\n Datamanager, backend, configuration,\n with_predictions=with_predictions,\n all_scoring_functions=all_scoring_functions,\n seed=seed,\n output_y_test=False,\n num_run='dummy',\n subsample=None)\n self.configuration = configuration\n\n self.X_train = Datamanager.data['X_train']\n self.Y_train = Datamanager.data['Y_train']\n\n self.X_test = Datamanager.data.get('X_test')\n self.Y_test = Datamanager.data.get('Y_test')\n\n def fit_predict_and_loss(self):\n self._fit_and_suppress_warnings(self.model, self.X_train, self.Y_train)\n return self.predict_and_loss()\n\n def predict_and_loss(self, train=False):\n\n if train:\n Y_pred = self.predict_function(self.X_train, self.model,\n self.task_type, self.Y_train)\n score = calculate_score(\n solution=self.Y_train,\n prediction=Y_pred,\n task_type=self.task_type,\n metric=self.metric,\n num_classes=self.D.info['label_num'],\n all_scoring_functions=self.all_scoring_functions)\n else:\n Y_pred = self.predict_function(self.X_test, self.model,\n self.task_type, self.Y_train)\n score = calculate_score(\n solution=self.Y_test,\n prediction=Y_pred,\n task_type=self.task_type,\n metric=self.metric,\n num_classes=self.D.info['label_num'],\n all_scoring_functions=self.all_scoring_functions)\n\n if hasattr(score, '__len__'):\n err = {key: 1 - score[key] for key in score}\n else:\n err = 1 - score\n\n return err, Y_pred, Y_pred, Y_pred\n\n\n# create closure for evaluating an algorithm\n# Has a stupid name so nosetests doesn't regard it as a test\ndef eval_t(queue, config, data, backend, seed, num_run, subsample,\n with_predictions, all_scoring_functions,\n output_y_test):\n evaluator = TestEvaluator(Datamanager=data, configuration=config,\n backend=backend, seed=seed,\n with_predictions=with_predictions,\n all_scoring_functions=all_scoring_functions)\n\n loss, opt_pred, valid_pred, test_pred = evaluator.fit_predict_and_loss()\n duration, result, seed, run_info = evaluator.finish_up(\n loss, opt_pred, valid_pred, test_pred, file_output=False)\n\n status = StatusType.SUCCESS\n queue.put((duration, result, seed, run_info, status))\n\n\n","sub_path":"autosklearn/evaluation/test_evaluator.py","file_name":"test_evaluator.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"61997546","text":"from __future__ import print_function, division\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport h5py\nimport csv\nimport numpy as np\nfrom numpy import array \nimport TLorentzVector\nimport uproot_methods.convert\nimport math\n\ndef TLV(x, y, z):\n\treturn uproot_methods.TLorentzVectorArray.from_ptetaphim(x,y,z,0.1057)\n\n# Para dar aos argumentos das funções, precisa ser o TLorentzVector\n\ndef Acoplanaridade(x,y):\n\treturn pd.DataFrame(1 - abs(x.delta_phi(y))/math.pi, columns = ['acoplanaridade'])\n\t\n\ndef MassaInvariante(x,y):\n\treturn pd.DataFrame((x + y).mass, columns = ['inv_mass'])\t\n\ndef DeltaEta(x,y):\n\treturn pd.DataFrame((x.rapidity - y.rapidity), columns=['delta_eta'])\n\ndef Pt(x,y):\n\treturn pd.DataFrame((x+y).pt, columns = ['Pt'])\t\t\n\n\n\nDF_ptetphi1 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ptetaphi_E1.csv'))),0,1), columns = ['pt1','pt2','eta1','eta2','phi1','phi2'])\nDF_ptetphi2 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ptetaphi_E2.csv'))),0,1), columns = ['pt1','pt2','eta1','eta2','phi1','phi2'])\nDF_ptetphi3 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ptetaphi_E3.csv'))),0,1), columns = ['pt1','pt2','eta1','eta2','phi1','phi2'])\nDF_ptetphi = pd.concat([DF_ptetphi1,DF_ptetphi2,DF_ptetphi3],axis=0)\n\n# Vertice Primário\n\nDataFrame_VertiPrima1 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_VertPrimaE1.csv'))),0,1), columns = ['VerticePrimario'])\nDataFrame_VertiPrima2 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_VertPrimaE2.csv'))),0,1), columns = ['VerticePrimario'])\nDataFrame_VertiPrima3 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_VertPrimaE3.csv'))),0,1), columns = ['VerticePrimario'])\nDataFrame_VertiPrima = pd.concat([DataFrame_VertiPrima1,DataFrame_VertiPrima2,DataFrame_VertiPrima3],axis=0)\n\n# modulo\n\nDataFrame_modulo1 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_moduloE1.csv'))),0,1), columns = ['almir1', 'almir2'])\nDataFrame_modulo2 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_moduloE2.csv'))),0,1), columns = ['almir1', 'almir2'])\nDataFrame_modulo3 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_moduloE3.csv'))),0,1), columns = ['almir1', 'almir2'])\nDataFrame_modulo = pd.concat([DataFrame_modulo1,DataFrame_modulo2,DataFrame_modulo3],axis=0)\n\n# carga\n\nDataFrame_carga1 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_chargeE1.csv'))),0,1), columns = ['carga1', 'carga2'])\nDataFrame_carga2 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_chargeE2.csv'))),0,1), columns = ['carga1', 'carga2'])\nDataFrame_carga3 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_chargeE3.csv'))),0,1), columns = ['carga1', 'carga2'])\nDataFrame_carga = pd.concat([DataFrame_carga1,DataFrame_carga2,DataFrame_carga3],axis=0)\n\n# istigh\n\nDataFrame_instight1 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_istightE1.csv'))),0,1), columns = ['instight1', 'instight2'])\nDataFrame_instight2 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_istightE2.csv'))),0,1), columns = ['instight1', 'instight2'])\nDataFrame_instight3 = pd.DataFrame(np.delete((np.array(pd.read_csv('Dados_istightE3.csv'))),0,1), columns = ['instight1', 'instight2'])\nDataFrame_instight = pd.concat([DataFrame_instight1,DataFrame_instight2,DataFrame_instight3],axis=0)\n\n# Extra Tracks\n\nDataFrame_extratracks1 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ExtraTracksE1.csv'))),0,1), columns = ['ExtraTracks'])\nDataFrame_extratracks2 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ExtraTracksE2.csv'))),0,1), columns = ['ExtraTracks'])\nDataFrame_extratracks3 = pd.DataFrame(np.delete((np.array(pd.read_csv('DF_ExtraTracksE3.csv'))),0,1), columns = ['ExtraTracks'])\nDataFrame_extratracks = pd.concat([DataFrame_extratracks1,DataFrame_extratracks2,DataFrame_extratracks3],axis=0)\n#####################################################################################\n\ndataset = pd.concat([DF_ptetphi, DataFrame_carga, DataFrame_VertiPrima, DataFrame_modulo, DataFrame_instight,DataFrame_extratracks], axis=1)\n\n# ínicio dos cortes\ndataset = dataset.dropna() # elimina os eventos que tenha pelo menos um elemento com NaN \ncorte_pt1 = dataset.loc[dataset['pt1'] > 50]\ncorte_pt2 = corte_pt1.loc[corte_pt1['pt2'] > 50]\ncorte_oppos_charged_muon = corte_pt2.loc[corte_pt2['carga1']*corte_pt2['carga2'] < 0] \ncorte_tight_muon_identification = corte_oppos_charged_muon.loc[corte_oppos_charged_muon['instight1']*corte_oppos_charged_muon['instight2']==1] \n\n# TLorentzVector já com os cortes\nTLV_0 = TLV(corte_tight_muon_identification['pt1'], corte_tight_muon_identification['eta1'], corte_tight_muon_identification['phi1'])\nTLV_1 = TLV(corte_tight_muon_identification['pt2'], corte_tight_muon_identification['eta2'], corte_tight_muon_identification['phi2'])\n\nDataFrame_Massa_inva = MassaInvariante(TLV_0,TLV_1)\nDataFrame_DeltaEta = DeltaEta(TLV_0,TLV_1)\nDF_PT = Pt(TLV_0,TLV_1)\nDataFrame_Acopla = Acoplanaridade(TLV_0,TLV_1)\nDataFrame_VerticePrima = abs(pd.DataFrame(np.array(corte_tight_muon_identification['VerticePrimario'])).rename(columns = {0:'vertice_prima'}))\nDataFrame_almir = pd.DataFrame(np.array(corte_tight_muon_identification.loc[:,'almir1':'almir2'])).rename(columns = {0:'almir1',1:'almir2'})\nDataFrame_extratracks = pd.DataFrame(np.array(corte_tight_muon_identification['ExtraTracks'])).rename(columns = {0:'ExtraTracks'})\n\namostra_doublemuon = pd.concat([DF_PT, DataFrame_Massa_inva, DataFrame_Acopla, DataFrame_DeltaEta, DataFrame_VerticePrima, DataFrame_almir,DataFrame_extratracks], axis = 1)\n\namostra_doublemuon.to_csv('amostra_doublemuon.csv')\n","sub_path":"DoubleMuon_cortes.py","file_name":"DoubleMuon_cortes.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"58020117","text":"\n\nfrom xai.brain.wordbase.nouns._yachtsman import _YACHTSMAN\n\n#calss header\nclass _YACHTSMEN(_YACHTSMAN, ):\n\tdef __init__(self,): \n\t\t_YACHTSMAN.__init__(self)\n\t\tself.name = \"YACHTSMEN\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"yachtsman\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_yachtsmen.py","file_name":"_yachtsmen.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373901089","text":"#############################################################################\n#\n# Copyright (c) 2009 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\nfrom zope.server.taskthreads import ThreadedTaskDispatcher\nimport gocept.selenium.base\nimport gocept.selenium.selenese\nimport asyncore\nimport threading\nimport zope.app.server.wsgi\nimport zope.app.testing.functional\nimport zope.app.wsgi\n\n\nclass Layer(gocept.selenium.base.Layer):\n\n def setUp(self):\n task_dispatcher = ThreadedTaskDispatcher()\n task_dispatcher.setThreadCount(1)\n db = zope.app.testing.functional.FunctionalTestSetup().db\n self.http = zope.app.server.wsgi.http.create(\n 'WSGI-HTTP', task_dispatcher, db, port=self.port)\n self.thread = threading.Thread(target=self.run_server)\n self.thread.setDaemon(True)\n self.thread.start()\n super(Layer, self).setUp()\n\n def tearDown(self):\n self.running = False\n self.thread.join()\n super(Layer, self).tearDown()\n\n def run_server(self):\n self.running = True\n while self.running:\n asyncore.poll(0.1)\n self.http.close()\n\n\nclass TestCase(gocept.selenium.base.TestCase,\n zope.app.testing.functional.FunctionalTestCase):\n # note: MRO requires the gocept.selenium.base.TestCase to come first,\n # otherwise setUp/tearDown happens in the wrong order\n\n def setUp(self):\n # switches the HTTP-server's database to the currently active\n # DemoStorage (which is set by FunctionalTestCase)\n super(TestCase, self).setUp()\n db = zope.app.testing.functional.FunctionalTestSetup().db\n application = self.layer.http.application\n assert isinstance(application, zope.app.wsgi.WSGIPublisherApplication)\n factory = type(application.requestFactory)\n application.requestFactory = factory(db)\n","sub_path":"gocept.selenium/tags/0.13/src/gocept/selenium/ztk/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"626038038","text":"from .common import * # NOQA\nimport pytest\n\nBAIDU_CCE_ACCESS_KEY = os.environ.get('RANCHER_BAIDU_CCE_ACCESS_KEY', \"\")\nBAIDU_CCE_SECRET_KEY = os.environ.get('RANCHER_BAIDU_CCE_SECRET_KEY', \"\")\nBAIDU_CCE_AMI = os.environ.get('RANCHER_BAIDU_CCE_AMI', \"\")\nBAIDU_CCE_REGION = os.environ.get('RANCHER_BAIDU_CCE_REGION', \"bj\")\nBAIDU_CCE_CONTAINER_CIDR = os.environ.get(\"RANCHER_BAIDU_CCE_CONTAINER_CIDR\",\"172.16.0.0/16\")\n\n\nbaiduccecredential = pytest.mark.skipif(not (BAIDU_CCE_ACCESS_KEY and BAIDU_CCE_SECRET_KEY),\n reason='BAIDU CCE Credentials not provided, '\n 'cannot create cluster')\n\n@baiduccecredential\ndef test_create_baidu_cce_cluster():\n\n client = get_admin_client()\n baidu_cceConfig = get_baidu_cce_config()\n\n print(\"Cluster creation\")\n cluster = client.create_cluster(baidu_cceConfig)\n print(cluster)\n cluster = validate_cluster(client, cluster, check_intermediate_state=True,\n skipIngresscheck=True)\n print(cluster)\n cluster_cleanup(client, cluster)\n\ndef get_baidu_cce_config():\n\n name = random_test_name(\"test-auto-baidu-cce\")\n baidu_cceConfig = {\n \"bandwidthInMbps\": 100,\n \"clusterName\": name,\n \"clusterVersion\": \"1.16.8\",\n \"containerCidr\": BAIDU_CCE_CONTAINER_CIDR,\n \"cpu\": 4,\n \"description\": \"\",\n \"diskSize\": 0,\n \"driverName\": \"baiducloudcontainerengine\",\n \"eipName\": name,\n \"gpuCard\": \"\",\n \"gpuCount\": 0,\n \"ifBuyEip\": True,\n \"imageId\": \"m-KX3IaJFg\",\n \"instanceType\": 10,\n \"memory\": 8,\n \"name\": \"\",\n \"nodeCount\": 1,\n \"osType\": \"\",\n \"osVersion\": \"\",\n \"region\": BAIDU_CCE_REGION,\n \"securityGroupId\": \"g-1f9xx3nhcvb2\",\n \"securityGroupName\": \"\",\n \"subProductType\": \"netraffic\",\n \"subnetId\": \"sbn-cvh9kcrz1nfv\",\n \"zone\": \"zoneD\",\n \"type\": \"baiduEngineConfig\",\n \"accessKey\": BAIDU_CCE_ACCESS_KEY,\n \"secretKey\": BAIDU_CCE_SECRET_KEY,\n \"adminPass\": \"X%jThoNguS(6rVewI!s!\",\n \"adminPassConfirm\": \"X%jThoNguS(6rVewI!s!\",\n \"cdsConfig\": [],\n \"vpcId\": \"vpc-k7gsv7af8857\"\n }\n\n\n if BAIDU_CCE_AMI is not None:\n baidu_cceConfig.update({\"ami\": BAIDU_CCE_AMI})\n\n # Generate the config for CCE cluster\n baidu_cceConfig = {\n\n \"baiduEngineConfig\": baidu_cceConfig,\n \"name\": name,\n \"type\": \"cluster\",\n \"dockerRootDir\": \"dockerRootDir\",\n \"fluentdLogDir\": \"/var/lib/rancher/fluentd/log\"\n }\n print(\"\\nBAIDU CCE Configuration\")\n print(baidu_cceConfig)\n\n return baidu_cceConfig\n","sub_path":"tests/v3_api/test_baidu_cce_cluster.py","file_name":"test_baidu_cce_cluster.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"72813864","text":"import argparse\nimport oauth2 as oauth\nimport urllib.request as urllib\nimport json\nimport sys\nimport csv\n\n# See Assignment 1 instructions for how to get these credentials\naccess_token_key = \"705795640534679553-TVQbpkHNCAT8ooLFSxIINBGgWtAWSES\"\naccess_token_secret = \"Z1JwcWCIlR0TP0Q9q3FIU2jUqxKQHyeSfXQQWNQnjY2hP\"\n\nconsumer_key = \"duqU0GAUWRZoFuWrIRRiQQSEF\"\nconsumer_secret = \"WD5fUSTv7wAeUiLZSADdPcQ3MhXcPSQWJv11zzicg5QDzIGF91\"\n\n_debug = 0\n\noauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)\noauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)\n\nsignature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()\n\nhttp_method = \"GET\"\n\n\nhttp_handler = urllib.HTTPHandler(debuglevel=_debug)\nhttps_handler = urllib.HTTPSHandler(debuglevel=_debug)\n\n'''\nConstruct, sign, and open a twitter request\nusing the hard-coded credentials above.\n'''\n\n\ndef twitterreq(url, method, parameters):\n req = oauth.Request.from_consumer_and_token(oauth_consumer,\n token=oauth_token,\n http_method=http_method,\n http_url=url, \n parameters=parameters)\n\n req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)\n\n headers = req.to_header()\n\n if http_method == \"POST\":\n encoded_post_data = req.to_postdata()\n else:\n encoded_post_data = None\n url = req.to_url()\n\n opener = urllib.OpenerDirector()\n opener.add_handler(http_handler)\n opener.add_handler(https_handler)\n\n response = opener.open(url, encoded_post_data)\n\n return response\n\n\ndef fetch_samples():\n url = \"https://stream.twitter.com/1.1/statuses/sample.json?language=en\"\n parameters = []\n response = twitterreq(url, \"GET\", parameters)\n for line in response:\n print(line.decode(\"utf-8\").strip())\n\n\ndef fetch_by_terms(term):\n url = \"https://api.twitter.com/1.1/search/tweets.json\"\n parameters = [(\"q\", term),(\"count\",\"100\")]\n response = twitterreq(url, \"GET\", parameters)\n # print(response.readline())\n if response.status == 200:\n string_tweet = response.readline().decode(\"utf-8\")\n twitter = json.loads(string_tweet)\n for status in twitter['statuses']:\n print(status['text'].encode(\"utf-8\"))\n\ndef fetch_by_user_names(user_name_file):\n #TODO: Fetch the tweets by the list of usernames and write them to stdout in the CSV format\n sn_file = open(user_name_file, encoding = \"utf-8\")\n sn_file1 = open('breaking_bad_tweets.csv','w',newline='', encoding = \"utf-8\")\n # writer = csv.writer(sys.stdout)\n writer = csv.writer(sn_file1)\n writer.writerow([\"user_name\",\"tweet\"])\n dict={}\n twitter=[]\n url = \"https://api.twitter.com/1.1/statuses/user_timeline.json\"\n for actor in sn_file:\n parameters = [(\"screen_name\", actor.rstrip(\"\\n\")), (\"count\", \"100\")]\n response = twitterreq(url, \"GET\", parameters)\n if response.status == 200:\n string_tweet = response.readline().decode(\"utf-8\")\n twitter = json.loads(string_tweet)\n for tweet in twitter:\n text_each_term = tweet['text']\n writer.writerow([actor.rstrip(\"\\n\"), text_each_term])\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', required=True, help='Enter the command')\n parser.add_argument('-term', help='Enter the search term')\n parser.add_argument('-file', help='Enter the user name file')\n opts = parser.parse_args()\n if opts.c == \"fetch_samples\":\n fetch_samples()\n elif opts.c == \"fetch_by_terms\":\n term = opts.term\n print(term)\n fetch_by_terms(term)\n elif opts.c == \"fetch_by_user_names\":\n user_name_file = opts.file\n fetch_by_user_names(user_name_file)\n else:\n raise Exception(\"Unrecognized command\")\n","sub_path":"stencil/fetch_tweets.py","file_name":"fetch_tweets.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"507013643","text":"from user_service.db.user_models.models import Connection\nfrom user_service.utils.exceptions import UnauthorisedException\n\n\ndef check_is_valid_customer_registration_get_object(customer_id):\n try:\n connection_object = Connection.objects.get(customer_id=customer_id)\n connection_object.is_valid=True\n connection_object.save()\n return connection_object\n except:\n raise UnauthorisedException(message=\"Customer id not valid !!\")\n","sub_path":"user_service/utils/user_validation.py","file_name":"user_validation.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"2305505","text":"from django.db import models\nfrom django import forms\nfrom wheelcms_axe.models import Content, Node\nfrom wheelcms_axe.models import type_registry\n\nclass BaseForm(forms.ModelForm):\n class Meta:\n exclude = [\"node\", \"meta_type\"]\n\n slug = forms.Field(required=True)\n\n def __init__(self, parent=None, *args, **kwargs):\n \"\"\"\n Django will put the extra slug field at the bottom, below\n all model fields. I want it just after the title field\n \"\"\"\n super(BaseForm, self).__init__(*args, **kwargs)\n slug = self.fields.pop('slug')\n titlepos = self.fields.keyOrder.index('title')\n self.fields.insert(titlepos+1, 'slug', slug)\n self.parent = parent\n\n def clean_slug(self):\n slug = self.data.get('slug', '').strip().lower()\n if not Node.validpathre.match(slug):\n raise forms.ValidationError(\"Only numbers, letters, _-\")\n try:\n existing = Node.objects.filter(path=self.parent.path + \"/\" + slug).get()\n if existing != self.instance.node:\n raise forms.ValidationError(\"Name in use\")\n except Node.DoesNotExist:\n pass\n\n return slug\n\ndef formfactory(type):\n class Form(BaseForm):\n class Meta:\n model = type\n exclude = [\"node\", \"meta_type\", \"created\", \"modified\"]\n return Form\n\n\nclass Page(Content):\n \"\"\" A simple page object \"\"\"\n body = models.TextField(blank=False)\n\nclass News(Content):\n \"\"\" A news object \"\"\"\n intro = models.TextField(blank=False)\n body = models.TextField(blank=False)\n\n##\n## Idee: combineer Model, Form en type-metadata in een aparte class,\n## e.g.\n## class PageType(..):\n## model = Page\n## form = formfactory(..)\n## name = \"spokes.page\"\n## title = \"A simple webpage\"\n##\n## type_registry.register(PageType)\n\ntype_registry.register(\"page\", Page, formfactory(Page))\ntype_registry.register(\"news\", News, formfactory(News))\n","sub_path":"wheel_cms/wheelcms_spokes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"369057472","text":"import locale\nimport datetime\nimport string\nfrom datetime import timedelta, date\n\n# Initialize 2 numeric values\ni = 39.75\nj = 39.75\ninitvalue = i\n\n# Store today's date\nx = datetime.datetime.now()\n#print(x)\n\n# Add days to a date\ny = x + datetime.timedelta(days=32)\nprint('End date: ' + str(y))\n\n# Subtract days from a date\nz = x + datetime.timedelta(days=-30)\nprint('Start date: ' + str(z))\ntotaldays = y-z\nprint('Total amount of days in the range: ' + str(totaldays))\n\n# Or simply set dates\n# z = datetime(1988, 2, 19, 2, 12, 49)\n# y = datetime(1988, 2, 19, 1, 56, 2)\n\n# Increase numeric value with the other value, until day is the correct date\nstart_date = z\nend_date = y\ndelta = timedelta(days=1)\nwhile start_date < end_date:\n i = i+j\n start_date += delta\n\nprint('Initial value: ' + str(initvalue))\nprint('Value added per day: ' + str(j))\nprint('Final date reached in loop: ' + str(start_date)) \nprint('Final value: ' + str(i))\n\n\n\n","sub_path":"increase_value_per_day_for_daterange.py","file_name":"increase_value_per_day_for_daterange.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"568538188","text":"from glob import glob\nimport argparse\nimport pandas as pd\nimport multiprocessing as mp\nimport os\n\ndef returnStrand(currentPosition, vector): \n\t#a function to knwo orientation of the full vector for the args.orientation option\n\tdiff = 10000000 # a big number, cause it will have the abs value of current position less position in vector of tss\n\tpos = 0 # the position with the closer value to 0 in diff\n\tfor i in range(len(vector)):\n\t\tif abs(currentPosition - vector[i]) < diff:\n\t\t\tdiff = abs(currentPosition - vector[i])\n\t\t\tpos = vector[i]\n\n\n\tif pos >= currentPosition:\n\t\treturn 1\n\telse:\n\t\treturn -1\n\n\ndef doFullDataset(tsv):\n\tdf1 = pd.read_csv(tsv,sep=\"\\t\")\n\n\tTSSList = [] # to make a list with TSS positions\n\n\tif args.orientation:\n\t\tfor i in range(len(df1[\"TSS\"])):\n\t\t\tif df1[\"TSS\"][i] == 1:\n\t\t\t\tTSSList.append(i)\n\n\n\tdict = {}\n\tsorted_name = [] #to write with ordered index\n\t#verctor names for left and the list wich will be filled with data of the correspondig part\n\ti = args.left_vector * -1\n\twhile i < 0:\n\t\tfor name in args.feature_list:\n\t\t\tdict[name+\"_\"+str(i)] = []\n\t\t\tsorted_name.append(name+\"_\"+str(i))\n\t\ti += 1\n\t#central vector\n\tfor name in args.feature_list:\n\t\tdict[name+\"_0\"] = []\n\t\tsorted_name.append(name+\"_0\")\n\n\t#right vectors\n\ti = 1\n\twhile i<= args.right_vector:\n\t\tfor name in args.feature_list:\n\t\t\tdict[name+\"_\"+str(i)] = []\n\t\t\tsorted_name.append(name+\"_\"+str(i))\n\t\ti += 1\n\tsorted_name.append(args.Class)\n\t\n\t#class\n\tdict[args.Class] = []\n\n\n\t#looping over dataset, and selecting vector if class is present or not (1 or -1)\n\tfor i in range(len(df1[args.Class])):\n\t\tif i >args.left_vector and i <(len(df1[args.Class])-args.right_vector):\n\t\t\tif df1[args.Class][i] == 1 or df1[args.Class][i] == -1:\n\t\t\t\torinetation = 1\n\t\t\t\tif args.orientation:\n\t\t\t\t\torientation = returnStrand(i, TSSList)\n\t\t\t\t#looping column names\n\t\t\t\tfor name in args.feature_list:\n\t\t\t\t\tdata = df1[name][i-args.left_vector:i+args.right_vector+1].values.tolist()\n\t\t\t\t\tj = -1 * args.left_vector\n\t\t\t\t\tk = args.right_vector +1\n\t\t\t\t\twhile j<0:\n\t\t\t\t\t\tdict[name+\"_\"+str(j*orientation)].append(data[j+args.left_vector])\n\t\t\t\t\t\tj += 1\n\t\t\t\t\tdict[name+\"_0\"].append(data[args.right_vector])\n\t\t\t\t\tj = 1\n\t\t\t\t\twhile j 2 : \n return n[0]+'.'+n[1]\n else :\n return self.name\n\n\n ## rename an outline, rewrite relationships, update element\n # not sure that's a good idea.. though it could be used by elementRemove(), wait and see\n #def rename(self,name) :\n # city = bpy.context.scene.city\n # oldname = self.name\n # self.name = name\n # if self.parent != '' :\n # city.outlines[self.parent].childRemove(oldname)\n # city.outlines[self.parent].childsAdd(name)\n # for child in self.childslist() :\n # city.outlines[child].parent = name\n # self.asElement().name = name\n\n\n\n ## returns the first child or None\n # @param id 0 (default) the child index -1 for last. id > len(childs) error free : returns last child\n # @param attached False (default) returns the outline parent. True returns the builder attached\n # @return the element or None\n def Child(self,id=0,attached=False) :\n outlines = bpy.context.scene.city.outlines\n childs = self.childsGet()\n if len(childs) > 0 :\n if id + 1 > len(childs) : id = -1\n if attached : return outlines[childs[id]].peer()\n return outlines[childs[id]]\n return None\n\n\n ## returns the parent element\n # @param attached False (default) returns the outline parent. True returns the builder attached\n # @return the element or None\n def Parent(self,attached=False) :\n outlines = bpy.context.scene.city.outlines\n self = self.asOutline()\n if self.parent :\n if attached : return outlines[self.parent].peer()\n return outlines[self.parent]\n return None\n\n\n ## returns the next sibling\n # @param attached False (default) returns the outline parent. True returns the builder attached\n # @return the element or None\n def Next(self,attached=False) :\n outlines = bpy.context.scene.city.outlines\n if self.asOutline().parent :\n siblings = self.Parent().childsGet()\n if len(siblings) > 1 :\n si = siblings.index(self.name)\n try : sibling = outlines[siblings[si+1]]\n except : return None\n return sibling.peer() if attached else sibling\n return None\n\n\n ## returns the previous sibling\n # @param attached False (default) returns the outline parent. True returns the builder attached\n # @return the element or None\n def Previous(self,attached=False) :\n outlines = bpy.context.scene.city.outlines\n if self.asOutline().parent :\n siblings = self.Parent().childsGet()\n if len(siblings) > 1 :\n si = siblings.index(self.name)\n if si > 0 : sibling = outlines[siblings[si-1]]\n else : return None\n return sibling.peer() if attached else sibling\n return None\n\n\n ## from an element, returns and select the object\n def select(self,attached=False) :\n #print('select %s %s %s'%(self.name,self.className(),attached))\n if attached :\n ob = self.peer().object()\n else :\n ob = self.object()\n if ob :\n bpy.ops.object.select_all(action='DESELECT')\n ob.select = True\n bpy.context.scene.objects.active = ob\n else : return False\n\n\n ## selects the parent object of the current element\n # @param attached (default False) if True returns always the builder object and not the outline\n def selectParent(self,attached=False) :\n if self.className() == 'elements' : self = self.asBuilder()\n if self.className() != 'outlines' :\n self = self.peer()\n attached = True\n outlines = bpy.context.scene.city.outlines\n if self.parent != '' :\n self = outlines[self.parent]\n self.select(attached)\n\n\n ## selects the first child object of the current element\n # @param attached (default False) if True returns always the builder object and not the outline\n def selectChild(self,attached=False) :\n child = self.Child()\n if child : child.select(attached)\n\n\n ## selects the next sibling object of the current element\n # @param attached (default False) if True returns always the builder object and not the outline\n def selectNext(self,attached=False) :\n if self.className() == 'elements' : self = self.asBuilder()\n if self.className() != 'outlines' :\n self = self.peer()\n attached = True\n outlines = bpy.context.scene.city.outlines\n if self.parent != '' :\n siblings = outlines[self.parent].childsGet()\n if len(siblings) > 1 :\n si = siblings.index(self.name)\n sibling = outlines[siblings[(si+1)%len(siblings)]]\n sibling.select(attached)\n\n\n ## selects the previous sibling object of the current element\n # @param attached (default False) if True returns always the builder object and not the outline\n def selectPrevious(self,attached=False) :\n if self.className() == 'elements' : self = self.asBuilder()\n if self.className() != 'outlines' :\n self = self.peer()\n attached = True\n outlines = bpy.context.scene.city.outlines\n if self.parent != '' :\n siblings = outlines[self.parent].childsGet()\n if len(siblings) > 1 :\n si = siblings.index(self.name)\n sibling = outlines[siblings[(si-1)%len(siblings)]]\n sibling.select(attached)\n\n\n ## add a child outline reference to this outline.\n # @param childname the outline name (string)\n def childsAdd(self,childname) :\n self = self.asOutline()\n if self.childs == '' :\n self.childs = childname\n elif childname not in self.childs :\n self.childs += ',%s'%childname\n\n\n ## delete a child outline reference of this outline.\n # @param childname the outline name (string)\n def childsRemove(self,childname) :\n self = self.asOutline()\n print('removing %s from %s : %s'%(childname,self.name,self.childs))\n if childname in self.childs :\n childs = self.childsGet()\n del childs[childs.index(childname)]\n newchilds = ''\n for child in childs : newchilds += child+','\n self.childs = newchilds[:-1]\n print('child list now : %s'%self.childs)\n\n\n ## returns outlines parented to this one (its childs) and mentionned in otl.childs, but as a list and not a string\n # @return a list of string (outline names) or an empty list\n def childsGet(self) :\n self = self.asOutline()\n if self.childs == '' :\n return []\n else :\n return self.childs.split(',')\n\n ## remove the element and its generated object\n # cares about relationship\n # @param del_object (default True) delete the attached object\n def remove(self,del_object=True) :\n city = bpy.context.scene.city\n otl = self.asOutline()\n bld = self.asBuilder()\n if del_object : bld.objectRemove()\n # rebuild relationship\n parent = otl.parent\n childs = otl.childsGet()\n for child in childs :\n city.outlines[child].parent = parent\n if parent != '' :\n otl.Parent().childsRemove(otl.name)\n for child in childs :\n otl.Parent().childsAdd(child)\n otl.Parent().asBuilder().build(True) # this to update the childs\n\n # remove elements from collections.\n iotl = otl.index()\n ielm = otl.asElement().index()\n city.elements.remove(ielm)\n city.outlines.remove(iotl)\n\n ibld = bld.index()\n ielm = bld.asElement().index()\n city.elements.remove(ielm)\n bldclass = bld.elementClass()\n bldclass.remove(ibld)\n\n\n ## stack an element above this one\n # @param builder (default 'same') the builderclass name of the new element. if not given, stack the same builder than the current element.\n def stack(self,builder='same') :\n city = bpy.context.scene.city\n otl_parent = self.asOutline()\n bld_parent = self.asBuilder()\n if builder == 'same' : builder = bld_parent.className()\n [ [bld_child, otl_child] ] = city.elementAdd(False,builder,False)\n otl_child.parent = otl_parent.name\n otl_child.data = otl_parent.data\n otl_parent.childsAdd(otl_child.name)\n\n data = otl_child.dataGet('perimeters')\n z = max(zcoords(data))\n z += bld_parent.height()\n\n for perimeter in data :\n for vert in perimeter :\n vert[2] = z\n\n otl_child.dataSet(data)\n otl_child.dataWrite()\n\n bld_child.inherit = True\n bld_child.build()\n otl_child.object().parent = otl_parent.object()\n bld_child.object().parent = otl_child.object()\n return bld_child, otl_child\n \n##\\brief the outlines collection\n#\n# this collection stores retionship between elements, and the geometry data of the outline. an outline is always attached to a builder element, and reciproquely.\n#\n# @param type not sure it's useful anymore... \n# @param attached (string) the name of the builder object attached to it\n# @param data (dictionnary as string)stores the geometry, outline oriented, of the outline object\n# @param childs (list as string) store outlines parented to the outline element \"child1,child2,..\"\n# @param parent the parent outline name if any (else '')\n\nclass BC_outlines(BC_elements,bpy.types.PropertyGroup) :\n type = bpy.props.StringProperty() # its tag\n attached = bpy.props.StringProperty() # its attached object name (the real mesh)\n data = bpy.props.StringProperty(default=\"{'perimeters':[], 'lines':[], 'dots':[], 'matrix':Matrix() }\") # global. if the outline object is missing, create from this\n childs = bpy.props.StringProperty(default='')\n parent = bpy.props.StringProperty(default='')\n\n ## given an outline, retrieves its geometry in meters as a dictionnary from the otl.data string field :\n # @param what 'perimeters', 'lines', 'dots', 'matrix', or 'all' default is 'perimeters'\n # @return a nested lists of vertices, or the world matrix, or all fields in a dict.\n def dataGet(self,what='perimeters',meters=True) :\n data = eval(self.data)\n if meters :\n print('dataGet returns %s %s datas in Meters'%(self.name,what))\n data['perimeters'] = buToMeters(data['perimeters'])\n data['lines'] = buToMeters(data['lines'])\n data['dots'] = buToMeters(data['dots'])\n else : print('dataGet returns %s %s datas in B.U.'%(self.name,what)) \n data['matrix'] = Matrix(data['matrix'])\n if what == 'all' : return data\n return data[what]\n\n\n ## set or modify the geometry of an outline\n # @param what 'perimeters', 'lines', 'dots', 'matrix', or 'all' default is 'perimeters'\n # @param data a list with nested list of vertices or a complete dictionnary conaining the four keys\n def dataSet(self,data,what='perimeters',meters=True) :\n if what == 'all' : pdata = data\n else :\n pdata = self.dataGet('all',meters)\n pdata[what] = data\n if meters :\n print('dataSet received %s %s datas in meters :'%(self.name,what)) \n pdata['perimeters'] = metersToBu(pdata['perimeters'])\n pdata['lines'] = metersToBu(pdata['lines'])\n pdata['dots'] = metersToBu(pdata['dots'])\n else :\n print('dataSet received %s %s datas in BU :'%(self.name,what))\n self.data = '{ \"perimeters\": ' + str(pdata['perimeters']) + ', \"lines\":' + str(pdata['lines']) + ', \"dots\":' + str(pdata['dots']) + ', \"matrix\":' + matToString(pdata['matrix']) +'}'\n\n\n ## read the geometry of the outline object and sets its data (dataSet call)\n # @return False if object does not exists\n def dataRead(self) :\n print('dataRead outline object of %s'%self.name)\n obsource=self.object()\n if obsource :\n # data extracted are in BU no meter so dataSet boolean is False\n mat, perims, lines,dots = outlineRead(obsource)\n data = {'perimeters':perims, 'lines':lines, 'dots':dots, 'matrix':mat }\n self.dataSet(data,'all',False)\n return True\n else :\n print('no object ! regenerate')\n self.dataWrite()\n print('done regenerate')\n return False\n print('dataReaddone')\n\n\n ## write the geometry in the outline object from its data field (dataGet call)\n # inputs and outputs are in meters\n def dataWrite(self) :\n print('dataWrite outline ob for %s'%self.name)\n data = self.dataGet()\n verts = []\n edges = []\n ofs = 0\n for perimeter in data :\n print('>',len(perimeter))\n for vi,v in enumerate(perimeter) :\n print(vi,v)\n verts.append(v)\n if vi < len(perimeter)-1 :\n edges.append([ofs+vi,ofs+vi+1])\n edges.append([ofs+vi,ofs])\n ofs += len(perimeter)\n print('>',verts,edges)\n print(len(verts),len(edges))\n ob = objectBuild(self,verts,edges)\n print('dataWrite done')\n\n\n##\\brief the builders registered\n#\n# By default this is empty and will be populated with builder collections\nclass BC_builders(bpy.types.PropertyGroup):\n builders_list = bpy.props.StringProperty()\n# for reference\n#BC_builders = type(\"BC_builders\", (bpy.types.PropertyGroup, ), {})","sub_path":"addon/blended_cities/core/class_main.py","file_name":"class_main.py","file_ext":"py","file_size_in_byte":19956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"236429188","text":"from pathlib import Path\nfrom typing import Union\nimport numpy as np\nimport pdb\n\n\ndef calc_norm_param(X):\n \"\"\"Assumes X to be a list of arrays (of differing sizes)\"\"\"\n total_len = 0\n mean_val = np.zeros(X[0].shape[1])\n std_val = np.zeros(X[0].shape[1])\n for obs in X:\n obs_len = obs.shape[0]\n mean_val += np.mean(obs,axis=0)*obs_len\n std_val += np.std(obs, axis=0)*obs_len\n total_len += obs_len\n \n mean_val /= total_len\n std_val /= total_len\n\n return mean_val, std_val, total_len\n\n\nX_train = []\n# max_cur = [0]*80\n# std_list=[]\nlist_file = '/home/hk/voice_conversion/nonparaSeq2seqVC_text-dependent_SE/reader/vctk_train_100speakers.txt'\nwith open(list_file) as f:\n # pdb.set_trace()\n lines = f.readlines()\n for line in lines:\n # print(\"line \", line)\n # path, n_frame, n_phones = line.strip().split()\n # path = line.strip().split()\n path = line.strip()\n # print(\"path \", path)\n # if int(n_frame) >= 1000:\n # continue\n mel = np.load(path)\n mel = np.transpose(mel)\n X_train.append(mel)\n\nmean_val, std_val, _ = calc_norm_param(X_train)\nnp.save('std.npy', std_val)\nnp.save('mean.npy', mean_val)\n","sub_path":"reader/cal_mean_std.py","file_name":"cal_mean_std.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"131146829","text":"# Copyright (C) 2021 Cancer Care Associates\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 base64\nimport pathlib\nfrom typing import Any, Dict, List, Tuple\n\nfrom pymedphys._imports import numpy as np\nfrom pymedphys._imports import pandas as pd\nfrom pymedphys._imports import streamlit as st\nfrom pymedphys._imports import toml\n\nimport pymedphys\nfrom pymedphys._streamlit import categories\nfrom pymedphys._streamlit.utilities import config as st_config\nfrom pymedphys._streamlit.utilities import mosaiq as _mosaiq\n\nCATEGORY = categories.PLANNING\nTITLE = \"Mosaiq to CSV\"\n\nLIB_ROOT = pathlib.Path(__file__).parents[3]\nTEST_DATA_DIR = LIB_ROOT.joinpath(\"tests\", \"mosaiq\", \"data\")\n\nPASSWORD_REPLACE = b\"\\x00\" * 15\nFIRST_NAME_USERNAME_MAP = {\n \"Simon\": \"dummyusername\",\n}\n\n# Given dynamic SQL queries are created in the functions below the SQL\n# query is sanitised by only allowing table names and column names to\n# pull from the below.\nALLOWLIST_TABLE_NAMES = [\n \"Ident\",\n \"Patient\",\n \"TxField\",\n \"TxFieldPoint\",\n \"Site\",\n \"TrackTreatment\",\n \"Staff\",\n \"Chklist\",\n \"QCLTask\",\n]\n\nALLOWLIST_COLUMN_NAMES = [\n \"IDA\",\n \"Pat_ID1\",\n \"SIT_Set_ID\",\n \"FLD_ID\",\n \"Staff_ID\",\n \"TSK_ID\",\n]\n\n\ndef main():\n config = st_config.get_config()\n connection = _mosaiq.get_single_mosaiq_connection_with_config(config)\n\n comma_sep_patient_ids: str = st.text_input(\"Comma Separated Patient IDs\")\n if comma_sep_patient_ids == \"\":\n st.stop()\n\n patient_ids = [item.strip() for item in comma_sep_patient_ids.split(\",\")]\n tables, types_map = _get_all_tables(connection, patient_ids)\n _apply_table_type_conversions_inplace(tables, types_map)\n\n _save_tables_to_tests_directory(tables, types_map)\n\n\ndef _get_all_tables(\n connection: pymedphys.mosaiq.Connection, patient_ids: List[str]\n) -> Tuple[Dict[str, pd.DataFrame], Dict[str, Dict[str, str]]]:\n \"\"\"Get Mosaiq tables that are relevant for PyMedPhys regression testing.\n\n Take a list of patient_ids and steps through the MSSQL Mosaiq\n database with the intent to extract the relevant rows from the\n relevant tables for PyMedPhys regression testing.\n\n\n Parameters\n ----------\n connection : pymedphys.mosaiq.Connection\n A connection object to the Mosaiq SQL server.\n patient_ids : List[str]\n The list of Patient IDs (MRNs) to use for extracting data from\n Mosaiq.\n\n Returns\n -------\n tables\n A dictionary of Pandas DataFrames with dictionary keys defined\n by the Mosaiq table name and the table contents being the Mosaiq\n rows that are relevant to the Patient IDs provided.\n\n types_map\n A dictionary of dictionaries that present the MSSQL column types\n of the tables.\n \"\"\"\n tables: Dict[str, pd.DataFrame] = {}\n types_map: Dict[str, Dict[str, str]] = {}\n\n tables[\"Ident\"] = get_filtered_table(\n connection, types_map, \"Ident\", \"IDA\", patient_ids\n )\n\n # Patient.Pat_ID1 = Ident.Pat_ID1\n pat_id1s = tables[\"Ident\"][\"Pat_Id1\"].unique()\n tables[\"Patient\"] = get_filtered_table(\n connection, types_map, \"Patient\", \"Pat_ID1\", pat_id1s\n )\n tables[\"TxField\"] = get_filtered_table(\n connection, types_map, \"TxField\", \"Pat_ID1\", pat_id1s\n )\n\n # TxField.SIT_Set_ID = Site.SIT_Set_ID\n sit_set_ids = tables[\"TxField\"][\"SIT_Set_ID\"].unique()\n tables[\"Site\"] = get_filtered_table(\n connection, types_map, \"Site\", \"SIT_Set_ID\", sit_set_ids\n )\n\n # TrackTreatment.FLD_ID = TxField.FLD_ID\n fld_ids = tables[\"TxField\"][\"FLD_ID\"].unique()\n tables[\"TrackTreatment\"] = get_filtered_table(\n connection, types_map, \"TrackTreatment\", \"FLD_ID\", fld_ids\n )\n\n # Chklist.Pat_ID1 = Ident.Pat_ID1 AND\n # Patient.Pat_ID1 = Ident.Pat_ID1 AND\n # QCLTask.TSK_ID = Chklist.TSK_ID AND\n # Staff.Staff_ID = Chklist.Rsp_Staff_ID AND\n tables[\"Chklist\"] = get_filtered_table(\n connection, types_map, \"Chklist\", \"Pat_ID1\", pat_id1s\n )\n\n tsk_ids = tables[\"Chklist\"][\"TSK_ID\"].unique()\n tables[\"QCLTask\"] = get_filtered_table(\n connection, types_map, \"QCLTask\", \"TSK_ID\", tsk_ids\n )\n\n responsible_staff_ids = tables[\"Chklist\"][\"Rsp_Staff_ID\"].unique()\n completed_staff_ids = tables[\"Chklist\"][\"Com_Staff_ID\"].unique()\n machine_staff_ids = tables[\"TrackTreatment\"][\"Machine_ID_Staff_ID\"].unique()\n staff_ids_with_nans = (\n set(responsible_staff_ids).union(completed_staff_ids).union(machine_staff_ids)\n )\n staff_ids = np.array(list(staff_ids_with_nans))\n staff_ids = staff_ids[np.logical_not(np.isnan(staff_ids))]\n staff_ids = staff_ids.astype(int)\n\n # Staff.Staff_ID = TrackTreatment.Machine_ID_Staff_ID\n tables[\"Staff\"] = get_filtered_table(\n connection, types_map, \"Staff\", \"Staff_ID\", staff_ids.tolist()\n )\n tables[\"Staff\"][\"PasswordBytes\"] = tables[\"Staff\"][\"PasswordBytes\"].apply(\n lambda x: PASSWORD_REPLACE\n )\n for index, row in tables[\"Staff\"].iterrows():\n first_name = row[\"First_Name\"]\n if first_name.strip() == \"\":\n continue\n\n new_username = FIRST_NAME_USERNAME_MAP[first_name]\n tables[\"Staff\"].loc[index, \"User_Name\"] = new_username\n\n # TxFieldPoint.FLD_ID = %(field_id)s\n tables[\"TxFieldPoint\"] = get_filtered_table(\n connection, types_map, \"TxFieldPoint\", \"FLD_ID\", fld_ids\n )\n\n return tables, types_map\n\n\ndef _apply_table_type_conversions_inplace(tables, types_map):\n \"\"\"Convert binary types to b64 and make sure pandas defines datetime\n types even if a column has a None entry.\n\n Utilised for reliable saving and loading to and from a csv file.\n \"\"\"\n for table_name, table in tables.items():\n column_types = types_map[table_name]\n for column_name, column_type in column_types.items():\n if column_type in [\"binary\", \"timestamp\"]:\n table[column_name] = table[column_name].apply(\n lambda x: base64.b64encode(x).decode()\n )\n continue\n if column_type == \"datetime\":\n table[column_name] = table[column_name].apply(_convert_to_datetime)\n\n st.write(f\"## `{table_name}` Table\")\n st.write(table)\n\n\ndef _save_tables_to_tests_directory(tables, types_map):\n \"\"\"Save the tables within the PyMedPhys testing directory.\"\"\"\n if not st.button(\"Save tables within PyMedPhys mosaiq testing dir\"):\n st.stop()\n\n for table_name, df in tables.items():\n filepath = TEST_DATA_DIR.joinpath(table_name).with_suffix(\".csv\")\n df.to_csv(filepath)\n\n toml_filepath = TEST_DATA_DIR.joinpath(\"types_map.toml\")\n\n with open(toml_filepath, \"w\") as f:\n toml.dump(types_map, f)\n\n\ndef get_filtered_table(\n connection: pymedphys.mosaiq.Connection,\n types_map: Dict[str, Dict[str, str]],\n table: str,\n column_name: str,\n column_values: List[Any],\n) -> \"pd.DataFrame\":\n \"\"\"Step through a set of provided column values extracting these\n from the MSSQL database.\n\n Parameters\n ----------\n connection : pymedphys.mosaiq.Connection\n types_map : Dict[str, Dict[str, str]]\n The types_map to append to the new column schema to\n table : str\n The table name to pull data from\n column_name : str\n The column name to pull data from\n column_values : List[Any]\n The values to match against within the columns\n\n Returns\n -------\n df : pd.DataFrame\n \"\"\"\n column_names, column_types = _get_all_columns(connection, table)\n df = pd.DataFrame(data=[], columns=column_names)\n for column_value in column_values:\n df = _append_filtered_table(connection, df, table, column_name, column_value)\n\n types_map[table] = dict(zip(column_names, column_types))\n\n return df\n\n\ndef _append_filtered_table(connection, df, table, column_name, column_value):\n \"\"\"Append the rows from an MSSQL table where the column_value\n matches within the given column_name.\n \"\"\"\n df = pd.concat(\n [df, _get_filtered_table(connection, table, column_name, column_value)],\n ignore_index=True,\n )\n return df\n\n\n@st.cache(ttl=86400, hash_funcs={pymedphys.mosaiq.Connection: id})\ndef _get_all_columns(connection, table):\n \"\"\"Get the column schema from an MSSQL table.\"\"\"\n raw_columns = pymedphys.mosaiq.execute(\n connection,\n \"\"\"\n SELECT COLUMN_NAME, DATA_TYPE\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = %(table)s\n \"\"\",\n {\n \"table\": table,\n },\n )\n\n columns = [item[0] for item in raw_columns]\n types = [item[1] for item in raw_columns]\n\n return columns, types\n\n\n@st.cache(ttl=86400, hash_funcs={pymedphys.mosaiq.Connection: id})\ndef _get_filtered_table(connection, table, column_name, column_value):\n \"\"\"Get the rows from an MSSQL table where the column_value matches\n within the given column_name.\"\"\"\n if not table in ALLOWLIST_TABLE_NAMES:\n raise ValueError(f\"{table} must be within the allowlist\")\n\n if not column_name in ALLOWLIST_COLUMN_NAMES:\n raise ValueError(f\"{column_name} must be within the allowlist\")\n\n column_value = str(column_value)\n column_names, _ = _get_all_columns(connection, table)\n\n sql_string = f\"\"\"\n SELECT *\n FROM {table}\n WHERE {table}.{column_name} = %(column_value)s\n \"\"\"\n\n raw_results = pymedphys.mosaiq.execute(\n connection,\n sql_string,\n {\n \"table\": table,\n \"column_name\": column_name,\n \"column_value\": column_value,\n },\n )\n\n df = pd.DataFrame(raw_results, columns=column_names)\n\n return df\n\n\ndef _convert_to_datetime(item):\n if item is not None:\n return pd.to_datetime(item)\n\n return item\n","sub_path":"lib/pymedphys/_experimental/streamlit/apps/mosaiq_to_csv.py","file_name":"mosaiq_to_csv.py","file_ext":"py","file_size_in_byte":10301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"204977338","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np;\nimport matplotlib.pyplot as plt;\n\nfrom Pyccat import model_ccat,read_input;\nfrom Kirchhoffpy.mirrorpy import deformation,adjuster;\n\n'''\nread input data file\n'''\ninputfile='CCAT_model'\ncoefficient_m2,coefficient_m1,List_m2,List_m1,M2_size,M1_size,R2,R1,p_m2,q_m2,p_m1,q_m1,M2_N,M1_N,fimag_N,fimag_size,distance,edge_taper,Angle_taper,k=read_input(inputfile);\n\nM2_size=M2_size+1.2;\nM1_size=M1_size+1.2;\nM2_N=[13,13]\nM1_N=[13,13]\n'''\nbuild model\n'''\nad_m2=np.zeros(5*List_m2.shape[0]);\nad_m1=np.zeros(5*List_m1.shape[0]);\nm2,m2_n,m2_dA,m1,m1_n,m1_dA,fimag,fimag_n,fimag_dA=model_ccat(coefficient_m2,List_m2,M2_size[0],M2_size[1],M2_N[0],M2_N[1],R2,\n coefficient_m1,List_m1,M1_size[0],M1_size[1],M1_N[0],M2_N[1],R1,\n fimag_size[0],fimag_size[1],fimag_N[0],fimag_N[1],\n ad_m2,ad_m1,p_m2,q_m2,p_m1,q_m1);\n\ndx2,dy2,dx1,dy1=adjuster(List_m2,List_m1,p_m2,q_m2,p_m1,q_m1,R2,R1)\n\n\n'''\ndefine function to reshape the mirror to mesh grid points;\n'''\ndef reshape_model(sizex,sizey,m,z,dy=1,Num=11):\n x0=np.linspace(-4.5*sizex+sizex/Num/2,4.5*sizex-sizex/Num/2,Num*9)\n y0=np.linspace(-4.5*sizey+sizey/Num/2,4.5*sizey-sizey/Num/2,Num*9)\n #m2\n y0=y0+dy;\n #m1\n #y0=y0;\n x,y=np.meshgrid(x0,y0)\n dz=np.zeros(x.shape)\n for i in range(9*Num):\n for n in range(9*Num): \n a=np.where((m.x>(x[i,n]-0.001))&(m.x<(x[i,n]+0.001)) &(m.y>(y[i,n]-0.001))&(m.y<(y[i,n]+0.001))) \n if a[0].size:\n dz[i,n]=z[a];\n else:\n dz[i,n]=np.nan;\n return x,y,dz\n\n\n# In[18]:\n\n\n'''\ndefine a color map plot function;\n'''\ndef colormap(x1,y1,z1,x2,y2,z2,Vmax=None,Vmin=None,savename='',suptitle=''):\n cmap = plt.get_cmap('hot');\n font = {'family': 'serif','color':'darkred','weight':'normal','size':16};\n fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(14,6));\n ax1=ax[0];\n ax2=ax[1];\n p1=ax1.pcolor(x2,y2,z2,cmap=cmap,vmin=Vmin,vmax=Vmax);\n ax1.axis('scaled');\n ax1.set_xlabel('Secondary mirror',fontdict=font);\n clb=fig.colorbar(p1, ax=ax1,shrink=0.95,fraction=.05);\n clb.set_label('um',labelpad=-40,y=1.05,rotation=0)\n p1=ax2.pcolor(x1,y1,z1,cmap=cmap,vmin=Vmin,vmax=Vmax);\n ax2.axis('scaled');\n ax2.set_xlabel('Primary mirror',fontdict=font);\n clb=fig.colorbar(p1, ax=ax2,shrink=0.95,fraction=.05);\n clb.set_label('um',labelpad=-40,y=1.05,rotation=0);\n fig.suptitle(suptitle,fontsize=15,color='k',verticalalignment='top')#'baseline')\n plt.savefig('output/picture/'+savename+'.png')\n plt.show();\n \n'''\ndefine a 5 adjuster plots\n'''\ndef ad_plots(err,name,scale=10):\n fig,ax=plt.subplots(nrows=2,ncols=3,figsize=(12,12));\n font = {'family': 'serif',\n 'color':'darkred',\n 'weight':'normal',\n 'size':16};\n ax1=ax[0,0];\n ax2=ax[0,1]\n ax3=ax[0,2]\n ax4=ax[1,0]\n ax5=ax[1,1]\n ax6=ax[1,2];\n ax6.set_visible(False);\n \n err2=err[0:List_m2.shape[0]*5].reshape(5,-1);\n err1=err[List_m2.shape[0]*5:].reshape(5,-1);\n \n ax1.plot(err2[0,...],'b*-',label='M2 adjuster 0');\n ax1.plot(err1[0,...],'ro-',label='M1 adjuster 0');\n ax1.set_ylim([-scale,scale])\n ax1.set_ylabel('Fitting error/$\\mu m$')\n ax1.legend();\n \n ax2.plot(err2[1,...],'b*-',label='M2 adjuster 1');\n ax2.plot(err1[1,...],'ro-',label='M1 adjuster 1');\n ax2.set_ylim([-scale,scale])\n ax2.legend();\n \n ax3.plot(err2[2,...],'b*-',label='M2 adjuster 2');\n ax3.plot(err1[2,...],'ro-',label='M1 adjuster 2');\n ax3.set_ylim([-scale,scale])\n ax3.legend();\n \n ax4.plot(err2[3,...],'b*-',label='M2 adjuster 3');\n ax4.plot(err1[3,...],'ro-',label='M1 adjuster 3');\n ax4.set_ylim([-scale,scale])\n ax4.set_ylabel('Fitting error/$\\mu m$')\n ax4.legend();\n \n ax5.plot(err2[4,...],'b*-',label='M2 adjuster 4');\n ax5.plot(err1[4,...],'ro-',label='M1 adjuster 4');\n ax5.set_ylim([-scale,scale])\n ax5.legend();\n \n plt.savefig('output/picture/fitting_adjuster_errorplots'+name+'.png')\n plt.show()\n \n \n\n\n# In[19]:\n\n\n'''\nDefine a function to plot error maps\n1. input panel error;\n2. fitting panel error;\n3. fitting accuracy;\n4. final error plots;\n5. error calculation;\n'''\ndef error_plots(file_input,file_fitting,name,inputrms=100,outputrms=10,scale=10):\n # 1. get input panel error (reference):\n ad0=np.genfromtxt(file_input)\n ad_m2=ad0[0:5*List_m2.shape[0]];\n ad_m1=ad0[5*List_m2.shape[0]:];\n ''' reshape the error matrixes shape'''\n M20=deformation(ad_m2.ravel(),List_m2,p_m2,q_m2,m2);\n M10=deformation(ad_m1.ravel(),List_m1,p_m1,q_m1,m1);\n x2,y2,dz2_0=reshape_model(M2_size[0],M2_size[1],m2,M20,dy=-1,Num=int(M2_N[0]));\n x1,y1,dz1_0=reshape_model(M1_size[0],M1_size[1],m1,M10,dy=35,Num=int(M1_N[0]));\n #2. panel error from holography fitting\n ad1=np.genfromtxt(file_fitting)[0:5*int((List_m2.size+List_m1.size)/2)];\n ad_m2=ad1[0:5*List_m2.shape[0]]\n ad_m1=ad1[5*List_m2.shape[0]:5*(List_m2.shape[0]+List_m1.shape[0])];\n ''' reshape the error matrixes shape''' \n M20=deformation(ad_m2.ravel(),List_m2,p_m2,q_m2,m2);\n M10=deformation(ad_m1.ravel(),List_m1,p_m1,q_m1,m1);\n x2,y2,dz2_1=reshape_model(M2_size[0],M2_size[1],m2,M20,dy=-1,Num=int(M2_N[0]));\n x1,y1,dz1_1=reshape_model(M1_size[0],M1_size[1],m1,M10,dy=35,Num=int(M1_N[0]));\n \n # 3. calculate the error; \n err2=(dz2_0-dz2_1)*1000;\n err1=(dz1_0-dz1_1)*1000;\n rms2=np.sqrt(np.nanmean(err2**2));\n rms1=np.sqrt(np.nanmean(err1**2));\n \n '''\n 1. input panel error map;\n '''\n colormap(x1,y1,dz1_0*1000,x2,y2,dz2_0*1000,Vmax=inputrms,Vmin=-inputrms,savename='Input_panel_error'+name,suptitle='Panel deformation map');\n '''\n 2. fitting results of the panel error;\n '''\n colormap(x1,y1,dz1_1*1000,x2,y2,dz2_1*1000,Vmax=inputrms,Vmin=-inputrms,savename='fitting_panel_error'+name,suptitle='Fitting results');\n \n '''\n 3. fitting error\n '''\n colormap(x1,y1,err1,x2,y2,err2,Vmax=outputrms,Vmin=-outputrms,savename='fitting_error'+name,suptitle='Error distribution');\n \n '''\n 4. fitting adjuster error cut plots\n '''\n ad_plots((ad1-ad0).ravel()*1000,name,scale=scale);\n \n print(' M2 error:',rms2,'um\\n','M1 error',rms1,'um');\n \n \n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"fitting_error_plot.py","file_name":"fitting_error_plot.py","file_ext":"py","file_size_in_byte":6514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53294733","text":"import logging\nimport os\nimport json_tricks as json\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom scipy.io import loadmat, savemat\n\nfrom dataset.JointsDataset import JointsDataset\n\nlogger = logging.getLogger(__name__)\n\n\nclass CabinDataset(JointsDataset):\n def __init__(self, cfg, root, image_set, is_train, transform=None):\n super().__init__(cfg, root, image_set, is_train, transform)\n\n self.num_joints = 10\n self.flip_pairs = [[2, 9], [3, 8], [4, 7], [5, 6]]\n self.db = self._get_db()\n\n logger.info('=> load {} samples'.format(len(self.db)))\n\n def _get_db(self):\n # create train/val split\n if self.is_train is True:\n file_name = os.path.join(\n self.root, 'annot', 'cabin_train_new.json'\n )\n else :\n file_name = os.path.join(\n self.root, 'annot', 'cabin_test_new.json'\n )\n with open(file_name) as anno_file:\n anno = json.load(anno_file)\n\n gt_db = []\n for a in anno:\n try:\n joints = np.array(a['anno']['data']['point2d'])\n\n image_name = a['image_name']\n # Adjust center/scale slightly to avoid cropping limbs\n # MPII uses matlab format, index is based 1,\n # we should first convert to 0-based index\n\n visible = a['anno']['data']['visible']\n visible = [0 if x == 3 else x for x in visible]\n joints_3d = np.zeros((self.num_joints, 3), dtype=np.float)\n joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float)\n\n if self.image_set != 'test':\n\n joints_vis = np.array(visible)\n assert len(joints) == self.num_joints, \\\n 'joint num diff: {} vs {}'.format(len(joints),\n self.num_joints)\n\n joints_3d[:, 0:2] = joints[:, 0:2]\n joints_3d_vis[:, 0] = joints_vis[:]\n joints_3d_vis[:, 1] = joints_vis[:]\n\n gt_db.append(\n {\n 'image': os.path.join(self.root, 'images', image_name),\n 'joints_3d': joints_3d,\n 'joints_3d_vis': joints_3d_vis,\n 'filename': '',\n 'imgnum': 0,\n }\n )\n except:\n continue\n\n return gt_db\n\n def evaluate(self, cfg, preds, output_dir, *args, **kwargs):\n # convert 0-based index to 1-based index\n preds = preds[:, :, 0:2] + 1.0\n\n if output_dir:\n pred_file = os.path.join(output_dir, 'pred.mat')\n savemat(pred_file, mdict={'preds': preds})\n\n if 'test' in cfg.DATASET.TEST_SET:\n return {'Null': 0.0}, 0.0\n\n SC_BIAS = 0.6\n threshold = 0.5\n\n gt_file = os.path.join(cfg.DATASET.ROOT,\n 'annot',\n 'gt_{}.mat'.format(cfg.DATASET.TEST_SET))\n gt_dict = loadmat(gt_file)\n dataset_joints = gt_dict['dataset_joints']\n jnt_missing = gt_dict['jnt_missing']\n pos_gt_src = gt_dict['pos_gt_src']\n headboxes_src = gt_dict['headboxes_src']\n\n pos_pred_src = np.transpose(preds, [1, 2, 0])\n\n head = np.where(dataset_joints == 'head')[1][0]\n lsho = np.where(dataset_joints == 'lsho')[1][0]\n lelb = np.where(dataset_joints == 'lelb')[1][0]\n lwri = np.where(dataset_joints == 'lwri')[1][0]\n lhip = np.where(dataset_joints == 'lhip')[1][0]\n lkne = np.where(dataset_joints == 'lkne')[1][0]\n lank = np.where(dataset_joints == 'lank')[1][0]\n\n rsho = np.where(dataset_joints == 'rsho')[1][0]\n relb = np.where(dataset_joints == 'relb')[1][0]\n rwri = np.where(dataset_joints == 'rwri')[1][0]\n rkne = np.where(dataset_joints == 'rkne')[1][0]\n rank = np.where(dataset_joints == 'rank')[1][0]\n rhip = np.where(dataset_joints == 'rhip')[1][0]\n\n jnt_visible = 1 - jnt_missing\n uv_error = pos_pred_src - pos_gt_src\n uv_err = np.linalg.norm(uv_error, axis=1)\n headsizes = headboxes_src[1, :, :] - headboxes_src[0, :, :]\n headsizes = np.linalg.norm(headsizes, axis=0)\n headsizes *= SC_BIAS\n scale = np.multiply(headsizes, np.ones((len(uv_err), 1)))\n scaled_uv_err = np.divide(uv_err, scale)\n scaled_uv_err = np.multiply(scaled_uv_err, jnt_visible)\n jnt_count = np.sum(jnt_visible, axis=1)\n less_than_threshold = np.multiply((scaled_uv_err <= threshold),\n jnt_visible)\n PCKh = np.divide(100. * np.sum(less_than_threshold, axis=1), jnt_count)\n\n # save\n rng = np.arange(0, 0.5 + 0.01, 0.01)\n pckAll = np.zeros((len(rng), 16))\n\n for r in range(len(rng)):\n threshold = rng[r]\n less_than_threshold = np.multiply(scaled_uv_err <= threshold,\n jnt_visible)\n pckAll[r, :] = np.divide(100. * np.sum(less_than_threshold, axis=1),\n jnt_count)\n\n PCKh = np.ma.array(PCKh, mask=False)\n PCKh.mask[6:8] = True\n\n jnt_count = np.ma.array(jnt_count, mask=False)\n jnt_count.mask[6:8] = True\n jnt_ratio = jnt_count / np.sum(jnt_count).astype(np.float64)\n\n name_value = [\n ('Head', PCKh[head]),\n ('Shoulder', 0.5 * (PCKh[lsho] + PCKh[rsho])),\n ('Elbow', 0.5 * (PCKh[lelb] + PCKh[relb])),\n ('Wrist', 0.5 * (PCKh[lwri] + PCKh[rwri])),\n ('Hip', 0.5 * (PCKh[lhip] + PCKh[rhip])),\n ('Knee', 0.5 * (PCKh[lkne] + PCKh[rkne])),\n ('Ankle', 0.5 * (PCKh[lank] + PCKh[rank])),\n ('Mean', np.sum(PCKh * jnt_ratio)),\n ('Mean@0.1', np.sum(pckAll[11, :] * jnt_ratio))\n ]\n name_value = OrderedDict(name_value)\n\n return name_value, name_value['Mean']\n","sub_path":"lib/dataset/cabin.py","file_name":"cabin.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"440663090","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of the instrument simulator project\n#\n# Copyright (c) 2018 Tiago Coutinho\n# Distributed under the MIT. See LICENSE for more info.\n\n\"\"\"Instrument Simulator\n\nTo start the server you can do something like::\n\n $ python -m sinstruments -c my_simulator.yml\n\"\"\"\n\nfrom __future__ import print_function\n\nimport io\nimport os\nimport pty\nimport sys\nimport logging\nimport weakref\n\nimport gevent\nfrom gevent.select import select\nfrom gevent.server import StreamServer\nfrom gevent.fileobject import FileObject\n\n\n_log = logging.getLogger(\"simulator\")\n\n__all__ = [\n \"Server\",\n \"BaseDevice\",\n \"SimulatorServerMixin\",\n \"SerialServer\",\n \"TCPServer\",\n \"main\",\n]\n\n\ndef delay(self, nb_bytes, baudrate=None):\n \"\"\"\n Simulate a delay simulating the transport of the given number of bytes,\n correspoding to the baudrate defined in the configuration\n\n Arguments:\n nb_bytes (int): number of bytes to transport\n \"\"\"\n # simulate baudrate\n if not baudrate:\n return\n byterate = baudrate / 10.0\n sleep_time = nb_bytes / byterate\n gevent.sleep(sleep_time)\n\n\nclass BaseHandler:\n\n def __init__(self, fobj, transport):\n self.fobj = fobj\n self.transport = transport\n\n @property\n def device(self):\n return self.transport.device\n\n @property\n def baudrate(self):\n return self.transport.baudrate\n\n\nclass LineHandler(BaseHandler):\n\n @property\n def newline(self):\n return self.transport.newline\n\n @property\n def special_messages(self):\n return self.transport.special_messages\n\n def readlines(self):\n if self.newline == \"\\n\" and not self.special_messages:\n for line in self.fobj:\n yield line\n else:\n # warning: in this mode read will block even if client\n # disconnects. Need to find a better way to handle this\n buff = \"\"\n while True:\n readout = self.fobj.read(1)\n if not readout:\n return\n buff += readout\n if buff in self.special_messages:\n lines = (buff,)\n buff = \"\"\n else:\n lines = buff.split(self.newline)\n buff, lines = lines[-1], lines[:-1]\n for line in lines:\n if line:\n yield line\n\n def handle(self):\n for line in self.readlines():\n self.handle_line(line)\n\n def handle_line(self, line):\n \"\"\"\n Handle a single command line. Simulates a delay if baudrate is defined\n in the configuration.\n\n Arguments:\n line (str): line to be processed\n\n Returns:\n str: response to give to client or None if no response\n \"\"\"\n delay(len(line), self.baudrate)\n response = self.transport.device.handle_line(line)\n if response is not None:\n delay(len(response), self.baudrate)\n self.transport.send(self.fobj, response)\n\n\nclass SimulatorServerMixin(object):\n \"\"\"\n Mixin class for TCP/Serial servers to handle line based commands.\n Internal usage only\n \"\"\"\n\n def __init__(self, device=None, newline=None, baudrate=None, handler=LineHandler):\n self.device = device\n self.baudrate = baudrate\n self.newline = device.newline if newline is None else newline\n self.special_messages = set(device.special_messages)\n name = \"{}[{}]\".format(device.name, self.address)\n self._log = logging.getLogger(\"{0}.{1}\".format(_log.name, name))\n self._log.info(\n \"listening on %s (newline=%r) (baudrate=%s)\",\n self.address,\n self.newline,\n self.baudrate,\n )\n self.handler = handler\n\n def handle(self, fobj):\n h = self.handler(fobj, self)\n try:\n h.handle()\n except Exception as err:\n self._log.info('error handling requests: %r', err)\n\n def broadcast(self, msg):\n raise NotImplementedError\n\n def send(self, fobj, data):\n raise NotImplementedError\n\n\nclass SerialServer(SimulatorServerMixin):\n \"\"\"\n Serial line emulation server. It uses :func:`pty.opentpy` to open a\n pseudo-terminal simulating a serial line.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n device = kwargs.pop(\"device\")\n self.link_name = kwargs.pop(\"url\")\n self.set_listener(kwargs.pop('listener', None))\n SimulatorServerMixin.__init__(self, device, **kwargs)\n\n def stop(self):\n self.close()\n\n def close(self):\n if os.path.islink(self.link_name):\n os.remove(self.link_name)\n if self.master:\n os.close(self.master)\n self.master = None\n if self.slave:\n os.close(self.slave)\n self.slave = None\n\n def set_listener(self, listener):\n if listener is None:\n self.master, self.slave = pty.openpty()\n else:\n self.master, self.slave = listener\n\n self.address = os.ttyname(self.slave)\n self.fileobj = FileObject(self.master, mode='rb')\n\n # Make a link to the randomly named pseudo-terminal with a known name.\n link_path, link_fname = os.path.split(self.link_name)\n try:\n os.remove(self.link_name)\n except:\n pass\n if not os.path.exists(link_path):\n os.makedirs(link_path)\n os.symlink(self.address, self.link_name)\n _log.info('Created symbolic link \"%s\" to simulator pseudo ' \\\n 'terminal \"%s\" ', self.link_name, self.address)\n\n def serve_forever(self):\n self.handle(self.fileobj)\n\n def broadcast(self, msg):\n self.fileobj.write(msg)\n\n def send(self, fobj, data):\n os.write(fobj.fileno(), data)\n\n\nclass TCPServer(StreamServer, SimulatorServerMixin):\n \"\"\"\n TCP emulation server\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.connections = {}\n listener = kwargs.pop(\"url\")\n if isinstance(listener, list):\n listener = tuple(listener)\n device = kwargs.pop(\"device\")\n e_kwargs = dict(\n baudrate=kwargs.pop(\"baudrate\", None),\n newline=kwargs.pop(\"newline\", None)\n )\n StreamServer.__init__(self, listener, *args, **kwargs)\n SimulatorServerMixin.__init__(self, device, **e_kwargs)\n\n def handle(self, sock, addr):\n info = self._log.info\n info(\"new connection from %s\", addr)\n fobj = sock.makefile('rwb', 0)\n self.connections[addr] = sock\n self.device.on_connection(self, sock)\n try:\n SimulatorServerMixin.handle(self, fobj)\n finally:\n del self.connections[addr]\n sock.close()\n info(\"client disconnected %s\", addr)\n\n def broadcast(self, msg):\n for _, sock in self.connections.items():\n try:\n sock.sendall(msg)\n except Exception:\n self._log.exception(\"error in broadcast\")\n\n def send(self, fobj, data):\n fobj.write(data)\n\n\nclass BaseDevice(object):\n \"\"\"\n Base intrument class. Override to implement an Simulator for a specific\n device\n \"\"\"\n\n DEFAULT_NEWLINE = \"\\n\"\n\n special_messages = set()\n\n def __init__(self, name, newline=None, **kwargs):\n self.name = name\n self.newline = self.DEFAULT_NEWLINE if newline is None else newline\n self._log = logging.getLogger(\"{0}.{1}\".format(_log.name, name))\n self.__transports = weakref.WeakKeyDictionary()\n if kwargs:\n self._log.warning(\n \"constructor keyword args ignored: %s\", \", \".join(kwargs.keys())\n )\n\n @property\n def transports(self):\n \"\"\"the list of registered transports\"\"\"\n return self.__transports.keys()\n\n @transports.setter\n def transports(self, transports):\n self.__transports.clear()\n for transport in transports:\n self.__transports[transport] = None\n\n def on_connection(self, transport, conn):\n pass\n\n def handle_line(self, line):\n \"\"\"\n To be implemented by the device.\n\n Raises: NotImplementedError\n \"\"\"\n raise NotImplementedError\n\n def broadcast(self, msg):\n \"\"\"\n broadcast the given message to all the transports\n\n Arguments:\n msg (str): message to be broadcasted\n \"\"\"\n for transport in self.transports:\n transport.broadcast(msg)\n\n\nclass Server(object):\n \"\"\"\n The instrument simulator server\n\n Handles a set of devices\n \"\"\"\n\n def __init__(self, devices=(), backdoor=None):\n self._log = _log\n self._log.info(\"Bootstraping server\")\n if backdoor:\n from gevent.backdoor import BackdoorServer\n\n banner = (\n \"Welcome to Simulator server console.\\n\"\n \"You can access me through the \"\n \"'server()' function. Have fun!\"\n )\n self.backdoor = BackdoorServer(\n backdoor, banner=banner, locals=dict(server=weakref.ref(self))\n )\n self.backdoor.start()\n self._log.info(\"Backdoor opened at %r\", backdoor)\n\n else:\n self._log.info(\"no backdoor declared\")\n\n self.devices = {}\n for device in devices:\n try:\n self.create_device(device)\n except Exception as error:\n dname = device.get(\"name\", device.get(\"class\", \"unknown\"))\n self._log.error(\n \"error creating device %s (will not be available): %s\", dname, error\n )\n self._log.debug(\"details: %s\", error, exc_info=1)\n\n def create_device(self, device_info):\n klass_name = device_info.get(\"class\")\n name = device_info.get(\"name\", klass_name)\n self._log.info(\"Creating device %s (%r)\", name, klass_name)\n device, transports = create_device(device_info)\n self.devices[device] = transports\n return device, transports\n\n def get_device_by_name(self, name):\n for device in self.devices:\n if device.name == name:\n return device\n\n def start(self):\n tasks = []\n for device in self.devices:\n for interface in self.devices[device]:\n tasks.append(gevent.spawn(interface.serve_forever))\n return tasks\n\n def stop(self):\n for device in self.devices:\n for transport in self.devices[device]:\n transport.stop()\n\n def serve_forever(self):\n tasks = self.start()\n try:\n gevent.joinall(tasks)\n finally:\n self.stop()\n\n def __str__(self):\n return \"{0}({1})\".format(self.__class__.__name__, self.name)\n\n\ndef create_device(device_info):\n device_info = dict(device_info)\n class_name = device_info.pop(\"class\")\n module_name = device_info.pop(\"module\", class_name.lower())\n package_name = device_info.pop(\"package\", None)\n name = device_info.pop(\"name\", class_name)\n\n if package_name is None:\n package_name = \"sinstruments.simulators.\" + module_name\n\n __import__(package_name)\n package = sys.modules[package_name]\n klass = getattr(package, class_name)\n device = klass(name, **device_info)\n\n transports_info = device_info.pop(\"transports\", ())\n transports = []\n for interface_info in transports_info:\n ikwargs = dict(interface_info)\n itype = ikwargs.pop(\"type\", \"tcp\")\n if itype == \"tcp\":\n iklass = TCPServer\n elif itype == \"serial\":\n iklass = SerialServer\n ikwargs[\"device\"] = device\n transports.append(iklass(**ikwargs))\n device.transports = transports\n return device, transports\n\n\ndef parse_config_file(file_name):\n parsers = {\n '.yml': 'yaml',\n '.yaml': 'yaml',\n '.json': 'json',\n '.toml': 'toml',\n }\n ext = os.path.splitext(file_name)[-1]\n parser = __import__(parsers[ext])\n with open(file_name, 'r') as config_file:\n return parser.load(config_file)\n\n\ndef create_server_from_config(config):\n backdoor, devices = config.get(\"backdoor\", None), config.get(\"devices\", ())\n return Server(devices=devices, backdoor=backdoor)\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(description=__doc__.split(\"\\n\")[1])\n parser.add_argument(\n \"--log-level\",\n default=\"WARNING\",\n help=\"log level\",\n choices=[\"CRITICAL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\"],\n )\n parser.add_argument(\n \"-c\", \"--config-file\", default='./sinstruments.yml',\n help=\"configuration file\",\n )\n args = parser.parse_args()\n\n fmt = \"%(asctime)-15s %(levelname)-5s %(name)s: %(message)s\"\n level = getattr(logging, args.log_level.upper())\n logging.basicConfig(format=fmt, level=level)\n config = parse_config_file(args.config_file)\n server = create_server_from_config(config)\n\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n print(\"\\nCtrl-C Pressed. Bailing out...\")\n try:\n server.stop()\n except Exception:\n logging.exception(\"Error while stopping.\")\n return 1\n\n\nif __name__ == \"__main__\":\n exit(main())\n","sub_path":"sinstruments/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":13407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"307558183","text":"saleprice = int(input(\"Enter the price of the sale.\"))\nproductprice = int(input(\"Enter the price of the product.\"))\nif saleprice>productprice :\n profit = saleprice - productprice\n Ppercent = profit/productprice*100\n print(f'The profit from this purchase was {profit} and the % gained is {Ppercent}')\nelif saleprice == productprice :\n print(\"There was no profit or loss from this purchase.\")\nelif saleprice str:\n \"\"\"Generates the default user agent.\n\n Args:\n name: Base name.\n proxy: Proxy type.\n\n Returns:\n User agent in format of ``{name}/{darc.__version__} ({proxy} Proxy)``.\n\n \"\"\"\n from darc import __version__ # pylint: disable=import-outside-toplevel\n\n if proxy is None:\n ua = f'{name}/{__version__}'\n else:\n ua = f'{name}/{__version__} ({proxy} Proxy)'\n return ua\n\n\ndef request_session(link: 'darc_link.Link', futures: bool = False) -> 'Union[Session, FuturesSession]':\n \"\"\"Get requests session.\n\n Args:\n link: Link requesting for requests.Session.\n futures: If returns a :class:`requests_futures.FuturesSession`.\n\n Returns:\n Union[requests.Session, requests_futures.FuturesSession]:\n The session object with corresponding proxy settings.\n\n Raises:\n :exc:`UnsupportedLink`: If the proxy type of ``link``\n if not specified in the :data:`~darc.proxy.LINK_MAP`.\n\n See Also:\n * :data:`darc.proxy.LINK_MAP`\n\n \"\"\"\n from darc.proxy import LINK_MAP # pylint: disable=import-outside-toplevel\n\n factory, _ = LINK_MAP[link.proxy]\n if factory is None:\n raise UnsupportedLink(link.url)\n\n return factory(futures=futures) # type: ignore\n\n\ndef i2p_session(futures: bool = False) -> 'Union[Session, FuturesSession]':\n \"\"\"I2P (.i2p) session.\n\n Args:\n futures: If returns a :class:`requests_futures.FuturesSession`.\n\n Returns:\n Union[requests.Session, requests_futures.FuturesSession]:\n The session object with I2P proxy settings.\n\n See Also:\n * :data:`darc.proxy.i2p.I2P_REQUESTS_PROXY`\n\n \"\"\"\n if futures:\n session = requests_futures_sessions.FuturesSession(max_workers=DARC_CPU)\n else:\n session = requests.Session()\n\n session.headers['User-Agent'] = default_user_agent(proxy='I2P')\n session.proxies.update(I2P_REQUESTS_PROXY)\n return session\n\n\ndef tor_session(futures: bool = False) -> 'Union[Session, FuturesSession]':\n \"\"\"Tor (.onion) session.\n\n Args:\n futures: If returns a :class:`requests_futures.FuturesSession`.\n\n Returns:\n Union[requests.Session, requests_futures.FuturesSession]:\n The session object with Tor proxy settings.\n\n See Also:\n * :data:`darc.proxy.tor.TOR_REQUESTS_PROXY`\n\n \"\"\"\n if futures:\n session = requests_futures_sessions.FuturesSession(max_workers=DARC_CPU)\n else:\n session = requests.Session()\n\n session.headers['User-Agent'] = default_user_agent(proxy='Tor')\n session.proxies.update(TOR_REQUESTS_PROXY)\n return session\n\n\ndef null_session(futures: bool = False) -> 'Union[Session, FuturesSession]':\n \"\"\"No proxy session.\n\n Args:\n futures: If returns a :class:`requests_futures.FuturesSession`.\n\n Returns:\n Union[requests.Session, requests_futures.FuturesSession]:\n The session object with no proxy settings.\n\n \"\"\"\n if futures:\n session = requests_futures_sessions.FuturesSession(max_workers=DARC_CPU)\n else:\n session = requests.Session()\n\n session.headers['User-Agent'] = default_user_agent()\n return session\n","sub_path":"darc/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"322197876","text":"import pygame, sys\nfrom pygame import *\n\nWINDOWWIDTH = 500\nWINDOWHEIGHT = 500\nRED = (255, 0, 0)\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nGREEN = (0, 255, 0)\nYELLOW = (255, 255, 0)\nBLACK = (255, 255, 255)\n\nclass Screen(object):\n\t\t\n\tdef open(self):\n\t\tpass\n\t\t\nclass Engine(object):\n\tdef __init__(self, display):\n\t\tself.display = display\n\t\t\n\t\t\n\tdef run(self):\n\t\tDISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)\n\t\tpygame.display.set_caption(\"Drawing\")\n\t\tpygame.init()\n\t\tcurrent_screen = self.display.opening_screen()\n\t\twhile True:\n\t\t\tDISPLAYSURF.fill(WHITE)\n\t\t\tcurrent_screen.open()\n\t\t\tCOLOR = current_screen.color\n\t\t\tpygame.draw.rect(DISPLAYSURF, COLOR, (200, 50, 100, 50))\n\t\t\t\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):\n\t\t\t\t\tpygame.quit()\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == KEYUP and event.key == K_g:\n\t\t\t\t\tname = current_screen.next_screen_name\n\t\t\t\t\tcurrent_screen = self.display.next_screen(name)\n\t\t\tpygame.display.update()\n\t\t\t\nclass OpeningScreen(Screen):\n\tdef open(self):\t\n\t\tself.name = \"Opening Screen\"\n\t\tself.color = RED\n\t\tself.next_screen_name = \"screen1\"\n\t\nclass ScreenOne(Screen):\n\tdef open(self):\n\t\tself.name = \"Screen One\"\n\t\tself.color = BLUE\n\t\tself.next_screen_name = \"screen2\"\n\t\nclass ScreenTwo(Screen):\n\tdef open(self):\n\t\tself.name = \"Screen Two\"\n\t\tself.color = GREEN\n\t\tself.next_screen_name = \"screen3\"\n\t\nclass ScreenThree(Screen):\n\tdef open(self):\n\t\tself.name = \"Screen Three\"\n\t\tself.color = YELLOW\n\t\tself.next_screen_name = \"closing screen\"\n\t\nclass ClosingScreen(Screen):\n\tdef open(self):\n\t\tself.name = \"Closing Screen\"\n\t\tself.color = BLACK\n\t\tself.next_screen_name = pygame.quit(), sys.exit()\n\t\t\t\t\t\n\t\n\t\t\n\t\nclass Display(object):\n\t\n\tscreens = {\n\t\t\"opening screen\" : OpeningScreen(),\n\t\t\"screen1\" : ScreenOne(),\n\t\t\"screen2\" : ScreenTwo(),\n\t\t\"screen3\" : ScreenThree(),\n\t\t\"closing screen\" : ClosingScreen(),\n\t}\n\t\n\tdef __init__(self, start_screen):\n\t\tself.start_screen = start_screen\n\t\t\n\tdef opening_screen(self):\n\t\treturn self.next_screen(self.start_screen)\n\t\t\n\tdef next_screen(self, next_screen_name):\n\t\tval = self.screens.get(next_screen_name)\n\t\treturn val\n\na_display = Display(\"opening screen\")\na_game = Engine(a_display)\na_game.run()","sub_path":"screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260063841","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nclass Extension(models.Model): \n _name = \"hc.extension\" \n _description = \"Extension\"\n\n url = fields.Char(\n string=\"URI\", \n required=\"True\", \n help=\"URI that identifies the meaning of the extension.\")\n value_type = fields.Selection(\n string=\"Value Type\", \n selection=[\n (\"integer\", \"Integer\"), \n (\"unsigned_int\", \"Unsigned Int\"),\n (\"positive_int\", \"Positive Int\"), \n (\"decimal\", \"Decimal\"),\n (\"date_time\", \"Datetime\"),\n (\"date\", \"Date\"),\n (\"time\", \"Time\"),\n (\"instant\", \"Instant\"),\n (\"string\", \"String\"),\n (\"uri\", \"URI\"),\n (\"oid\", \"OID\"),\n (\"uuid\", \"UUID\"),\n (\"id\", \"ID\"),\n (\"boolean\", \"Boolean\"),\n (\"code\", \"Code\"),\n (\"markdown\", \"Markdown\"),\n (\"base_64_binary\", \"Base 64 Binary\"),\n (\"coding\", \"Coding\"),\n (\"codeable_concept\", \"Codeable Concept\"), \n (\"attachment\", \"Attachment\"),\n (\"identifier\", \"Identifier\"),\n (\"quantity\", \"Quantity\"),\n (\"sample_data\", \"Sample Data\"),\n (\"range\", \"Range\"),\n (\"period\", \"Period\"),\n (\"ratio\", \"Ratio\"), \n (\"human_name\", \"Human Name\"),\n (\"address\", \"Address\"),\n (\"contact_point\", \"Contact Point\"),\n (\"timing\", \"Timing\"),\n (\"Reference\", \"Reference\"),\n (\"annotation\", \"Annotation\"),\n (\"signature\", \"Signature\"),\n (\"meta\", \"Meta\")],\n help=\"Type of value of extension.\")\n value_name = fields.Char(\n string=\"Value\", \n compute=\"_compute_value_name\", \n store=\"True\", \n help=\"Value of extension.\")\n value_integer = fields.Integer(\n string=\"Value Integer\", \n help=\"Integer value of extension.\")\n value_unsigned_int = fields.Integer(\n string=\"Value Unsigned Integer\", \n help=\"Unsigned Integer value of extension.\")\n value_positive_int = fields.Integer(\n string=\"Value Positive Integer\", \n help=\"Positive Integer value of extension.\")\n value_decimal = fields.Float(\n string=\"Value Decimal\", \n help=\"Decimal value of extension.\")\n value_date_time = fields.Datetime(\n string=\"Value Date Time\", \n help=\"Date Time value of extension.\")\n value_date = fields.Date(\n string=\"Value Date\", \n help=\"Date value of extension.\")\n value_instant = fields.Datetime(\n string=\"Value Instant\", \n help=\"Instant value of extension.\")\n value_string = fields.Char(\n string=\"Value String\", \n help=\"String value of extension.\")\n value_uri = fields.Char(\n string=\"Value URI\", \n help=\"URI value of extension.\")\n value_oid = fields.Char(\n string=\"Value OID\", \n help=\"OID value of extension.\")\n value_uuid = fields.Char(\n string=\"Value UUUID\", \n help=\"UUUID value of extension.\")\n value_id = fields.Char(\n string=\"Value Id\", \n help=\"Id value of extension.\")\n value_boolean = fields.Boolean(\n string=\"Value Boolean\", \n help=\"Boolean value of extension.\")\n value_code_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.code\", \n string=\"Value Code\", \n help=\"Code value of extension.\")\n value_markdown = fields.Text(\n string=\"Value Markdown\", \n help=\"Markdown value of extension.\")\n value_base_64_binary = fields.Binary(\n string=\"Value Base 64 Binary\", \n help=\"Base 64 Binary value of extension.\")\n value_coding_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.coding\", \n string=\"Value Coding\", \n help=\"Coding value of extension.\")\n value_codeable_concept_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.codeable.concept\", \n string=\"Value Codeable Concept\", \n help=\"Codeable Concept value of extension.\")\n value_attachment_id = fields.Many2one(\n comodel_name=\"hc.extension.attachment\", \n string=\"Value Attachment\", \n help=\"Attachment value of extension.\")\n value_identifier_id = fields.Many2one(\n comodel_name=\"hc.extension.identifier\", \n string=\"Value Identifier\", \n help=\"Identifier value of extension.\")\n value_quantity = fields.Float(\n string=\"Value Quantity\", \n help=\"Quantity value of extension.\")\n value_quantity_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Quantity UOM\", \n help=\"Quantity unit of measure.\")\n value_sampled_data = fields.Many2one(\n comodel_name=\"hc.extension.sampled.data\", \n string=\"Value Sampled Data\", \n help=\"Sampled Data value of extension.\")\n value_range_low = fields.Float(\n string=\"Value Range Low\", \n help=\"Low limit of range value of extension.\")\n value_range_high = fields.Float(\n string=\"Value Range High\", \n help=\"High limit of range value of extension.\")\n value_range_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Range UOM\", \n help=\"Range unit of measure.\")\n value_period_start_date = fields.Datetime(\n string=\"Value Period Start Date\", \n help=\"Start of the period for value of extension.\")\n value_period_end_date = fields.Datetime(\n string=\"Value Period End Date\", \n help=\"End of the period for value of extension.\")\n value_period_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Period UOM\", \n help=\"Period unit of measure.\")\n value_ratio_numerator = fields.Float(\n string=\"Value Ratio Numerator\", \n help=\"Ratio value of extension.\")\n value_ratio_numerator_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Ratio Numerator UOM\", \n help=\"Ratio unit of measure.\")\n value_denominator = fields.Float(\n string=\"Value Denominator\", \n help=\"Ratio value of extension.\")\n value_denominator_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Denominator UOM\", \n help=\"Ratio unit of measure.\")\n value_ratio = fields.Float(\n string=\"Value Ratio\", \n compute=\"_compute_value_ratio\", \n store=\"True\", \n help=\"Ratio value of extension.\")\n value_ratio_uom_id = fields.Many2one(\n comodel_name=\"product.uom\", \n string=\"Value Ratio UOM\", \n help=\"Ratio unit of measure.\")\n value_human_name_id = fields.Many2one(\n comodel_name=\"hc.extension.human.name\", \n string=\"Value Human Name\", \n help=\"Human Name value of extension.\")\n value_address_id = fields.Many2one(\n comodel_name=\"hc.extension.address\", \n string=\"Value Address\", \n help=\"Address value of extension.\")\n value_contact_point_id = fields.Many2one(\n comodel_name=\"hc.extension.telecom\", \n string=\"Value Contact Point\", \n help=\"Contact Point (Telecom) value of extension.\")\n value_timing_id = fields.Many2one(\n comodel_name=\"hc.extension.timing\", \n string=\"Value Timing\", \n help=\"Timing value of extension.\")\n value_reference_id = fields.Many2one(\n comodel_name=\"hc.extension.reference\", \n string=\"Value Reference\", \n help=\"Reference value of extension.\")\n value_annotation_id = fields.Many2one(\n comodel_name=\"hc.extension.annotation\", \n string=\"Value Annotation\", \n help=\"Annotation value of extension.\")\n value_signature_id = fields.Many2one(\n comodel_name=\"hc.extension.signature\", \n string=\"Value Signature\", \n help=\"Signature value of extension.\")\n value_meta_id = fields.Many2one(\n comodel_name=\"hc.extension.meta\", \n string=\"Value Meta\", \n help=\"Meta value of extension.\")\n\nclass ExtensionAttachment(models.Model): \n _name = \"hc.extension.attachment\" \n _description = \"Extension Attachment\" \n _inherit = [\"hc.basic.association\", \"hc.attachment\"] \n\nclass ExtensionIdentifier(models.Model): \n _name = \"hc.extension.identifier\" \n _description = \"Extension Identifier\" \n _inherit = [\"hc.basic.association\", \"hc.identifier\"] \n\nclass ExtensionSampledData(models.Model): \n _name = \"hc.extension.sampled.data\" \n _description = \"Extension Sampled Data\" \n _inherit = [\"hc.basic.association\", \"hc.sampled.data\"] \n\nclass ExtensionHumanName(models.Model): \n _name = \"hc.extension.human.name\" \n _description = \"Extension Human Name\" \n _inherit = [\"hc.human.name.use\"] \n _inherits = {\"hc.human.name\": \"name_id\"}\n\n name_id = fields.Many2one(\n comodel_name=\"hc.human.name\", \n string=\"Name\", \n ondelete=\"restrict\", \n required=\"True\", \n help=\"Name associated with this Extension Human Name.\") \n \nclass ExtensionAddress(models.Model): \n _name = \"hc.extension.address\" \n _description = \"Extension Address\" \n _inherit = [\"hc.address.use\"] \n _inherits = {\"hc.address\": \"address_id\"}\n\n address_id = fields.Many2one(\n comodel_name=\"hc.address\", \n string=\"Address\", \n ondelete=\"restrict\", \n required=\"True\", \n help=\"Address associated with this Extension Address.\") \n \nclass ExtensionTelecom(models.Model): \n _name = \"hc.extension.telecom\" \n _description = \"Extension Telecom\" \n _inherit = [\"hc.contact.point.use\"] \n _inherits = {\"hc.contact.point\": \"telecom_id\"}\n\n telecom_id = fields.Many2one(\n comodel_name=\"hc.contact.point\", \n string=\"Telecom\", \n ondelete=\"restrict\", \n required=\"True\", \n help=\"Telecom associated with this Extension Telecom.\") \n\nclass ExtensionTiming(models.Model): \n _name = \"hc.extension.timing\" \n _description = \"Extension Timing\" \n _inherit = [\"hc.basic.association\", \"hc.timing\"] \n\nclass ExtensionReference(models.Model): \n _name = \"hc.extension.reference\" \n _description = \"Extension Reference\" \n _inherit = [\"hc.basic.association\", \"hc.reference\"] \n\nclass ExtensionAnnotation(models.Model): \n _name = \"hc.extension.annotation\" \n _description = \"Extension Annotation\" \n _inherit = [\"hc.basic.association\", \"hc.annotation\"] \n\nclass ExtensionSignature(models.Model): \n _name = \"hc.extension.signature\" \n _description = \"Extension Signature\" \n _inherit = [\"hc.basic.association\", \"hc.signature\"] \n\nclass ExtensionMeta(models.Model): \n _name = \"hc.extension.meta\" \n _description = \"Extension Meta\" \n _inherit = [\"hc.basic.association\", \"hc.meta\"] \n\nclass ExtensionCoding(models.Model): \n _name = \"hc.vs.extension.coding\" \n _description = \"Extension Coding\" \n _inherit = [\"hc.value.set.contains\"] \n\nclass ExtensionCodeableConcept(models.Model): \n _name = \"hc.vs.extension.codeable.concept\" \n _description = \"Extension Codeable Concept\" \n _inherit = [\"hc.value.set.contains\"] \n\nclass ExtensionCode(models.Model): \n _name = \"hc.vs.extension.code\" \n _description = \"Extension Code\"\n _inherit = [\"hc.value.set.contains\"]\n\n name = fields.Char(\n string=\"Name\", \n help=\"Name of this extension code.\") \n code = fields.Char(\n string=\"Code\", \n help=\"Code of this extension code.\") \n contains_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.code\", \n string=\"Contains\", \n help=\"Parent extension code.\")\n\nclass ExtensionCoding(models.Model): \n _name = \"hc.vs.extension.coding\" \n _description = \"Extension Coding\"\n _inherit = [\"hc.value.set.contains\"]\n\n name = fields.Char(\n string=\"Name\", \n help=\"Name of this extension coding.\") \n code = fields.Char(\n string=\"Code\", \n help=\"Code of this extension coding.\") \n contains_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.coding\", \n string=\"Contains\", \n help=\"Parent extension coding.\") \n\nclass ExtensionCodeableConcept(models.Model): \n _name = \"hc.vs.extension.codeable.concept\" \n _description = \"Extension Codeable Concept\"\n _inherit = [\"hc.value.set.contains\"]\n\n name = fields.Char(\n string=\"Name\", \n help=\"Name of this extension codeable concept.\") \n code = fields.Char(\n string=\"Code\", \n help=\"Code of this extension codeable concept.\") \n contains_id = fields.Many2one(\n comodel_name=\"hc.vs.extension.codeable.concept\", \n string=\"Contains\", \n help=\"Parent extension codeable concept.\") \n\n\n\n","sub_path":"addons/hc_base/models/hc_extension.py","file_name":"hc_extension.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250633933","text":"import csv\n\n# Method 1 way of opening and reading the csv using csv.DictReader\nwith open('files/mpg.csv') as csv_file:\n mpg = list(csv.DictReader(csv_file)) \nprint(mpg[:2], '\\n')\n\n# Method 2 way of opening and reading the csv using csv.DictReader\nfile = open('files/mpg.csv')\nfile_content = list(csv.DictReader(file))\nprint(file_content[:2], '\\n')\n\n# Show the number of rows in the csv, minus the heading row\nprint(len(file_content), '\\n')\n\n# Show the column headers\nprint(file_content[0].keys(), '\\n')\n\n# Find the average mpg\nprint(sum(float(d['mpg']) for d in file_content) / len(file_content), '\\n')\n\n# Find the average weight of vehicles\nprint(sum(float(d['weight']) for d in file_content) / len(file_content), '\\n')\n\n# Using set to return all the unique number of cylinders of the cars\ncylinders = set(d['cylinders'] for d in file_content)\nprint(cylinders, '\\n')\n\n# find the average mpg grouped by the number of cylinders\nmpg_by_cylinders = []\nfor c in cylinders: # iterate over all the cylinder levels\n sum_mpg = 0\n cylinders_type_count = 0\n for d in file_content: # iterate over all dictionaries\n if d['cylinders'] == c: # if the cylinder level type matches,\n sum_mpg += float(d['mpg']) # add the mpg\n cylinders_type_count += 1 # increment the count\n mpg_by_cylinders.append((c, sum_mpg / cylinders_type_count)) # append the tuple ('cylinder', 'avg mpg')\n\n\nmpg_by_cylinders.sort(key=lambda x: x[0])\nprint(mpg_by_cylinders, '\\n')\n\n# Using set to return all the unique year numbers of the cars\nvehicle_year = set(d['model_year'] for d in file_content) # what are the year models in the data set\nprint(vehicle_year, '\\n')\n\n\n# find the average mpg grouped by the year\nmpg_by_year = []\nfor y in vehicle_year: # iterate over all the vehicle years\n sum_mpg = 0\n vehicle_years_count = 0\n for d in file_content: # iterate over all dictionaries\n if d['model_year'] == y: # if the year model type matches,\n sum_mpg += float(d['mpg']) # add the mpg\n vehicle_years_count += 1 # increment the count\n mpg_by_year.append((y, sum_mpg / vehicle_years_count)) # append the tuple ('model_year', 'avg mpg')\n\n \nmpg_by_year.sort(key=lambda x: x[1])\nprint(mpg_by_year, '\\n')","sub_path":"files_csv/files_csv.py","file_name":"files_csv.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20660920","text":"from spockbot import Client\nfrom spockbot.plugins import default_plugins as plugins\nfrom bat import bat, command, curses\n\nplugins.extend([\n ('bat', bat.BatPlugin),\n ('commands', command.CommandPlugin),\n ('curses', curses.CursesPlugin),\n])\n\n# login_credentials should contain a dict with 'username' and 'password'\n#from login_credentials import settings\nsettings = {\n 'start': { 'username': 'Bat', },\n 'auth': { 'authenticated': False, },\n}\nclient = Client(plugins=plugins, start=settings)\n\nclient.start('localhost', 25565)\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45919398","text":"from models.base import BaseModel\n\nclass Links():\n\n def __init__(self):\n\n self.previous = \"\"\n self.current = \"\"\n self.following = \"\"\n\n def setLinks(self,request, recordNumber):\n\n self._getPagination(request,recordNumber)\n\n def _getVisibleFields(self):\n\n visibles = []\n\n if self.following:\n visibles.append('following')\n if self.previous:\n visibles.append('previous')\n \n visibles.append('current')\n\n return tuple(visibles)\n\n def _getPagination(self,request, recordNumber):\n\n parameter = request.query.decode()\n\n completeURL = str(request.url)\n completeURL = completeURL.replace(\"%2C\", ',')\n\n currentURL = \"\"\n previousURL = \"\"\n forwardURL = \"\"\n\n if not parameter.get('pagesize', False):\n\n if not (recordNumber < 5):\n\n forwardURL = completeURL + \"&pagesize=5\" + \"&continuetoken=2\"\n\n else:\n\n pagesize = int(parameter.get('pagesize'))\n currentURL = completeURL\n\n if not parameter.get('continuetoken', False):\n\n if not (recordNumber < pagesize):\n forwardURL = completeURL + \"&continuetoken=2\"\n\n else:\n \n tokenValue = int(parameter.get('continuetoken', False))\n\n previous = tokenValue - 1\n forward = tokenValue + 1\n\n if previous > 0:\n previousURL = completeURL.replace(\n \"continuetoken=\" + str(tokenValue), \"continuetoken=\" + str(previous))\n \n print(\"Entre en el previous\")\n print(previousURL)\n\n if not (recordNumber < pagesize):\n \n forwardURL = completeURL.replace(\n \"continuetoken=\" + str(tokenValue), \"continuetoken=\" + str(forward))\n\n self.current = currentURL\n self.previous = previousURL\n self.following = forwardURL\n\n \n\n\n","sub_path":"models/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365290275","text":"# -*- coding:utf-8 -*-\n\"\"\"\n 进度报告模块(暂时只报告时间)\n\"\"\"\n\nimport time as _time\nfrom threading import Thread\nimport global_variable as _gv\nfrom cyberlib_log_stdout import StdOutLog\n\nLOG_LEVEL = _gv.GLOBAL_LOG_LEVEL['progress_reporter']\n\nclass ProgressReporter(Thread):\n \"\"\"\n\n \"\"\"\n def __init__(self, ms_manager=None):\n \"\"\"ProgressReporter 类的构造方法\n\n :param ms_manager: MultiScanManager instance if the param is not None\n :type ms_manager: MultiScanManager or None\n :return:\n \"\"\"\n Thread.__init__(self)\n self.logger = StdOutLog(LOG_LEVEL)\n\n self.ms_manager = ms_manager\n\n self.is_continue = True\n # reference time\n self.zero_t = _time.mktime(_time.strptime(\"00:00:00\",\"%H:%M:%S\"))\n # start time\n self.start_time = _time.time()\n\n def run(self):\n while self.is_continue:\n current_time = _time.time()\n time_cost = self.zero_t + current_time - self.start_time\n self.logger.info('Status {0}'.format(_time.strftime('%H:%M:%S', _time.localtime(time_cost))), \"[ProgressReporter]\")\n\n _time.sleep(2)\n\n def stop(self):\n self.is_continue = False\n","sub_path":"DeviceRecognition/progress_reporter/progress_reporter.py","file_name":"progress_reporter.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"262263774","text":"# import math\n# print(math.sqrt(16))\n# print(dir(math))\n\nfrom functools import wraps\n\ndef beg(target_function):\n @wraps(target_function)\n def wrapper(*args,**kwargs):\n msg, say_please=target_function(*args, **kwargs)\n if say_please:\n return \"{} {}\".format(msg,\"Please! I am poor :()\")\n return msg\n\n return wrapper\n\n@beg\ndef say(say_please=False):\n msg = \"Can you buy me a milk?\"\n return msg, say_please\n\nprint(say())\nprint(say(say_please=True))\nprint(say(True))\n","sub_path":"day3python.py","file_name":"day3python.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53533259","text":"# Director\r\nfrom tkinter import *\r\nimport tkinter.messagebox\r\nimport Project_backend\r\n\r\nclass Director:\r\n def __init__(self, root):\r\n root = Tk()\r\n root.title(\"Director window\")\r\n root.geometry(\"3000x850+0+0\")\r\n root.resizable(True, True)\r\n root.config(bg=\"white\")\r\n \r\n Movie_ID = StringVar(root)\r\n Director_name =StringVar(root)\r\n DOB=StringVar(root)\r\n\r\n # Fuctions\r\n\r\n def clcdata():\r\n self.txtMovie_ID.delete(0, END)\r\n self.txtDirector_name.delete(0, END)\r\n self.txtDOB.delete(0, END)\r\n \r\n def adddata():\r\n x=Project_backend.check_movieid(Movie_ID.get())\r\n if(len(Movie_ID.get()) != 0 and x == 0):\r\n Project_backend.AddDirectorData(Movie_ID.get(), Director_name.get(), DOB.get())\r\n searchdb()\r\n else:\r\n clcdata()\r\n messagebox.showerror(\"Error\",\"Movie id not exists!\")\r\n \r\n def disdata():\r\n clcdata()\r\n MovieList.delete(0, END)\r\n for row in Project_backend.ViewDirectorData():\r\n s0=\"Movie_id :- \"+str(row[0])\r\n s1=\" Director_name : \"+str(row[1])\r\n s2=\" DOB : \"+str(row[2])\r\n\r\n MovieList.insert(END, str(s0), str(\"\"))\r\n MovieList.insert(END, str(s1))\r\n MovieList.insert(END, str(s2), str(\"\"))\r\n\r\n MovieList.insert(END, str(\"---------------------------------------------------------------------------------------------------------------\"), str(\"\"))\r\n i=0\r\n j=5\r\n for row in Project_backend.ViewDirectorData():\r\n MovieList.itemconfig(i, {'fg': '#a4ebf3'})\r\n MovieList.itemconfig(j, {'fg': '#eff48e'})\r\n i=i+7\r\n j=j+7\r\n\r\n def movierec(event):\r\n global sd\r\n searchmovie = MovieList.curselection()[0]\r\n sd = MovieList.get(searchmovie)\r\n\r\n self.txtMovie_ID.delete(0, END)\r\n self.txtMovie_ID.insert(END, sd[12])\r\n\r\n row=Project_backend.SearchDirectorData(sd[12])\r\n self.txtDirector_name.delete(0, END)\r\n self.txtDirector_name.insert(END, row[0][1])\r\n self.txtDOB.delete(0, END)\r\n self.txtDOB.insert(END, row[0][2])\r\n\r\n def searchdb():\r\n MovieList.delete(0, END)\r\n for row in Project_backend.SearchDirectorData(Movie_ID.get()):\r\n s0=\"Movie_id :- \"+str(row[0])\r\n s1=\" Director_Name : \"+str(row[1])\r\n s2=\" DOB : \"+str(row[2])\r\n\r\n MovieList.insert(END, str(s0), str(\"\"))\r\n MovieList.insert(END, str(s1))\r\n MovieList.insert(END, str(s2),str(\"\"))\r\n \r\n MovieList.insert(END, str(\"---------------------------------------------------------------------------------------------------------------\"), str(\"\"))\r\n\r\n i=0\r\n j=5\r\n for row in Project_backend.ViewDirectorData():\r\n MovieList.itemconfig(i, {'fg': '#a4ebf3'})\r\n MovieList.itemconfig(j, {'fg': '#eff48e'})\r\n i=i+7\r\n j=j+7\r\n \r\n def deldata():\r\n if(len(Movie_ID.get()) != 0):\r\n Project_backend.DeleteDirectorData(sd[12])\r\n clcdata()\r\n disdata()\r\n\r\n def updata():\r\n if(len(Movie_ID.get()) != 0):\r\n Project_backend.DeleteDirectorData(sd[12])\r\n if(len(Movie_ID.get()) != 0):\r\n Project_backend.AddDirectorData(Movie_ID.get(), Director_name.get(), DOB.get())\r\n searchdb()\r\n\r\n #Frames\r\n MainFrame = Frame(root, bg=\"#28282A\")\r\n MainFrame.grid()\r\n\r\n TFrame = Frame(MainFrame, bd=5, padx=54, pady=10,bg=\"#28282A\", relief=RIDGE)\r\n TFrame.pack(side=TOP)\r\n\r\n self.TFrame = Label(TFrame, font=('Arial', 51, 'bold'),text=\" DIRECTOR \", bg=\"#28282A\", fg=\"#a4ebf3\")\r\n self.TFrame.grid() \r\n\r\n BFrame = Frame(MainFrame, bd=0, width=1350, height=70,padx=112, pady=10, bg=\"#28282A\", relief=RIDGE)\r\n BFrame.pack(side=BOTTOM)\r\n\r\n DFrame = Frame(MainFrame, bd=0, width=1300, height=400,padx=120, pady=20, bg=\"#28282A\", relief=RIDGE)\r\n DFrame.pack(side=BOTTOM)\r\n\r\n DFrameL = LabelFrame(DFrame, bd=2, width=1000, height=600, padx=20, pady=45, bg=\"#28282A\",relief=RIDGE, font=('Arial', 20, 'bold'), text=\"Movie Info\\n\", fg=\"#ff847c\")\r\n DFrameL.pack(side=LEFT)\r\n\r\n DFrameR = LabelFrame(DFrame, bd=0, width=450, height=300, padx=31, pady=0, bg=\"#28282A\", relief=RIDGE, font=('Arial', 20, 'bold'), text=\"\\tMovie Details\\n\", fg=\"#ff847c\")\r\n DFrameR.pack(side=RIGHT)\r\n\r\n # Labels & Entry Box\r\n self.lblMovie_ID = Label(DFrameL, font=('Arial', 18, 'bold'), text=\"Movie ID\", padx=2, pady=2, bg=\"#28282A\", fg=\"#eff48e\")\r\n self.lblMovie_ID.grid(row=0, column=0, sticky=W)\r\n self.txtMovie_ID = Entry(DFrameL, font=('Arial', 18, 'bold'), textvariable=Movie_ID, width=39, bg=\"light grey\", fg=\"black\")\r\n self.txtMovie_ID.grid(row=0, column=1)\r\n\r\n self.lblDirector_name = Label(DFrameL, font=('Arial', 18, 'bold'), text=\"Director Name\", padx=2, pady=2, bg=\"#28282A\", fg=\"#eff48e\")\r\n self.lblDirector_name.grid(row=1, column=0, sticky=W)\r\n self.txtDirector_name = Entry(DFrameL, font=('Arial', 18, 'bold'), textvariable=Director_name, width=39, bg=\"light grey\", fg=\"black\")\r\n self.txtDirector_name.grid(row=1, column=1)\r\n\r\n self.lblDOB = Label(DFrameL, font=('Arial', 18, 'bold'), text=\"DOB\", padx=2, pady=2, bg=\"#28282A\", fg=\"#eff48e\")\r\n self.lblDOB.grid(row=2, column=0, sticky=W)\r\n self.txtDOB = Entry(DFrameL, font=('Arial', 18, 'bold'), textvariable=DOB, width=39, bg=\"light grey\", fg=\"black\")\r\n self.txtDOB.grid(row=2, column=1)\r\n\r\n # ListBox & ScrollBar\r\n sb = Scrollbar(DFrameR)\r\n sb.grid(row=0, column=1, sticky='ns')\r\n\r\n MovieList = Listbox(DFrameR, width=41, height=16, font=('Arial', 12, 'bold'), bg=\"black\", fg=\"white\", yscrollcommand=sb.set)\r\n MovieList.bind('<>', movierec)\r\n MovieList.grid(row=0, column=0, padx=9)\r\n sb.config(command=MovieList.yview)\r\n\r\n # Buttons\r\n self.btnadd = Button(BFrame, text=\"Add New\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=adddata)\r\n self.btnadd.grid(row=0, column=0)\r\n\r\n self.btndis = Button(BFrame, text=\"Display\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=disdata)\r\n self.btndis.grid(row=0, column=1)\r\n\r\n self.btnclc = Button(BFrame, text=\"Clear\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=clcdata)\r\n self.btnclc.grid(row=0, column=2)\r\n\r\n self.btnse = Button(BFrame, text=\"Search\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=searchdb)\r\n self.btnse.grid(row=0, column=3)\r\n\r\n self.btnclc = Button(BFrame, text=\"Delete\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=deldata)\r\n self.btnclc.grid(row=0, column=4)\r\n\r\n self.btnup = Button(BFrame, text=\"Update\", font=('Arial', 20, 'bold'), width=9, height=1, bd=4, bg=\"#c6fced\", command=updata)\r\n self.btnup.grid(row=0, column=5)\r\n\r\n self.btnx = Button(BFrame, text=\"Exit\", font=('Arial', 20, 'bold'), width=9, height=20, bd=0, bg=\"#28282A\")\r\n self.btnx.grid(row=100, column=1)\r\n\r\n","sub_path":"director.py","file_name":"director.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"437232664","text":"import datetime\nimport cStringIO as StringIO\nfrom django.conf import settings\nimport requests\nimport lxml.html\nfrom namelist.models import Player\n\n\nPROFILES_URL = 'http://profiles.urbandead.net/index.php'\nPROFILE_URL = 'http://urbandead.com/profile.cgi'\n\nclass NotFound(Exception):\n pass\n\n\ndef get_user_profile_id(name):\n io = StringIO.StringIO()\n io.write(requests.get(PROFILES_URL, params={'name': name}).content)\n io.seek(0)\n xml = lxml.html.parse(io)\n try:\n return int(xml.xpath('//table/tbody/tr/td[1]/a')[0].attrib['href'][40:])\n except (IndexError, ValueError) as e:\n raise NotFound(name)\n finally:\n io.close()\n\n\ndef scrape_profile(profile_id):\n io = StringIO.StringIO()\n io.write(requests.get(PROFILE_URL, params={'id': profile_id}).content)\n io.seek(0)\n profile_xml = lxml.html.parse(io)\n name = profile_xml.xpath('/html/body/div/h1/span')[0].text_content()\n group = profile_xml.xpath('/html/body/div/table/tr[3]/td[4]')[0].text_content()\n join_date = profile_xml.xpath('/html/body/div/table/tr[4]/td[2]')[0].text_content()\n \n if not group:\n group = 'none'\n return name, group, datetime.datetime.strptime(join_date, '%Y-%m-%d %H:%M:%S')\n\n","sub_path":"brains/namelist/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"95349692","text":"#last updated by @lyonkvalid\n\n#check the Authentication models , updated the custom User object \n#>>>might be deprecated in future\n\n#from Authentication.models import User\n\n#import bitcoinlib module \n#>>>check bitcoinlib documentation for reference\nfrom bitcoinlib.wallets import Wallet, wallet_delete, wallet_exists\nfrom bitcoinlib.networks import NETWORK_DEFINITIONS, print_value\n\n#python-notification-hr \n#>>> check python-notification-hr documentation for reference\nfrom .settings import DEBUG\n\nfrom Wallet.models import NetworkDefinition\n\nNETWORKS = [\"bitcoin\", \"litecoin\", \"dash\", \"dogecoin\"]\nNETWORK_TEST = [\"testnet\", \"litecoin_testnet\", \"dash_testnet\", \"dogecoin_testnet\", ]\n\nNETWORKS_SYMBOL = list(map(lambda network: NETWORK_DEFINITIONS[network][\"currency_code\"], NETWORKS))\n\nclass HavwisCryptoWallet():\n def __init__(self, request=None, user=None):\n self.user = request.user if user is None else user\n self.networks = NETWORKS #if not DEBUG else NETWORK_TEST\n \n def get_wallet(self):\n wallet_id = self.user.wallet_id\n if wallet_exists(wallet_id):\n return Wallet(wallet_id)\n \n def create_wallet(self, create_wallet_id):\n wallet = Wallet.create(create_wallet_id, network=self.networks[0])\n for network in self.networks:\n if network != self.networks[0]:\n wallet.new_account(\"%s wallet\"%network, network=network)\n return create_wallet_id\n \n def update_wallet(self):\n wallet = self.get_wallet()\n for network in self.networks:\n wallet.utxos_update(network=network)\n wallet.transaction_update(network=network)\n return {\"status\": True}\n \n def get_address(self, network):\n return self.get_wallet().get_key(network=network).address\n \n def get_balance(self, network):\n return self.get_wallet().balance(network=network)\n\nclass HavwisTransaction():\n def __init__(self, wallet, network, amount, address):\n self.wallet = wallet\n self.network = network\n self.amount = float(amount)*100000000\n self.address = address\n self.symbol = NETWORK_DEFINITIONS[self.network][\"currency_code\"]\n self.network_definition = NetworkDefinition.objects.get(network=self.network)\n\n def send(self, address, fee=None):\n try:\n if self.amount <= self.wallet.balance(network=self.network):\n try:\n if fee is None:\n tx_object = self.wallet.send_to(address, self.amount, network=self.network, offline=True)\n else:\n tx_object = self.wallet.send_to(address, self.amount, network=self.network, fee=fee, offline=True)\n return {\"status\":True, \"data\":{\"tx_id\":str(tx_object)}}\n except Exception as e:\n return {\"status\": False, \"data\":{\"error\": e.args[0]}}\n else:\n return {\"status\":False, \"data\":{\"error\":\"Low balance, send more {} to complete transaction\".format(self.network)}}\n except:\n return {\"status\":False, \"data\":{\"err\": e.args[0]}}\n\n def get_transaction_fee(self, request):\n wallet = Wallet(request.user.wallet_id)\n try:\n tx_object = self.wallet.send_to(self.address, self.amount, network=self.network, offline=True)\n tx_fee = float(tx_object.fee)\n return {\"status\":True, \"data\":{\"fee\":print_value(tx_fee, network=self.network).replace(self.symbol, \"\")}}\n except Exception as e:\n if e.args[0] == \"Not enough unspent transaction outputs found\":\n return {\"status\":False, \"data\":{\"error\": \"Balance to low for transaction 😁.\"}}\n else:\n return {\"status\":False, \"data\":{\"error\": \"An error occurs❗.\"}}\n\nfrom Havwis import havwis\n\n# Get wallet and dashboard getaway utils\nclass HavwisWalletUtils():\n def __init__(self):\n self.networks = NETWORKS\n self.symbols = NETWORKS_SYMBOL\n \n '''\n method getWalletPrice: return current price of networks defined on havwis,\n returns dict: prices and network infos\n '''\n def getNetworkDefinitionsInfos(self):\n final_info = []\n shrimpy_getaway = havwis.HavwisShrimpyGetaway()\n currency_infos = shrimpy_getaway.getCryptoPrices()\n for symbol in self.symbols:\n for info in currency_infos:\n if info[\"symbol\"] == symbol:\n final_info.append(info)\n return final_info","sub_path":"Havwis/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"652779983","text":"import socket\nimport threading\nimport time\nimport random\nip = \"139.199.213.83\"\n\n\ndef sendInfo(s,ip):\n while True:\n print(s.recv(1024).decode('utf-8'))\n \n\n\ndef recvInfo(s,ip):\n for i in range(1000):\n s.send(bytes(str(i),encoding=\"utf-8\"))\n time.sleep(1)\n s.send('exit')\n s.close()\n\ndef main():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 建立连接:\n s.connect((ip, 19999))\n # 接收欢迎消息:\n #print(s.recv(1024).decode('utf-8'))\n threading.Thread(target=sendInfo, args=(s,ip)).start()\n threading.Thread(target=recvInfo, args=(s,ip)).start()\n time.sleep(10000)\n\nif __name__ == '__main__':\n main()\n","sub_path":"program/Python/pythonPractice/NetProgram/tcp/client/TcpClient.py","file_name":"TcpClient.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"242325073","text":"class Solution:\r\n def defangIPaddr(self, address: str) -> str:\r\n a = 0\r\n ans = str(\"\")\r\n for x in range(0, len(address)):\r\n if address[a]==\".\":\r\n ans = ans + \"[\" + address[a] + \"]\"\r\n else: ans += address[a]\r\n a += 1 \r\n return ans","sub_path":"Week2/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"490201032","text":"\"\"\"Processing container startup script.\"\"\"\nimport array\nimport asyncio\nimport concurrent\nimport json\nimport logging\nimport os\nimport select\nimport shlex\nimport shutil\nimport signal\nimport socket\nimport sys\nimport uuid\nfrom contextlib import closing, suppress\nfrom distutils.util import strtobool\nfrom functools import partial\nfrom pathlib import Path\nfrom time import time\nfrom typing import Dict, List, Optional, Sequence\n\ntry:\n import constants\n from socket_utils import (\n BaseCommunicator,\n BaseProtocol,\n Message,\n PeerIdentity,\n Response,\n SocketCommunicator,\n )\n\nexcept ImportError:\n from resolwe.flow.executors import constants\n from resolwe.flow.executors.socket_utils import (\n BaseCommunicator,\n BaseProtocol,\n Message,\n PeerIdentity,\n Response,\n SocketCommunicator,\n )\n\n# The directory where local processing is done.\nTMP_DIR = Path(os.environ.get(\"TMP_DIR\", \".tmp\"))\nDATA_ID = int(os.getenv(\"DATA_ID\", \"-1\"))\n\n# Basic constants.\nWORKING_DIRECTORY = Path.cwd().resolve()\nSTDOUT_LOG_PATH = WORKING_DIRECTORY / \"stdout.txt\"\nJSON_LOG_PATH = WORKING_DIRECTORY / \"jsonout.txt\"\n\n# Update log files every 30 seconds.\nUPDATE_LOG_FILES_TIMEOUT = 30\n\n# Keep data settings.\nKEEP_DATA = bool(strtobool(os.environ.get(\"FLOW_MANAGER_KEEP_DATA\", \"False\")))\n\n# Read configuration from environmental variables.\nCOMMUNICATION_SOCKET = (\n constants.SOCKETS_VOLUME / constants.COMMUNICATION_PROCESSING_SOCKET\n)\nSCRIPT_SOCKET = constants.SOCKETS_VOLUME / constants.SCRIPT_SOCKET\nUPLOAD_FILE_SOCKET = constants.SOCKETS_VOLUME / constants.UPLOAD_FILE_SOCKET\n\n# How many file descriptors to sent over socket in a single message.\nDESCRIPTOR_CHUNK_SIZE = int(os.environ.get(\"DESCRIPTOR_CHUNK_SIZE\", 100))\n\n# Configure container log level.\nLOG_LEVEL = int(os.environ.get(\"LOG_LEVEL\", logging.DEBUG))\n\n# Max characters to log in a single message: the processing script messages can\n# be hundreds lines long.\nLOG_MAX_LENGTH = int(os.environ.get(\"LOG_MAX_LENGTH\", 200))\n\n# How long to wait for the response from the communication container.\n# Do not set too low or script may fail to start. The default is 20 minutes.\nSCRIPT_START_TIMEOUT = int(os.environ.get(\"SCRIPT_START_TIMEOUT\", 1200))\n\nlogging.basicConfig(\n stream=sys.stdout,\n level=LOG_LEVEL,\n format=f\"%(asctime)s - %(name)s - %(levelname)s - %(message).{LOG_MAX_LENGTH}s\",\n)\nlogger = logging.getLogger(__name__)\n\n\nassert sys.version_info[0] == 3, \"Only Python3 is supported\"\nassert sys.version_info[1] >= 6, \"Only Python >= 3.6 is supported\"\n\n\nasync def stop_task(task: Optional[asyncio.Task], timeout: int = 1):\n \"\"\"Cancel the given task.\n\n Also wait for task to stop for up to timeout seconds.\n \"\"\"\n if task is not None and not task.done():\n task.cancel()\n with suppress(asyncio.CancelledError):\n await asyncio.wait_for(task, timeout=timeout)\n\n\nasync def log_exception(\n message: str, communicator: BaseCommunicator, timeout: int = 60\n):\n \"\"\"Log the exception via logger and send it to the communicator.\n\n Log it using logger and send error message to the communication\n container. Make sure no exception is ever raised and that the method\n completes in timeout seconds.\n \"\"\"\n with suppress(Exception):\n logger.exception(message)\n with suppress(Exception):\n log_coroutine = communicator.process_log({\"error\": [message]})\n\n await asyncio.wait_for(log_coroutine, timeout)\n\n\nasync def heartbeat_task(communicator: BaseCommunicator, heartbeat_interval: int = 60):\n \"\"\"Periodically send heartbeats.\n\n This task will run indefinitely and has to be cancelled to stop.\n\n :attr heartbeat_interval: seconds between successive heartbeat messages.\n \"\"\"\n while True:\n await communicator.send_heartbeat()\n await asyncio.sleep(heartbeat_interval)\n\n\nasync def log_error(message: str, communicator: BaseCommunicator, timeout: int = 60):\n \"\"\"Log the error via logger and send it to the communicator.\n\n Log it using logger and send error message to the communication\n container. Make sure no exception is ever raised and that the method\n completes in timeout seconds.\n \"\"\"\n with suppress(Exception):\n logger.error(message)\n with suppress(Exception):\n log_coroutine = communicator.process_log({\"error\": [message]})\n\n await asyncio.wait_for(log_coroutine, timeout)\n\n\nasync def connect_to_communication_container(path: str) -> SocketCommunicator:\n \"\"\"Wait for the communication container to start.\n\n Assumption is that the communication container is accepting connections\n and will send a single PING when connected.\n\n The coroutine will only exit when the connection is successfully\n established it is the responsibility of the caller to terminate the\n coroutine when the connection can not be established for some time.\n \"\"\"\n while True:\n with suppress(Exception):\n reader, writer = await asyncio.open_unix_connection(path)\n line = (await reader.readline()).decode(\"utf-8\")\n assert line.strip() == \"PING\", \"Expected 'PING', got '{}'.\".format(line)\n return SocketCommunicator(\n reader, writer, \"processing<->communication\", logger\n )\n await asyncio.sleep(1)\n\n\nasync def start_script(script: str) -> asyncio.subprocess.Process:\n \"\"\"Start processing the script.\n\n :raises Exception: when script could not be started.\n \"\"\"\n # Start the bash subprocess and write script to its standard input.\n logger.debug(\"Executing script: '%s'.\", script)\n bash_command = \"/bin/bash --login\" + os.linesep\n proc = await asyncio.subprocess.create_subprocess_exec(\n *shlex.split(bash_command),\n limit=4 * (2**20), # 4MB buffer size for line buffering\n stdin=asyncio.subprocess.PIPE,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n )\n # Assert that stdin and stdout streams are connected to the proc.\n error_message = \"The stream '{}' could not connect to the script.\"\n assert proc.stdin is not None, error_message.format(\"stdin\")\n assert proc.stdout is not None, error_message.format(\"stdout\")\n proc.stdin.write(script.encode(\"utf-8\"))\n proc.stdin.close()\n logger.debug(\"Code sent to stdin of the script process.\")\n return proc\n\n\nasync def communicate_with_process(\n proc: asyncio.subprocess.Process, manager: \"ProcessingManager\"\n) -> int:\n \"\"\"Read the given process standard output and write it to the log file.\n\n :return: the process's return code.\n \"\"\"\n try:\n assert proc.stdout is not None\n while not proc.stdout.at_eof():\n # Here we tap into the internal structures of the StreamReader\n # in order to read as much data as we can in one chunk.\n await proc.stdout._wait_for_data(\"execute_script\") # type: ignore\n # Send received data to upload manager.\n manager.upload_handler.update_stdout(proc.stdout._buffer)\n proc.stdout._buffer.clear()\n # Break the loop if EOF is reached.\n if proc.stdout.at_eof():\n logger.debug(\"Processing script stdout eof.\")\n break\n # Wait for the script to terminate.\n await proc.wait()\n\n except Exception:\n logger.exception(\"Exception running the script process.\")\n # Terminate process if it is still running.\n with suppress(Exception):\n if proc.returncode is None:\n proc.terminate()\n with suppress(asyncio.TimeoutError):\n await asyncio.wait_for(proc.wait(), timeout=60)\n if proc.returncode is None:\n proc.kill()\n with suppress(asyncio.TimeoutError):\n await asyncio.wait_for(proc.wait(), timeout=60)\n finally:\n # Return the return code (if available) or general error code 1.\n return_code = proc.returncode if proc.returncode is not None else 1\n logger.debug(\"Script finished with the return code '%d'.\", return_code)\n manager.terminate()\n return return_code\n\n\nasync def initialize_connections(\n loop: asyncio.AbstractEventLoop,\n) -> \"ProcessingManager\":\n \"\"\"Start the processing manager.\n\n This method does the following:\n - connects to the communication container,\n - connects to the upload socket (unix socket) and\n - starts the socket server for the communication with the processing\n script.\n\n :raises ConnectionError: when connection can not be established.\n :return: the processing manager instance.\n \"\"\"\n # Connect to the communication container and start processing script\n # server first.\n logger.debug(\n \"Connecting to the communication container via socket '%s'.\",\n COMMUNICATION_SOCKET,\n )\n start = time()\n communicator_future: asyncio.Task = asyncio.ensure_future(\n connect_to_communication_container(str(COMMUNICATION_SOCKET))\n )\n try:\n socket_communicator = await asyncio.wait_for(\n communicator_future, timeout=constants.CONTAINER_TIMEOUT\n )\n except (asyncio.CancelledError, asyncio.TimeoutError):\n raise ConnectionError(\"Timeout connecting to communication container.\")\n logger.debug(\n \"Connected to the communication container in '%.2f' seconds.\",\n time() - start,\n )\n\n # Connect to the upload socket and start the periodic upload of log files.\n upload_socket = socket.socket(family=socket.AF_UNIX)\n upload_socket.connect(str(UPLOAD_FILE_SOCKET))\n upload_handler = UploadHandler(upload_socket, loop)\n logger.debug(\"Connected to the upload socket '%s'.\", UPLOAD_FILE_SOCKET)\n upload_handler.start_log_upload()\n\n # Start the server to handle processing script connections.\n logger.debug(\n \"Starting the processing script server on the socket '%s'.\", SCRIPT_SOCKET\n )\n script_server_future: asyncio.Task = asyncio.ensure_future(\n asyncio.start_unix_server(\n partial(\n handle_processing_script_connection,\n socket_communicator,\n upload_handler,\n ),\n str(SCRIPT_SOCKET),\n )\n )\n try:\n script_server = await asyncio.wait_for(script_server_future, timeout=60)\n except asyncio.CancelledError:\n raise ConnectionError(\"Timeout starting processing script server.\")\n\n return ProcessingManager(socket_communicator, upload_handler, script_server, loop)\n\n\nasync def handle_processing_script_connection(\n communication_communicator: SocketCommunicator,\n upload_handler: \"UploadHandler\",\n reader: asyncio.StreamReader,\n writer: asyncio.StreamWriter,\n):\n \"\"\"Handle incoming connection from the processing script.\n\n Python process opens a single connection while Resolwe runtime utils opens\n a new connection for every request.\n \"\"\"\n try:\n logger.info(\"Processing script connected to the socket.\")\n communicator = SocketCommunicator(reader, writer, \"script\", logger)\n protocol_handler = ScriptProtocol(\n communication_communicator, communicator, upload_handler\n )\n await protocol_handler.communicate()\n except (asyncio.IncompleteReadError, GeneratorExit):\n logger.info(\"Processing script closed connection.\")\n except Exception:\n logger.exception(\"Unknown exception while handling processing script message.\")\n raise\n\n\nclass CommunicationProtocol(BaseProtocol):\n \"\"\"Handles communication with the communication container.\"\"\"\n\n def __init__(self, manager: \"ProcessingManager\"):\n \"\"\"Initialize variables.\"\"\"\n super().__init__(manager.communicator, logger)\n self.processing_manager = manager\n self.script_task: Optional[asyncio.Task] = None\n self._script_starting = asyncio.Lock()\n self.script_started = asyncio.Event()\n\n async def handle_process_script(\n self, message: Message, identity: PeerIdentity\n ) -> Response[int]:\n \"\"\"Handle the process_script message.\"\"\"\n # This message can arrive multiple times so make sure the script is\n # started only once.\n if self.script_started.is_set():\n return message.respond_ok(\"Already processing\")\n self.script_started.set()\n if self.script_task is None:\n process = await start_script(message.message_data)\n self.script_task = asyncio.ensure_future(\n communicate_with_process(process, self.processing_manager)\n )\n return message.respond_ok(\"Script started.\")\n\n async def terminate_script(self):\n \"\"\"Terminate the script.\"\"\"\n await stop_task(self.script_task)\n\n async def post_terminate(self, message: Message, identity: PeerIdentity):\n \"\"\"Stop the processing script and stop the manager.\"\"\"\n logger.debug(\"Stopping all the tasks in the post_terminate handler.\")\n await stop_task(self.script_task)\n self.processing_manager.terminate()\n\n async def handle_terminate(\n self, message: Message, identity: PeerIdentity\n ) -> Response[str]:\n \"\"\"Handle the terminate command.\"\"\"\n logger.debug(\"Received terminate command from the communication container.\")\n return message.respond_ok(\"Terminating\")\n\n\nclass ProcessingManager:\n \"\"\"Manager class.\n\n It starts network servers and executes the received script.\n \"\"\"\n\n def __init__(\n self,\n communicator: BaseCommunicator,\n upload_handler: \"UploadHandler\",\n script_server,\n loop: asyncio.AbstractEventLoop,\n ):\n \"\"\"Initialize variables, start the communicator and heartbeat task.\"\"\"\n self.upload_handler = upload_handler\n self.communicator = communicator\n self.loop = loop\n self.protocol_handler = CommunicationProtocol(self)\n self.script_server = script_server\n\n self.communicator_task = asyncio.ensure_future(\n self.protocol_handler.communicate()\n )\n self.heartbeat_task = asyncio.ensure_future(heartbeat_task(communicator))\n\n # TODO: drop this when we stop supporting Python 3.6.\n # This class has been implicitly getting the current running loop since 3.7.\n lock_arguments: Dict[str, asyncio.AbstractEventLoop] = {}\n if sys.version_info < (3, 7):\n lock_arguments = {\"loop\": loop}\n self._terminating = asyncio.Event(**lock_arguments)\n\n def terminate(self):\n \"\"\"Terminate the processing container.\"\"\"\n self._terminating.set()\n\n async def _stop_all_tasks(self, stop_timeout=60):\n \"\"\"Stop all running tasks.\"\"\"\n # Stop the processing script.\n logger.debug(\"Stopping all the tasks in the processing manager.\")\n logger.debug(\"Stopping the processing script task.\")\n await stop_task(self.protocol_handler.script_task)\n\n # Stop the script server.\n logger.debug(\"Stopping the script server.\")\n with suppress(Exception):\n self.script_server.close()\n await asyncio.wait_for(\n self.script_server.wait_closed(), timeout=stop_timeout\n )\n\n # Stop the periodic log upload task.\n logger.debug(\"Stopping periodic log upload task.\")\n await self.upload_handler.stop_log_upload()\n\n # Upload latest log files (in case there was a change). Notify the\n # listener on failure.\n logger.debug(\"Uploading latest log files.\")\n try:\n # Give it up to one minute to upload the latest log files.\n latest_log_upload = asyncio.ensure_future(\n self.upload_handler.upload_log_files()\n )\n await asyncio.wait_for(latest_log_upload, timeout=60)\n except Exception:\n await log_exception(\"Unable to upload the latest logs.\", self.communicator)\n\n # If data should be kept it must be uploaded to the data dir.\n if KEEP_DATA:\n logger.debug(\"Flag KEEP_DATA is set, uploading files.\")\n try:\n # The KEEP_DATA setting is used only for debugging purposes so the\n # task should not be used to transfer very large files.\n # We wait for up to 10 minutes for it to complete.\n send_coroutine = self.upload_handler.send_file_descriptors(\n [str(file) for file in Path(\"./\").rglob(\"*\") if file.is_file()]\n )\n await asyncio.wait_for(send_coroutine, timeout=600)\n except Exception:\n await log_exception(\n \"Unable to upload the data (KEEP_DATA flag is set).\",\n self.communicator,\n )\n\n # Send the finish command to the communication container.\n logger.debug(\"Send the finish command to the communication container.\")\n await self.communicator.finish(self.return_code)\n\n # Stop the heartbeat task.\n logger.debug(\"Stopping the heartbeat task.\")\n await stop_task(self.heartbeat_task)\n\n # Finally, stop the communicator task.\n with suppress(Exception):\n logger.debug(\"Stopping communication with the communication container.\")\n self.protocol_handler.stop_communicate()\n await asyncio.wait_for(self.communicator_task, timeout=stop_timeout)\n logger.debug(\"All tasks stopped.\")\n\n @property\n def return_code(self):\n \"\"\"Get the return code.\n\n :return: return the script task return code. When the script task is\n still running return 1.\n \"\"\"\n task = self.protocol_handler.script_task\n if task is None or task.result() is None:\n return 1\n return task.result()\n\n async def run(self) -> int:\n \"\"\"Start the main method.\n\n :raises RuntimeError: in case of failure.\n \"\"\"\n try:\n await asyncio.wait(\n [self.protocol_handler.script_started.wait(), self._terminating.wait()],\n timeout=SCRIPT_START_TIMEOUT,\n return_when=asyncio.FIRST_COMPLETED,\n )\n if self._terminating.is_set():\n logger.debug(\"Terminating message received.\")\n elif not self.protocol_handler.script_started.is_set():\n await log_error(\n f\"The script failed to start in {SCRIPT_START_TIMEOUT} seconds.\",\n self.communicator,\n )\n else:\n monitored_tasks = (\n self.script_server.wait_closed(),\n self.upload_handler.upload_task,\n self.communicator_task,\n self._terminating.wait(),\n )\n # Stop processing when any of the following tasks complete.\n await asyncio.wait(monitored_tasks, return_when=asyncio.FIRST_COMPLETED)\n except Exception:\n await log_exception(\n \"Unexpected exception in the processing container.\", self.communicator\n )\n finally:\n # Send the return code to the communicate container.\n await self._stop_all_tasks()\n return self.return_code\n\n\nclass UploadHandler:\n \"\"\"Handle upload of files via communication container.\"\"\"\n\n def __init__(\n self, upload_socket: socket.socket, loop: asyncio.AbstractEventLoop\n ) -> None:\n \"\"\"Initialize local variables.\"\"\"\n self._log_buffers = {\"JSON\": bytearray(), \"STDOUT\": bytearray()}\n self._log_files = {\"JSON\": JSON_LOG_PATH, \"STDOUT\": STDOUT_LOG_PATH}\n\n self.upload_socket = upload_socket\n self.exported_files_mapper: Dict[str, str] = dict()\n self.upload_task: Optional[asyncio.Task] = None\n lock_arguments: Dict[str, asyncio.AbstractEventLoop] = dict()\n if sys.version_info < (3, 7):\n lock_arguments = {\"loop\": loop}\n self._uploading_log_files_lock = asyncio.Lock(**lock_arguments)\n self._send_file_descriptors_lock = asyncio.Lock(**lock_arguments)\n self.loop = loop\n\n async def export_files(self, file_names: Sequence[str]):\n \"\"\"Handle export files.\"\"\"\n unique_names = []\n for file_name in file_names:\n unique_name = \"export_\" + uuid.uuid4().hex\n shutil.move(file_name, unique_name)\n unique_names.append(unique_name)\n presigned_urls = await self.send_file_descriptors(\n unique_names, need_presigned_urls=True, storage_name=\"upload\"\n )\n for file_name, presigned_url in zip(file_names, presigned_urls):\n self.exported_files_mapper[file_name] = presigned_url\n\n def update_stdout(self, data: bytes):\n \"\"\"Write data bytes to stdout.\"\"\"\n self._log_buffers[\"STDOUT\"] += data\n\n def update_jsonout(self, data: bytes):\n \"\"\"Write data bytes to jsonout.\"\"\"\n self._log_buffers[\"JSON\"] += data\n\n def start_log_upload(self) -> asyncio.Task:\n \"\"\"Start the timer that periodically uploads the log files.\n\n On multiple calls already created task is returned.\n \"\"\"\n if self.upload_task is None or self.upload_task.done():\n self.upload_task = asyncio.ensure_future(self._update_logs_timer())\n return self.upload_task\n\n async def stop_log_upload(self):\n \"\"\"Stop the timer that periodically uploads the log files.\"\"\"\n if self.upload_task is not None:\n # Only cancel the task when uploading is not in progress.\n async with self._uploading_log_files_lock:\n await stop_task(self.upload_task)\n\n async def _update_logs_timer(self, stop_after: int = 3):\n \"\"\"Update log files every UPDATE_LOG_FILES_TIMEOUT secods.\n\n :attr stop_after: the integer indication how many exceptions must occur\n during log upload to terminate the timer task.\n\n :raises Exception: when stop_after exceptions occur during transfer the\n last exception is re-raised.\n \"\"\"\n exception_count = 0\n while True:\n try:\n await asyncio.sleep(UPDATE_LOG_FILES_TIMEOUT)\n logger.debug(\"Uploading log timer triggered.\")\n await self.upload_log_files()\n except asyncio.CancelledError:\n logger.debug(\"Update log files timer canceled.\")\n break\n except Exception:\n logger.exception(\"Error uploading log files.\")\n exception_count += 1\n if exception_count >= stop_after:\n raise\n\n async def upload_log_files(self):\n \"\"\"Upload log files if needed.\n\n :raises BrokenPipeError: when upload socket is not available.\n \"\"\"\n to_upload = []\n for log_type in [\"JSON\", \"STDOUT\"]:\n if self._log_buffers[log_type]:\n to_upload.append(\n self._log_files[log_type].relative_to(WORKING_DIRECTORY)\n )\n with self._log_files[log_type].open(\"ba\") as log_file:\n log_file.write(self._log_buffers[log_type])\n self._log_buffers[log_type].clear()\n\n if to_upload:\n logger.debug(\"Uploading log files: %s.\", to_upload)\n async with self._uploading_log_files_lock:\n await self.send_file_descriptors(to_upload)\n\n async def send_file_descriptors(\n self,\n filenames: Sequence[str],\n need_presigned_urls: bool = False,\n storage_name: str = \"data\",\n ):\n \"\"\"Send file descriptors over UNIX sockets.\n\n Code is based on the sample in manual\n https://docs.python.org/3/library/socket.html#socket.socket.sendmsg .\n\n :returns: the list of presigned urls for filenames (in the same order)\n if need_presigned_urls is set to True. Otherwise empty list is\n returned.\n\n :raises RuntimeError: on failure.\n \"\"\"\n\n def receive(length: int) -> bytes:\n \"\"\"Receive the length bytes from the upload socket.\"\"\"\n received = 0\n message = b\"\"\n while received != length:\n select.select([self.upload_socket], [], [])\n payload = self.upload_socket.recv(length - received)\n if payload == b\"\":\n raise RuntimeError(\"Error reading data from the upload socket.\")\n message += payload\n received = len(message)\n return message\n\n def send(payload: bytes):\n \"\"\"Send the payload over the upload socket.\"\"\"\n bytes_sent = 0\n to_send = len(payload)\n while bytes_sent < to_send:\n select.select([], [self.upload_socket], [])\n chunk_size = self.upload_socket.send(payload)\n bytes_sent += chunk_size\n payload = payload[chunk_size:]\n if chunk_size == 0:\n raise RuntimeError(\"Error sending data to the upload socket.\")\n\n def send_chunk(processing_filenames: Sequence[str]) -> List[str]:\n \"\"\"Send chunk of filenames to uploader.\n\n :raises RuntimeError: on failure.\n :returns: the list of presigned urls (if requested) or empty list.\n \"\"\"\n logger.debug(\"Sending file descriptors for files: %s\", processing_filenames)\n message = [storage_name, processing_filenames, need_presigned_urls]\n payload = json.dumps(message).encode()\n\n # File handlers must be created before file descriptors otherwise\n # garbage collector will kick in and close the handlers. Handlers\n # will be closed when function completes.\n file_handlers = [open(filename, \"rb\") for filename in processing_filenames]\n file_descriptors = [file_handler.fileno() for file_handler in file_handlers]\n send(len(payload).to_bytes(8, byteorder=\"big\"))\n select.select([], [self.upload_socket], [])\n self.upload_socket.sendmsg(\n [payload],\n [\n (\n socket.SOL_SOCKET,\n socket.SCM_RIGHTS,\n array.array(\"i\", file_descriptors),\n )\n ],\n )\n response_length = int.from_bytes(receive(8), byteorder=\"big\")\n response = json.loads(receive(response_length).decode())\n if not response[\"success\"]:\n raise RuntimeError(\n \"Communication container response indicates error sending \"\n \"files {}.\".format(processing_filenames)\n )\n return response[\"presigned_urls\"]\n\n result = []\n self.upload_socket.setblocking(False)\n async with self._send_file_descriptors_lock:\n with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:\n for i in range(0, len(filenames), DESCRIPTOR_CHUNK_SIZE):\n processing_filenames = [\n str(file_) for file_ in filenames[i : i + DESCRIPTOR_CHUNK_SIZE]\n ]\n response = await self.loop.run_in_executor(\n pool, send_chunk, processing_filenames\n )\n if need_presigned_urls:\n result += response\n return result\n\n def close(self):\n \"\"\"Close the upload socket.\"\"\"\n self.upload_socket.close()\n\n\nclass ScriptProtocol(BaseProtocol):\n \"\"\"Process the processing script messages.\"\"\"\n\n def __init__(\n self,\n communication_communicator: SocketCommunicator,\n script_communicator: SocketCommunicator,\n upload_handler: UploadHandler,\n ):\n \"\"\"Initialize.\"\"\"\n super().__init__(script_communicator, logger)\n self.communication_communicator = communication_communicator\n self.upload_handler = upload_handler\n\n async def process_command(\n self, peer_identity: PeerIdentity, received_message: Message\n ):\n \"\"\"Log the received message and call the parents handler.\"\"\"\n self.upload_handler.update_jsonout(\n json.dumps(received_message.to_dict()).encode()\n )\n return await super().process_command(peer_identity, received_message)\n\n async def handle_export_files(\n self, message: Message, identity: PeerIdentity\n ) -> Response[str]:\n \"\"\"Export files by sending them to the communication container.\"\"\"\n await self.upload_handler.export_files(message.message_data)\n return message.respond_ok(\"\")\n\n async def handle_upload_files(\n self, message: Message, identity: PeerIdentity\n ) -> Response[str]:\n \"\"\"Upload files by sending them to the communication container.\"\"\"\n filenames = message.message_data\n await self.upload_handler.send_file_descriptors(filenames)\n return message.respond_ok(\"\")\n\n async def handle_run(\n self, message: Message, identity: PeerIdentity\n ) -> Response[str]:\n \"\"\"Handle the run command.\"\"\"\n command_data = {\n \"data\": message.message_data,\n \"export_files_mapper\": self.upload_handler.exported_files_mapper,\n }\n command = Message.command(message.command_name, command_data)\n return await self.communication_communicator.send_command(command)\n\n async def default_command_handler(\n self, message: Message, identity: PeerIdentity\n ) -> Response:\n \"\"\"By default proxy all commands to the communication container.\"\"\"\n return await self.communication_communicator.send_command(message)\n\n\ndef sig_term_handler(processing_manager: ProcessingManager):\n \"\"\"Gracefully terminate the running process.\"\"\"\n logger.debug(\"SIG_INT received, shutting down.\")\n processing_manager.terminate()\n\n\nasync def init(loop: asyncio.AbstractEventLoop) -> ProcessingManager:\n \"\"\"Create necessary objects.\"\"\"\n # Create temporary directory inside working directory.\n temporary_directory = WORKING_DIRECTORY / TMP_DIR\n temporary_directory.mkdir(exist_ok=True)\n\n # Create (empty) log files.\n STDOUT_LOG_PATH.touch()\n JSON_LOG_PATH.touch()\n\n # Create the processing manager.\n processing_manager = await initialize_connections(loop)\n\n # Addd signal handler for SIGINT and SIGTERM.\n loop.add_signal_handler(\n signal.SIGINT, partial(sig_term_handler, processing_manager)\n )\n loop.add_signal_handler(\n signal.SIGTERM, partial(sig_term_handler, processing_manager)\n )\n\n return processing_manager\n\n\nif __name__ == \"__main__\":\n # Replace the code bellow with asyncio.run when we no longer have to\n # support python 3.6.\n with closing(asyncio.get_event_loop()) as loop:\n processing_manager = loop.run_until_complete(init(loop))\n return_code = loop.run_until_complete(processing_manager.run())\n sys.exit(return_code)\n","sub_path":"resolwe/flow/executors/startup_processing_container.py","file_name":"startup_processing_container.py","file_ext":"py","file_size_in_byte":31156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"117285906","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nif __name__ == '__main__':\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n data = np.loadtxt('3dpd.out', delimiter=',')\n x = data[:,0]\n y = data[:,1]\n z = data[:,2]\n a = 1\n b = 0.4\n c = -2.4\n xr = data[np.where(a*data[:, 2] + b*(np.square(data[:, 1]) + np.square(data[:, 0])) + c >= 0)]\n ax.scatter(xr[:, 0], xr[:, 1], xr[:, 2], c='b', marker='o')\n xb = data[np.where(a*data[:, 2] + b*(np.square(data[:, 1]) + np.square(data[:, 0])) + c < 0)]\n ax.scatter(xb[:, 0], xb[:, 1], xb[:, 2], c='r', marker='o')\n plt.show()","sub_path":"P2/scatter_quad.py","file_name":"scatter_quad.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"593057453","text":"import pandas as pd,numpy as np\ntrain = pd.read_csv('train.csv')\nX_train = train.drop(['project_number','bid_days','bid_total','engineers_estimate','start_date'],axis=1)\ny_train = train['bid_total']\ntest = pd.read_csv('test.csv')\nX_test = test.drop(['project_number','bid_days','bid_total','engineers_estimate','start_date'],axis=1)\ny_test = test['bid_total']\n\nfrom sklearn.ensemble import RandomForestRegressor\nclf=RandomForestRegressor(n_estimators=82, n_jobs=-1,min_samples_split=2,random_state=90)\nclf.fit(X_train,y_train)\nprint(\"p=\",len(X_train.columns),\"accuracy=\",clf.score(X_test,y_test))\nimportances=clf.feature_importances_\nimport matplotlib.pyplot as plt\n'''\nplt.yscale('log', nonposy='clip')\nplt.hist(importances.ravel(), bins=2048, range=(0.0, 1e-1), fc='k', ec='k')\nplt.title(\"cdot feature importances\")\nplt.show()\n'''\ndic=dict(zip(X_train.columns,clf.feature_importances_))\ni=0\nlabels=[[]]\nclf=RandomForestRegressor(n_estimators=82, n_jobs=-1,min_samples_split=2,random_state=90)\nx=[]\ny=[]\nf=open('x_yRF.csv','bw')\nfor p in range(20,1000,1):\n for item in sorted(dic.items(), key=lambda x: x[1], reverse=True):\n labels=np.column_stack((labels,[item[0]]))\n i=i+1\n if i==p:\n break\n xx=X_train[labels[0][0]]\n xt=X_test[labels[0][0]]\n for i in range(1,p-1):\n xx=np.column_stack((xx,X_train[labels[0][i]]))\n xt=np.column_stack((xt,X_test[labels[0][i]]))\n clf.fit(xx,y_train)\n accuracy=clf.score(xt,y_test)\n# print(\"p=\",p,\" accuracy=\",accuracy)\n st=str(p)+','+str(\"%.6f\"%accuracy)+'\\n'\n f.write(st.encode('utf-8'))\n x.append(int(p))\n y.append(float(accuracy))\nplt.xlabel('no. of parameters')\nplt.ylabel('accuracy')\nplt.plot(x,y,'ko')\nfig=plt.figure(1)\nplt.savefig('accuracy.png',dpi=fig.dpi,bbox_inches='tight')\nplt.show()\nf.close()\n\n","sub_path":"cdot_rf.py","file_name":"cdot_rf.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"148720530","text":"from PIL import Image, ImageDraw, ImageFont\nfrom math import floor\nfrom data import *\n\n#########################################################################\n# Global variables\n#########################################################################\n\nXCENTER = 1600\ndotList = []\n\nSONG_TITLE_FONT_SIZE = 170\nTRANSITION_FONT_SIZE = 140\nTRANSITION_SUBTITLE_FONT_SIZE_FACTOR = 0.65\n\nMAIN_FONT_NAME = \"Arial\"\nMAIN_FONT_EXTENSION = \".ttf\"\nMAIN_FONT = MAIN_FONT_NAME + MAIN_FONT_EXTENSION\nBOLD_FONT = MAIN_FONT_NAME + \" Bold\" + MAIN_FONT_EXTENSION\n\nPRINT_INSTRUMENTS_STARTING_X = 4000\n#PRINT_INSTRUMENTS_X = [3700, 4100, 5300, 6100, 7500] #when FONT_SIZE was 140\nPRINT_INSTRUMENTS_X = [3600, 3900, 4800, 5400, 6100, 6500, 7000]\nPRINT_INSTRUMENTS_FONT_SIZE = 120\nPRINT_INSTRUMENTS_LEGEND_FONT_SIZE = 90\nPRINT_INSTRUMENTS_TAB_WIDTH = 50\n\nVERTICAL_SPACE_BETWEEN_DOTS = 3800 / len(entries)\n\n#########################################################################\n# Function definitions\n#########################################################################\n\ndef formatEntry (x, y, title, subtitle, size, alignment, bold):\n\tfontString=MAIN_FONT\n\tif bold==\"bold\":\n\t\tfontString = BOLD_FONT\n\n\tmyFont = ImageFont.truetype (fontString, size)\n\ttitleWidth, titleHeight = myFont.getsize(title)\n\tsubtitleX = x\n\n\tif alignment==\"right\":\n\t\tx = x - titleWidth\n\telif alignment==\"center\":\n\t\tx = x - floor(titleWidth/2)\n\n\tdrawtxt.text((x,y), title, font=myFont, fill=TEXT_COLOUR)\n\n\tsubtitleHeight=0\n\t\n\tif subtitle!=\"\":\n\t\tyOffset = 15\n\t\tmyFont = ImageFont.truetype (MAIN_FONT, floor(size * TRANSITION_SUBTITLE_FONT_SIZE_FACTOR))\n\t\tsubtitleWidth, subtitleHeight = myFont.getsize(subtitle)\n\t\t\n\t\tif alignment==\"right\":\n\t\t\tsubtitleX = x - subtitleWidth + titleWidth\n\t\telif alignment==\"center\":\n\t\t\tsubtitleX = x - floor((subtitleWidth + titleWidth)/2)\n\t\telif alignment==\"left\":\n\t\t\tsubtitleX = x\n\n\t\tdrawtxt.text((subtitleX,y+titleHeight+yOffset), subtitle, font=myFont, fill=TEXT_COLOUR)\n\treturn titleHeight, subtitleHeight\n\n\ndef addEntry (printInstruments, song, y, title, subtitle=\"\"):\n\tx = XCENTER\n\tresetY = y\n\tresetTitle = title\n\txoffset = 200\n\tbold = False\n\talignment = \"right\"\n\tsize = TRANSITION_FONT_SIZE\n\n\tif song:\n\t\tbold = \"bold\"\n\t\talignment = \"left\"\n\t\tx += xoffset\n\t\tsize = SONG_TITLE_FONT_SIZE\n\t\ttitle = title.upper()\n\telse:\n\t\tx -= xoffset\n\n\t(titleHeight, subtitleHeight) = formatEntry (x, y, title, subtitle, size, alignment, bold)\n\tx = XCENTER\n\t#y += (titleHeight + subtitleHeight) * 0.6\n\to = 50\n\tyCorrection = 80\n\tdrawobj.ellipse(xy=[(x-o,y-o+yCorrection),(x+o,y+o+yCorrection)], fill=TEXT_COLOUR, outline=None)\n\tdotList.append((x,y+yCorrection,song))\n\ty += VERTICAL_SPACE_BETWEEN_DOTS \n\t\n\tif printInstruments and song:\n\t\ttitle = resetTitle\n\n\t\tfor i in range(0,len(songInstruments[title])):#songInstruments[title]:\n\t\t\tmyFont = ImageFont.truetype (MAIN_FONT, PRINT_INSTRUMENTS_FONT_SIZE)\n\t\t\tx = PRINT_INSTRUMENTS_X[i]\n\t\t\ty = resetY\n\t\t\tname = songInstruments[title][i]\n\t\t\tif name!=\"\":\n\t\t\t\tif name[0]=='*':\n\t\t\t\t\tnumberStr = name[1]\n\t\t\t\t\tspecialInstrument = specials[name[3:]]\n\t\t\t\t\tinstrumentName = specialInstrument[0]\n\t\t\t\t\tif int(numberStr)>1:\n\t\t\t\t\t\tinstrumentName = instrumentName + \"s\"\n\n\t\t\t\t\tline1 = numberStr + ' ' + instrumentName\n\t\t\t\t\tL1offset = 100\n\t\t\t\t\ty -= L1offset\n\n\t\t\t\t\tdrawtxt.text((x,y), line1, font=myFont, fill=TEXT_COLOUR)\n\t\t\t\t\tnLines = len(specialInstrument)-1\n\n\t\t\t\t\tx += 50\n\t\t\t\t\ty += L1offset + 20\n\t\t\t\t\tmyFont = ImageFont.truetype (MAIN_FONT, PRINT_INSTRUMENTS_LEGEND_FONT_SIZE)\n\t\t\t\t\tfor j in range (0, nLines):\n\t\t\t\t\t\tdrawtxt.text((x,y), '• '+specialInstrument[j+1], font=myFont, fill=TEXT_COLOUR)\n\t\t\t\t\t\ty += 100\n\t\t\t\t\t#print (line1 + str(nLines))\n\t\t\t\telse:\n\t\t\t\t\tdrawtxt.text((x,y), name, font=myFont, fill=TEXT_COLOUR)\n\t\t\t\t\t#instrumentWidth, instrumentHeight = myFont.getsize(i)\n\t\t\t\t\t#x += 1000 #instrumentWidth + PRINT_INSTRUMENTS_TAB_WIDTH\n\n\ndef addAllEntries(y, printInstruments):\n\tx = XCENTER\n\ty0 = y\n\tdashLineWidth = 6000\n\tystep = VERTICAL_SPACE_BETWEEN_DOTS\n\tfor e in entries:\n\t\tif len(e) == 3:\n\t\t\taddEntry (printInstruments, e[0], y, e[1], e[2])\n\t\telse:\n\t\t\taddEntry (printInstruments, e[0], y, e[1])\n\t\ty += ystep\n\tdrawobj.line([dotList[0][0], dotList[0][1], dotList[-1][0], dotList[-1][1]], fill=TEXT_COLOUR, width=25)\n\n\tyInterval = averageSongDotYInterval()\n\n\tfor d in dotList:\n\t\t#print (str(d[0]) + \", \" + str(d[1]) + \" -- \" + str(d[2]))\n\t\tendX = d[0]\n\t\tspan = 100\n\t\tif d[2]: #if song==True\n\t\t\tendX += span\n\t\telse:\n\t\t\tendX -= span\n\t\tdrawobj.line([d[0], d[1], endX, d[1]], fill=TEXT_COLOUR, width=25)\n\t\tif d[2]:\n\t\t\tx = d[0] + 2000\n\t\t\ty = d[1] - floor(yInterval/2)\n\t\t\tdrawDashedLine (x, y, dashLineWidth)\n\n\tdrawDashedLine (x, dotList[-1][1] + floor(yInterval/2), dashLineWidth)\n\ndef averageSongDotYInterval():\n\tlistOfYValues = []\n\tlistOfYIntervals = []\n\tfor e in dotList:\n\t\tif e[2]:\n\t\t\tlistOfYValues.append(e[1])\n\tfor i in range (0, len(listOfYValues)-1):\n\t\tlistOfYIntervals.append(listOfYValues[i+1]-listOfYValues[i])\n\taverageYInterval = sum(listOfYIntervals) / len(listOfYIntervals)\n\treturn averageYInterval\n\ndef drawDashedLine (x, y, w):\n\tmedian = floor(255/2)\n\tgrey = (median, median, median, median)\n\tstop = x + w\n\twidth = 30\n\tspace = 25\n\t#drawobj.line([x, y, x+w, y], fill=grey, width=2)\n\twhile (x < stop):\n\t\tdrawobj.line([x, y, x+width, y], fill=grey, width=2)\n\t\tx += width + space\n\ndef generatePage(img, txt, suffix):\n\typosition = 300\n\tyincrement = 400\n\tformatEntry (XCENTER, yposition, TITLE, \"\", 250, \"center\", \"bold\")\n\typosition += yincrement*2\n\taddAllEntries (yposition, True)\n\tif suffix==\"\":\n\t\tsuffix = BACKGROUND_COLOUR\n\telif suffix==\"phone\":\n\t\tbasewidth = 300\n\t\twpercent = (basewidth/float(txt.size[0]))\n\t\thsize = int((float(img.size[1])*float(wpercent)))\n\t\ttxt = txt.resize((basewidth,hsize), Image.ANTIALIAS)\n\timg.paste(txt,(0,0),txt)\n\timg.save(\"Timeline - \" + suffix + \".png\",'PNG')\n\t\t\n#########################################################################\n# A4, black background\n#########################################################################\n\nBACKGROUND_COLOUR = \"black\"\nimg = Image.open (BACKGROUND_COLOUR+\"-bg.png\")\ntxt = Image.new ('RGBA', img.size, (255,255,255,0))\nTEXT_COLOUR=\"white\"\ndrawtxt = ImageDraw.Draw (txt)\ndrawobj = ImageDraw.ImageDraw (img)\ndotList = []\ngeneratePage(img, txt, \"black\")\n\n#########################################################################\n# Phone screen, black background\n#########################################################################\n\nBACKGROUND_COLOUR = \"black\"\nphone = img.crop((0,0,3600,5500))\nphone.save(\"Timeline - phone.png\",'PNG')\n\n#########################################################################\n# A4, white background\n#########################################################################\n\nBACKGROUND_COLOUR = \"white\"\nimg = Image.open (BACKGROUND_COLOUR+\"-bg.png\")\ntxt = Image.new ('RGBA', img.size, (255,255,255,0))\nTEXT_COLOUR=\"black\"\ndrawtxt = ImageDraw.Draw (txt)\ndrawobj = ImageDraw.ImageDraw (img)\ndotList = []\ngeneratePage(img, txt, \"white\")\n\n","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"578030719","text":"import requests\n\nRATES_API_URL = 'http://openexchangerates.org/api/latest.json'\nRATES_BASE_CURRENCY = 'USD'\nRATES_API_KEY = '6811c6886579435393126dc9bab941af'\nCURRENCY_TO = ['CNY', 'USD', 'EUR', 'JPY', 'HKD', 'TWD', 'GBP', 'SEK', 'THB']\nFORMAT = '{}?app_id={}&base={}'\n\ndef yield_rates():\n '''\n 生成汇率\n '''\n\n print('yield_rates')\n res = requests.get(\n FORMAT\n .format(RATES_API_URL, RATES_API_KEY, RATES_BASE_CURRENCY)\n )\n\n if not res.status_code == 200:\n raise Exception(\"ERROR: API rquest unsuccessful\")\n\n data = res.json()\n rates = data.get('rates')\n usd_to_cny = rates.get('CNY')\n\n for currency_to in CURRENCY_TO:\n yield currency_to, change_base_currency(usd_to_cny, rates.get(currency_to))\n\n\ndef change_base_currency(usd_to_cny, usd_to_currency):\n '''\n from usd -> from cny\n '''\n\n return usd_to_currency / usd_to_cny\n","sub_path":"depostSystem/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"317201464","text":"def consume_archive(out, iterable, smoke=False):\n if smoke:\n error_out = out\n else:\n from sys import stderr as error_out\n for y in iterable:\n try:\n out.write(y)\n except TypeError:\n print(*y[:2], sep=r': ', file=error_out)\n error_out.write(y[2])\n","sub_path":"pyar/consume_archive.py","file_name":"consume_archive.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"555905117","text":"\n\n#calss header\nclass _DISEMBOWEL():\n\tdef __init__(self,): \n\t\tself.name = \"DISEMBOWEL\"\n\t\tself.definitions = [u'to remove the stomach and bowels from a dead animal, or to kill a person in this way, especially in the past as a punishment']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_disembowel.py","file_name":"_disembowel.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"74919173","text":"'LeetCode 231 power_of_two'\r\n\r\nclass Solution(object):\r\n def isPowerOfTwo(self, n):\r\n \"\"\"\r\n :type n: int\r\n :rtype: bool\r\n \"\"\"\r\n if n == 1:\r\n return False\r\n while n>1:\r\n if n%2:\r\n return False\r\n else:\r\n n=n/2\r\n return True\r\n def isPower(self, n):\r\n \treturn n>0 and not (n & n-1)\r\n\r\nif __name__ == '__main__':\r\n s=Solution()\r\n n=-11\r\n d=s.isPower(n)\r\n print (d)\r\n","sub_path":"power_of_two.py","file_name":"power_of_two.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"250125209","text":"from lxml import etree\nfrom bs4 import BeautifulSoup\nfrom requests import RequestException\nimport requests, random, re, json,os\nfrom pyquery import PyQuery\nfrom urllib.parse import urlencode\nfrom urllib.request import urlretrieve\n\nuserAgent = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586',\n'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',\n'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',\n'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',\n'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0)',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 BIDUBrowser/8.3 Safari/537.36',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.9.2.1000 Chrome/39.0.2146.0 Safari/537.36',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 Core/1.47.277.400 QQBrowser/9.4.7658.400',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 UBrowser/5.6.12150.8 Safari/537.36',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER',\n'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36 TheWorld 7',\n'Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36 V1_AND_SQ_5.3.1_196_YYB_D QQ/5.3.1.2335 NetType/WIFI',\n'Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36 MicroMessenger/6.0.2.56_r958800.520 NetType/WIFI',\n'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257 QQ/5.2.1.302 NetType/WIFI Mem/28',\n'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257 MicroMessenger/6.0.1 NetType/WIFI',]\n# 报头信息,多种用户代理可供选择\n\ndef getPage(url):\n '''\n 通过网址得到网页代码\n :param url: 网址\n :return: 如果网页不响应,返回None,如果响应返回网页代码\n '''\n try:\n headers = {'User-Agent':random.choice(userAgent)}\n res=requests.get(url,headers=headers)\n if(res.status_code==200):\n return res.text\n else:\n return None\n except RequestException:\n return None\n\n\ndef parsePagePY(content):\n '''\n 用PyQuery方法处理豆瓣图书数据\n :param content: 网页内容\n :return: 带有相应信息的字典\n '''\n html = PyQuery(content)\n items = html(\"tr.item\")\n\n for item in items.items():\n a = item.find('a.nbg').attr('onclick')\n print(a)\n print(item.find('p:eq(0)').text())\n yield {\n 'rank': str(int(re.findall(\"moreurl\\(this,{i:'(.*?)'}\\)\",a)[0])+1),\n 'pic': item.find('a').attr('href'),\n 'name': item.find('div a').attr('title'),\n 'mark': item.find('span.rating_nums').text(),\n 'author': item.find('p:eq(0)').text(),\n }\n\n\ndef parsePageXP(content):\n '''\n 用XPath方法处理豆瓣图书数据\n :param content: 网页内容\n :return: 带有相应信息的字典\n '''\n html = etree.HTML(content)\n items = html.xpath('//table/tr')\n #print(items)\n for item in items:\n a=item.xpath('.//a[@class=\"nbg\"]/@onclick')\n print(item.xpath('.//img[@width=\"90\"]/@src'))\n\n yield {\n 'rank': str(int(re.findall(\"moreurl\\(this,{i:'(.*?)'}\\)\",a[0])[0])+1),\n 'pic': item.xpath('.//img[@width=\"90\"]/@src')[0],\n 'name': item.xpath('.//div/a/@title')[0],\n 'mark': item.xpath('.//span[@class=\"rating_nums\"]/text()')[0],\n 'author' : item.xpath('//p/text()')[2],\n }\n\n\n\ndef parsePageBS(content):\n '''\n 用BeautifulSoup方法处理豆瓣图书数据\n :param content: 网页内容\n :return: 带有相应信息的字典\n '''\n html = BeautifulSoup(content,'lxml')\n items = html.find_all(name=\"tr\", attrs={\"class\":\"item\"})\n\n for item in items:\n a = item.find(name=\"a\",attrs={'class':'nbg'}).attrs['onclick']\n\n yield {\n 'rank': str(int(re.findall(\"moreurl\\(this,{i:'(.*?)'}\\)\",a)[0])+1),#测试这个的问题\n 'pic': item.find(name=\"img\", attrs={'width':'90'}).attrs['src'],\n 'name': item.find(name=\"a\", attrs={'title': True}).attrs['title'],\n 'mark': item.select('span.rating_nums')[0].string,\n 'author': item.find(name=\"p\", attrs={\"class\":True}).string,\n }\n\n\ndef writeFile(content):\n '''\n 解析爬取网页中内容,并返回结果\n :param content: 网页代码\n :return: None\n '''\n with open(\"./result.txt\",'a',encoding=\"utf-8\") as f:\n f.write(json.dumps(content,ensure_ascii=False)+\"\\n\")\n\ndef bookMain(offset, option):\n '''\n\n :param offset: 选择爬取的页数\n :param option: 选择解析的方法\n :return:\n '''\n for i in range(0,offset+1):\n url = 'https://book.douban.com/top250?start='+str(offset)\n html = getPage(url) #执行爬取\n if html:\n if(option=='1'):\n for item in parsePageXP(html): #执行解析并遍历\n print(item)\n writeFile(item) #执行写操作\n elif(option=='2'):\n for item in parsePageBS(html): #执行解析并遍历\n print(item)\n writeFile(item) #执行写操作\n elif(option=='3'):\n for item in parsePagePY(html): #执行解析并遍历\n print(item)\n writeFile(item) #执行写操作\n\n\ndef showCart():\n '''\n 京东购物车爬虫。通过对cookie等处理,爬取其商品描述与价格,并打印出来。用BeautifulSoup筛选数据\n :return: None\n '''\n para = {'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',\n 'cache-control':'max-age=0',\n 'cookie':'3AB9D23F7A4B3C9B=7OJ4YCECRFKW3VVAJRUHD35I37MRKSDDNQL6BWXXQNLPEZTC37WARLSNXQLSWZIPMGLLZOQFSEHAJPO4OI3MOK6F6A; __jdv=122270672|direct|-|none|-|1525709885231; __jdu=14782404; PCSYCityID=1213; ipLoc-djd=1-72-2799-0; user-key=770bec6c-1c30-43f9-a684-a1a3fece95fc; shshshfp=131cccb7ba454e168f0b7781af85c969; shshshfpa=7c6b6cd4-3dbc-783a-9818-baeef089469e-1526388623; __jda=122270672.14782404.1521363148.1525709885.1526388624.2; __jdc=122270672; shshshfpb=211fc1ba49005430ab5029f4c14f3304c5afa060853c96c1866d9d6d93; cart-main=xx; cn=4; cd=0; __jdb=122270672.7.14782404|2.1526388624; shshshsID=a8f0a54b156bbde9fb91183f320a9aa6_4_1526388944597',\n 'referer':'https://cart.jd.com/addToCart.html?rcd=1&pid=10430900577&pc=1&eb=1&rid=1526388740244&em=',\n 'upgrade-insecure-requests':'1',\n 'user-agent':random.choice(userAgent),}\n url = 'https://cart.jd.com/cart.action'\n\n response = requests.get(url,headers= para)\n\n html = BeautifulSoup(response.text, 'lxml')\n name = html.find_all(name='a', attrs={'clstag':'clickcart|keycount|xincart|cart_sku_name'})\n price = html.find_all(name='div', attrs={'class':'cell p-price p-price-new '})\n for i in range(0, len(name)):\n print(\"详细描述: \"+name[i].string)\n print(\"价格: \"+price[i].find(name='strong').string)\n\ndef getImgPage(offset):\n '''\n 处理网页数据,将处理好带有图片url信息的字典返回。首先将带有页数信息的参数传入网页,将返回信息筛选,有效信息返回。\n :param offset: 需要爬取的页数\n :return: 带有图片url信息的字典\n '''\n params = []\n for i in range(30, 30 * offset + 30, 30):\n params.append({\n 'tn': 'resultjson_com',\n 'ipn': 'rj',\n 'ct': 201326592,\n 'is': '',\n 'fp': 'result',\n 'queryWord': '街拍',\n 'cl': 2,\n 'lm': -1,\n 'ie': 'utf-8',\n 'oe': 'utf-8',\n 'adpicid': '',\n 'st': -1,\n 'z': '',\n 'ic': 0,\n 'word': '街拍',\n 's': '',\n 'se': '',\n 'tab': '',\n 'width': '',\n 'height': '',\n 'face': 0,\n 'istype': 2,\n 'qc': '',\n 'nc': 1,\n 'fr': '',\n 'pn': i,\n 'rn': 30,\n 'gsm': '1e',\n '1488942260214': ''\n })\n url = 'https://image.baidu.com/search/acjson'\n urls = []\n for i in params:\n urls.append(requests.get(url, params=i).json().get('data'))\n\n return urls\n\n\ndef saveImage(item):\n '''\n 保存图片于程序根目录下的mypic文件夹中。如果mypic文件夹不存在,建立此文件夹。通过遍历参数传递过来的字典,取得其中url\n 的值,并用urlretrieve方法将其存下来。\n :param item: 带有url信息的字典\n :return: None\n '''\n path = \"./mypic/\"\n if not os.path.exists(path): # 如果文件夹不存在新建文件夹\n os.mkdir(path)\n\n x = 0\n for list in item:\n for i in list:\n if i.get('thumbURL') != None:\n urlretrieve(i.get('thumbURL'),path+str(x)+'.jpg')\n x += 1\n else:\n print('图片链接不存在')\n\n print(\"爬取完成,图片已存在根目录下mypic文件夹\")\n\n\nif __name__ == '__main__':\n '''主入口程序,简单的GUI界面让用户简单使用程序'''\n x=True\n while x==True:\n print(\"欢迎使用爬虫程序,请选择需要使用的功能\\n\")\n print(\"1. 豆瓣图书TOP250爬虫\\n\")\n print(\"2. 京东购物车爬虫\\n\")\n print(\"3. 百度图片街拍爬虫\\n\")\n print(\"请选择(q键为退出键)\")\n a=input()\n if a=='1':\n print(\"请选择爬取方式:\\n\")\n print(\"1. Xpath爬取\\n\")\n print(\"2. BeautifulSoup爬取\\n\")\n print(\"3. PyQuery爬取\\n\")\n b=input()\n print(\"请选择爬取的页数:\\n\")\n c=input()\n bookMain(int(c),b)\n elif a=='2':\n showCart()\n elif a=='3':\n print(\"请选择想要爬取的页数(每页30张图片)\")\n a=input()\n saveImage(getImgPage(int(a)))\n elif a=='q':\n x=False","sub_path":"ClassHomeWork/Week8/threeSpiders.py","file_name":"threeSpiders.py","file_ext":"py","file_size_in_byte":11113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259917785","text":"#Sara Margaret Rizzo\r\n#2020-08-22\r\n\r\n#Problem 1: Write a function areaOfCircle(r) which returns the area of a circle of radius r. \r\n#Make sure you use the math module in your solution.\r\n\r\n#use math module, need for pi\r\nimport math\r\n\r\n#function that calculates area of circle, area = pi*r^2\r\ndef area(r):\r\n a = math.pi * r**2\r\n return a\r\n\r\n#ask user for radius, change type to integer\r\nr = int(input(\"What is the radius of the circle? \"))\r\n\r\n#take input, calculate area\r\nresult = area(r)\r\nprint(\"The area of the circle is\", result)\r\n\r\n\r\n\r\n","sub_path":"Problem1AreaOfCircle.py","file_name":"Problem1AreaOfCircle.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"251285257","text":"from django import forms\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.utils.translation import ugettext_lazy as _\nfrom .models import Invoice\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm \n\nclass BootstrapAuthenticationForm(AuthenticationForm):\n \"\"\"Authentication form which uses boostrap CSS.\"\"\"\n username = forms.CharField(max_length=254,\n widget=forms.TextInput({\n 'class': 'form-control',\n 'placeholder': 'User name'}))\n password = forms.CharField(label=_(\"Password\"),\n widget=forms.PasswordInput({\n 'class': 'form-control',\n 'placeholder':'Password'}))\n\nclass InvoiceForm(forms.ModelForm):\n class Meta:\n model = Invoice\n fields = ['date_creation', 'amount', 'product','company',]\n widgets = {\n 'date_creation': forms.DateInput(attrs={'class':'datepicker'}),\n }\n labels = {\n 'date_creation': 'Fecha',\n 'amount': 'Monto',\n 'product': 'Concepto',\n 'company': 'Facturar a:',\n }\n help_texts = {\n 'date_creation': 'Ingrese la fecha del periodo a facturar',\n 'amount': 'Ingrese el monto a facturar en valores absolutos',\n }\n\nclass InvoiceClientEdit(forms.ModelForm):\n class Meta:\n model = Invoice\n fields = ['date_creation', 'amount', 'product','company',]\n widgets = {\n 'date_creation': forms.DateInput(format=('%Y-%m-%d'),attrs={'class':'datepicker'}),\n }\n labels = {\n 'date_creation': 'Fecha',\n 'amount': 'Monto',\n 'product': 'Concepto',\n 'company': 'Facturar a:',\n }\n help_texts = {\n 'date_creation': 'Ingrese la fecha del periodo a facturar',\n 'amount': 'Ingrese el monto a facturar en valores absolutos',\n }\n\nclass InvoiceAdminEdit(forms.ModelForm):\n class Meta:\n model = Invoice\n fields = ['date_creation', 'amount', 'date_jde', 'jde_number', 'product', 'company', 'description']\n widgets = {\n 'date_creation': forms.DateInput(format=('%Y-%m-%d'),attrs={'class':'datepicker'}),\n 'date_jde': forms.DateInput(format=('%Y-%m-%d'),attrs={'class':'datepicker'}),\n }\n labels = {\n 'date_creation': 'Fecha Facturacion',\n 'amount': 'Monto',\n 'date_jde': 'Fecha factura JDE',\n 'jde_number': 'Numero Factura JDE',\n 'product': 'Concepto',\n 'company':'Facturar a:',\n 'description': 'Descripcion',\n }\n\nclass RegistrationForm(UserCreationForm):\n username = forms.CharField(required = True, label = \"Usuario - Codigo JDE\")\n first_name = forms.CharField(required = True, label = \"Razon Social\")\n\n class Meta:\n model = User\n fields = ('username', 'first_name', 'password1', 'password2') \n\n def save(self,commit = True): \n user = super(RegistrationForm, self).save(commit = False)\n user.username = self.cleaned_data['username']\n user.first_name = self.cleaned_data['first_name']\n \n if commit:\n user.save()\n\n return user\n\nclass UserEdit(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name',) \n labels = {\n 'first_name': 'Razon Social' \n }\n help_texts = {\n 'first_name': 'Ingrese la razon social del usuario',\n }","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"428526120","text":"import tkinter\n\nclass MyApp(tkinter.Frame):\n def __init__(self, master=None):\n super().__init__()\n self.pack()\n\n self.names = (\"Donald Duck\", \"Dagobert Duck\", \"Gustav Gans\")\n\n self.group = tkinter.LabelFrame(self)\n self.group.configure(text = \"Entenhausen\")\n self.group.pack()\n\n self.checks = list()\n self.vars = list()\n\n for name in self.names:\n var = tkinter.BooleanVar()\n var.set(False)\n \n check = tkinter.Checkbutton(self.group)\n check.configure(text = name, command = self.handler, variable = var)\n check.pack(anchor = \"w\")\n \n self.checks.append(check)\n self.vars.append(var)\n \n self.label = tkinter.Label()\n self.label.pack()\n\n def handler(self):\n self.label.configure(text = \" und \".join([name for name, var in zip(self.names, self.vars) if var.get()]))\n\nroot = tkinter.Tk()\napp = MyApp(root)\napp.mainloop()\n","sub_path":"Tk_Toolkit/NewBook/widgets5.py","file_name":"widgets5.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"551027046","text":"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nfrom torchvision import datasets, transforms\r\nimport torch.utils.data\r\nimport torch.optim as optim\r\nimport owntool\r\nimport model\r\nimport mutil\r\nfrom datetime import datetime\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport data_convert\r\n\r\nimport os\r\nimport sys,shutil\r\n\r\n# chagne today : 2017/5/9\r\nngpu = 1\r\nif __name__ == '__main__':\r\n hidden_d = 128 # the dimension of the feature map in the first layer\r\n\r\nmain_gpu = 7\r\n\r\ncolumn = 10\r\ntorch.cuda.set_device(main_gpu)\r\n\r\nmnist = input_data.read_data_sets('../../MNIST_data', one_hot=False)\r\nmm = data_convert.owndata()\r\n\r\nseed_num = 1\r\ntorch.cuda.manual_seed(seed_num)\r\ndata_dir = '/home/bike/data/mnist/'\r\nout_dir = '/home/bike/2027/generative-models/GAN/conditional_gan/new_f3_no_label_{}/'.format(datetime.now())\r\n\r\nif not os.path.exists(out_dir):\r\n os.makedirs(out_dir)\r\n shutil.copyfile(sys.argv[0], out_dir + '/new_mnist_feature3_no_label.py')\r\n\r\nsys.stdout = mutil.Logger(out_dir)\r\n\r\nbatch_size = 50\r\nfeature_size = 32\r\n\r\nkwargs = {'num_workers': 1, 'pin_memory': True}\r\n\r\ndef weights_init(m):\r\n classname = m.__class__.__name__\r\n if classname.find('Conv') != -1:\r\n m.weight.data.normal_(0.0, 0.02)\r\n # elif classname.find('BatchNorm') != -1:\r\n # m.weight.data.normal_(1.0, 0.02)\r\n # m.bias.data.fill_(0)\r\n\r\n\r\n# layer_names = list(model.keys())\r\n\r\n# write the origin model again.\r\n\r\n# D0 = model.E_Net_small()\r\nencoder_model = torch.load(\"/home/bike/2027/generative-models/tools/D_mnist_little3.model\")\r\n\r\n# 24*24\r\nenet = model.E_Net_small().cuda()\r\nenet.load_state_dict(encoder_model)\r\n\r\nadd_in_feature = feature_size+ hidden_d # Add one dimension data for the input_feature data.\r\nG = model.G_Net_FM_3(ngpu,add_in_feature,main_gpu=main_gpu).cuda()\r\n# g_model = torch.load(\"/home/bike/2027/generative-models/GAN/conditional_gan/mnist_pretrain_DG/G_60000.model\")\r\n# G.load_state_dict(g_model)\r\n\r\nin_channel = 1\r\nE = model.Ev_Net_conv(ngpu,in_channel,main_gpu=main_gpu).cuda()\r\n# E.apply(weights_init)\r\n# G.apply(weights_init)\r\n\r\nd_in_demension = 1\r\nD = model.D_Net_conv(ngpu,d_in_demension,main_gpu=main_gpu).cuda()\r\n# d_model = torch.load(\"/home/bike/2027/generative-models/GAN/conditional_gan/mnist_pretrain_DG/D_60000.model\")\r\n# D.load_state_dict(d_model)\r\n\r\nG_solver = optim.Adam(G.parameters(),lr = 1e-4)\r\nD_solver = optim.Adam(D.parameters(), lr = 1e-4)\r\nE_solver = optim.Adam(E.parameters(), lr = 1e-4)\r\n\r\nhalf_label = Variable(torch.ones(batch_size)*0.5).cuda()\r\n\r\ncheck_points = 500\r\nnum_epoches = 100000\r\ncriterion = nn.BCELoss()\r\ncriterion_t = nn.TripletMarginLoss(p=1)\r\ncriterion_mse = nn.MSELoss()\r\n\r\nfor epoch in (range(1,num_epoches)):\r\n# D PART ./ data_old/ d_f3 / error\r\n data, label = mm.batch_next(batch_size,label = [8], shuffle=False)\r\n D_solver.zero_grad()\r\n G_solver.zero_grad()\r\n data_old = Variable(torch.from_numpy(data.astype('float32'))).cuda()\r\n data_old.data.resize_(batch_size, 1, 28, 28)\r\n _,_,_,f3 = enet(data_old.detach())\r\n d_f3 = f3.cuda()\r\n g_sampler = Variable((torch.randn([batch_size,hidden_d,1,1]))).cuda()\r\n d_f3.data.resize_(batch_size,feature_size,1,1)\r\n d_f3 = d_f3.detach()\r\n d_f3_output = G(torch.cat([d_f3,g_sampler],1)).detach()\r\n d_false_decision = D(d_f3_output)\r\n d_false_error = criterion(d_false_decision,Variable(torch.zeros(batch_size)).cuda())\r\n\r\n d_real_decision = D(data_old)\r\n d_real_error = criterion(d_real_decision,Variable(torch.ones(batch_size)).cuda())\r\n\r\n # d_real_false_error = criterion(d_real_decision/2 + d_false_decision/2, half_label)\r\n d_real_error.backward()\r\n d_false_error.backward()\r\n # error = d_real_error + d_false_errord_false_error\r\n # error.backward()\r\n D_solver.step()\r\n\r\n# G Part / data_g / g_f3 / dg_error\r\n D.zero_grad()\r\n G.zero_grad()\r\n data_g, label_g = mm.batch_next(batch_size,label = [8], shuffle=False)\r\n data_g = Variable(torch.from_numpy(data_g.astype('float32'))).cuda()\r\n # data_g.data.resize_(batch_size, 1, 28, 28)\r\n _,_,_,f3 = enet(data_g)\r\n g_f3 = f3.cuda()\r\n g_f3.data.resize_(batch_size,feature_size,1,1)\r\n g_f3 = g_f3.detach()\r\n\r\n g_sampler = Variable((torch.randn([batch_size,hidden_d,1,1]))).cuda()\r\n g_f3_output = G(torch.cat([g_f3,g_sampler],1))\r\n # G for fake data\r\n # c_v = Variable(model.set_label_f3(f3)).cuda()\r\n dg_decision = D(g_f3_output)\r\n dg_error = criterion(dg_decision,Variable(torch.ones([batch_size,1])).cuda())\r\n dg_error.backward()\r\n G_solver.step()\r\n# Evaluator: Triplet Net\r\n # E part\r\n # For E, triplet part\r\n D_solver.zero_grad()\r\n G_solver.zero_grad()\r\n # E_solver.zero_grad()\r\n\r\n# X, c = mm.batch_next(batch_size, shuffle=False)\r\n# X = Variable(torch.from_numpy(X.astype('floatxccc'))).cuda()\r\n# E_anch = E(X)\r\n#\r\n# X2, c2 = mm.batch_next(batch_size, shuffle=False)\r\n# X2 = Variable(torch.from_numpy(X2.astype('float32'))).cuda()\r\n# E_real = E(X2)\r\n#\r\n# new_label_base = np.array(range(10))\r\n# new_label = (new_label_base + (np.random.rand(10) * 9 + 1).astype('int'))%10\r\n# X3, c3 = mm.batch_next(batch_size, label=new_label, shuffle=False)\r\n# X3 = Variable(torch.from_numpy(X3.astype('float32'))).cuda()\r\n# E_fake = E(X3)\r\n#\r\n# E_loss = criterion_t(E_anch, E_real, E_fake)\r\n# E_loss.backward()\r\n# E_solver.step()\r\n#\r\n# # Evaluator: G\r\n# D.zero_grad()\r\n# E.zero_grad()\r\n#\r\n# # For E ( generated data )\r\n# _,_,_,f3 = enet(X)\r\n# e_f3 = f3.cuda()\r\n# e_f3.data.resize_(batch_size,feature_size,1,1)\r\n# e_f3 = e_f3.detach()\r\n# # e_f3 = F.sigmoid(e_f3)\r\n# g_sampler = Variable((torch.randn([batch_size,hidden_d,1,1]))).cuda()\r\n# G_sample = G(torch.cat([e_f3,g_sampler],1))\r\n# E_real = E(G_sample)\r\n# E_anch = E(X)\r\n# # genereted (another kind of data)\r\n# # data_ol == data_other_label\r\n# new_label_base = np.array(range(10))\r\n# new_label = (new_label_base + (np.random.rand(10) * 9 + 1).astype('int'))%10\r\n# data_ol, label_ol = mm.batch_next(batch_size, label = new_label, shuffle=False)\r\n# data_ol = Variable(torch.from_numpy(data_ol.astype('float32'))).cuda()\r\n# # data_ol.data.resize_(batch_size, 1, 28, 28)\r\n# _,_,_,f3_fake = enet(data_ol)\r\n# g_f3_fake = f3_fake.cuda()\r\n# # g_f3_fake = F.sigmoid(g_f3_fake)\r\n# g_f3_fake.data.resize_(batch_size,feature_size,1,1)\r\n# g_f3_fake = g_f3_fake.detach()\r\n# g_sampler = Variable(torch.randn([batch_size,hidden_d,1,1])).cuda()\r\n# G_sample_fake = G(torch.cat([g_f3_fake,g_sampler],1))\r\n# E_fake = E(G_sample_fake)\r\n# # E_anch = E(X)\r\n# E_loss = criterion_t(E_anch, E_real, E_fake)\r\n# E_loss.backward()\r\n# G_solver.step()\r\n\r\n # Housekeeping - reset gradient\r\n # print(\"heelo\")\r\n if(epoch%check_points==0):\r\n # observe the weight of two pictures\r\n zeroinput = Variable(torch.zeros([batch_size, hidden_d,1,1])).cuda()\r\n g_zero_output = G(torch.cat([g_f3, zeroinput], 1))\r\n\r\n g_sampler2 = Variable((torch.rand([batch_size, hidden_d,1,1]))).cuda()\r\n g_f3_output1 = G(torch.cat([g_f3, g_sampler2], 1))\r\n\r\n\r\n\r\n # owntool.save_picture(data, out_dir + \"recon_epoch{}_data.png\".format(epoch ),column=column)\r\n owntool.save_picture(data_g, out_dir + \"recon_epoch{}_data_old.png\".format(epoch ),column=column)\r\n owntool.save_picture(g_zero_output, out_dir + \"recon_epoch{}_zero.png\".format(epoch),column=column)\r\n owntool.save_picture(g_f3_output1, out_dir + \"recon_epoch{}_real.png\".format(epoch),column=column)\r\n\r\n print(\"%s: D: %s/%s G: %s (Real: %s, Fake: %s) \"% (epoch,\r\n owntool.extract(d_real_error)[0],\r\n owntool.extract(d_false_error)[0],\r\n owntool.extract(dg_error)[0],\r\n owntool.stats(owntool.extract(d_real_decision)),\r\n owntool.stats(owntool.extract(d_false_decision)),\r\n # owntool.stats(owntool.extract(E_loss)[0])\r\n )\r\n )\r\n if(epoch%(check_points*10)==0):\r\n np.set_printoptions(precision=2,suppress=True)\r\n # print(\"real\")\r\n # print( np.array(E_real.data.tolist()))\r\n # print(\"anch\")\r\n # print( np.array(E_anch.data.tolist()))\r\n # print(\"fake\")\r\n # print( np.array(E_fake.data.tolist()))\r\n torch.save(G.state_dict(), '{}/G_{}.model'.format(out_dir, str(epoch)))\r\n torch.save(D.state_dict(), '{}/D_{}.model'.format(out_dir, str(epoch)))","sub_path":"GAN/conditional_gan/cgan_feature3_single.py","file_name":"cgan_feature3_single.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"184589189","text":"import os\nimport pickle\nimport time\nimport sys\n\nfrom LoadVietSentiWordNet import SentimentWordNet\n\nclass Word(object):\n def __init__(self, string ,idf_positive=0, idf_neutral=0, idf_negative=0, label_idx = 0):\n self.string = string\n self.sentiment_labels = [idf_negative, idf_neutral, idf_positive]\n self.idf_positive = self.get_idf_pos()\n self.idf_neutral = self.get_idf_neu()\n self.idf_negative = self.get_idf_neg()\n self.index = -1\n\n def get_idf_neg(self):\n return self.sentiment_labels[0]\n\n def get_idf_neu(self):\n return self.sentiment_labels[1]\n\n def get_idf_pos(self):\n return self.sentiment_labels[2]\n\n def get_idf(self):\n return (self.sentiment_labels[0], self.sentiment_labels[1], self.sentiment_labels[2])\n\n @classmethod\n def init_with_sentiment_label(cls, string, label_idx):\n try:\n word = Word(string)\n word.sentiment_labels[label_idx] +=1\n return word\n except:\n print(label_idx)\n\nclass BoomVocabulary(object):\n def __init__(self, vocabulary = {}, alphabet = None):\n self.vocabulary = vocabulary\n self.vocabulary[\"unk\"] = Word(\"unk\",0,0,0)\n self.alphabet = alphabet\n self.number_doc = [0,0,0]\n\n def conpute_idf(self, word):\n if word in self.vocabulary.keys(): # if not in vocab\n boomword = self.vocabulary[word]\n else:\n boomword = self.vocabulary[\"unk\"]\n # not in alphabet, symbol\n return (boomword.sentiment_labels[0], boomword.sentiment_labels[1], boomword.sentiment_labels[2])\n\n def re_compute_number_doc(self):\n max_neg = 0\n max_neu = 0\n max_pos = 0\n for key in self.vocabulary.keys():\n a,b,c = self.conpute_idf(key)\n if a > max_neg:\n max_neg = a\n if b > max_neu:\n max_neu = b\n if c > max_pos:\n max_pos = c\n self.number_doc[0] = max_neg\n self.number_doc[1] = max_neu\n self.number_doc[2] = max_pos\n\n @classmethod\n def convert_sentiment_str2idx(cls, label):\n label = label.lower()\n if label == \"negative\" or label == \"tiêu cực\" or label == \"tiêu_cực\":\n return 0\n elif label == \"neutral\" or label == \"trung lập\" or label == \"trung_lập\":\n return 1\n elif label == \"positive\" or label == \"tích cực\" or label == \"tích_cực\":\n return 2\n else:\n return 3\n\n def check_alphabet(self, string):\n for char in string:\n if char not in self.alphabet:\n return False\n return True\n\n def update_idf(self, string, sentiment_label):\n label_idx = self.convert_sentiment_str2idx(sentiment_label)\n self.number_doc[label_idx] +=1\n words = set(string.split())\n for word in words:\n if self.check_alphabet(word):\n if word in self.vocabulary.keys():\n self.vocabulary[word].sentiment_labels[label_idx] +=1\n else:\n self.vocabulary[word] = Word.init_with_sentiment_label(word, label_idx)\n\n @classmethod\n def load_alphabet(cls, filename):\n fi = open(filename, \"r\")\n alphabet = fi.readline()\n fi.close()\n return alphabet\n\n @classmethod\n def load(cls, file):\n if os.path.isfile(file):\n with open(file, mode=\"rb\") as f:\n return pickle.load(f)\n else:\n print(\"No such file !\")\n return None\n\n def __str__(self):\n return \"Boom vocabulary\"\n\n def save(self, file):\n with open(file, mode=\"wb\") as f:\n pickle.dump(self, f)\n\n @classmethod\n def build_from_file(cls, filepath):\n alphabet = BoomVocabulary.load_alphabet(\"rule/alphabet.txt\")\n boomvocab = BoomVocabulary(alphabet=alphabet)\n with open(filepath, mode=\"r\") as f:\n for i,line in enumerate(f):\n if i % 10000 ==0 and i != 0:\n print(\"Process line: \", i)\n elements = line.split(\"splitword\")\n content = elements[1]\n label = elements[2][1:-2]\n boomvocab.update_idf(content, label)\n boomvocab.filter_vocab(min_count=10, max_count=100)\n boomvocab.re_compute_number_doc()\n boomvocab.vocabulary[\"unk\"] = Word(\"unk\", boomvocab.number_doc[0], boomvocab.number_doc[1], boomvocab.number_doc[2])\n return boomvocab\n\n def filter_vocab(self, min_count = 10, max_count = 100):\n new_dict = {}\n for word in self.vocabulary.keys():\n sum_idf = self.vocabulary[word].sentiment_labels[0] + self.vocabulary[word].sentiment_labels[1] + self.vocabulary[word].sentiment_labels[2]\n if sum_idf >= min_count and sum_idf <=max_count:\n new_dict[word] = self.vocabulary[word]\n self.vocabulary = new_dict\n\n\nimport numpy as np\n\nclass PrepareTFIDF(object):\n def __init__(self, boomvocab, vietsentiwordnet):\n self.boomvocab = boomvocab\n self.vietsentiwordnet = vietsentiwordnet\n\n def compute_tf_idf(self, string, min_idf = 5):\n words = set(string.split())\n tf_idf_neg = 0\n tf_idf_neu = 0\n tf_idf_pos = 0\n for word in words:\n tf = string.count(word)\n idf_neg, idf_neu, idf_pos = self.boomvocab.conpute_idf(word)\n if idf_neg < min_idf :\n idf_neg = self.boomvocab.number_doc[0]\n if idf_neu < min_idf :\n idf_neu = self.boomvocab.number_doc[1]\n if idf_pos < min_idf:\n idf_pos = self.boomvocab.number_doc[2]\n\n tf_idf_neg += tf*np.log(self.boomvocab.number_doc[0]/idf_neg)\n tf_idf_neu += tf*np.log(self.boomvocab.number_doc[1]/idf_neu)\n tf_idf_pos += tf*np.log(self.boomvocab.number_doc[2]/idf_pos)\n\n return tf_idf_neg, tf_idf_neu, tf_idf_pos\n\"\"\"\n 1. Đọc 1 câu -> tách ra \"title\" + \"content\" and \"label\"\n 2. Từ \"content\" --> vector tfidf\n 3. từ \"content\" --> vector vietsentiwordnet\n 4. concatenate 2 vector của bước 2 và 3.\n\"\"\"\n\n\"\"\"\n 1. Cố định số từ: 1000 từ\n 2. title or content --> vector index\n\"\"\"\n\nclass FeatureExtractor(object):\n def __init__(self, boom_vocab, sentiwordnet):\n self.boom_vocab = boom_vocab\n self.sentiwordnet = sentiwordnet\n self.preparetfidf = PrepareTFIDF(self.boom_vocab, None)\n\n @classmethod\n def create_from_vocab_sentiwn(self, file_vocab, list_file_senti):\n boomvocab = BoomVocabulary.load(file_vocab)\n sentiwordnet = SentimentWordNet.load_from_list_file(list_file_senti)\n return FeatureExtractor(boomvocab,sentiwordnet)\n\n def extract_features(self, file_in):\n result = []\n labels = []\n with open(file_in, mode=\"r\") as f:\n for i,line in enumerate(f):\n elements = line.split(\"splitword\")\n title = elements[0]\n content = elements[1]\n wordnet_vector = self.sentiwordnet.compute_score(title+\" \"+content)\n neg_tf_idf, neu_tf_idf, pos_tf_idf = self.preparetfidf.compute_tf_idf(title+\" \"+content)\n feature_vector = np.array([neg_tf_idf, neu_tf_idf, pos_tf_idf])\n label = BoomVocabulary.convert_sentiment_str2idx(label = elements[2][1:-1])\n labels.append(label)\n newsample = np.concatenate((wordnet_vector,feature_vector))\n result.append(newsample)\n result_np = np.array(result)\n labels_np = np.array(labels)\n return result_np, labels_np\n\n\nif __name__ == \"__main__\":\n\n boomvocab = BoomVocabulary.load(\"model/vocab.pickle\")\n\n if boomvocab == None:\n boomvocab = BoomVocabulary.build_from_file(\"/Users/HyNguyen/Documents/Boomerang/data4ws.row.ws.txt\")\n boomvocab.save(\"model/vocab.pickle\")\n sentiwordnet = SentimentWordNet.load_from_list_file([\"rule/VietSentiWordNet.txt\", \"rule/milk_negativewordnet.txt\"])\n\n print(\"SentiwordnetKey \", len(sentiwordnet.vocabulary.keys()))\n print(\"Vocabulary \", len(boomvocab.vocabulary.keys()))\n\n # f_neg = open(\"staticstic.neg.csv\", mode=\"w\")\n # f_neu = open(\"staticstic.neu.csv\", mode=\"w\")\n # f_pos = open(\"staticstic.pos.csv\", mode=\"w\")\n # for key in boomvocab.vocabulary.keys():\n # idf_neg, idf_neu, idf_pos = boomvocab.vocabulary[key].get_idf()\n # if idf_neg > idf_pos and idf_neg > idf_neu:\n # f_neg.write(key + \",\"+str(boomvocab.vocabulary[key].sentiment_labels[0])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[1])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[2]) +\"\\n\")\n # if idf_neu > idf_neg and idf_neu > idf_pos:\n # f_neu.write(key + \",\"+str(boomvocab.vocabulary[key].sentiment_labels[0])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[1])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[2]) +\"\\n\")\n # if idf_pos > idf_neg and idf_pos > idf_neu:\n # f_pos.write(key + \",\"+str(boomvocab.vocabulary[key].sentiment_labels[0])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[1])+\",\"+ str(boomvocab.vocabulary[key].sentiment_labels[2]) +\"\\n\")\n\n X_pos = []\n pos_counter = 1\n\n X_neu = []\n neu_counter = 1\n\n X_neg = []\n neg_counter = 1\n\n preparetfidf = PrepareTFIDF(boomvocab, None)\n with open(\"/Users/HyNguyen/Documents/Boomerang/data4ws.row.ws.txt\", mode=\"r\") as f:\n start = time.time()\n for i,line in enumerate(f):\n if len(X_pos) == 20000:\n X_pos = np.array(X_pos)\n np.save(\"data/data4nn.X.pos.\"+str(pos_counter), X_pos)\n print(\"Save data/data4nn.X.pos.\", pos_counter)\n pos_counter+=1\n X_pos = []\n\n if len(X_neu) == 20000:\n X_neu = np.array(X_neu)\n np.save(\"data/data4nn.X.neu.\"+str(neu_counter), X_neu)\n print(\"Save data/data4nn.X.neu.\", neu_counter)\n neu_counter+=1\n X_neu = []\n\n if len(X_neg) == 20000:\n X_neg = np.array(X_neg)\n np.save(\"data/data4nn.X.neg.\"+str(neg_counter), X_neg)\n print(\"Save data/data4nn.X.neg.\", neg_counter)\n neg_counter+=1\n X_neg = []\n\n elements = line.split(\"splitword\")\n content = elements[1]\n title = elements[0]\n wordnet_vector = sentiwordnet.compute_score(title + \" \"+ content)\n neg_tf_idf, neu_tf_idf, pos_tf_idf = preparetfidf.compute_tf_idf(title + \" \"+ content)\n feature_vector = np.array([neg_tf_idf, neu_tf_idf, pos_tf_idf])\n label = BoomVocabulary.convert_sentiment_str2idx(label = elements[2][1:-2])\n newsample = np.concatenate((wordnet_vector,feature_vector))\n if label == 0:\n X_neg.append(newsample)\n elif label == 1:\n X_neu.append(newsample)\n elif label == 2:\n X_pos.append(newsample)\n\n X_pos = np.array(X_pos)\n np.save(\"data/data4nn.X.pos.\"+str(pos_counter), X_pos)\n print(\"Save data/data4nn.X.pos.\", pos_counter)\n X_neu = np.array(X_neu)\n np.save(\"data/data4nn.X.neu.\"+str(neu_counter), X_neu)\n print(\"Save data/data4nn.X.neu.\", neu_counter)\n X_neg = np.array(X_neg)\n np.save(\"data/data4nn.X.neg.\"+str(neg_counter), X_neg)\n print(\"Save data/data4nn.X.neg.\", neg_counter)\n\n","sub_path":"preparedata4boom.py","file_name":"preparedata4boom.py","file_ext":"py","file_size_in_byte":11568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259329199","text":"# Crie um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa,\n# retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL ou OBRIGRATÓRIO nas eleições.\n\n\ndef voto(anoNascimento):\n from datetime import datetime\n anoAtual = datetime.now().year\n idade = anoAtual - anoNascimento\n if idade < 16:\n return f'Com {idade} anos: VOTO NEGADO.'\n if idade < 18 or idade >= 65:\n return f'Com {idade} anos: VOTO OPCIONAL.'\n else:\n return f'Com {idade} anos: VOTO OBRIGATÓRIO.'\n\n\nprint(voto(2003))\n","sub_path":"Mundo 3/ex101.py","file_name":"ex101.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"596244861","text":"import cv2\nimport numpy as np\n\n# compute intersection over union (IOU) of two contours.\n# IOU = (area of intersection) / (area of union)\n#\n# returns: (area of intersection, area of union)\ndef iou_frac(c1, c2):\n max_x = max(c1[:,:,0].max(), c2[:,:,0].max())\n max_y = max(c1[:,:,1].max(), c2[:,:,1].max())\n # just in case there is some float business going on\n max_x = int(max_x + 1)\n max_y = int(max_x + 1)\n\n canvas1 = np.zeros((max_x, max_y), dtype=np.uint8)\n canvas2 = canvas1.copy()\n cv2.fillPoly(canvas1, [c1], 1) \n cv2.fillPoly(canvas2, [c2], 1)\n\n canvas = canvas1 + canvas2\n\n intersection = np.sum(canvas == 2)\n union = np.sum(canvas != 0)\n return intersection, union\n\n# compute intersection over union (IOU) of two contours.\n# IOU = (area of intersection) / (area of union)\ndef iou(c1, c2):\n i, u = iou_frac(c1, c2)\n return float(i) / u\n\n# compute the center of contour. returns (cx, cy)\ndef center(contour):\n M = cv2.moments(contour)\n return M[\"m10\"]/M[\"m00\"], M[\"m01\"]/M[\"m00\"]\n\n# sort a list of points in clockwise order around a center\n#\n# arguments:\n# * pts_list: the points to be sorted, stored as a 2D list:\n# [[x1, y1], [x2, y2], ...]\n# * center: the center point: [cx, cy]\n#\n# thanks to: http://stackoverflow.com/a/6989383/2498956\ndef sort_pts(pts_list, center):\n def cmp_pts(a, b):\n if a[0] - center[0] >= 0 and b[0] - center[0] < 0:\n return 1\n if a[0] - center[0] < 0 and b[0] - center[0] >= 0:\n return -1\n if a[0] - center[0] == 0 and b[0] - center[0] == 0:\n if a[1] - center[1] >= 0 or b[1] - center[1] >= 0:\n return cmp(a[1], b[1])\n return cmp(b[1], a[1])\n\n det = (a[0] - center[0])*(b[1] - center[1]) - (b[0] - center[0])*(a[1] - center[1])\n if det < 0:\n return 1\n if det > 0:\n return -1\n\n d1 = (a[0] - center[0])**2 + (a[1] - center[1])**2\n d2 = (b[0] - center[0])**2 + (b[1] - center[1])**2\n return cmp(d1, d2)\n\n sorted_pts = sorted(pts_list, cmp=cmp_pts)\n return sorted_pts\n\n# sort a contour so that its points are in clockwise order\n#\n# arguments:\n# * contour: a numpy array of points with shape (n_points, 1, 2)\ndef sort_contour(contour):\n return sort_contour_center(contour, center(contour))\n\n# sorts a contour so that its points are in clockwise order\n#\n# arguments:\n# * contour: a numpy array of points with shape (n_points, 1, 2)\n# * center: the center of the contour\ndef sort_contour_center(contour, center):\n pts = list(contour.reshape((-1, 2)))\n\n sorted_pts = sort_pts(pts, center)\n ret = np.array(sorted_pts).reshape((-1, 1, 2))\n return ret\n","sub_path":"contours.py","file_name":"contours.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"633665469","text":"import cv2\r\nimport argparse\r\nimport numpy as np\r\nfrom tkinter import * \r\nfrom tkinter import messagebox \r\nap = argparse.ArgumentParser()\r\nap.add_argument('-i', '--image', required=True,\r\n help = 'path to input image')\r\nap.add_argument('-c', '--config', required=True,\r\n help = 'path to yolo config file')\r\nap.add_argument('-w', '--weights', required=True,\r\n help = 'path to yolo pre-trained weights')\r\nap.add_argument('-cl', '--classes', required=True,\r\n help = 'path to text file containing class names')\r\nargs = ap.parse_args()\r\n\r\nlst1=[0,0,0,0,0,0,0,0,0]\r\nlst = []\r\nst = ['gun','bullet','blood','knife','glove','scissors','glass','body','needles']\r\n\r\ndef get_output_layers(net):\r\n \r\n layer_names = net.getLayerNames()\r\n \r\n output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\r\n\r\n return output_layers\r\n\r\n\r\ndef draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):\r\n\r\n global label\r\n label = str(classes[class_id])\r\n print(\"hi\")\r\n #print(label)\r\n\r\n color = COLORS[class_id]\r\n\r\n cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)\r\n\r\n cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\r\n\r\n \r\nimage = cv2.imread(args.image)\r\n\r\nWidth = image.shape[1]\r\nHeight = image.shape[0]\r\nscale = 0.00392\r\n\r\nclasses = None\r\n\r\nwith open(args.classes, 'r') as f:\r\n classes = [line.strip() for line in f.readlines()]\r\n\r\nCOLORS = np.random.uniform(0, 255, size=(len(classes), 3))\r\n\r\nnet = cv2.dnn.readNet(args.weights, args.config)\r\n\r\nblob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)\r\n\r\nnet.setInput(blob)\r\n\r\nouts = net.forward(get_output_layers(net))\r\n\r\nclass_ids = []\r\nconfidences = []\r\nboxes = []\r\nconf_threshold = 0.5\r\nnms_threshold = 0.4\r\n\r\n\r\nfor out in outs:\r\n for detection in out:\r\n scores = detection[5:]\r\n class_id = np.argmax(scores)\r\n confidence = scores[class_id]\r\n if confidence > 0.5:\r\n center_x = int(detection[0] * Width)\r\n center_y = int(detection[1] * Height)\r\n w = int(detection[2] * Width)\r\n h = int(detection[3] * Height)\r\n x = center_x - w / 2\r\n y = center_y - h / 2\r\n class_ids.append(class_id)\r\n confidences.append(float(confidence))\r\n boxes.append([x, y, w, h])\r\n\r\n\r\nindices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)\r\n\r\nfor i in indices:\r\n i = i[0]\r\n box = boxes[i]\r\n x = box[0]\r\n y = box[1]\r\n w = box[2]\r\n h = box[3]\r\n draw_prediction(image, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))\r\n\r\ncv2.imshow(\"object detection\", image)\r\ncv2.waitKey()\r\n#print(label)\r\ni=0\r\nfor i in range(len(st)):\r\n #print(\"hello\")\r\n #print(string[i])\r\n if(label == st[i]):\r\n print(\"yes\")\r\n lst1[i]=1\r\n #top = Tk() \r\n #top.geometry(\"100x100\") \r\n messagebox.showinfo(\"information\",\"Most useful forensic item detected\") \r\n \r\n #top.mainloop() \r\n ####print the list####\r\n #print(lst)\r\n else:\r\n continue\r\nlst = lst1\r\nprint(lst)\r\nprint(type(lst1))\r\n#lst = [0, 1, 0, 1, 0, 1, 0, 1, 0] \r\ngun=lst[0]\r\nbullet=lst[1]\r\nblood=lst[2]\r\nknife=lst[3]\r\nglove=lst[4]\r\nscissors=lst[5]\r\nglass=lst[6]\r\nbody=lst[7]\r\nneedles=lst[8]\r\nstring1=[int(gun),int(bullet),int(blood),int(knife),int(glove),int(scissors),int(glass),int(body),int(needles)]\r\nstring = ['gun','bullet','blood','knife','glove','scissors','glass','body','needles']\r\n\r\nif string1[0]==1:\r\n a=string[0]\r\n a=80\r\nif string1[0]==0:\r\n a=string[0]\r\n a=0\r\nif string1[1]==1:\r\n b=string[1]\r\n b=10\r\nif string1[1]==0:\r\n b=string[1]\r\n b=0\r\nif string1[2]==1:\r\n c=string[2]\r\n c=25\r\nif string1[2]==0:\r\n c=string[2]\r\n c=0\r\nif string1[3]==1:\r\n d=string[3]\r\n d=50\r\nif string1[3]==0:\r\n d=string[3]\r\n d=0\r\nif string1[4]==1:\r\n e=string[4]\r\n e=60\r\nif string1[4]==0:\r\n e=string[4]\r\n e=0\r\nif string1[5]==1:\r\n f=string[5]\r\n f=35\r\nif string1[5]==0:\r\n f=string[5]\r\n f=0\r\nif string1[6]==1:\r\n g=string[6]\r\n g=10\r\nif string1[6]==0:\r\n g=string[6]\r\n g=0\r\nif string1[7]==1:\r\n h=string[7]\r\n h=90\r\nif string1[7]==0:\r\n h=string[7]\r\n h=0\r\nif string1[8]==1:\r\n i=string[8]\r\n i=75\r\nif string1[8]==0:\r\n i=string[8]\r\n i=0\r\nlst=[int(a),int(b),int(c),int(d),int(e),int(f),int(g),int(h),int(i)]\r\n\r\n\r\n \r\n# sorting the list \r\nlst.sort()\r\n#print greatest value\r\ncc=lst[-1] \r\nif int(cc)==int(a):\r\n\tprint(string[0])\r\nif int(cc)==int(b):\r\n\tprint(string[1])\r\nif int(cc)==int(c):\r\n\tprint(string[2])\r\nif int(cc)==int(d):\r\n\tprint(string[3])\r\nif int(cc)==int(e):\r\n\tprint(string[4])\r\nif int(cc)==int(f):\r\n\tprint(string[5])\r\nif int(cc)==int(g):\r\n\tprint(string[6])\r\nif int(cc)==int(h):\r\n\tprint(string[7])\r\nif int(cc)==int(i):\r\n\tprint(string[8])\r\n\r\ncv2.imwrite(\"object-detection.jpg\", image)\r\ncv2.destroyAllWindows()\r\n\r\n","sub_path":"detect_updated.py","file_name":"detect_updated.py","file_ext":"py","file_size_in_byte":4999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"29371152","text":"# Settings\n# https://docs.djangoproject.com/en/2.0/topics/settings/\n# https://docs.djangoproject.com/en/2.0/ref/settings/\n\nimport os\nimport re\n\nfrom django.conf.global_settings import STATICFILES_FINDERS\n\nimport dj_database_url\n\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = os.environ.get('SECRET_KEY', 'fake-key')\n\nDEBUG = os.environ.get('DEBUG', True)\n\nALLOWED_HOSTS = [\n '127.0.0.1',\n 'localhost',\n '.compute-1.amazonaws.com',\n '.richardcornish.com',\n '.richi.ec',\n]\n\nINTERNAL_IPS = [\n '127.0.0.1',\n]\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.redirects',\n 'django.contrib.sites',\n 'django.contrib.sitemaps',\n 'django.contrib.staticfiles',\n 'compressor',\n 'debug_toolbar',\n 'markdowny',\n 'smarty',\n 'storages',\n 'about',\n 'blog',\n 'contact',\n 'media',\n 'portfolio',\n 'process',\n 'references',\n 'resume',\n 'utils',\n]\n\nMIDDLEWARE = [\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'richardcornish.middleware.BrokenLinkEmailsMiddlewareNoReferer',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.contrib.sites.middleware.CurrentSiteMiddleware',\n 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',\n]\n\nROOT_URLCONF = 'richardcornish.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, 'templates'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'richardcornish.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n# https://pypi.python.org/pypi/dj-database-url\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\ndb_from_env = dj_database_url.config(env='DATABASE_URL_RC', conn_max_age=600)\n\nDATABASES['default'].update(db_from_env)\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nLOCALE_PATHS = [\n os.path.join(BASE_DIR, 'locale'),\n]\n\nDATETIME_FORMAT = 'l, F j, Y, P e'\n\n\n# Boto 3\n# https://boto3.readthedocs.io/en/latest/\n\n# Django Storages\n# http://django-storages.readthedocs.io/en/latest/index.html\n\nAWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '')\n\nAWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '')\n\nAWS_REGION_NAME = 'us-east-1'\n\nAWS_STORAGE_BUCKET_NAME = 'richardcornish'\n\nAWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME\n\nGZIP_CONTENT_TYPES = (\n 'text/css',\n 'text/javascript',\n 'application/javascript',\n 'application/x-javascript',\n 'image/svg+xml',\n 'image/vnd.microsoft.icon',\n)\n\nAWS_S3_OBJECT_PARAMETERS = {\n 'CacheControl': 'max-age=604800', # 7 days\n}\n\nAWS_DEFAULT_ACL = None\n\nAWS_IS_GZIPPED = True\n\nAWS_QUERYSTRING_AUTH = False\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATICFILES_PATH = 'static'\n\nif DEBUG:\n STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'\n STATIC_URL = '/%s/' % STATICFILES_PATH\nelse:\n STATICFILES_STORAGE = 'richardcornish.storages.StaticStorage'\n STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_PATH)\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'static'),\n]\n\nSTATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'assets', STATICFILES_PATH)\n\n\n# Django Compressor\n# https://django-compressor.readthedocs.io/en/latest/\n\nSTATICFILES_FINDERS += [\n 'compressor.finders.CompressorFinder',\n]\n\nCOMPRESS_STORAGE = STATICFILES_STORAGE\n\nCOMPRESS_OUTPUT_DIR = 'c'\n\n\n# Media\n# https://docs.djangoproject.com/en/2.0/topics/files/\n\nMEDIAFILES_PATH = 'media'\n\nDEFAULT_FILE_STORAGE = 'richardcornish.storages.MediaStorage'\n\nMEDIA_URL = \"https://%s/%s/\" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_PATH)\n\nMEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'assets', MEDIAFILES_PATH)\n\n\n# Sites\n# https://docs.djangoproject.com/en/2.0/ref/contrib/sites/\n\nif DEBUG:\n SITE_ID = 1\nelse:\n SITE_ID = 2\n\n\n# Security\n# https://docs.djangoproject.com/en/2.0/topics/security/\n\nif not DEBUG:\n CSRF_COOKIE_SECURE = True\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n SECURE_SSL_REDIRECT = True\n SESSION_COOKIE_SECURE = True\n\n\n# E-mail\n# https://docs.djangoproject.com/en/2.0/topics/email/\n\nEMAIL_SUBJECT_PREFIX = ''\n\nSERVER_EMAIL = 'rich@richardcornish.com'\n\nADMINS = [\n ('Richard Cornish', 'rich@richardcornish.com')\n]\n\nMANAGERS = ADMINS\n\nIGNORABLE_404_URLS = [\n re.compile(r'^/cdn-cgi/'),\n re.compile(r'^/cgi-bin/'),\n re.compile(r'^/phpmyadmin/'),\n re.compile(r'^/static/'),\n re.compile(r'^/wp-content/'),\n re.compile(r'(.*)\\.(css|js|jpg|png|gif|ico|swf|fla|xml|json|php|cgi|cfm|txt)$'),\n]\n\nDEFAULT_FROM_EMAIL = 'rich@richardcornish.com'\n\nif DEBUG:\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\nelse:\n EMAIL_BACKEND = 'richardcornish.backends.SesEmailBackend'\n EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'\n EMAIL_HOST_USER = os.environ.get('AWS_SMTP_USERNAME', '')\n EMAIL_HOST_PASSWORD = os.environ.get('AWS_SMTP_PASSWORD', '')\n EMAIL_PORT = 587\n EMAIL_USE_TLS = True\n\n\n# Akismet\n# http://akismet.readthedocs.io/en/latest/\n# https://akismet.com/development/api/#comment-check\n\nPYTHON_AKISMET_API_KEY = os.environ.get('PYTHON_AKISMET_API_KEY', '')\n\nPYTHON_AKISMET_BLOG_URL = os.environ.get('PYTHON_AKISMET_BLOG_URL', 'https://richardcornish.com')\n\n\n# Geolocation\n# https://docs.djangoproject.com/en/2.0/ref/contrib/gis/geoip2/\n# http://dev.maxmind.com/geoip/geoip2/geolite2/\n\nGEOIP_PATH = os.path.join(BASE_DIR, 'utils', 'maxmind')\n\n\n# Anonymous login\n\nANONYMOUS_PASSWORDS = [\n 'pbkdf2_sha256$120000$6gqsaY8nic4m$uE7+Rvn0fF7yWYkpBAbSMFRHmmNCmjk6KLW2lUPC9jA=',\n]\n","sub_path":"richardcornish/richardcornish/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104101641","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n# 在原model_wm基础上加入speaker、listener,因为太复杂且不易于实现后续的WM部分,所以先放着用自己的想法实现\n\nclass SimpleAttention(nn.Module):\n\n def __init__(self, D_m, D_g):\n super(SimpleAttention, self).__init__()\n self.D_m = D_m\n self.D_g = D_g\n\n self.scalar = nn.Linear(self.D_m, self.D_g, bias=False)\n\n def forward(self, g_hist, U): # U shape: batch_size, D_m\n \"\"\"\n alpha = softmax(ut.T mm W(alpha) mm [g1, g2, ... , g(t-1)])\n ct = alpha mm [g1, g2, ... , g(t-1)].T\n \"\"\"\n #\n # print(\"Simple attention : U shape, \", U.shape)\n # print(\"Simple attention : g_hist shape, \", g_hist.shape)\n # print(\"Simple attention : self.scalar(U).unsqueeze(1) shape, \", self.scalar(U).unsqueeze(1).shape)\n # print(\"Simple attention : g_hist.permute(1, 0, 2) shape, \", g_hist.permute(1, 2, 0).shape)\n scale = self.scalar(U).unsqueeze(1).bmm(g_hist.permute(1, 2, 0)).squeeze(1) # batch_size , (t-1)\n # U mm W(alpha)\n s = self.scalar(U) # batch_size, D_g\n # s mm g_hist\n # 把g_hist维度转为 batch_size, (t-1), D_g, 把s维度转为 batch_size, D_g, 1\n # g_hist mm s\n scale = g_hist.permute(1, 0, 2).bmm(s.unsqueeze(2)) # batch_size, (t-1), 1\n scale = scale.squeeze(2) # batch_size, (t-1)\n # print(\"Simple attention : scale shape\", scale.shape)\n alpha = F.softmax(scale, dim=1) # batch_size , (t-1) 在第1个维度上做softmax\n # print(\"````````````````````````````````````````\")\n # print(\"Simple attention : alpha.unsqueeze(1) shape\", alpha.unsqueeze(1).shape)\n # print(\"Simple attention : g_hist.permute(1, 0, 2) shape\", g_hist.permute(1, 0, 2).shape)\n ct = alpha.unsqueeze(1).bmm(g_hist.permute(1, 0, 2)).squeeze(1) # batch_size , D_g\n # print(\"Simple attention : ct shape\", ct.shape)\n return ct, alpha\n\n\nclass WMRnnCell(nn.Module):\n def __init__(self, D_m, D_g, D_p, D_e, D_gm, dropout=0.6):\n super(WMRnnCell, self).__init__()\n self.D_m = D_m # input ut dim\n self.D_g = D_g # global GRU hidden state dim\n self.D_p = D_p # party state GRU hidden state dim\n self.D_e = D_e # emotion GRU hidden state dim\n self.D_gm = D_gm\n\n self.G_g = nn.GRUCell(D_m + D_p, D_g)\n self.G_p = nn.GRUCell(D_m + D_g, D_p)\n self.G_e = nn.GRUCell(D_p, D_e)\n self.G_gm = nn.GRUCell(D_p, D_gm)\n self.dropout = nn.Dropout(dropout)\n self.attention = SimpleAttention(D_m, D_g)\n\n def select_parties(self, X, indices): # X shape: batch_size, party, D_p\n q0_sel = []\n for idx, j in zip(indices, X):\n q0_sel.append(j[idx].unsqueeze(0)) # 存储多个 party, D_p 的tensor\n q0_sel = torch.cat(q0_sel, 0) # batch_size, D_p batch_size个对话,当前时刻每个对话中说话者的party state\n return q0_sel\n\n def forward(self, U, g_hist, p_hist, e_hist, gm_last, pmask,\n p0): # U shape: batch_size, D_m gm_last: batch_size, D_gm 表示GRUm的最后一个hidden state\n \"\"\"\n input_g shape:(batch_size, D_m+D_p) , ut cat h_p[-1]\n input_p shape:(batch_size, D_m+D_g) , ut cat ct, ct = softmax(ut.T.mm(Walpha).mm[g1 cat g2 cat ... cat g(t-1)])\n\n :param U: batch_size, D_m\n :param g_hist: t-1, batch_size, D_g\n :param p_hist: t-1, batch_size, party, D_p\n :param e_hist: t-1, batch_size, D_e\n :param gm_last: batch_size*party, D_gm 表示GRUm的最后一个hidden state\n :param p0: batch_size, party, D_p batch_size个对话,上一时刻每个对话中party个人的party state\n :param pmask: batch_size, party\n \"\"\"\n\n pm_idx = torch.argmax(pmask, 1) # batch_size\n p0_sel = self.select_parties(p0, pm_idx) # batch_size, D_p batch个对话中,当前说话者的上一party state,即 q(s(ut),t-1)\n\n # 初始化 h_d h_gm h_g h_p h_e\n h_g = torch.zeros(U.shape[0], self.D_g).type(U.type())\n # h_p = torch.zeros(U.shape[0], self.D_p).type(U.type())\n h_e = torch.zeros(U.shape[0], self.D_e).type(U.type())\n h_gm = torch.zeros(U.shape[0], self.D_gm).type(U.type()) # batch_size*party, D_p\n\n # DialogueRNN ct shape : batch_size, D_g\n if g_hist.shape[0] == 0:\n ct = torch.zeros(U.shape[0], self.D_g).type(U.type())\n alpha = None\n else:\n ct, alpha = self.attention(g_hist, U)\n\n # 按列拼接,即p, g各自接在U的后面组成新的矩阵\n input_g = torch.cat((U, p0_sel), dim=1)\n # h_g shape: (batch_size, D_g), 如果 g_hist为空,则用初始化的h_g\n h_g = self.G_g(input_g, h_g if g_hist.shape[0] == 0 else g_hist[-1])\n h_g = self.dropout(h_g)\n\n U_c_ = torch.cat([U, ct], dim=1).unsqueeze(1).expand(-1, pmask.shape[1],\n -1) # batch_size, party, (D_m + D_g)\n input_p = U_c_.contiguous().view(-1, self.D_m + self.D_p) # (batch_size*party), (D_m + D_g)\n last_p = p0.view(-1,\n self.D_p) # (batch_size*party), D_p # p(t-1) 当前时刻,先把两个人都当作是speaker,复制这一刻是说话者的上一时刻的party state给这一时刻的倾听者\n ps_ = self.G_p(input_p, last_p).view(U.shape[0], -1,\n self.D_p) # batch_size, party, D_p 当前时刻两个人都作为说话者的party state,最后ps_ * pmask_会筛选出真正的说话者的状态\n ps_ = self.dropout(ps_)\n pl_ = p0 # batch_size, party, D_p 上一时刻两个人的party state\n pmask_ = pmask.unsqueeze(2)\n h_p = pl_ * (1 - pmask_) + ps_ * pmask_ # 上一时刻的party state * 倾听者 + 当前时刻的party state * 说话者\n\n # Working Memory\n # short-term memory system\n Q = 8 # STS 中的MN的记忆单元个数\n K = 6 # STS 中的MN的K hops\n q = self.select_parties(h_p, pm_idx) # STS 中MN的输入q batch_size, D_p 当前时刻说话者的party state\n # print(\"wm sts, p_hist.shape \", p_hist.shape)\n # print(\"wm sts, q.shape \", q.shape)\n # p_attn(r) (batch_size, Q) = ( (batch_size, 1, D_p) X (batch_size, D_p, Q) ).squeeze(1)\n # m (batch_size, D_p) = ( (batch_size, 1, Q) X (batch_size, Q, D_p) ).squeeze(1)\n if p_hist.shape[0] != 0: # 第一个p,没有历史p,所以不需要做任何操作,直接传给GRUe\n M = torch.zeros(0).type(U.type())\n for party in p_hist[-Q:]:\n speaker_pre_p = self.select_parties(party, pm_idx) # 从历史p中选出,当前时刻说话者的前Q个时刻的p, 不论前Q个时刻他是说话者还是倾听者\n M = torch.cat([M, speaker_pre_p.unsqueeze(0)], dim=0) # Q, bath_size, D_p\n for k in range(K):\n # memory read\n # print(\"wm sts, M.shape \", M.shape)\n p_attn = F.softmax(torch.bmm(q.unsqueeze(1), M.permute(1, 2, 0)).squeeze(1), dim=1) # p_attn(r)\n m = torch.bmm(p_attn.unsqueeze(1), M.permute(1, 0, 2)).squeeze(1) # m(r)\n # q = torch.tanh(m + q) # h_p(r+1) = tanh(q(r) + m(r))\n q = torch.tanh(m + q)\n\n # memory write\n # D_gm == D_p\n M_next = torch.zeros(0).type(U.type())\n for p in M: # p shape: batch_size*party, D_p\n h_gm = self.G_gm(p, h_gm if gm_last.shape[0] == 0 else gm_last)\n gm_last = h_gm\n M_next = torch.cat([M_next, h_gm.unsqueeze(0)], dim=0)\n M = M_next\n\n # exe-control\n input_e = q # batch_szie, D_p 当前时刻说话者的 q\n # h_e shape : batch_size, D_e\n h_e = self.G_e(input_e, h_e if e_hist.shape[0] == 0 else e_hist[-1])\n h_e = self.dropout(h_e)\n\n return h_g, h_p, h_e, gm_last, alpha\n\n\nclass WMRnn(nn.Module):\n def __init__(self, D_m, D_g, D_p, D_e, D_gm, D_l, D_c, dropout=0.6):\n super(WMRnn, self).__init__()\n self.D_m = D_m\n self.D_g = D_g\n self.D_p = D_p\n self.D_e = D_e\n self.D_gm = D_gm\n self.D_l = D_l\n self.D_c = D_c # 表情分类数:6\n self.dropout = nn.Dropout(dropout)\n\n self.WMRnn_cell = WMRnnCell(D_m, D_g, D_p, D_e, D_gm, dropout)\n self.ReLU_Linear = nn.Linear(D_e, D_l)\n self.Prob_Linear = nn.Linear(D_l, D_c)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, U, labels, qmask): # U shape: seq_len, batch_size, D_m labels shape: batch_size, seq_len\n g_hist = torch.zeros(0).type(U.type())\n p_hist = torch.zeros(0).type(U.type())\n e_hist = torch.zeros(0).type(U.type())\n gm_last = torch.zeros(0).type(U.type())\n log_ps = torch.zeros(0).type(U.type())\n\n q_ = torch.zeros(qmask.shape[1], qmask.shape[2], self.D_p).type(U.type()) # batch_size, party, D_p\n\n for u, label, qmask_ in zip(U, range(labels.shape[1]), qmask):\n # g_hist shape : t-1, batch_size, D_g\n # p_hist shape : t-1, batch_size, party, D_p\n # e_hist shape : t-1, batch_size, D_e\n # h_g shape: batch_size, D_g\n # h_p shape: batch_size, party, D_p\n # h_e shape : batch_size, D_e\n h_g, h_p, h_e, gm_last, alpha = self.WMRnn_cell(u, g_hist, p_hist, e_hist, gm_last, qmask_, q_)\n g_hist = torch.cat([g_hist, h_g.unsqueeze(0)], dim=0) # 按行拼接到g_hist中\n p_hist = torch.cat([p_hist, h_p.unsqueeze(0)], dim=0)\n e_hist = torch.cat([e_hist, h_e.unsqueeze(0)], dim=0)\n\n l = F.relu(self.ReLU_Linear(h_e)) # batch_size , D_l\n # l = self.dropout(l)\n t = self.Prob_Linear(l) # batch_size , D_c\n log_p = F.log_softmax(t, 1) # batch_size , D_c\n # print(\"DialogueRNN , log_p shape : \", log_p.shape)\n # labels的列才是该批次的label\n # loss += loss_fn(prob, labels[:, label].long())\n # print(p)\n # print(y_hat)\n # print(\"DialogueRNN , y_hat shape : \", y_hat.shape)\n\n log_ps = torch.cat([log_ps, log_p.unsqueeze(0)],\n dim=0) # 要先升维再拼,否则会拼成(seq_len*batch_size), D_c最后拼成 seq_len, batch_size, D_c\n # print(\"DialogueRNN , log_ps shape : \", log_ps.shape)\n return log_ps\n\n\nclass MaskedNLLLoss(nn.Module):\n def __init__(self, weight=None):\n super(MaskedNLLLoss, self).__init__()\n self.weight = weight\n self.loss = nn.NLLLoss(weight=weight, reduction='sum')\n\n def forward(self, pred, target, mask):\n \"\"\"\n pred -> batch*seq_len, n_classes (log_softmax的结果)\n target -> batch*seq_len\n mask -> batch, seq_len\n \"\"\"\n mask_ = mask.view(-1, 1) # (batch_size*sq_len), 1\n if type(self.weight) == type(None):\n loss = self.loss(pred * mask_, target) / torch.sum(mask)\n else:\n loss = self.loss(pred * mask_, target) / torch.sum(self.weight[target] * mask_.squeeze())\n\n return loss","sub_path":"model_wm_speakerAndListener.py","file_name":"model_wm_speakerAndListener.py","file_ext":"py","file_size_in_byte":11385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"418427404","text":"def linear_search(arr, target):\n for i in range(0, len(arr)):\n if arr[i] == target:\n return i\n\n return -1 # why not return None?\n\n\n# Write an iterative implementation of Binary Search\ndef binary_search(arr, target):\n lo = 0\n hi = len(arr)\n\n while True:\n mid = round((lo + hi) / 2)\n if hi < lo or mid >= len(arr):\n return -1 # why not return None?\n current = arr[mid]\n\n if target == current:\n return mid\n elif target < current:\n hi = mid\n else:\n lo = mid + 1\n\n\nblah = [1, 5, 9, 12, 12, 14, 17, 30, 42, 250, 390, 533]\n\ni = binary_search(blah, 42)\nprint(i)\n","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483544052","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom openerp import models, fields, api, exceptions\nfrom .product_product import FEATURED_DEVELOPMENTS_TAG_REF, FEATURED_RENTALS_TAG_REF, FEATURED_SALES_TAG_REF\nfrom .website import SITE_ID\n\n__author__ = 'Rui Coelho'\n_logger = logging.getLogger(__name__)\n\n_FEATURE_TYPE = [('sales', 'Sales'), ('rentals', 'Rentals'), ('developments', 'Development')]\n\n\nclass featured_product_Website(models.Model):\n \"\"\"\n Products featured in the website\n \"\"\"\n _name = 'featured.product.website'\n _order = 'display_order'\n\n @api.model\n def create(self, values):\n values['is_created'] = True\n \n if 'product_id' in values and values['product_id'] is not False:\n product = self.env['product.product'].browse(values['product_id'])\n \n tag_ref = self._get_tag_by_feature_type(values['type'])\n if tag_ref is None:\n raise exceptions.ValidationError('Invalid type.')\n\n tag_id = self.env.ref(tag_ref).id\n # sudo() because only the admin is allowed to change the feature tags\n product.sudo().categ_tag_ids = [(4, tag_id, False)]\n \n result = super(featured_product_Website, self).create(values)\n self.env['website'].browse(SITE_ID).regenerate_featured_products_html()\n return result\n \n @api.multi\n def unlink(self):\n for featured in self:\n if featured.product_id:\n tag_ref = self._get_tag_by_feature_type(featured.type)\n if tag_ref is None:\n raise exceptions.ValidationError('Invalid type.')\n \n tag_id = self.env.ref(tag_ref).id\n # sudo() because only the admin is allowed to change the feature tags\n featured.product_id.sudo().categ_tag_ids = [(3, tag_id, False)]\n \n result = super(featured_product_Website, self).unlink()\n self.env['website'].browse(SITE_ID).regenerate_featured_products_html()\n return result\n\n def _get_tag_by_feature_type(self, feature_type):\n \"\"\"\n Translate the feature type\n :param feature_type: The website section of the feature (sales | rentals | developments)\n :type feature_type: str\n :return: The corresponding product category tag\n \"\"\"\n tag_ref = None\n \n if feature_type == 'sales':\n tag_ref = FEATURED_SALES_TAG_REF\n elif feature_type == 'rentals':\n tag_ref = FEATURED_RENTALS_TAG_REF\n elif feature_type == 'developments':\n tag_ref = FEATURED_DEVELOPMENTS_TAG_REF\n\n return tag_ref\n\n @api.multi\n def write(self, values):\n if 'is_embedded_video' in values:\n raise exceptions.ValidationError('Switching between video and real estate is not allowed.')\n \n if 'type' in values:\n raise exceptions.ValidationError('Type cannot be changed.')\n \n if 'product_id' in values:\n raise exceptions.ValidationError('Real estate cannot be changed.')\n\n result = super(featured_product_Website, self).write(values)\n self.env['website'].browse(SITE_ID).regenerate_featured_products_html()\n return result\n \n is_created = fields.Boolean(string='Created')\n \n is_embedded_video = fields.Boolean(string=\"It's a video\", help='e.g. Youtube', default=False)\n \n # The featured product\n product_id = fields.Many2one(string='Real Estate', comodel_name='product.product', domain=[('website_published', '=', True)])\n website_published = fields.Boolean(related='product_id.website_published')\n availability_id = fields.Many2one(string='Availability', comodel_name='product.availability', related='product_id.availability_id')\n county_id = fields.Many2one(comodel_name='res.country.county', related='product_id.county_id')\n \n # The image to be displayed if the product is featured\n image = fields.Binary(string='Image for the features section in the website')\n \n # The video be displayed if the product is featured\n video_html = fields.Char(string='Embed video code for the features section in the website')\n \n # Alternative URL associated with the feature (e.g. link to a search result instead of the product page)\n alternative_featured_url = fields.Char(string='Alternative URL')\n \n # Caption shown under the image\n caption = fields.Char(string='Caption for the features section in the website', translate=True, required=True)\n \n # Display order in the features carroussel\n display_order = fields.Integer(string='Feature order', help='Lower comes first', required=True)\n\n # Feature type\n type = fields.Selection(string='Type', selection=_FEATURE_TYPE, required=True)\n","sub_path":"pdf_website/models/featured_product_website.py","file_name":"featured_product_website.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"473701784","text":"import torch\nfrom .observation_type import ObservationType\n\ndef get_tensorrt_backend_config_dict():\n \"\"\" Get the backend config dictionary for tensorrt backend\n NOTE: Current api will change in the future, it's just to unblock experimentation for\n new backends, please don't use it right now.\n \"\"\"\n # dtype configs\n weighted_op_qint8_dtype_config = {\n # optional, input activation dtype\n \"input_dtype\": torch.qint8,\n # optional, weight dtype\n \"weight_dtype\": torch.qint8,\n # optional, bias dtype\n \"bias_dtype\": torch.float,\n # optional, output activation dtype\n \"output_dtype\": torch.qint8\n }\n non_weighted_op_qint8_dtype_config = {\n # optional, input activation dtype\n \"input_dtype\": torch.qint8,\n # optional, output activation dtype\n \"output_dtype\": torch.qint8,\n }\n\n # operator (module/functional/torch ops) configs\n linear_module_config = {\n # Please see README under this folder for pattern format\n \"pattern\": torch.nn.Linear,\n \"observation_type\": ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,\n \"dtype_configs\": [\n weighted_op_qint8_dtype_config,\n ]\n }\n conv_module_config = {\n \"pattern\": torch.nn.Conv2d,\n \"observation_type\": ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,\n \"dtype_configs\": [\n weighted_op_qint8_dtype_config,\n ]\n }\n cat_config = {\n \"pattern\": torch.cat,\n \"observation_type\": ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,\n \"dtype_configs\": [\n non_weighted_op_qint8_dtype_config,\n ]\n }\n return {\n # optional\n \"name\": \"tensorrt\",\n \"configs\": [\n linear_module_config,\n conv_module_config,\n cat_config,\n ]\n }\n","sub_path":"torch/ao/quantization/fx/backend_config_dict/tensorrt.py","file_name":"tensorrt.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455649635","text":"import abc\nfrom unittest import SkipTest\nfrom typing import Dict\nfrom django.test import TestCase\n\nfrom .util import TestEachExample\n\n\nclass ExamplesReturn200Tests(TestCase, metaclass=TestEachExample):\n def test(self, example):\n res = self.client.get('/example/' + example.basename)\n self.assertEqual(res.status_code, 200)\n\n\nclass ExampleMixin(metaclass=abc.ABCMeta):\n @property\n @abc.abstractmethod\n def url(self) -> str:\n '''\n URL for example. Must be defined by subclasses.\n '''\n\n @property\n @abc.abstractmethod\n def valid_post(self) -> Dict[str, str]:\n '''\n Valid POST data for example to succeed. Must be defined by subclasses.\n If the form has no required fields, set this to {}.\n '''\n\n def test_empty_post_shows_errors(self):\n if self.valid_post == {}:\n raise SkipTest('Form has no required fields')\n res = self.client.post(self.url, {})\n self.assertContains(res, 'Submission unsuccessful')\n\n def test_valid_post_shows_success(self):\n res = self.client.post(self.url, self.valid_post)\n self.assertContains(res, 'Submission successful')\n\n\nclass RadiosExampleTests(ExampleMixin, TestCase):\n url = '/example/radios'\n\n valid_post = {\n 'president': 'washington',\n }\n\n\nclass CheckboxesExampleTests(ExampleMixin, TestCase):\n url = '/example/checkboxes'\n\n valid_post = {} # type: Dict[str, str]\n\n\nclass DateExampleTests(ExampleMixin, TestCase):\n url = '/example/date'\n\n valid_post = {\n 'date_1': '4',\n 'date_2': '28',\n 'date_0': '2016',\n }\n\n\nclass EverythingExampleTests(ExampleMixin, TestCase):\n url = '/example/everything'\n\n valid_post = {\n 'president': 'washington',\n 'park': 'foo',\n 'date_1': '4',\n 'date_2': '28',\n 'date_0': '2016',\n }\n\n def test_non_field_errors_are_displayed(self):\n res = self.client.post(self.url, {\n 'trigger_non_field_error': 'on',\n })\n self.assertContains(res, 'This is the non-field error you requested')\n","sub_path":"example/app/tests/test_examples.py","file_name":"test_examples.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"541893896","text":"class Solution(object):\n def permute(self, nums):\n res = []\n def backtrack(cur):\n if(len(cur) == len(nums)):\n res.append(cur)\n return\n for num in nums:\n if num not in cur:\n backtrack(cur+[num])\n backtrack([])\n return res\n\n def permute2(self, nums):\n #iterative sol\n res = [[]]\n for num in nums:\n new_res = []\n for r in res:\n #be careful of this range\n for i in range(len(r)+1):\n new_res.append(r[:i]+[num]+r[i:])\n res = new_res\n return res\n \n","sub_path":"041/46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"368440607","text":"from bs4 import BeautifulSoup\nimport csv\n\n\nclass ParserHtml(object):\n\n def __init__(self, files: list):\n self.files = files\n self.out_put = {}\n\n def insert_tag_check(self):\n html = \"\"\n with open(\"result2.csv\", \"a\", encoding=\"utf-8_sig\", newline=\"\") as f:\n csv_header = [\n \"ファイル名\", \"headタグ内\", \"結果\"\n ]\n writer = csv.writer(f)\n writer.writerow(csv_header)\n for file in self.files:\n open_file_for_beautifulsoup = open(file, \"r\", encoding=\"utf-8\")\n html = open_file_for_beautifulsoup.read()\n open_file_for_beautifulsoup.close()\n html = BeautifulSoup(html, \"html.parser\")\n heads = html.find_all(\"head\")\n result: dict = {}\n\n result[file] = {\n \"file_name\": file,\n \"head_tag_content\": \"\",\n \"check\": \"\"\n }\n\n for head in heads:\n result[file][\"head_tag_content\"] = head\n \n \"\"\"headタグ内に挿入したタグがあるかを文字列の一致で確認する\"\"\"\n if (\"Global site tag (gtag.js)\" in str(head)) or (\"googletagmanager\" in str(head)):\n result[file][\"check\"] = \"○\"\n else:\n result[file][\"check\"] = \"×\"\n csv_data = [\n result[file][\"file_name\"],\n result[file][\"head_tag_content\"],\n result[file][\"check\"]\n ]\n writer.writerow(csv_data)\n","sub_path":"hiyoko/ParserHtml.py","file_name":"ParserHtml.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"95201430","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef multiply(x,y):#multiply two n-digit numbers\n n = len(str(x))\n if n == 1:\n return x*y\n \n #x= 10**(n/2)*a+b\n #y= 10**(n/2)*c+d\n a = int(str(x)[0])\n b = int(str(x)[1])\n c = int(str(y)[0])\n d = int(str(y)[1])\n p = a + b\n q = c + d\n ac = a*c\n bd = b*d\n pq = p*q\n adbc = pq - ac - bd\n return 10**n*(ac)+10**(n/2)*(adbc)+b*d\n \ndef main(x,y):\n print (multiply(x,y))\n\nif __name__ == \"__main__\":\n x = int(sys.argv[1])\n y = int(sys.argv[2])\n main(x,y)\n","sub_path":"Karatsuba.py","file_name":"Karatsuba.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"635169018","text":"import json\nimport sqlite3\nimport threading\nimport time\nfrom collections import defaultdict\n\nimport networkx as nx\nfrom py2neo import Graph\n\nfrom services import common\nfrom services.tools.sentence_topic_tool import get_sentence_dict\nfrom tools import yaml_utils\nfrom tools.shell_utils import Shell\n\nip = 'bolt://localhost:7687'\nusername = 'neo4j'\npassword = '123456'\n\n\ndef get_whole_graph():\n print('开始读取图数据库')\n\n def multiThreadLoad(func, epoch):\n ts = []\n # 44\n for i in range(epoch):\n if i % 10 == 0 and i != 0:\n print('{}的第{}代:'.format(func, i))\n t = threading.Thread(target=func, args=(i,))\n t.start()\n ts.append(t)\n time.sleep(1)\n\n for t in ts:\n t.join()\n\n def loadEdges(time, num_per_time=100000):\n query = ''' MATCH (n1)-[r]->(n2)\n RETURN id(n1), id(n2), id(r), type(r), r.name\n SKIP {} LIMIT {} '''.format(time * num_per_time, num_per_time)\n results = neo_graph.run(query).data()\n for node_data in results:\n # 如果该关系没有访问过\n n1_id = node_data['id(n1)']\n n2_id = node_data['id(n2)']\n\n r_type = node_data['type(r)']\n r_id = node_data['id(r)']\n r_name = node_data['r.name']\n r_en_name = '' # todo feature in english\n graph.add_edge(n1_id, n2_id, r_id=r_id)\n rel2data[r_id] = (r_type, r_name, r_en_name)\n\n def loadNodes(time, num_per_time=100000):\n query = ''' MATCH (n)\n RETURN id(n), labels(n), n.name, n.en_name, n.code\n SKIP {} LIMIT {} '''.format(time * num_per_time, num_per_time)\n results = neo_graph.run(query).data()\n for node_data in results:\n # 如果该关系没有访问过\n # print(node_data)\n n_id = node_data['id(n)']\n\n labels = node_data['labels(n)']\n if len(labels) != 1:\n # print(node_data) #有些啥都没有的节点,应该是没用的节点\n n_type = ''\n else:\n n_type = labels[0]\n n_name = node_data['n.name']\n n_en_name = node_data['n.en_name']\n n_code = node_data['n.code']\n if n_id in node2data:\n print(node2data[n_id], (n_type, n_name, n_en_name, n_code), n_id, '重复了')\n node2data[n_id] = (n_type, n_name, n_en_name, n_code)\n\n neo_graph = Graph(ip, username=username, password=password)\n graph = nx.MultiDiGraph()\n node2data = {}\n rel2data = {}\n # multiThreadLoad(loadEdges, 3)\n # multiThreadLoad(loadNodes, 3)\n multiThreadLoad(loadEdges, 100)\n print('所有边加载完')\n multiThreadLoad(loadNodes, 15)\n print('所有的点数量:{};所有的边数量{}'.format(graph.number_of_nodes(), graph.number_of_edges()))\n return graph, node2data, rel2data\n\n\ndef save2sqlite(graph, node2data, rel2data, db_path):\n print('开始保存图数据库内容到LiteSQL')\n conn = sqlite3.connect(db_path)\n c = conn.cursor()\n c.execute('''CREATE TABLE graph\n (\n source BIGINT NOT NULL,\n target BIGINT NOT NULL,\n r_id BIGINT NOT NULL,\n data TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE node2data\n (\n id BIGINT PRIMARY KEY,\n label TEXT NOT NULL,\n name TEXT,\n en_name TEXT,\n code BIGINT,\n data TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE rel2data\n (\n id BIGINT PRIMARY KEY,\n label TEXT NOT NULL,\n name TEXT,\n en_name TEXT,\n data TEXT NOT NULL\n );\n ''')\n # 还要加个name的\n c.execute('''CREATE INDEX source_index ON graph (source)''')\n c.execute('''CREATE INDEX target_index ON graph (target)''')\n c.execute('''CREATE INDEX r_id_index ON graph (r_id)''')\n c.execute('''CREATE INDEX node_code_index ON node2data (code)''')\n c.execute('''CREATE INDEX node_label_index ON node2data (label)''')\n c.execute('''CREATE INDEX node_label_code_index ON node2data (label, code)''')\n c.execute('''CREATE INDEX rel_label_index ON rel2data (label)''')\n\n for source, target, key in graph.edges(keys=True):\n data = graph[source][target][key]\n r_id = data['r_id']\n c.execute(\"INSERT INTO graph VALUES (?,?,?,?)\", (source, target, r_id, json.dumps({})))\n\n for _id in node2data:\n label, name, en_name, n_code = node2data[_id]\n c.execute(\"INSERT INTO node2data VALUES (?,?,?,?,?,?)\", (_id, label, name, en_name, n_code, json.dumps({})))\n\n for _id in rel2data:\n label, name, en_name = rel2data[_id]\n c.execute(\"INSERT INTO rel2data VALUES (?,?,?,?,?)\", (_id, label, name, en_name, json.dumps({})))\n conn.commit()\n\n print('graph is save')\n\n\ndef insert_node2person2count(db_path):\n # 建立反向查询表\n print('create node2person2count start')\n GRAPH_DAO = common.GRAPH_DAO\n NodeLabels = common.NodeLabels\n GRAPH_DAO.start_connect()\n node_id2person_ids = defaultdict(lambda **arg: defaultdict(int))\n person_ids = GRAPH_DAO.get_node_ids_by_label(NodeLabels['person'])\n num_persons = len(person_ids)\n for _i, person_id in enumerate(person_ids):\n print('\\r node2person2count {}/{}'.format(_i + 1, num_persons), end='')\n person_id2sentence_ids, _, _ = get_sentence_dict([person_id], random_epoch=1000)\n sentence_ids = person_id2sentence_ids[person_id]\n if len(sentence_ids) < 10:\n continue\n for sentence_id in sentence_ids:\n node_ids = set([word_id for _j, word_id in enumerate(sentence_id) if _j % 2 == 0])\n for node_id in node_ids:\n node_id2person_ids[node_id][person_id] += 1\n GRAPH_DAO.close_connect()\n conn = sqlite3.connect(db_path)\n c = conn.cursor()\n c.execute('''CREATE TABLE node2person2count\n (\n node_id BIGINT PRIMARY KEY,\n person_id2count TEXT NOT NULL\n );\n ''')\n for node_id, person_id2count in node_id2person_ids.items():\n c.execute(\"INSERT INTO node2person2count VALUES (?,?)\", (int(node_id), json.dumps(person_id2count)))\n conn.commit()\n print('node2person2count finish')\n\n\ndef insert_condition2person(db_path):\n # 建立反向查询表\n print('create condition2person start')\n GRAPH_DAO = common.GRAPH_DAO\n NodeLabels = common.NodeLabels\n MetaPaths = common.MetaPaths\n GRAPH_DAO.start_connect()\n person_ids = GRAPH_DAO.get_node_ids_by_label(NodeLabels['person'])\n address2person_ids = defaultdict(set)\n post_type2person_ids = defaultdict(set)\n post_address2person_ids = defaultdict(set)\n office2person_ids = defaultdict(set)\n office_type2person_ids = defaultdict(set)\n entry2person_ids = defaultdict(set)\n entry_type2person_ids = defaultdict(set)\n num_persons = len(person_ids)\n for _i, _id in enumerate(person_ids):\n print('\\r condition2person {}/{}'.format(_i + 1, num_persons), end='')\n all_paths = MetaPaths['籍贯'].get_all_paths_by_node_id(_id)\n for _path in all_paths:\n if GRAPH_DAO.get_node_label_by_id(_path[-2]) == NodeLabels['address']:\n address2person_ids[_path[-2]].add(_id)\n all_paths = MetaPaths['官职'].get_all_paths_by_node_id(_id)\n for _path in all_paths:\n for i, word_id in enumerate(_path):\n if i % 2 == 0:\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['post_type']:\n post_type2person_ids[word_id].add(_id)\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['address']:\n post_address2person_ids[word_id].add(_id)\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['office']:\n office2person_ids[word_id].add(_id)\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['office_type']:\n office_type2person_ids[word_id].add(_id)\n all_paths = MetaPaths['入仕'].get_all_paths_by_node_id(_id)\n for _path in all_paths:\n for i, word_id in enumerate(_path):\n if i % 2 == 0:\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['entry']:\n entry2person_ids[word_id].add(_id)\n if GRAPH_DAO.get_node_label_by_id(word_id) == NodeLabels['entry_type']:\n entry_type2person_ids[word_id].add(_id)\n GRAPH_DAO.close_connect()\n conn = sqlite3.connect(db_path)\n c = conn.cursor()\n c.execute('''CREATE TABLE post_type2person_ids\n (\n post_type_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE post_address2person_ids\n (\n post_address_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE office2person_ids\n (\n office_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE office_type2person_ids\n (\n office_type_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE entry2person_ids\n (\n entry_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE entry_type2person_ids\n (\n entry_type_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n c.execute('''CREATE TABLE address2person_ids\n (\n address_id BIGINT PRIMARY KEY,\n person_ids TEXT NOT NULL\n );\n ''')\n for post_type_id, person_ids in post_type2person_ids.items():\n c.execute(\"INSERT INTO post_type2person_ids VALUES (?,?)\", (int(post_type_id), json.dumps(list(person_ids))))\n for address_id, person_ids in post_address2person_ids.items():\n c.execute(\"INSERT INTO post_address2person_ids VALUES (?,?)\", (int(address_id), json.dumps(list(person_ids))))\n for post_id, person_ids in office2person_ids.items():\n c.execute(\"INSERT INTO office2person_ids VALUES (?,?)\", (int(post_id), json.dumps(list(person_ids))))\n for post_id, person_ids in office_type2person_ids.items():\n c.execute(\"INSERT INTO office_type2person_ids VALUES (?,?)\", (int(post_id), json.dumps(list(person_ids))))\n for entry_id, person_ids in entry2person_ids.items():\n c.execute(\"INSERT INTO entry2person_ids VALUES (?,?)\", (int(entry_id), json.dumps(list(person_ids))))\n for entry_type_id, person_ids in entry_type2person_ids.items():\n c.execute(\"INSERT INTO entry_type2person_ids VALUES (?,?)\", (int(entry_type_id), json.dumps(list(person_ids))))\n for address_id, person_ids in address2person_ids.items():\n c.execute(\"INSERT INTO address2person_ids VALUES (?,?)\", (int(address_id), json.dumps(list(person_ids))))\n conn.commit()\n print('condition2person finish')\n\n\nif __name__ == \"__main__\":\n pass\n # neo4j = Shell('neo4j.bat console', 'Started')\n # neo4j.run_background()\n # whole_g, node2data, rel2data = get_whole_graph()\n # sql_dataset = Path('./dataset/graph.db')\n # if sql_dataset.exists():\n # sql_dataset.unlink()\n # save2sqlite(whole_g, node2data, rel2data, str(sql_dataset))\n # insert_node2person2count(str(sql_dataset))\n # insert_condition2person(str(sql_dataset))\n","sub_path":"build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":12170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"438488032","text":"import pytest\n\nfrom users.models import User\n\npytestmark = [pytest.mark.django_db]\n\n\ndef get_user():\n return User.objects.last()\n\n\ndef test_creating(api):\n api.post('/api/v2/leads/email/eggs/', {\n 'name': 'Monty Python',\n 'email': 'monty@python.org',\n }, format='multipart')\n\n created = get_user()\n\n assert created.first_name == 'Monty'\n assert created.last_name == 'Python'\n assert created.email == 'monty@python.org'\n\n\ndef test_creating_response(api):\n got = api.post('/api/v2/leads/email/eggs/', {\n 'name': 'Monty Python',\n 'email': 'monty@python.org',\n }, format='multipart')\n\n assert got['ok'] is True\n assert got['message'] == 'No spam, only ham'\n\n\ndef test_nameless(api):\n api.post('/api/v2/leads/email/eggs/', {\n 'email': 'monty@python.org',\n }, format='multipart')\n\n created = get_user()\n\n assert created.email == 'monty@python.org'\n\n\ndef test_wrong_email(api):\n api.post('/api/v2/leads/email/eggs/', {\n 'name': 'Monty Python',\n }, format='multipart', expected_status_code=400)\n","sub_path":"src/magnets/tests/email_lead_magnet/tests_emaiL_lead_magnet_creating_api.py","file_name":"tests_emaiL_lead_magnet_creating_api.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"36850240","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n### List of models for attribution generation\n\nclass SeedNetwork(nn.Module):\n \"\"\"3 layer ANN for prediction of minimum number among C numbers\"\"\"\n def __init__(self, C=5, fc1=16, fc2=8):\n \"\"\" C represents number of classes \"\"\"\n super(SeedNetwork, self).__init__()\n self.fc1 = nn.Linear(C, fc1)\n self.dp1 = nn.Dropout(p=0.3)\n self.fc2 = nn.Linear(fc1, fc2)\n self.dp2 = nn.Dropout(p=0.3)\n self.output = nn.Linear(fc2, C)\n \n def forward(self, x):\n \"\"\" Forward pass with input x of shape N x C \"\"\"\n #Layer 1\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dp1(x)\n #Layer 2\n x = self.fc2(x)\n x = F.relu(x)\n x = self.dp2(x)\n #Output Layer\n x = torch.sigmoid(self.output(x))\n return x\n \n#main model for loan prediction (try out different values for hidden layers to improve baseline)\nclass LoanNetwork(nn.Module):\n def __init__(self, input_features, layer1=30, layer2=20, out_features=2):\n \"\"\"Initialize the model for loan prediction\"\"\"\n super().__init__()\n self.fc1 = nn.Linear(input_features, layer1)\n self.fc2 = nn.Linear(layer1, layer2)\n self.out = nn.Linear(layer2, out_features)\n \n def forward(self, x):\n \"\"\"Forward pass with 11 input features\"\"\"\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.out(x)\n return x\n \nclass LawsNetwork(nn.Module):\n \"\"\" 4 layer ANN for Laws regression \"\"\"\n def __init__(self, input_features, output_features, fc1=32, fc2=16, fc3=8):\n \"\"\" C represents number of classes \"\"\"\n super(LawsNetwork, self).__init__()\n self.fc1 = nn.Linear(input_features, fc1)\n self.fc2 = nn.Linear(fc1, fc2)\n self.fc3 = nn.Linear(fc2, fc3)\n self.output = nn.Linear(fc3, output_features)\n \n def forward(self, x):\n \"\"\" Forward pass with input x of shape N x C \"\"\"\n #Layer 1\n x = self.fc1(x)\n x = F.relu(x)\n #Layer 2\n x = self.fc2(x)\n x = F.relu(x)\n #Layer 3\n x = self.fc3(x)\n x = F.relu(x)\n #Output Layer\n x = self.output(x)\n return x","sub_path":"attribution/code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"370172072","text":"'''\r\nMenu implementation for Assignment 1, that is used to test the Binary Search Tree\r\n\r\nOriginal code from FIT1008, modified by Nicholas Wong for FIT2004\r\n'''\r\n\r\n\r\nfrom Binary_Tree import *\r\nimport random\r\nfrom math import * \r\n\r\ntree = BinaryTree()\r\n\r\ndef menu():\r\n\r\n quit = False\r\n \r\n while not quit:\r\n print('### MAIN MENU ###\\n')\r\n print('Read $filename.txt')\r\n print('Search $number')\r\n print('Height')\r\n print('Print')\r\n print('Quit\\n')\r\n\r\n command = input(\"Enter a command: \")\r\n command_split = command.split(\" \")\r\n \r\n if len(command_split) == 1:\r\n if command.lower() == 'quit':\r\n print('Program is now quitting!')\r\n quit = True\r\n #print('height stopped')\r\n elif command.lower() == 'print':\r\n tree.print_inorder()\r\n else:\r\n try:\r\n error = command_split[1]\r\n except IndexError:\r\n print(\"Nothing was entered! You need to specify more parameters for that command!\\n\")\r\n \r\n elif len(command_split) == 2:\r\n if command_split[0].lower() == 'read':\r\n tree.reset()\r\n print(\"Reading the file!\")\r\n valid = False\r\n try:\r\n f = open(command_split[1], 'r')\r\n valid = True\r\n except IOError:\r\n print(\"That file does not exist!\")\r\n if valid:\r\n numbers(f, False)\r\n f.close()\r\n\r\n elif command_split[0].lower() == 'height':\r\n #print('height running')\r\n tree.reset()\r\n array = []\r\n for i in range(int(command_split[1])):\r\n array.append(i+1)\r\n\r\n perm_array = permute_array(array)\r\n print(perm_array)\r\n\r\n for item in perm_array:\r\n tree.insert(item)\r\n\r\n tree.print_inorder()\r\n\r\n print(\"height is: \"+str(tree.height()))\r\n\r\n elif command_split[0].lower() == 'search':\r\n valid = False\r\n # To check whether the input was a positive integer\r\n try:\r\n sqrt(int(command_split[1]))\r\n valid = True\r\n except ValueError:\r\n print(\"Need to enter a positive integer.\\n\")\r\n if valid:\r\n print(\"Searching and printing the route to the number \" + str(command_split[1]) + \" in the Binary Search Tree\")\r\n tree.search(int(command_split[1]))\r\n\r\n else:\r\n print(\"Too many paremeters. Try again.\\n\")\r\n\r\n\r\ndef permute_array(alist):\r\n n = len(alist) \r\n for i in range(0, n-1): \r\n j = random.randint(i, n-1) \r\n swap(alist, i, j)\r\n #print(alist)\r\n return alist \r\n\r\ndef swap(alist, i, j):\r\n tmp = alist[i] \r\n alist[i] = alist[j] \r\n alist[j] = tmp \r\n\r\n\r\ndef numbers(filename, random):\r\n \r\n number_list = []\r\n if not random:\r\n # Writing all numbers into number_list\r\n for _ in filename:\r\n number_list += _.split()\r\n # Inserting the numbers into the BST\r\n for i in number_list:\r\n tree.insert(int(i))\r\n print(\"All numbers have been inserted\")\r\n else:\r\n # Writing all numbers into number_list\r\n for _ in filename:\r\n number_list += _.split()\r\n # Inserting the numbers randomly into the BST\r\n for i in permute_array(number_list):\r\n tree.insert(int(i))\r\n print(\"All numbers have been inserted\")\r\n \r\n print(\"Printing inorder: \")\r\n tree.print_inorder()\r\n\r\nif __name__ == \"__main__\":\r\n menu()","sub_path":"week04/Question_4.py","file_name":"Question_4.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588715485","text":"dimensions = (192,192,192)\ninterval = 16\n\nimport vtk\n\noutput = vtk.vtkImageData()\noutput.SetOrigin(0,0,0)\noutput.SetSpacing(0.5,0.5,1.0)\noutput.SetDimensions(dimensions)\noutput.SetNumberOfScalarComponents(1)\noutput.SetScalarTypeToUnsignedChar()\noutput.AllocateScalars()\n\nscalars = output.GetPointData().GetScalars()\nscalars.FillComponent(0, 0) # second element is fill value\n\nc = 0\niborders = [0,0]\njborders = [0,0]\nkborders = [0,0]\n\nfor idx,borders in ((0, iborders), (1, jborders), (2, kborders)):\n b = dimensions[idx] / 4\n borders[0] = b\n borders[1] = dimensions[idx] - b\n\nfor k in xrange(kborders[0],kborders[1]):\n kOdd = (k / interval) % 2\n \n for j in xrange(jborders[0], jborders[1]):\n jOdd = (j / interval) % 2\n \n for i in xrange(iborders[0], iborders[1]):\n iOdd = (i / interval) % 2\n \n if iOdd ^ jOdd ^ kOdd:\n c = 255\n else:\n c = 254\n\n output.SetScalarComponentFromDouble(i,j,k,0,c)\n\n print(\"%d\\n\" % k)\n \nwriter = vtk.vtkXMLImageDataWriter()\nwriter.SetFileName('cube.vti')\nwriter.SetInput(output)\nwriter.Write()\n\n","sub_path":"Examples/Rendering/Python/create_cube.py","file_name":"create_cube.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"301588223","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom .base import Directory, DirectoryObject\n\nclass Channel(DirectoryObject):\n \n def __init__(self, id: str, name: str = None):\n \n self.id = id\n self.name = name\n self.hash_name = \"#\" + name\n\nclass ChannelDirectory(Directory):\n \n # The directory attribute is required by the Directory super class and is used to lookup DirectoryObjects\n directory = [\n Channel(id=\"C018EDFN5NJ\", name=\"github-actions\"),\n Channel(id=\"C027K0PEH0X\", name=\"autobuild-frontend\")\n ]\n \n # logging = \"CJ6JV6JR2\"\n # errors = \"CJ0RM8GGH\"\n # general = \"C0B13A6MR\"\n ","sub_path":"source/slack/directories/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"623931433","text":"#!/usr/bin/python3\n\nimport sys\nimport getopt\nimport os\n\nfrom shutil import copyfile\n\ndef main(argv):\n #default directory for notes\n directory = os.environ.get('STUDYUS') or os.path.expanduser('~') + \"/studyus-notes\"\n viewer = os.environ.get('STUDYUS_VIEWER') or \"sumatraPDF\"\n cls = ''\n fileName = ''\n\n directory = directory + \"/\"\n\n #process args\n try:\n opts, args = getopt.getopt(argv, \"e\", ['edit'])\n except getopt.GetoptError:\n print(\"lol u stupid\")\n sys.exit(2)\n\n location = directory + args[0] + \"/\" + args[1]\n if not os.path.exists(directory + args[0]):\n print(\"Course '\" + args[0] + \"' does not exist yet. Create it? [Y/n]\")\n create = input()\n if not (create == \"n\" or create == \"N\"):\n os.mkdir(directory + args[0])\n else:\n sys.exit(0)\n\n if not os.path.exists(location):\n print (\"Lecture '\" + args[1] + \"' does not exist yet. Create it? [Y/n]\")\n create = input()\n if not (create == \"n\" or create == \"N\"):\n os.mkdir(location);\n print(\"Title of Lecture: \")\n title = input()\n\n texFileLocation = location + \"/\" + args[1] + \".tex\"\n\n f = open(texFileLocation, \"w\")\n f.write(\"\\input{preamble}\\n\")\n f.write(\"\\\\title{\" + title + \"}\")\n f.write(\"\\\\begin{document}\\n\")\n f.write(\"\\\\maketitle\\n\\n\")\n f.write(\"\\\\end{document}\\n\")\n f.close()\n copyfile(\"./preamble.tex\", location + \"/preamble.tex\")\n\n os.chdir(location);\n os.system('pdflatex -output-directory '+ location + ' ' + texFileLocation)\n os.system(viewer + \" \" + location + \"/\" + args[1] + \".pdf\" + '&')\n os.system('vim ' + texFileLocation)\n else:\n sys.exit(0);\n else:\n texFileLocation = location + \"/\" + args[1] + \".tex\"\n os.chdir(location);\n os.system(viewer + \" \" + location + \"/\" + args[1] + \".pdf\" + '&')\n if opts and opts[0] != \"-e\" and opts[0] != \"--edit\":\n os.system('vim ' + texFileLocation)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"study.py","file_name":"study.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"368464885","text":"# -*- coding: utf-8 -*-\n# 两层神经卷积网络加两层全连接神经网络\n\nfrom numpy import *\nimport cv2\nimport tensorflow as tf\n\n# 神经网络最终输出个数\nPEOPLENUM = 10\n\n# 2维=>1维\ndef img2vector1(path):\n img = cv2.imread(path,0)\n row,col = img.shape\n vector1 = zeros((1,row*col),float32)\n vector1 = reshape(img,(1,row*col))\n return vector1\n\n# 计算测试集成功率\ndef compute_accuracy(v_xs, v_ys):\n global prediction\n y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})\n correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})\n return result\n\n# 神经元权重\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n# 神经元偏置\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n# ��积\ndef conv2d(x, W):\n # stride [1, x_movement, y_movement, 1]\n # Must have strides[0] = strides[3] = 1\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n# 最大池化,x,y步进值均为2\ndef max_pool_2x2(x):\n # stride [1, x_movement, y_movement, 1]\n return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\n\n# define placeholder for inputs to network\nxs = tf.placeholder(tf.float32, [None, 64*64])/255. # 64*64\nys = tf.placeholder(tf.float32, [None, PEOPLENUM]) # 10个输出\nkeep_prob = tf.placeholder(tf.float32)\nx_image = tf.reshape(xs, [-1, 64,64, 1])\n# print(x_image.shape) # [n_samples, 112,92,1]\n\n# 第一层卷积层\nW_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32\nb_conv1 = bias_variable([32])\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 64x64x32\nh_pool1 = max_pool_2x2(h_conv1) # output size 32x32x64\n\n\n# 第二层卷积层\nW_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 32x32x64\nh_pool2 = max_pool_2x2(h_conv2) # output size 16x16x64\n\n\n# 第一层神经网络全连接层\nW_fc1 = weight_variable([16*16*64, 1024])\nb_fc1 = bias_variable([1024])\n# [n_samples, 28, 23, 64] ->> [n_samples, 28*23*64]\nh_pool2_flat = tf.reshape(h_pool2, [-1, 16*16*64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n# 第二层神经网络全连接层\nW_fc2 = weight_variable([1024, PEOPLENUM])\nb_fc2 = bias_variable([PEOPLENUM])\nprediction = tf.nn.softmax((tf.matmul(h_fc1_drop, W_fc2) + b_fc2))\n\nsess = tf.Session()\ninit = tf.global_variables_initializer()\n\n# 下载训练数据\nsaver = tf.train.Saver()\nsaver.restore(sess,'my_data/save_net.ckpt')\n\n\ndef test(path):\n test_face = img2vector1(path)/255\n\n # 计算输出比重最大的人及其所占比重\n prediction1 = sess.run(prediction,feed_dict={xs:test_face,keep_prob:1})\n prediction1 = prediction1[0].tolist()\n people_num = prediction1.index(max(prediction1))+1\n result = max(prediction1)/sum(prediction1)\n print(prediction1)\n print(people_num,result)\n print()\n\nfor i in range(10):\n for j in range(16):\n path = 'face2/' + str(i+1) + '/' + str(j+1) + '.jpg'\n print('第%s个人,第%s张图片'%((i+1),(j+1)))\n test(path)\n'''\nfor i in range(10):\n for j in range(16):\n path = 'face2/' + str(i+1) + '/' + str(j+1) + '.jpg'\n print('第%s个人,第%s张图片'%((i+1),(j+1)))\n test_face = img2vector1(path)/255\n test_face_num = zeros((1,10))\n test_face_num[0][i] = 1\n print(compute_accuracy(test_face,test_face_num))\n'''","sub_path":"test/true_test.py","file_name":"true_test.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"19259430","text":"import numpy as np\n#import matplotlib.pyplot as plt\nfrom scipy.spatial.distance import pdist#, cdist\nimport time\n\ndef pcf2_iso_histo(data_location='../../fake_DATA/DATOS/data_500.dat',rand_location='../../fake_DATA/DATOS/rand0_500.dat', d_max=180.0, bins_number=30):\n \"\"\"\n Calculates the DD, RR, DR onedimentional histograms for the isotropic points given in the data and random text files. Both files must have the same number of points with three dimesions.\n \n args:\n -data_location: str. It is the file location of the data. Each row a different point with the coordinates (x,y,z) as the first three columns separated with blank spaces.\n -rand_location: str. It is the file location of the file with random points. Each row a different point with the coordinates (x,y,z) as the first three columns separated with blank spaces.\n -d_max: float. The maximum distance that will be considered in the histogram\n -bins_number: int. The number of bins to use to separate the data.\n \n return:\n -DD: np.array. Array with the frequencies of the distances between data points and data points\n -RR: np.array. Array with the frequencies of the distances between random points and random points\n -DR: np.array. Array with the frequencies of the distances between data points and random points\n -bins: np.array. With the edges of the bins for later xaxis plot\n \n \"\"\"\n \n data = np.loadtxt(fname=data_location, delimiter=\" \", usecols=(0,1,2))\n rand0 = np.loadtxt(fname=rand_location, delimiter=\" \", usecols=(0,1,2))\n \n if not data.shape == rand0.shape:\n raise Exception(\"The data file and rand file do not have the same size\")\n \n start = time.perf_counter()\n DR = np.zeros(bins_number)\n for point in data:\n distances = point-rand0\n DR_temp, bins_DR = np.histogram(np.sqrt(distances[:,0]**2+distances[:,1]**2), bins=bins_number, range=(0, d_max))\n #DR_temp, bins_DR = np.histogram(np.sqrt(np.sum((point-rand0)**2,1)), bins=bins_number, range=(0, d_max))\n DR += DR_temp\n end = time.perf_counter()\n print(f'{end-start} for the DR histogram')\n\n start = time.perf_counter()\n DD, bins_DD = np.histogram(pdist(data[:,:2]), bins=bins_number, range=(0,d_max))\n DD *= 2\n end = time.perf_counter()\n print(f'{end-start} for the DD histogram')\n\n start = time.perf_counter()\n RR, bins_RR = np.histogram(pdist(rand0[:,:2]), bins=bins_number, range=(0,d_max))\n RR *= 2\n end = time.perf_counter()\n print(f'{end-start} for the RR histogram')\n \n return DD, RR, DR, bins_DR\n\nstart = time.perf_counter()\n\nDD, RR, DR, bins_DR = pcf2_iso_histo(data_location='../../fake_DATA/DATOS/data.dat',rand_location ='../../fake_DATA/DATOS/rand0.dat')\n\nend = time.perf_counter()\nprint(f'total time: {end-start}')\n\nnp.savetxt('DD_BF.dat', DD)\nnp.savetxt('RR_BF.dat', RR)\nnp.savetxt('DR_BF.dat', DR)\n","sub_path":"python/MALLA/bf_iso_2pcf_xy.py","file_name":"bf_iso_2pcf_xy.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"51652219","text":"from gtts import gTTS \nimport os\nimport playsound\n\ntimes = 1\n\ndef speak(textToSpeak):\n\tglobal times\n\n\ttimes += 1\n\n\ttoSpeak = gTTS(text = textToSpeak, lang = 'en', slow = False)\n\tfile = str(times)+\".mp3\"\n\ttoSpeak.save(file)\n\n\tplaysound.playsound(file, True)\n\tos.remove(file)","sub_path":"speak.py","file_name":"speak.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"171001991","text":"from collections import deque \n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n answer = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1':\n self.bfs(grid, i, j)\n answer += 1\n return answer\n \n def bfs(self, grid, i, j):\n directions = [(i,j+1),(i,j-1),(i-1,j),(i+1,j)]\n q = deque()\n for x, y in directions:\n q.append((x, y))\n while q:\n d1, d2 = q.popleft()\n if 0 <= d1 < len(grid) and 0 <= d2 < len(grid[0]) and grid[d1][d2] == '1':\n grid[d1][d2] = '0'\n dirs = [(d1,d2+1),(d1,d2-1),(d1-1,d2),(d1+1,d2)]\n for x1, y1 in dirs:\n q.append((x1,y1))\n","sub_path":"queue_and_stack/number_of_islands.py","file_name":"number_of_islands.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"85226311","text":"from django import forms\n\nfrom board.models import Board\n\n\nclass BoardWriteForm(forms.ModelForm):\n\n class Meta:\n model = Board\n exclude = []\n\n def clean_title(self):\n title = self.cleaned_data.get('title')\n if not title:\n raise forms.ValidationError('제목을 입력해 주세요.')\n\n return title\n\n def clean_content(self):\n content = self.cleaned_data.get('content')\n if not content:\n raise forms.ValidationError('내용을 입력해 주세요.')\n\n return content\n\n\n","sub_path":"board/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"186982371","text":"import numpy as np\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QBrush, QColor\nfrom PyQt5.QtWidgets import (QWidget, QVBoxLayout, QGridLayout, QMdiArea, QGroupBox, QPushButton, QRadioButton,\n QCheckBox, QMessageBox)\n\nfrom plot_window import PlotWindow\nfrom info_window import ObjectInfoWindow\nfrom view_tab import ViewTab\nfrom detector_selector import MultiDitherDetectorSelector\nimport utils\n\n\n# FIXME: these should be provided as inputs\n\nJ_WAV = 13697.01 # in angstroms\nH_WAV = 17761.52 # in angstroms\n\nflag = {\"ZERO\": np.uint32(2**18), # zeroth-order: bit 18\n \"MISSING\": np.uint32(2**19), # missing data: bit 19\n \"SIGCONT\": np.uint32(2**20)} # significantly contaminated; contamination flux is > 10% of source flux: bit 20\n\n\nclass PlotSelector(QWidget):\n \"\"\"\n A widget for selecting the type of plot that will be generated. This also contains the Plot button, which triggers\n the plotting.\n \"\"\"\n X_PIX = 0\n X_WAV = 1\n\n Y_DN = 0\n Y_FLUX = 1\n\n S_ORIG = 1\n S_DECON = 2\n S_CONTAM = 4\n S_MODEL = 8\n\n def __init__(self, object_tab, *args):\n super().__init__(*args)\n\n self.object_tab = object_tab\n\n # data series selection\n\n data_series_group = QGroupBox('Data Series', self)\n data_series_group.setAlignment(Qt.AlignCenter)\n data_series_group.setMaximumWidth(550)\n data_series_group.setMinimumWidth(300)\n\n original_check = QCheckBox('Original', data_series_group)\n original_check.setChecked(True)\n\n decontaminated_check = QCheckBox('Decontaminated', data_series_group)\n decontaminated_check.setChecked(True)\n\n contamination_check = QCheckBox('Contamination', data_series_group)\n contamination_check.setChecked(True)\n\n model_check = QCheckBox('Model', data_series_group)\n\n data_series_group.setLayout(QGridLayout())\n data_series_group.layout().addWidget(original_check, 0, 0)\n data_series_group.layout().addWidget(decontaminated_check, 0, 1)\n data_series_group.layout().addWidget(contamination_check, 1, 0)\n data_series_group.layout().addWidget(model_check, 1, 1)\n\n self._original = original_check\n self._decon = decontaminated_check\n self._contam = contamination_check\n self._model = model_check\n\n # y-axis type selection\n\n y_axis_type = QGroupBox('y-axis type', self)\n y_axis_type.setAlignment(Qt.AlignCenter)\n y_axis_type.setMaximumWidth(300)\n y_axis_type.setMinimumWidth(200)\n data_number_radio = QRadioButton('Image Units', y_axis_type)\n calibrated_flux_radio = QRadioButton('Calibrated Flux', y_axis_type)\n if self.object_tab.inspector.sensitivities[self.object_tab.dither] is None:\n calibrated_flux_radio.setDisabled(True)\n data_number_radio.setChecked(True)\n else:\n calibrated_flux_radio.setChecked(True)\n y_axis_type.setLayout(QVBoxLayout())\n y_axis_type.layout().addWidget(data_number_radio)\n y_axis_type.layout().addWidget(calibrated_flux_radio)\n\n self._data_number = data_number_radio\n self._flux = calibrated_flux_radio\n\n # x-axis type selection\n\n x_axis_type = QGroupBox('x-axis type', self)\n x_axis_type.setAlignment(Qt.AlignCenter)\n x_axis_type.setMaximumWidth(300)\n x_axis_type.setMinimumWidth(200)\n wavelength_radio = QRadioButton('Wavelength', x_axis_type)\n wavelength_radio.setChecked(True)\n pixel_number_radio = QRadioButton('Pixel number', x_axis_type)\n x_axis_type.setLayout(QVBoxLayout())\n x_axis_type.layout().addWidget(pixel_number_radio)\n x_axis_type.layout().addWidget(wavelength_radio)\n\n self._wavelength = wavelength_radio\n self._pixel_num = pixel_number_radio\n\n # buttons\n\n detector_button = QPushButton('Show Detectors', self)\n detector_button.setMaximumWidth(128)\n detector_button.pressed.connect(self.object_tab.open_detectors)\n detector_button.setDisabled(True)\n plot_button = QPushButton('Make Plot(s)', self)\n plot_button.setMaximumWidth(128)\n plot_button.setMinimumWidth(100)\n plot_button.pressed.connect(self.object_tab.make_plots)\n plot_button.setDisabled(True)\n\n self.detector_button = detector_button\n self.plot_button = plot_button\n\n buttons = QVBoxLayout()\n buttons.addSpacing(23)\n buttons.addWidget(detector_button)\n buttons.addWidget(plot_button)\n\n layout = QGridLayout()\n layout.setSpacing(15)\n layout.setContentsMargins(10, 0, 10, 10)\n\n layout.addWidget(data_series_group, 0, 0)\n layout.addWidget(y_axis_type, 0, 1)\n layout.addWidget(x_axis_type, 0, 2)\n layout.addLayout(buttons, 0, 3)\n\n self.setContentsMargins(8, 0, 8, 8)\n\n self.setLayout(layout)\n\n @property\n def x_type(self):\n if self._wavelength.isChecked():\n return self.X_WAV\n else:\n return self.X_PIX\n\n @property\n def y_type(self):\n if self._data_number.isChecked():\n return self.Y_DN\n else:\n return self.Y_FLUX\n\n @property\n def series(self):\n result = 0\n if self._original.isChecked():\n result |= self.S_ORIG\n\n if self._contam.isChecked():\n result |= self.S_CONTAM\n\n if self._decon.isChecked():\n result |= self.S_DECON\n\n if self._model.isChecked():\n result |= self.S_MODEL\n\n return result\n\n\nclass SpecPlot:\n\n def __init__(self, inspector, plot_selector, detector_selector):\n self._inspector = inspector\n self._plot_selector = plot_selector\n self._detector_selector = detector_selector\n self._detectors = None\n self._object_id = None\n self._x_type = None\n self._y_type = None\n self._data_series = None\n self._windows = []\n\n @property\n def windows(self):\n return self._windows\n\n def make_plots(self, object_id):\n self._object_id = object_id\n self._detectors = self._detector_selector.selected_detectors()\n self._x_type = self._plot_selector.x_type\n self._y_type = self._plot_selector.y_type\n self._data_series = self._plot_selector.series\n\n for dither, detectors in self._detectors.items():\n if detectors is not None:\n for detector in detectors:\n plot = self._plot(dither, detector)\n self._windows.append(plot)\n\n def _calibrate_spectrum(self, dither, spec_1d, wavelengths):\n \"\"\"\n Applies the calibration correction to convert `spec_1d` from detector units to erg/s/cm^2/Angstrom\n \"\"\"\n if self._inspector.sensitivities[dither] is None:\n m = QMessageBox(self._inspector, 'You need to load the grism sensitivity curves first.')\n m.exec()\n return\n\n exposure_time = self._inspector.exposures[dither][1].header['EXPTIME']\n\n dl = np.fabs(np.diff(wavelengths))\n\n denom = np.append(dl, dl[0]) * exposure_time\n\n sensitivity_wav, sensitivity_value = self._inspector.sensitivities[dither]\n\n inverse_sensitivity = utils.div0(1.0, sensitivity_value)\n\n return utils.interp_multiply(wavelengths, spec_1d / denom, sensitivity_wav, inverse_sensitivity)\n\n def _plot(self, dither, detector):\n if self._data_series == 0:\n return\n\n plot = PlotWindow(f\"object {self._object_id} detector: {dither}.{detector}\")\n\n spec = self._inspector.collection.get_spectrum(dither, detector, self._object_id)\n dispersion_axis = spec.solution.dispersion_orientation()\n\n plot_flux = self._y_type == PlotSelector.Y_FLUX\n plot_wavelength = self._x_type == PlotSelector.X_WAV\n\n if dispersion_axis == 0:\n pixels = spec.x_offset + np.arange(0, spec.science.shape[1])\n wavelengths = spec.solution.compute_wavelength(pixels)\n else:\n pixels = spec.y_offset + np.arange(0, spec.science.shape[0])\n wavelengths = spec.solution.compute_wavelength(pixels)\n\n min_wav, max_wav = 12400, 18600\n\n short_wav_end = np.argmin(np.fabs(wavelengths - min_wav))\n long_wav_end = np.argmin(np.fabs(wavelengths - max_wav))\n i_min = min(short_wav_end, long_wav_end)\n i_max = max(short_wav_end, long_wav_end)\n\n x_values = wavelengths[i_min: i_max] if plot_wavelength else pixels[i_min: i_max]\n\n # determine and set the limits of the x-axis\n\n if plot_wavelength and plot_flux:\n plot.axis.set_xlim((min_wav, max_wav))\n elif plot_flux and not plot_wavelength:\n short_wav_end = np.argmin(np.fabs(wavelengths - min_wav))\n long_wav_end = np.argmin(np.fabs(wavelengths - max_wav))\n x_min = min(pixels[short_wav_end], pixels[long_wav_end])\n x_max = max(pixels[short_wav_end], pixels[long_wav_end])\n plot.axis.set_xlim((x_min, x_max))\n\n zeroth_mask = np.sum(spec.mask & flag['ZERO'], axis=dispersion_axis)\n\n if self._data_series & PlotSelector.S_ORIG == PlotSelector.S_ORIG:\n if plot_flux:\n uncalibrated = np.sum(spec.science + spec.contamination, axis=dispersion_axis)\n y_values = self._calibrate_spectrum(dither, uncalibrated, wavelengths)\n else:\n y_values = np.sum(spec.science + spec.contamination, axis=dispersion_axis)\n\n y_values = np.ma.masked_where(zeroth_mask != 0, y_values)\n\n plot.axis.plot(x_values, y_values[i_min: i_max], label='original spectrum', color='k', linewidth=0.5,\n alpha=0.7)\n\n if self._data_series & PlotSelector.S_CONTAM == PlotSelector.S_CONTAM:\n if plot_flux:\n y_values = self._calibrate_spectrum(dither, spec.contamination.sum(dispersion_axis), wavelengths)\n else:\n y_values = spec.contamination.sum(dispersion_axis)\n\n plot.axis.plot(x_values, y_values[i_min: i_max], label='contamination', color='g', linewidth=0.75,\n alpha=0.8)\n\n if self._data_series & PlotSelector.S_DECON == PlotSelector.S_DECON:\n if plot_flux:\n y_values_unmasked = self._calibrate_spectrum(dither, spec.science.sum(dispersion_axis), wavelengths)\n else:\n y_values_unmasked = spec.science.sum(dispersion_axis)\n\n y_values = np.ma.masked_where(zeroth_mask != 0, y_values_unmasked)\n\n plot.axis.plot(x_values, y_values[i_min: i_max], label='decontaminated spectrum', color='b', linewidth=0.9)\n\n if self._data_series & PlotSelector.S_MODEL == PlotSelector.S_MODEL:\n model = self._inspector.collection.get_model(dither, detector, self._object_id, order=1)\n if model is not None:\n if plot_flux:\n y_values = self._calibrate_spectrum(dither, model.pixels.sum(dispersion_axis), wavelengths)\n else:\n y_values = model.pixels.sum(dispersion_axis)\n\n plot.axis.plot(x_values, y_values[i_min: i_max], label='model spectrum', color='r', linewidth=0.9,\n alpha=0.9)\n\n # plot the J and H band fluxes if the plot shows flux vs wavelength\n\n if plot_wavelength and plot_flux:\n info = self._inspector.location_tables.get_info(self._object_id)\n j_microjansky = utils.mag_to_fnu(info.jmag, zero_point=22)\n h_microjansky = utils.mag_to_fnu(info.hmag, zero_point=22)\n j_fnu = utils.mjy_to_angstrom(j_microjansky, J_WAV)\n h_fnu = utils.mjy_to_angstrom(h_microjansky, H_WAV)\n plot.axis.scatter(J_WAV, j_fnu, color='r', label='J and H band fluxes')\n plot.axis.scatter(H_WAV, h_fnu, color='r')\n\n x_label = r'Wavelength $\\rm (\\AA)$' if self._x_type == PlotSelector.X_WAV else 'Pixel'\n y_label = r'Flux ($\\rm erg/s/cm^2/\\AA$)' if self._y_type == PlotSelector.Y_FLUX else 'Electrons / second'\n\n plot.axis.set_xlabel(x_label)\n plot.axis.set_ylabel(y_label)\n plot.axis.legend()\n\n # set the descriptor; a string in the format: id.dither.detector.data_series.y_type.x_type\n plot.descriptor = f'{self._object_id}.{dither}.{detector}.{self._data_series}.{self._y_type}.{self._x_type}'\n\n return plot\n\n\nclass ObjectTab(QWidget):\n \"\"\"\n This class constructs the entire contents of the Object tab.\n \"\"\"\n def __init__(self, inspector, dither, detector, object_id, *args):\n super().__init__(*args)\n\n self._inspector = inspector\n self._dither = dither # remove\n self._detector = detector # remove\n self._object_id = object_id\n self.contents = list()\n self.setMouseTracking(True)\n\n self.plot_selector = PlotSelector(self)\n\n detectors = self.determine_relevant_detectors(object_id)\n\n selector_area = MultiDitherDetectorSelector(detectors)\n selector_area.updated.connect(self.update_plot_button)\n\n self.mdi = QMdiArea(self)\n self.mdi.setContentsMargins(0, 0, 0, 0)\n self.mdi.setBackground(QBrush(QColor('#56595e')))\n\n h_layout = QGridLayout()\n h_layout.setSpacing(0)\n h_layout.setContentsMargins(0, 0, 0, 0)\n h_layout.addWidget(selector_area, 0, 0)\n h_layout.setAlignment(selector_area, Qt.AlignTop)\n h_layout.addWidget(self.mdi, 0, 1)\n\n h_layout.setColumnStretch(0, 0)\n h_layout.setColumnStretch(1, 10)\n\n self.detector_selector = selector_area\n\n v_layout = QVBoxLayout()\n v_layout.setSpacing(0)\n\n v_layout.addWidget(self.plot_selector)\n\n v_layout.addItem(h_layout)\n\n self.setLayout(v_layout)\n self.setContentsMargins(0, 0, 0, 0)\n self._spec_plots = None\n\n self._plot_descriptors = set()\n\n self._info_window = None\n\n @property\n def object_id(self):\n return self._object_id\n\n @property\n def dither(self):\n return self._dither\n\n @property\n def detector(self):\n return self._detector\n\n @property\n def inspector(self):\n return self._inspector\n\n def make_plots(self):\n self._spec_plots = SpecPlot(self._inspector, self.plot_selector, self.detector_selector)\n self._spec_plots.make_plots(self._object_id)\n for window in self._spec_plots.windows:\n if window.descriptor not in self._plot_descriptors:\n self.mdi.addSubWindow(window)\n self._plot_descriptors.add(window.descriptor)\n window.closing.connect(self.handle_closed_subwindow)\n window.activateWindow()\n window.show()\n\n def show_info(self):\n if self._inspector.location_tables is not None:\n info = self._inspector.location_tables.get_info(self._object_id)\n info_window = ObjectInfoWindow(info, self._inspector)\n self.mdi.addSubWindow(info_window)\n info_window.activateWindow()\n info_window.show()\n self._info_window = info_window\n else:\n m = QMessageBox(0, 'Missing Data',\n 'Location tables containing the requested information must be loaded before showing info.')\n m.exec()\n\n def determine_relevant_detectors(self, object_id):\n \"\"\"\n Returns the detectors in which the spectra of the object can be found, in the format {dither: [detectors]}\n \"\"\"\n detectors = {}\n\n for dither in self._inspector.spectra[object_id]:\n detectors[dither] = list(self._inspector.spectra[object_id][dither].keys())\n\n for d in (1, 2, 3, 4):\n if d not in detectors:\n detectors[d] = []\n\n return detectors\n\n def update_plot_button(self):\n selected = list(self.detector_selector.selected_detectors().values())\n\n if all(item is None for item in selected):\n self.plot_selector.plot_button.setDisabled(True)\n self.plot_selector.detector_button.setDisabled(True)\n else:\n self.plot_selector.detector_button.setEnabled(True)\n self.plot_selector.plot_button.setEnabled(True)\n\n def handle_closed_subwindow(self, descriptor):\n if descriptor in self._plot_descriptors:\n self._plot_descriptors.remove(descriptor)\n\n active_window = self.mdi.activeSubWindow()\n\n if active_window is not None and descriptor == active_window.widget().descriptor:\n self.mdi.closeActiveSubWindow()\n\n def open_detectors(self):\n\n selected_detectors = self.detector_selector.selected_detectors()\n\n inspector = self._inspector\n\n # make a list of all open detectors (detectors currently being viewed in tabs)\n\n open_detectors = []\n\n for tab_index in range(inspector.tabs.count()):\n tab = inspector.tabs.widget(tab_index)\n if isinstance(tab, ViewTab):\n open_detectors.append((tab.current_dither, tab.current_detector))\n\n # open new tabs, where necessary\n\n for dither in selected_detectors:\n if selected_detectors[dither] is not None:\n for detector in selected_detectors[dither]:\n if (dither, detector) not in open_detectors:\n inspector.new_view_tab(dither, detector)\n\n # pin the object in all tabs:\n\n for tab_index in range(inspector.tabs.count()):\n tab = inspector.tabs.widget(tab_index)\n if isinstance(tab, ViewTab):\n tab.select_spectrum_by_id(self._object_id)\n","sub_path":"object_tab.py","file_name":"object_tab.py","file_ext":"py","file_size_in_byte":17838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"228151982","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 ('majitel', '0001_initial'),\n ('nemov', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Dotaz',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.CharField(max_length=100)),\n ('checked', models.BooleanField(default=False)),\n ('majitel_from', models.ForeignKey(related_name=b'majitel_from', to='majitel.Majitel')),\n ('majitel_to', models.ForeignKey(related_name=b'majitel_to', to='majitel.Majitel')),\n ('nemov', models.ForeignKey(default=None, to='nemov.Nemovitost')),\n ('old_dotaz', models.ForeignKey(default=None, to='dotaz.Dotaz', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"dotaz/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"204042982","text":"import logging\nimport scrapy\nfrom scrapy.spiders import CrawlSpider\nfrom booking_parser.items import HotelItem\nfrom booking_parser.items import RoomTypeItem\nfrom booking_parser.items import RoomItem\nfrom helpers.db_helper import DBHelper\n\n\nclass BookingSpider(CrawlSpider, DBHelper):\n name = \"booking\"\n config_id = None\n\n hdrs = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,'\n 'image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'max-age=0',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '\n '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'\n }\n\n allowed_domains = ['www.booking.com']\n start_urls = [\n\n ]\n\n def __init__(self, *args, **kwargs):\n console = logging.StreamHandler()\n console.setLevel(logging.DEBUG)\n logging.getLogger('').addHandler(console)\n\n self.arguments = kwargs.get('kwargs')\n self.use_vpn = self.arguments['use_vpn']\n self.vpn_response_error_counter = 0\n self.config_id = self.arguments.get('config_id', None)\n\n super().__init__(*args, **kwargs)\n\n def start_requests(self):\n return [scrapy.FormRequest(\n url=\"https://www.booking.com/searchresults.ru.html?id=test\",\n method=\"GET\",\n formdata={\n 'ss': self.arguments['country'] + ' ' + self.arguments['city'],\n 'checkin_monthday': str(self.arguments['checkin_monthday']),\n 'checkin_month': str(self.arguments['checkin_month']),\n 'checkin_year': str(self.arguments['checkin_year']),\n\n 'checkout_monthday': str(self.arguments['checkout_monthday']),\n 'checkout_month': str(self.arguments['checkout_month']),\n 'checkout_year': str(self.arguments['checkout_year']),\n },\n callback=self.parse,\n headers=self.hdrs\n )]\n\n def parse(self, response):\n for link in response.xpath(\"//div[@id='hotellist_inner']//div[@class='sr-cta-button-row']/a\"):\n hotel_page_href = link.css('a::attr(href)').extract_first().strip()\n hotel_page = response.urljoin(hotel_page_href)\n yield scrapy.Request(hotel_page, callback=self.parse_hotel,\n headers=self.hdrs)\n\n next_page = response.xpath(\"//li[contains(@class,'bui-pagination__item bui-pagination__next-arrow')]/a/@href\").extract_first()\n if next_page is not None:\n next_page = response.urljoin(next_page)\n yield scrapy.Request(next_page, callback=self.parse,\n headers=self.hdrs)\n\n def parse_hotel(self, response):\n hotel = HotelItem()\n hotel['hotel_id'] = response.xpath(\"//form[@id='top-book']/input[@name='hotel_id']/@value\").extract_first()\n hotel['url'] = response.url[:response.url.find('?')]\n hotel['name'] = response.xpath(\"//h2[@class='hp__hotel-name']/text()\").extract_first().strip()\n hotel['description'] = \" \".join(response.xpath(\"//div[@id='summary']/p/text()\").extract()).strip()\n hotel['address'] = response.xpath(\n \"//span[contains(@class, 'hp_address_subtitle')]/text()\").extract_first().strip()\n hotel['rate'] = response.css(\n \"span.review-score-widget__auto > span.review-score-badge::text\").extract_first()\n\n image = response.xpath(\"//div[@id='photos_distinct']/a[1] | \"\n \"//a[contains(@class,'bh-photo-grid-photo1')]\")\n hotel['image_urls'] = image.xpath(\"@href\").extract()\n hotel['photo_url'] = image.xpath(\"@href\").extract_first()\n\n checkin_date = response.xpath(\"//form[@id='top-book']/input[@name='checkin']/@value\").extract_first()\n raw_rooms = self.get_raw_rooms(response)\n parsed_rooms = self.get_parsed_rooms(raw_rooms, hotel['hotel_id'], checkin_date)\n hotel['rooms'] = parsed_rooms\n\n for room_type in parsed_rooms:\n if room_type['image_url'] is not None:\n hotel['image_urls'].append(room_type['image_url'])\n\n yield hotel\n\n # Method get_rooms accepts response and finds all rows(tr tags) which belongs to one room type and selects external\n # data about room.\n # Then return 2D array, where each row represents one room type and contoinas all trs which bellong to it\n def get_raw_rooms(self, response):\n rooms = []\n room_types = []\n\n for row in response.xpath(\"//form[@id='hprt-form']/table[contains(@class, 'hprt-table')]/tbody/tr\"):\n class_list = row.xpath(\"@class\").extract_first()\n data_block_id = row.xpath(\"@data-block-id\").extract_first()\n\n if data_block_id is not '' and class_list.find('hprt-cheapest-block-row') is not 1:\n if class_list.find(\"hprt-table-last-row \") is not -1:\n rooms.append(row)\n room_id = row.xpath(\".//select[@class='hprt-nos-select']/@data-room-id\").extract_first()\n room_details = response.xpath(\"//div[@data-room-id='\" + room_id + \"']\")\n room_data = {\n 'room_details': room_details,\n 'rooms': rooms\n }\n room_types.append(room_data)\n rooms = []\n else:\n rooms.append(row)\n\n return room_types\n\n def get_parsed_rooms(self, raw_rooms, h_id, checkin_date):\n result = []\n\n for rooms_data in raw_rooms:\n raw_room = rooms_data['rooms']\n\n room_type_item = RoomTypeItem()\n room_type_item['id'] = raw_room[0].xpath(\n \".//select[@class='hprt-nos-select']/@data-room-id\").extract_first()\n room_type_item['hotel_id'] = h_id\n room_type_item['name'] = raw_room[0].xpath(\n \".//a[contains(@class,'hprt-roomtype-link')]/@data-room-name\").extract_first()\n room_type_item['image_url'] = self.get_photo_url(rooms_data['room_details'])\n room_type_item['room_items'] = []\n\n for tr in raw_room:\n room_item = RoomItem()\n room_item['price'] = tr.xpath(\n \".//div[contains(@class,'hprt-price-price')]/span/text()\").extract_first()\n\n if room_item['price'] is not None:\n room_item['room_type_id'] = room_type_item['id']\n room_item['price'] = room_item['price'].strip()\n room_item['date'] = checkin_date\n room_item['sleeps'] = tr.xpath(\n \"count( .//div[contains(@class,'hprt-occupancy-occupancy-info')]/i )\").extract_first()\n\n room_type_item['room_items'].append(room_item)\n\n result.append(room_type_item)\n\n return result\n\n def get_photo_url(self, room_details):\n photo_id = room_details.xpath(\n \".//div[@class='b_nha_hotel_small_images']//a/@data-photoid\").extract_first()\n\n if photo_id is not None:\n photo_url = room_details.xpath(\"//a[@data-photoid='\" + photo_id + \"']/@href | \"\n \"//div[@data-photoid='\" + photo_id + \"']/img/@data-lazy\").extract_first()\n else:\n photo_url = None\n\n return photo_url\n","sub_path":"src/booking_parser/booking_parser/spiders/booking_spider.py","file_name":"booking_spider.py","file_ext":"py","file_size_in_byte":7575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"259071416","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, 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\"\"\"\nFine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa).\nGPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned\nusing a masked language modeling (MLM) loss.\n\"\"\"\n\nfrom __future__ import absolute_import\nimport os\nimport sys\nimport bleu\nimport pickle\nimport torch\nimport json\nimport random\nimport logging\nimport argparse\nfrom bleu import _bleu\nimport numpy as np\nfrom io import open\nfrom itertools import cycle\nimport torch.nn as nn\nfrom model import Seq2Seq\nfrom tqdm import tqdm, trange\nfrom torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler,TensorDataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup,\n RobertaConfig, RobertaModel, RobertaTokenizer)\nMODEL_CLASSES = {'roberta': (RobertaConfig, RobertaModel, RobertaTokenizer)}\n\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO)\nlogger = logging.getLogger(__name__)\nfrom parser import DFG_python,DFG_java,DFG_ruby,DFG_go,DFG_php,DFG_javascript,DFG_csharp\nfrom parser import (remove_comments_and_docstrings,\n tree_to_token_index,\n index_to_code_token,\n tree_to_variable_index)\nfrom tree_sitter import Language, Parser\ndfg_function={\n 'python':DFG_python,\n 'java':DFG_java,\n 'ruby':DFG_ruby,\n 'go':DFG_go,\n 'php':DFG_php,\n 'javascript':DFG_javascript,\n 'c_sharp':DFG_csharp,\n}\n\ndef get_example(item):\n source,target,tokenizer,args,parser=item\n code=source.replace('. ','.')\n nl=target.strip()\n #remove comments\n try:\n code=remove_comments_and_docstrings(code,lang)\n except:\n pass \n \n #obtain dataflow\n try:\n tree = parser[0].parse(bytes(code,'utf8')) \n root_node = tree.root_node \n tokens_index=tree_to_token_index(root_node) \n code=code.split('\\n')\n code_tokens=[index_to_code_token(x,code) for x in tokens_index] \n index_to_code={}\n for idx,(index,code) in enumerate(zip(tokens_index,code_tokens)):\n index_to_code[index]=(idx,code) \n try:\n DFG,_=parser[1](root_node,index_to_code,{}) \n except:\n DFG=[]\n DFG=sorted(DFG,key=lambda x:x[1])\n indexs=set()\n for d in DFG:\n if len(d[-1])!=0:\n indexs.add(d[1])\n for x in d[-1]:\n indexs.add(x)\n new_DFG=[]\n for d in DFG:\n if d[1] in indexs:\n new_DFG.append(d)\n codes=code_tokens\n dfg=new_DFG\n except:\n codes=code.split()\n dfg=[]\n #merge nodes\n dic={}\n for d in dfg:\n if d[1] not in dic:\n dic[d[1]]=d\n else:\n dic[d[1]]=(d[0],d[1],d[2],list(set(dic[d[1]][3]+d[3])),list(set(dic[d[1]][4]+d[4])))\n DFG=[]\n for d in dic:\n DFG.append(dic[d])\n dfg=DFG\n return convert_examples_to_features(codes,dfg,nl,tokenizer,args)\n\nclass InputFeatures(object):\n \"\"\"A single training/test features for a example.\"\"\"\n def __init__(self,\n input_tokens,\n input_ids,\n target_tokens,\n target_ids, \n dfg_tokens,\n dfg_ids,\n dfg_to_code,\n dfg_to_dfg,\n target,\n\n\n ):\n self.input_tokens = input_tokens\n self.input_ids = input_ids\n self.target_tokens=target_tokens\n self.target_ids=target_ids\n self.dfg_tokens=dfg_tokens\n self.dfg_ids=dfg_ids\n self.dfg_to_code=dfg_to_code\n self.dfg_to_dfg=dfg_to_dfg\n self.target=target\n \ndef convert_examples_to_features(code,dfg,nl,tokenizer,args):\n code_tokens=[tokenizer.tokenize(x) for x in code]\n dfg=dfg[:args.max_dfg_length]\n reverse_index={}\n for idx,x in enumerate(dfg):\n reverse_index[x[1]]=idx\n for idx,x in enumerate(dfg):\n dfg[idx]=x[:-1]+([reverse_index[i] for i in x[-1] if i in reverse_index],)\n dfg_tokens=[x[0] for x in dfg]\n dfg_to_dfg=[x[-1] for x in dfg]\n dic={}\n dic[-1]=(0,0)\n for i in range(len(code_tokens)):\n dic[i]=(dic[i-1][1],dic[i-1][1]+len(code_tokens[i]))\n dfg_to_code=[dic[x[1]] for x in dfg] \n \n \n code_tokens=[y for x in code_tokens for y in x][:args.max_source_length-2]\n source_tokens =[tokenizer.cls_token]+code_tokens+[tokenizer.sep_token]\n source_ids = tokenizer.convert_tokens_to_ids(source_tokens)\n padding_length = args.max_source_length - len(source_ids)\n source_ids+=[tokenizer.pad_token_id]*padding_length\n \n nl_tokens=tokenizer.tokenize(nl)[:args.max_target_length-2]\n target_tokens =[tokenizer.cls_token]+nl_tokens+[tokenizer.sep_token]\n target_ids = tokenizer.convert_tokens_to_ids(target_tokens)\n padding_length = args.max_target_length - len(target_ids)\n target_ids+=[tokenizer.pad_token_id]*padding_length \n \n \n index=1\n dfg_ids=tokenizer.convert_tokens_to_ids(dfg_tokens)\n dfg_to_code=[(x[0]+index,x[1]+index) for x in dfg_to_code]\n padding_length = args.max_dfg_length - len(dfg_ids)\n dfg_ids+=[tokenizer.pad_token_id]*padding_length\n \n return InputFeatures(source_tokens,source_ids,target_tokens,target_ids,\n dfg_tokens,dfg_ids,dfg_to_code,dfg_to_dfg,nl)\n\n\n\n\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, args, source_file_path,target_file_path):\n self.args=args\n #load dataflow parser\n LANGUAGE = Language('parser/my-languages.so', args.language)\n parser = Parser()\n parser.set_language(LANGUAGE) \n parser = [parser,dfg_function[args.language]]\n \n #get examples\n self.examples = []\n with open(source_file_path) as f1,open(target_file_path) as f2:\n for line1,line2 in zip(f1,f2):\n self.examples.append((line1,line2,tokenizer, args,parser))\n \n #extract data flow and tokenize \n self.examples=[get_example(x) for x in tqdm(self.examples,total=len(self.examples))]\n \n\n if 'train' in source_file_path:\n for idx, example in enumerate(self.examples[:3]):\n logger.info(\"*** Example ***\")\n logger.info(\"idx: {}\".format(idx))\n logger.info(\"input_tokens: {}\".format([x.replace('\\u0120','_') for x in example.input_tokens]))\n logger.info(\"input_ids: {}\".format(' '.join(map(str, example.input_ids)))) \n logger.info(\"target_tokens: {}\".format([x.replace('\\u0120','_') for x in example.target_tokens]))\n logger.info(\"target_ids: {}\".format(' '.join(map(str, example.target_ids)))) \n logger.info(\"dfg_tokens: {}\".format(example.dfg_tokens))\n logger.info(\"dfg_ids: {}\".format(' '.join(map(str, example.dfg_ids))))\n logger.info(\"dfg_to_code: {}\".format(' '.join(map(str, example.dfg_to_code))))\n logger.info(\"dfg_to_dfg: {}\".format(' '.join(map(str, example.dfg_to_dfg))))\n rate=[]\n for example in self.examples:\n rate.append(len(example.dfg_tokens)!=0)\n logger.info(\"DFG Rate: %s\",round(np.mean(rate),4))\n \"\"\"\n dfg_to_code_mask: shape(#nodes,#input), 1 means edge between nodes and codes\n dfg_to_dfg_mask: shape(#nodes,#node), 1 means edge between nodes and nodes\n \"\"\"\n self.dfg_to_code_mask=np.zeros((len(self.examples),args.max_dfg_length,args.max_source_length),dtype=np.bool)\n self.dfg_to_dfg_mask=np.zeros((len(self.examples),args.max_dfg_length,args.max_dfg_length),dtype=np.bool)\n self.tag=[False for x in range(len(self.examples))]\n \n \n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, item):\n if self.tag[item]:\n dfg_to_code_mask=self.dfg_to_code_mask[item]\n dfg_to_dfg_mask=self.dfg_to_dfg_mask[item]\n else:\n dfg_to_code_mask=self.dfg_to_code_mask[item]\n dfg_to_dfg_mask=self.dfg_to_dfg_mask[item] \n self.tag[item]=True\n dfg_to_code=self.examples[item].dfg_to_code\n dfg_to_dfg=self.examples[item].dfg_to_dfg\n for i in range(len(dfg_to_code)):\n begin=min(dfg_to_code[i][0],self.args.max_source_length)\n end=min(dfg_to_code[i][1],self.args.max_source_length)\n dfg_to_code_mask[i,begin:end]=True\n for x in dfg_to_dfg[i]:\n dfg_to_dfg_mask[i,x]=True\n dfg_to_dfg_mask[i,i]=True\n \n return (torch.tensor(self.examples[item].input_ids),\n torch.tensor(self.examples[item].target_ids),\n torch.tensor(self.examples[item].dfg_ids),\n torch.tensor(dfg_to_code_mask),\n torch.tensor(dfg_to_dfg_mask))\n\n\n\n\n\n\ndef set_seed(args):\n \"\"\"set random seed.\"\"\"\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n \ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters \n parser.add_argument(\"--model_type\", default=None, type=str, required=True,\n help=\"Model type: e.g. roberta\")\n parser.add_argument(\"--model_name_or_path\", default=None, type=str, required=True,\n help=\"Path to pre-trained model: e.g. roberta-base\" )\n parser.add_argument(\"--tokenizer_name\", default=\"\", required=True,\n help=\"Pretrained tokenizer name or path if not the same as model_name\") \n parser.add_argument(\"--output_dir\", default=None, type=str, required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n parser.add_argument(\"--load_model_path\", default=None, type=str, \n help=\"Path to trained model: Should contain the .bin files\" ) \n ## Other parameters\n parser.add_argument(\"--train_source_filename\", default=None, type=str, \n help=\"The train filename. Should contain the .jsonl files for this task.\")\n parser.add_argument(\"--train_target_filename\", default=None, type=str, \n help=\"The dev filename. Should contain the .jsonl files for this task.\")\n parser.add_argument(\"--dev_source_filename\", default=None, type=str, \n help=\"The train filename. Should contain the .jsonl files for this task.\")\n parser.add_argument(\"--dev_target_filename\", default=None, type=str, \n help=\"The dev filename. Should contain the .jsonl files for this task.\")\n parser.add_argument(\"--test_source_filename\", default=None, type=str, \n help=\"The train filename. Should contain the .jsonl files for this task.\")\n parser.add_argument(\"--test_target_filename\", default=None, type=str, \n help=\"The dev filename. Should contain the .jsonl files for this task.\")\n \n parser.add_argument(\"--config_name\", default=\"\", type=str,\n help=\"Pretrained config name or path if not the same as model_name\")\n\n parser.add_argument(\"--max_source_length\", default=64, type=int,\n help=\"The maximum total source sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\")\n parser.add_argument(\"--max_target_length\", default=32, type=int,\n help=\"The maximum total target sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\")\n parser.add_argument(\"--max_dfg_length\", default=32, type=int,\n help=\"The maximum total target sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\")\n \n parser.add_argument(\"--do_train\", action='store_true',\n help=\"Whether to run training.\")\n parser.add_argument(\"--do_eval\", action='store_true',\n help=\"Whether to run eval on the dev set.\")\n parser.add_argument(\"--do_test\", action='store_true',\n help=\"Whether to run eval on the dev set.\")\n parser.add_argument(\"--do_lower_case\", action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Avoid using CUDA when available\") \n \n parser.add_argument(\"--train_batch_size\", default=8, type=int,\n help=\"Batch size per GPU/CPU for training.\")\n parser.add_argument(\"--eval_batch_size\", default=8, type=int,\n help=\"Batch size per GPU/CPU for evaluation.\")\n parser.add_argument('--gradient_accumulation_steps', type=int, default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\")\n parser.add_argument(\"--learning_rate\", default=5e-5, type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--beam_size\", default=10, type=int,\n help=\"beam size for beam search\") \n parser.add_argument(\"--weight_decay\", default=0.0, type=float,\n help=\"Weight deay if we apply some.\")\n parser.add_argument(\"--adam_epsilon\", default=1e-8, type=float,\n help=\"Epsilon for Adam optimizer.\")\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float,\n help=\"Max gradient norm.\")\n parser.add_argument(\"--num_train_epochs\", default=3.0, type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--max_steps\", default=-1, type=int,\n help=\"If > 0: set total number of training steps to perform. Override num_train_epochs.\")\n parser.add_argument(\"--eval_steps\", default=-1, type=int,\n help=\"\")\n parser.add_argument(\"--train_steps\", default=-1, type=int,\n help=\"\")\n parser.add_argument(\"--warmup_steps\", default=0, type=int,\n help=\"Linear warmup over warmup_steps.\")\n parser.add_argument(\"--local_rank\", type=int, default=-1,\n help=\"For distributed training: local_rank\") \n parser.add_argument('--seed', type=int, default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--language', type=str, default='') \n # print arguments\n args = parser.parse_args()\n logger.info(args)\n\n # Setup CUDA, GPU & distributed training\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.n_gpu = torch.cuda.device_count()\n else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend='nccl')\n args.n_gpu = 1\n logger.warning(\"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s\",\n args.local_rank, device, args.n_gpu, bool(args.local_rank != -1))\n args.device = device\n # Set seed\n set_seed(args)\n # make dir if output_dir not exist\n if os.path.exists(args.output_dir) is False:\n os.makedirs(args.output_dir)\n \n config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\n config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path)\n tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name,do_lower_case=args.do_lower_case)\n \n #budild model\n encoder = model_class.from_pretrained(args.model_name_or_path,config=config) \n decoder_layer = nn.TransformerDecoderLayer(d_model=config.hidden_size, nhead=config.num_attention_heads)\n decoder = nn.TransformerDecoder(decoder_layer, num_layers=6)\n model=Seq2Seq(encoder=encoder,decoder=decoder,config=config,\n beam_size=args.beam_size,max_length=args.max_target_length,\n sos_id=tokenizer.cls_token_id,eos_id=tokenizer.sep_token_id)\n if args.load_model_path is not None:\n logger.info(\"reload model from {}\".format(args.load_model_path))\n model.load_state_dict(torch.load(args.load_model_path))\n \n model.to(device)\n if args.local_rank != -1:\n # Distributed training\n try:\n from apex.parallel import DistributedDataParallel as DDP\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n model = DDP(model)\n elif args.n_gpu > 1:\n # multi-gpu training\n model = torch.nn.DataParallel(model)\n\n\n\n\n if args.do_train:\n # Prepare training data loader\n train_dataset =TextDataset(tokenizer, args, args.train_source_filename,args.train_target_filename)\n if args.local_rank == -1:\n train_sampler = RandomSampler(train_dataset)\n else:\n train_sampler = DistributedSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size//args.gradient_accumulation_steps)\n\n num_train_optimization_steps = args.train_steps\n\n # Prepare optimizer and schedule (linear warmup and decay)\n no_decay = ['bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n 'weight_decay': args.weight_decay},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,\n num_training_steps=num_train_optimization_steps)\n \n \n #Start training\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_dataset))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num epoch = %d\", num_train_optimization_steps*args.train_batch_size//len(train_dataset))\n \n \n model.train()\n dev_dataset={}\n nb_tr_examples, nb_tr_steps,tr_loss,global_step,best_bleu,best_loss = 0, 0,0,0,0,1e6 \n bar = tqdm(range(num_train_optimization_steps),total=num_train_optimization_steps)\n train_dataloader=cycle(train_dataloader)\n eval_flag = True\n for step in bar:\n batch = next(train_dataloader)\n batch = tuple(t.to(device) for t in batch)\n source_ids,target_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask = batch\n loss,_,_ = model(source_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask,target_ids=target_ids)\n \n if args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n tr_loss += loss.item()\n train_loss=round(tr_loss*args.gradient_accumulation_steps/(nb_tr_steps+1),4)\n bar.set_description(\"loss {}\".format(train_loss))\n nb_tr_examples += source_ids.size(0)\n nb_tr_steps += 1\n loss.backward()\n\n if (nb_tr_steps + 1) % args.gradient_accumulation_steps == 0:\n #Update parameters\n optimizer.step()\n optimizer.zero_grad()\n scheduler.step()\n global_step += 1\n eval_flag = True\n \n if args.do_eval and ((global_step + 1) %args.eval_steps == 0) and eval_flag:\n #Eval model with dev dataset\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0 \n eval_flag=False \n if 'dev_loss' in dev_dataset:\n eval_dataset=dev_dataset['dev_loss']\n else:\n eval_dataset =TextDataset(tokenizer, args, args.dev_source_filename,args.dev_target_filename) \n dev_dataset['dev_loss']=eval_dataset\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n \n logger.info(\"\\n***** Running evaluation *****\")\n logger.info(\" Num examples = %d\", len(eval_dataset))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n\n #Start Evaling model\n model.eval()\n eval_loss,tokens_num = 0,0\n for batch in eval_dataloader:\n batch = tuple(t.to(device) for t in batch)\n source_ids,target_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask = batch \n\n with torch.no_grad():\n _,loss,num = model(source_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask,target_ids=target_ids) \n eval_loss += loss.sum().item()\n tokens_num += num.sum().item()\n #Pring loss of dev dataset \n model.train()\n eval_loss = eval_loss / tokens_num\n result = {'eval_ppl': round(np.exp(eval_loss),5),\n 'global_step': global_step+1,\n 'train_loss': round(train_loss,5)}\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n logger.info(\" \"+\"*\"*20) \n \n #save last checkpoint\n last_output_dir = os.path.join(args.output_dir, 'checkpoint-last')\n if not os.path.exists(last_output_dir):\n os.makedirs(last_output_dir)\n model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n output_model_file = os.path.join(last_output_dir, \"pytorch_model.bin\")\n torch.save(model_to_save.state_dict(), output_model_file) \n if eval_lossbest_bleu:\n logger.info(\" Best bleu:%s\",dev_bleu)\n logger.info(\" \"+\"*\"*20)\n best_bleu=dev_bleu\n # Save best checkpoint for best bleu\n output_dir = os.path.join(args.output_dir, 'checkpoint-best-bleu')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n output_model_file = os.path.join(output_dir, \"pytorch_model.bin\")\n torch.save(model_to_save.state_dict(), output_model_file)\n \n if args.do_test:\n files=[]\n if args.dev_source_filename is not None:\n files.append((args.dev_source_filename,args.dev_target_filename))\n if args.test_target_filename is not None:\n files.append((args.test_source_filename,args.test_target_filename))\n for idx,file in enumerate(files): \n logger.info(\"Test file: {}\".format(file))\n eval_dataset =TextDataset(tokenizer, args, file[0],file[1]) \n\n # Calculate bleu\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)\n\n model.eval() \n p=[]\n for batch in tqdm(eval_dataloader,total=len(eval_dataloader)):\n batch = tuple(t.to(device) for t in batch) \n source_ids,target_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask = batch \n with torch.no_grad():\n preds = model(source_ids,dfg_ids,dfg_to_code_mask,dfg_to_dfg_mask) \n for pred in preds:\n t=pred[0].cpu().numpy()\n t=list(t)\n if 0 in t:\n t=t[:t.index(0)]\n text = tokenizer.decode(t,clean_up_tokenization_spaces=False)\n p.append(text)\n model.train()\n predictions=[]\n with open(os.path.join(args.output_dir,\"test_{}.output\".format(str(idx))),'w') as f, open(os.path.join(args.output_dir,\"test_{}.gold\".format(str(idx))),'w') as f1:\n for i,(ref,gold) in enumerate(zip(p,eval_dataset.examples)):\n predictions.append(ref)\n f.write(ref+'\\n')\n f1.write(gold.target+'\\n') \n\n dev_bleu = round(_bleu(os.path.join(args.output_dir,\"test_{}.gold\".format(str(idx))), \n os.path.join(args.output_dir,\"test_{}.output\".format(str(idx)))),2) \n logger.info(\" %s = %s \"%(\"bleu-4\",str(dev_bleu)))\n logger.info(\" \"+\"*\"*20) \n\n\n\n \n\n \n \nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"Code-Code/code-to-code-trans/code/model3/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":29732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"481571722","text":"import os, shutil\nfrom os.path import splitext\n\n# Type Working Directory here\nos.chdir(r\"C:\\Users\\User\\Pictures\\iPhone pics\\Phone Pics\")\n\n# Load contents of directory\ndirContents = os.listdir('.\\\\')\n\n# Define function to list all extension types.\ndef extensionsPresent(sourceList):\n print('Listing all present file types...')\n if not sourceList:\n print('No files present')\n return None\n else:\n extensionsList = []\n for item in sourceList:\n filename, extension = splitext(item)\n if extension not in extensionsList:\n extensionsList.append(extension)\n print('File types present: {}'.format(extensionsList)) \n return extensionsList \n \n\n# Main function - creates folder for an extension and moves files into it.\ndef pickyList(sourceList, extension):\n oneFolderCreation(extension)\n destinationPath = ('.\\\\{} Files\\\\'.format(extension[1:]))\n movedFileCount = 0\n for item in sourceList:\n \n itemFilename, itemExtension = splitext(item)\n \n if itemExtension == extension:\n shutil.move(item, destinationPath)\n movedFileCount += 1\n print('Moved {} files to {}'.format(movedFileCount, destinationPath))\n movedFileCount = 0\n# Define a function to create a new folder for each extension type.\ndef folderCreation(extensionsList):\n for item in extensionsList:\n foldername = ('{} Files'.format(item[1:]))\n if not os.path.exists(foldername):\n os.makedirs(foldername)\n print('{} folder created'.format(foldername))\n \ndef oneFolderCreation(extension):\n foldername = ('{} Files'.format(extension[1:]))\n if not os.path.exists(foldername):\n os.makedirs(foldername)\n print('{} folder created'.format(foldername))\n \n\n \nextensionsInFolder = extensionsPresent(dirContents) # Make as a variable, else it will run this function each time\n\nfolderCreation(extensionsInFolder)\n\nfor item in extensionsInFolder:\n pickyList(dirContents, item)\n ","sub_path":"RAW_JPG_MOV_separator.py","file_name":"RAW_JPG_MOV_separator.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365318908","text":"#!/usr/bin/env python\n# Copyright 2018 Iguazio\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\"\"\"Cut a release\"\"\"\n\nimport re\nfrom argparse import ArgumentParser\nfrom subprocess import run\nfrom os import environ\nfrom sys import executable\n\nis_valid_version = re.compile(r'\\d+\\.\\d+\\.\\d+$').match\ninit_file = 'nuclio/__init__.py'\n\n\ndef git_branch():\n branch = environ.get('TRAVIS_BRANCH')\n if branch:\n return branch\n\n cmd = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']\n out = run(cmd, capture_output=True)\n if out.returncode != 0:\n return ''\n\n return out.stdout.decode('utf-8').strip()\n\n\ndef change_version(version):\n with open(init_file) as fp:\n data = fp.read()\n\n # __version__ = '0.3.0'\n new_version = '__version__ = {!r}'.format(version)\n data = re.sub(r'__version__\\s*=.*', new_version, data)\n\n with open(init_file, 'w') as out:\n out.write(data)\n\n\ndef next_version():\n cmd = [executable, 'setup.py', '--version']\n version = run(cmd, check=True, capture_output=True).stdout.decode()\n version = [int(v) for v in version.split('.')]\n version[-1] += 1\n return '.'.join(map(str, version))\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description=__doc__)\n parser.add_argument('version', help='version (use + for next)')\n args = parser.parse_args()\n\n if git_branch() != 'master':\n raise SystemExit('error: not on \"master\" branch')\n\n version = next_version() if args.version == '+' else args.version\n if not is_valid_version(version):\n raise SystemExit('error: bad version (should be major.minor.patch)')\n\n print(f'setting version to {version}')\n change_version(version)\n run(['git', 'add', init_file])\n run(['git', 'commit', '-m', 'version {}'.format(version)])\n run(['git', 'tag', 'v{}'.format(version)])\n run(['git', 'push'])\n run(['git', 'push', '--tags'])\n","sub_path":"cut_release.py","file_name":"cut_release.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187458501","text":"# -*- coding: utf-8 -*-\n\n__author__ = \"mawentao119@gmail.com\"\n\n\"\"\"\n\n\"\"\"\n\nimport os\nfrom flask import current_app, session, request\nfrom flask_restful import Resource, reqparse\n\nfrom utils.parsing import update_resource\nfrom utils.file import exists_path, rename_file, make_nod, remove_file, mk_dirs, remove_dir, write_file, read_file, copy_file, get_splitext\nfrom utils.mylogger import getlogger\nfrom utils.model_design import gen_casefile\n\n\nclass TestDesign(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('method', type=str)\n self.parser.add_argument('name', type=str)\n self.parser.add_argument('project_name', type=str)\n self.parser.add_argument('suite_name', type=str)\n self.parser.add_argument('category', type=str)\n self.parser.add_argument('key', type=str)\n self.parser.add_argument('data', type=str)\n\n self.app = current_app._get_current_object()\n self.log = getlogger(\"TestDesign\")\n\n def get(self):\n # TODO\n result = {\"status\": \"success\", \"msg\": \"读取文件成功.\"}\n return result, 201\n\n def post(self):\n args = self.parser.parse_args()\n if args[\"key\"]:\n args[\"key\"] = args[\"key\"].replace(\"--\", \"/\")\n self.log.debug(\"Post args:{}\".format(args))\n method = args[\"method\"].lower()\n if method == \"create\":\n result = self.__create(args)\n elif method == \"save\":\n result = self.__save(args)\n elif method == \"casetemplate\":\n result = self.__gen_casefile(args)\n elif method == \"handcase\":\n result = self.__gen_casefile(args)\n elif method == \"autocase\":\n result = self.__gen_casefile(args)\n else:\n print(request.files[\"files\"])\n\n return result, 201\n\n def __create(self, args):\n\n self.log.info(\n \"***create***name:{} **cat:{}\".format(args['name'], args['category']))\n if args['name'].endswith(args['category']):\n args['name'] = args['name'].split('.')[0]\n if args['category'] == '.oth':\n user_path = args[\"key\"] + '/' + args['name']\n else:\n user_path = args[\"key\"] + '/' + args['name'] + args['category']\n\n result = {\"status\": \"success\", \"msg\": \"创建测试模型成功\" +\n \":\"+os.path.basename(user_path)+\":\"+user_path}\n if not exists_path(user_path):\n make_nod(user_path)\n mod = '''\n{ \"class\": \"GraphLinksModel\",\n \"nodeKeyProperty\": \"id\",\n \"linkKeyProperty\": \"key\",\n \"nodeDataArray\": [ \n {\"id\":-1, \"loc\":\"-256 -210\", \"category\":\"Start\", \"text\":\"开始节点\", \"description\":\"这里也可以定义变量\", \"outputvariable\":\"产品列表\", \"disabled\":false, \"properties\":\"\"},\n {\"id\":0, \"loc\":\"-113 -126\", \"text\":\"Shopping页\", \"description\":\"\", \"outputvariable\":\"\", \"disabled\":false, \"properties\":\"产品列表=产品列表\"},\n {\"id\":2, \"loc\":\"82 -127\", \"text\":\"购买\", \"description\":\"\", \"outputvariable\":\"\", \"disabled\":false, \"properties\":\"购物列表=手表\"},\n {\"text\":\"页面关闭\", \"id\":-5, \"loc\":\"71.0 -74.0\"}\n ],\n \"linkDataArray\": [ \n {\"key\":-1, \"from\":-1, \"to\":0, \"text\":\"打开网站\", \"points\":[-187,-166,-161,-159,-140,-146,-124,-126], \"description\":\"\", \"parameters\":\"\", \"mainpath\":true},\n {\"key\":0, \"from\":0, \"to\":2, \"progress\":\"true\", \"text\":\"买手表\", \"points\":[-70,-122,-30,-131,13,-131,60,-118], \"description\":\"\", \"parameters\":\"手表\", \"weight\":\"2.0\", \"mainpath\":true, \"action\":\"buy\"},\n {\"key\":1, \"from\":0, \"to\":-5, \"points\":[-70,-111,-27,-111,13,-98,49,-74], \"text\":\"关闭\", \"description\":\"\", \"action\":\"close\", \"parameters\":\"window\", \"mainpath\":false}\n ],\n \"modelData\": {\"version\":1, \"nodes\":4, \"links\":3, \"actions\":3, \"variables\":5, \"variable\":[], \"init_actions\":\"模块的初始化条件\"}\n}\n '''\n with open(user_path, 'w') as f:\n f.write(mod)\n else:\n result[\"status\"] = \"fail\"\n result[\"msg\"] = \"失败: 文件已存在 !\"\n\n self.app.config['DB'].insert_loginfo(\n session['username'], 'model', 'create', user_path, result['status'])\n\n return result\n\n def __save(self, args):\n result = {\"status\": \"success\", \"msg\": \"成功:保存成功.\"}\n user_path = args[\"key\"]\n\n self.log.info(\n \"***save path:{} \\n***json:{}\".format(user_path, args[\"data\"]))\n\n if not write_file(user_path, args[\"data\"]):\n result[\"status\"] = \"fail\"\n result[\"msg\"] = \"失败:保存失败\"\n\n if user_path.endswith('.robot'):\n self.app.config['DB'].refresh_caseinfo(user_path, 'force')\n self.app.config['DB'].insert_loginfo(\n session['username'], 'suite', 'edit', user_path, result['status'])\n\n # delete keywords or update highlight\n if user_path.endswith('.resource'):\n update_resource(user_path)\n\n return result\n\n def __gen_casefile(self, args):\n\n modle_file = args[\"key\"]\n\n if args[\"method\"] == \"casetemplate\":\n output_file = os.path.splitext(modle_file)[0] + '.tplt'\n else:\n output_file = os.path.splitext(modle_file)[0] + '.robot'\n\n self.log.info(\"开始生成用例模版,模型:{}, 输出模版:{}\".format(\n modle_file, output_file))\n #result = {\"status\": \"success\", \"msg\": \"成功:保存成功.\"}\n result = gen_casefile(modle_file, args[\"method\"], output_file)\n\n return result\n","sub_path":"auto/www/api/test_design.py","file_name":"test_design.py","file_ext":"py","file_size_in_byte":5567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"294476242","text":"'''\nSplit the sentence \n“Hi He Lied Because Boron Could Not Oxidize Fluorine. \nNew Nations Might Also Sign Peace Security Clause. Arthur King Can.” \ninto words, and extract the first letter from the 1st, 5th, 6th, 7th, 8th, 9th, 15th, 16th, 19th words \nand the first two letters from the other words. \nCreate an associative array (dictionary object or mapping object) \nthat maps from the extracted string to the position (offset in the sentence) of the corresponding word.\n\n'''\nimport re\n\nindexes = [1, 5, 6, 7, 8, 9, 15, 16, 19]\norigin_text = \"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.\"\n# splitの時に\"\"が入るのは内包表記を使うと一度に書ける\nnew_text = [t for t in re.split(r'[ ,.]', origin_text) if t != \"\"]\ncut_text = {}\n\n# インデックスが欲しい時はenumerate使った方が綺麗(らしい)\nfor index, text in enumerate(new_text):\n if index + 1 in indexes:\n cut_text[index + 1] = text[:1:]\n else:\n cut_text[index + 1] = text[:2:]\n\nprint(cut_text)","sub_path":"Python/Chapter1/04_Atomic_Symbols.py","file_name":"04_Atomic_Symbols.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"395272937","text":"import subprocess\nimport os.path\nimport maxminddb\nfrom band import expose, worker, logger, settings, response\nfrom prodict import Prodict as pdict\nfrom async_lru import alru_cache\nfrom aiohttp.web_exceptions import HTTPServiceUnavailable\nfrom transliterate import translit\n\nstate = pdict(db=None)\n\n\n@worker()\nasync def open_db():\n try:\n if not os.path.isfile(settings.db_file):\n raise FileNotFoundError(\"db file not found\")\n state.db = maxminddb.open_database(settings.db_file)\n logger.info('DB loaded')\n except Exception:\n logger.exception('error while opening database file')\n\n\n@expose()\nasync def cache_info():\n return enrich.cache_info()\n\n\n@expose.enricher(keys=['in.gen.track'], props=dict(ip='td.ip'))\n@alru_cache(maxsize=512)\nasync def enrich(ip, **params):\n try:\n if state.db:\n location = state.db.get(ip)\n if location:\n return handle_location(**location)\n return {}\n raise HTTPServiceUnavailable()\n except Exception:\n logger.exception('mmgeo error.', location=location)\n return response.error()\n\n\ndef handle_location(city=None, country=None, subdivisions=None, **kwargs):\n result = pdict()\n if country:\n result.country_en = country['names']['en']\n result.country_ru = country['names']['ru']\n result.country_iso = country['iso_code']\n if city and 'names' in city:\n result.city_en = city['names']['en']\n result.city_ru = (city['names']['ru']\n if 'ru' in city['names'] else en_to_ru(\n city['names']['en']))\n if subdivisions and len(subdivisions) > 0:\n region = subdivisions[0]\n result.region_en = region['names']['en']\n result.region_ru = (region['names']['ru']\n if 'ru' in region['names'] else en_to_ru(\n region['names']['en']))\n result.region_iso = region['iso_code']\n return result\n\n\ndef en_to_ru(text):\n return translit(text, 'ru')\n","sub_path":"mmgeo/mmgeo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"67136904","text":"class Settings():\n \"\"\"A class to store all settings for alien invasioon.\"\"\"\n\n\n def __init__(self):\n \"\"\"Initialize the game's settings.\"\"\"\n # Screen settings\n self.screen_width = 1376\n self.screen_height = 700\n self.bg_color = (89, 26, 67)\n self.rocket_speed_factor = 1.5","sub_path":"alien_invasion/exercise/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"222419100","text":"\n\n'''定一个整数数组,返回一个数组。该返回数组中第i个数字为,原数组中第i个位置的数字至少往右走多少步才能遇到比它大的数字。如果遇不到或者已经处于最右的位置,则置为-1。\n\n\n输入描述:\n输入为多行,第一行为一个整数N,1≤N≤106\n\n接下来一共有N行,每一行为一个整数M,0≤M≤232-1\n\n\n\n输出描述:\n输出 N 行,每行一个数字表示转换之后的数组\n\n示例1\n输入\n5\n91\n10\n3\n22\n40\n输出\n-1\n2\n1\n1\n-1'''\n#超时80%\nn=int(input())\na=[]\nfor i in range(n):\n a.append(int(input()))\nfor i in range(n):\n cnt=1\n if i==len(a)-1:\n print('-1')\n for j in range(i+1,len(a)):\n if a[j]<=a[i]:\n cnt+=1\n if j==len(a)-1:\n print('-1')\n else:\n print(cnt)\n break\n\n\n\n\n\n\n#单调栈O(n)\nimport sys\n \nfor n in sys.stdin:\n n = int(n)\n nums = [int(input().strip()) for _ in range(n)]\n\n stack = [] #保存位置\n res = [-1] * n #保存有几个比他大\n\n for i in range(n):\n while len(stack) > 0 and nums[i] > nums[stack[-1]]:\n j = stack.pop()\n res[j] = i - j\n stack.append(i)\n print('\\n'.join([str(x) for x in res]))\n\n ","sub_path":"笔试面试题/公司牛客刷题/数组字符串/美团找更大的数.py","file_name":"美团找更大的数.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"490952576","text":"from django import template\nfrom django.shortcuts import get_object_or_404\nfrom jdatetime import timedelta\nfrom jdatetime import datetime as JDATETIMETOOL\nfrom jdatetime import timedelta as jtimedelta\nfrom booking.models import BookingModel\nimport jdatetime\nimport datetime\nfrom jdatetime import date as jdate\n\nregister = template.Library()\n\n\nfrom session.models import SessionModel, SessionCategoryModel\n\n@register.filter(name='session_end')\ndef session_end(value):\n session = get_object_or_404(SessionModel,pk=value)\n duration = JDATETIMETOOL.strptime(session.duration,'%H:%M')\n session_end = duration + timedelta(hours = session.time.hour,\n minutes = session.time.minute)\n if session_end.minute == 0:\n session_end_str = str(session_end.hour)+':'+str(session_end.minute)+'0'\n else:\n session_end_str = str(session_end.hour)+':'+str(session_end.minute)\n\n return session_end_str\n\n\n@register.filter(name='ceil')\ndef ceil(pk):\n session_category = get_object_or_404(SessionCategoryModel,pk=pk)\n\n for existing_session in session_category.sessions.all():\n existing_duration = JDATETIMETOOL.strptime(existing_session.duration,'%H:%M')\n time_var = existing_duration + timedelta(hours = existing_session.time.hour,\n minutes = existing_session.time.minute)\n try:\n if time_var > ceil :\n ceil = time_var\n\n except:\n ceil = existing_duration + timedelta(hours = existing_session.time.hour,\n minutes = existing_session.time.minute)\n\n try:\n if JDATETIMETOOL.strptime(str(existing_session.time),'%H:%M') < floor:\n floor = existing_session.time\n\n\n except:\n floor = JDATETIMETOOL.strptime(str(existing_session.time),'%H:%M')\n try:\n\n return ceil.time()\n except:\n return 2\n\n\n@register.filter(name='floor')\ndef floor(pk):\n session_category = get_object_or_404(SessionCategoryModel,pk=pk)\n\n for existing_session in session_category.sessions.all():\n\n existing_duration = JDATETIMETOOL.strptime(existing_session.duration,'%H:%M')\n time_var = existing_duration + timedelta(hours = existing_session.time.hour,\n minutes = existing_session.time.minute)\n try:\n if time_var > ceil :\n ceil = time_var\n\n except:\n ceil = existing_duration + timedelta(hours = existing_session.time.hour,\n minutes = existing_session.time.minute)\n\n try:\n if JDATETIMETOOL.strptime(str(existing_session.time),'%H:%M') < floor:\n floor = existing_session.time\n\n\n except:\n floor = JDATETIMETOOL.strptime(str(existing_session.time),'%H:%M')\n try:\n\n return floor.time()\n except:\n return 2\n\n\n@register.filter(name='duration')\ndef duration(pk):\n session_category = get_object_or_404(SessionCategoryModel,pk=pk)\n\n for existing_session in session_category.sessions.all():\n duration = existing_session.duration\n break\n try:\n\n return duration\n except:\n return 2\n\n\n\n@register.filter(name='final_price')\ndef final_price(value):\n session = get_object_or_404(SessionModel,pk=value)\n price = session.price\n final_price = (((100-session.discount_percentage)/100) * price ) * ((100 - session.salon.company_discount_percentage)/100)\n return final_price\n\n\n@register.filter(name='pay_back_generator')\ndef pay_back_generator(value):\n today = jdatetime.datetime.now().date()\n now_time = datetime.datetime.now().time()\n\n booking_object = get_object_or_404(BookingModel, pk = value)\n session = booking_object.session\n ceil_date = jdate(today.year,today.month,today.day)+jtimedelta(days=2)\n ceil_time = (datetime.datetime.combine(datetime.date(1,1,1),now_time) + timedelta(hours = 5)).time()\n if booking_object.session.day >= ceil_date: # percent harm 3 for sportclub 2 for company\n if booking_object.is_contract:\n contract_discount = booking_object.contract_discount\n pay_back = (booking_object.final_price * (100-contract_discount-5))/100\n else:\n pay_back = booking_object.final_price * (95/100)\n\n elif booking_object.session.day == today and booking_object.session.time < ceil_time:\n payback = False\n elif booking_object.session.day < today:\n payback = False\n else:\n if not booking_object.is_contract:\n pay_back = (booking_object.final_price * 85)/100\n else:\n contract_discount = booking_object.contract_discount\n pay_back = (booking_object.final_price * (85-contract_discount))/100\n return pay_back\n\n\n\n@register.filter(name='the_past_day')\ndef the_past_day(value):\n day = value + timedelta(days=-1)\n return day\n\n@register.filter(name='only_day')\ndef only_day(value):\n values = value.split('-')\n day = values[2]\n return day\n\n\n@register.filter(name='cutbr')\ndef cutbr(value):\n value = value.replace('-br','')\n return value\n\n\n@register.filter(name='only_month')\ndef only_month(value):\n values = value.split('-')\n month = values[1]\n if month == '1' :\n month = 'فروردین'\n if month == '2' :\n month = 'اردیبهشت'\n if month == '3' :\n month = 'خرداد'\n if month == '4' :\n month = 'تیر'\n if month == '5' :\n month = 'مرداد'\n if month == '6' :\n month = 'شهریور'\n if month == '7' :\n month = 'مهر'\n if month == '8' :\n month = 'آبان'\n if month == '9' :\n month = 'آذر'\n if month == '10' :\n month = 'دی'\n if month == '11' :\n month = 'بهمن'\n if month == '12' :\n month = 'اسفند'\n return month\n\n\n@register.filter(name='only_year')\ndef only_year(value):\n values = value.split('-')\n year = values[0]\n return year\n","sub_path":"session/templatetags/customtags_session.py","file_name":"customtags_session.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"257461346","text":"import requests\nimport time\nfrom lxml import etree\nimport random\nimport os\nimport json\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\",\n }\n\ndef getContent(url):\n try:\n re = requests.get(url,headers = headers)\n re.encoding = re.apparent_encoding\n # print(re.text)\n html = etree.HTML(re.text)\n title = html.xpath(\"//*[@id='__next']/div[1]/div/div/section[1]/h1/text()\")\n content = []\n for each in html.xpath(\"//*[@id='__next']/div[1]/div/div/section[1]/article/*\"):\n con_temp = each.xpath(\"string(.)\")\n if con_temp:\n content.append(str(con_temp))\n con_temp = each.xpath(\".//@data-original-src\")\n\n if con_temp:\n for ImgIndex in range(len(con_temp)):\n if ImgIndex>0 and con_temp[ImgIndex] is not con_temp[ImgIndex-1]:\n content.append(\"![]({})\".format(con_temp[ImgIndex]))\n elif ImgIndex==0:\n content.append(\"![]({})\".format(con_temp[ImgIndex]))\n # print(ImgIndex,con_temp[ImgIndex])\n return title,content\n except:\n return \"\",\"\"\ndef save(title,content):\n with open(\"{}.md\".format(title[0]),'w',encoding='utf-8') as f:\n f.write(str(title[0])+'\\n\\n')\n for each in content:\n f.write(each+'\\n')\n\n\nif __name__ == '__main__':\n url = \"https://www.jianshu.com/p/280c6a6f2594\"\n url = \"https://www.jianshu.com/p/d75211cec9df\"\n title,content = getContent(url)\n if title is not \"\":\n save(title,content)\n pass\n else:\n print(\"访问出错,请确认下url试试\")","sub_path":"BlogSpider/Jianshu.py","file_name":"Jianshu.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"486776290","text":"import unittest\nimport HTMLTestRunner\nimport time\ntestdir = './testcase'\ntestreport = './report'\ndiscover = unittest.defaultTestLoader.discover(testdir,pattern='test*.py')\nnow = time.strftime(\"%Y-%m-%d %H_%M_%S\")\nfilename = testreport + '/' + now + 'result.html'\nfp = open(filename, 'wb')\nrunner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'测试报告', description=u'用例执行情况')\nrunner.run(discover)\n\n\n\n\n\n\n\n","sub_path":"pycharmProjects/selenium/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"333579955","text":"# -*- coding: utf8 -*-\r\n\r\nimport requests\r\nimport pdb\r\nimport time\r\nimport re\r\nimport pickle\r\nimport os\r\nimport html\r\nimport csv\r\n\r\n# Extraction des pages de chaque action\r\nfor k in ['l.v.m.h.','accor','air-liquide','eads','arcelormittal-reg','atos-origin','axa','bnp-paribas','bouygues','cap-gemini','carrefour','credit-agricole','danone','dassault-system','gdf-suez','essilor-internat','hermes-international','kering','l-oreal','legrand','michelin','france-telecom','pernod-ricard','peugeot','publicis-groupe','renault','safran','saint-gobain','sanofi-aventis','schneider-electr','societe-generale','sodexho-alliance','stmicroelectroni','thales','total','veolia-environ','vinci','vivendi','uniball','worldline-sa']:\r\n url='https://fr.investing.com/equities/'+k+'-ratios'\r\n request_headers={'User-Agent': \"(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6\" }\r\n\r\n i=0\r\n while i<5:\r\n j=0\r\n while j<5:\r\n try:\r\n req=requests.get(url,headers=request_headers,timeout=10)\r\n j=1000\r\n except:\r\n time.sleep(1)\r\n j=j+1\r\n\r\n if j==1000:\r\n if req.status_code==200:\r\n content=req.text\r\n with open('pages_ratios/'+k+'.txt','w',encoding='utf8') as output:\r\n output.write(content)\r\n\r\n i=1000\r\n else:\r\n i=i+1\r\n time.sleep(1)\r\n\r\n if i==1000:\r\n print(\"code source de la page\",k,\"est collecté\")\r\n else:\r\n if j==1000:\r\n print(\"probléme au niveau de la collecte de la page \",k)\r\n else:\r\n print(\"problème au niveau du timeout\",k)\r\n\r\npdb.set_trace()\r\n\r\n","sub_path":"sbf_120/01 CAC 40/01 collect - ratios.py","file_name":"01 collect - ratios.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"285332173","text":"# # # Inhabilita las alertas\nimport warnings\nwarnings.filterwarnings('ignore')\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\ntf.compat.v1.disable_v2_behavior()\n\n# Importa AnimalAI\nfrom animalai.envs.gym.environment import AnimalAIGym\nfrom animalai.envs.arena_config import ArenaConfig\nfrom baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\n\n# Importa Baselines\nfrom baselines.bench import Monitor\nfrom baselines import logger\nfrom baselines.acktr import acktr\n\n# Otras librerias\nimport sys\nimport os\n\ndef make_aai_env(env_directory, num_env, arenas_configurations, start_index=0):\n def make_env(rank, arena_configuration):\n def _thunk():\n env = AnimalAIGym(\n environment_filename=env_directory,\n worker_id=rank,\n flatten_branched=True,\n arenas_configurations=arena_configuration,\n uint8_visual=True,\n )\n env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))\n return env\n\n return _thunk\n return SubprocVecEnv(\n [make_env(i + 30 + start_index, arenas_configurations) for i in range(num_env)]\n )\n\n\ndef main(total_timesteps,alpha,gamma):\n arenas_configurations = ArenaConfig(\"BasicExplorationArenas.yml\")\n \n # Directorio de registro\n logger.configure(dir=\"./logs/acktr\", format_strs=['stdout', 'log', 'csv', 'tensorboard'])\n\n env = make_aai_env(\"AnimalAI/AnimalAI\", 1, arenas_configurations)\n act = acktr.learn(env=env, network=\"cnn\", total_timesteps=total_timesteps, lr=alpha, gamma=gamma)\n\n # Guardar el modelo entrenado\n print(\"Guardando modelo en acktr_model.pkl\")\n act.save(\"./models/acktr_model.pkl\")\n\nif __name__ == \"__main__\":\n # total_timesteps,alpha,gamma\n argv = [str(arg) for arg in sys.argv[1:]]\n main(int(argv[0]),float(argv[1]),float(argv[2]))\n # python -i .\\acktr_learn.py 40000000 0.25 0.9","sub_path":"acktr_learn.py","file_name":"acktr_learn.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"189488866","text":"from FormulaLTLAtomica import FormulaLTLAtomica\r\nfrom FormulaLTLNext import FormulaLTLNext\r\nfrom FormulaLTLNegacion import FormulaLTLNegacion\r\nfrom FormulaLTLConjuncion import FormulaLTLConjuncion\r\nfrom FormulaLTLUntil import FormulaLTLUntil\r\n\r\nclass ParserFormulaLTL(object):\r\n\tdef __init__(self):\r\n\t\tself.__THEN = \"->\"\r\n\t\tself.__SSI = \"<->\"\r\n\t\tself.__AND = \"&&\"\r\n\t\tself.__OR = \"||\"\r\n\t\tself.__UNTIL = \"U\"\r\n\t\tself.__NOT = \"-\"\r\n\t\tself.__NEXT = \"()\"\r\n\t\tself.__ALWAYS = \"[]\"\r\n\t\tself.__EVENTUALLY = \"<>\"\r\n\t\r\n\tdef parsearFormula(self, formula):\r\n\t\ti_1 = formula.find(self.__THEN)\r\n\t\ti_2 = formula.find(self.__SSI)\r\n\t\tif ((i_2 != -1) and ((i_2 < i_1) or (i_1 == -1))):\r\n\t\t\tsubIzq = self.parsearFormula2(formula[:i_2].rstrip())\r\n\t\t\tsubDer = self.parsearFormula(formula[(i_2+len(self.__SSI)):].lstrip())\r\n\t\t\treturn FormulaLTLConjuncion(FormulaLTLNegacion(FormulaLTLConjuncion(subIzq, FormulaLTLNegacion(subDer))), FormulaLTLNegacion(FormulaLTLConjuncion(subDer, FormulaLTLNegacion(subIzq))))\r\n\t\telif (i_1 != -1):\r\n\t\t\tsubIzq = self.parsearFormula2(formula[:i_1].rstrip())\r\n\t\t\tsubDer = self.parsearFormula(formula[(i_1+len(self.__THEN)):].lstrip())\r\n\t\t\treturn FormulaLTLNegacion(FormulaLTLConjuncion(subIzq, FormulaLTLNegacion(subDer)))\r\n\t\telse:\r\n\t\t\treturn self.parsearFormula2(formula)\r\n\t\r\n\tdef parsearFormula2(self, formula):\r\n\t\ti_1 = formula.find(self.__AND)\r\n\t\ti_2 = formula.find(self.__OR)\r\n\t\tif ((i_2 != -1) and ((i_2 < i_1) or (i_1 == -1))):\r\n\t\t\tsubIzq = self.parsearFormula3(formula[:i_2].rstrip())\r\n\t\t\tsubDer = self.parsearFormula2(formula[(i_2+len(self.__OR)):].lstrip())\r\n\t\t\treturn FormulaLTLNegacion(FormulaLTLConjuncion(FormulaLTLNegacion(subIzq), FormulaLTLNegacion(subDer)))\r\n\t\telif (i_1 != -1):\r\n\t\t\tsubIzq = self.parsearFormula3(formula[:i_1].rstrip())\r\n\t\t\tsubDer = self.parsearFormula2(formula[(i_1+len(self.__AND)):].lstrip())\r\n\t\t\treturn FormulaLTLConjuncion(subIzq, subDer)\r\n\t\telse:\r\n\t\t\treturn self.parsearFormula3(formula)\r\n\t\t\r\n\tdef parsearFormula3(self, formula):\r\n\t\ti = formula.find(self.__UNTIL)\r\n\t\tif (i != -1):\r\n\t\t\tsubIzq = self.parsearFormula4(formula[:i].rstrip())\r\n\t\t\tsubDer = self.parsearFormula3(formula[(i+len(self.__UNTIL)):].lstrip())\r\n\t\t\treturn FormulaLTLUntil(subIzq, subDer)\r\n\t\telse:\r\n\t\t\treturn self.parsearFormula4(formula)\r\n\t\r\n\tdef parsearFormula4(self, formula):\r\n\t\ti_1 = formula.find(self.__NOT)\r\n\t\ti_2 = formula.find(self.__NEXT)\r\n\t\ti_3 = formula.find(self.__ALWAYS)\r\n\t\ti_4 = formula.find(self.__EVENTUALLY)\r\n\t\tif (i_1 == 0):\r\n\t\t\tsubForm = self.parsearFormula4(formula[len(self.__NOT):].lstrip())\r\n\t\t\treturn FormulaLTLNegacion(subForm)\r\n\t\telif (i_2 == 0):\r\n\t\t\tsubForm = self.parsearFormula4(formula[len(self.__NEXT):].lstrip())\r\n\t\t\treturn FormulaLTLNext(subForm)\r\n\t\telif (i_3 == 0):\r\n\t\t\tsubForm = self.parsearFormula4(formula[len(self.__ALWAYS):].lstrip())\r\n\t\t\treturn FormulaLTLNegacion(FormulaLTLUntil(FormulaLTLAtomica(\"TRUE\"), FormulaLTLNegacion(subForm)))\r\n\t\telif (i_4 == 0):\r\n\t\t\tsubForm = self.parsearFormula4(formula[len(self.__EVENTUALLY):].lstrip())\r\n\t\t\treturn FormulaLTLUntil(FormulaLTLAtomica(\"TRUE\"), subForm)\r\n\t\telse:\r\n\t\t\treturn self.parsearFormula5(formula)\r\n\r\n\tdef parsearFormula5(self, formula):\r\n\t\treturn FormulaLTLAtomica(formula.strip())\r\n\t","sub_path":"parser/ply-3.4/example/calc/ParserFormulaLTL.py","file_name":"ParserFormulaLTL.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649983181","text":"# -*- coding: utf-8 -*-\n\nfrom kivy.uix.scatter import Scatter\nfrom kivy.animation import Animation\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.properties import NumericProperty\nfrom random import randint, random\n\n\n\ndef get_game_type(BaseClass):\n\n class Puzzle(BaseClass):\n\n blocksize = NumericProperty(100)\n\n def on_texture_size(self, instance, value):\n self.build()\n\n def on_blocksize(self, instance, value):\n self.build()\n\n def build(self):\n self.clear_widgets()\n texture = self.texture\n if not texture:\n return\n bs = self.blocksize\n tw, th = self.texture_size\n for x in range(int(tw / bs)):\n for y in range(int(th / bs)):\n bx = x * bs\n by = y * bs\n subtexture = texture.get_region(bx, by, bs, bs)\n node = Scatter(pos=(bx, by), size=(bs, bs))\n with node.canvas:\n Color(1, 1, 1)\n Rectangle(size=node.size, texture=subtexture)\n self.add_widget(node)\n\n self.shuffle()\n\n def shuffle(self):\n texture = self.texture\n bs = self.blocksize\n tw, th = self.texture_size\n count = int(tw / bs) * int(th / bs)\n indices = list(range(count))\n childindex = 0\n while indices:\n index = indices.pop(randint(0, len(indices) - 1))\n x = bs * (index % int(tw / bs))\n y = bs * int(index / int(tw / bs))\n child = self.children[childindex]\n a = Animation(d=random() / 4.) + Animation(pos=(\n x, y), t='out_quad', d=.4)\n a.start(child)\n childindex += 1\n\n def on_touch_down(self, touch):\n if touch.is_double_tap:\n self.shuffle()\n return True\n super(Puzzle, self).on_touch_down(touch)\n\n return Puzzle\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"386679853","text":"from flask import Flask\nfrom flask import request\nfrom flask import render_template\nimport database\nfrom flask import url_for,redirect,flash\nimport urllib2\n\napp = Flask(__name__)\napp.secret_key = 'secret'\n\napp = Flask(__name__)\n@app.route(\"/\",methods=['GET', 'POST'])\n\n\n@app.route(\"/\", methods = ['GET', 'POST'])\ndef home():\n #stories=['fun', 'story', 'god']\n stories = database.getStories()\n if request.method == 'GET':\n return render_template('home.html', story = stories)\n else:\n story = request.form['story']\n button = request.form['button']\n if button == 'Go':\n #storey = 'Odessy'#request.form['storey']\n url=urllib2.quote('/story/%s'%(story))\n return redirect(url)\n elif button == 'Delete':\n #storey = request.form['story']\n database.deleteStory(story)\n return redirect(url_for('home'))\n elif button == 'New':\n return redirect(url_for('newStory'))\n return redirect(url_for('home'))\n\n\n #stories = database.getStories()\n return render_template('home', story = stories)\n\n\n\n\n\n@app.route(\"/story/\", methods = ['GET', 'POST'])\ndef story(story):\n #story = database.getStory(story)\n # if request.method == 'POST':\n # line = request.form['newLine']\n # database.addLine(story, line)\n # lastline = database.getLastLine(story)\n #return render_template('story', title=story, lastline=lastline)\n#return render_template(\"story.html\",title=story,lastline=lastline.get_lastline(story)) \n if request.method == 'GET':\n return render_template('story.html', title = story , lastline =database.getLastLine(story))\n else:\n line = request.form['newLine']\n database.addLine(story, line)\n url=urllib2.quote('/story/%s'%(story))\n return redirect(url)\n \n\n\n@app.route(\"/newstory\", methods = ['GET', 'POST'])\ndef newStory():\n if request.method == 'GET':\n return render_template('newstory.html')\n else:\n name = request.form[\"title\"]\n #name = \"BH\"\n lines = request.form[\"lines\"]\n #lines = \"lines\"\n database.addStory(name)\n database.addLine(name, lines)\n url=urllib2.quote('/story/%s'%(name))\n return redirect(url)\n\n@app.route(\"/delete\", methods = ['GET', 'POST'])\ndef delete():\n database.clearStories()\n return redirect('/')\n\n\n\nif __name__==\"__main__\":\n app.run(debug = True)\n\n\n\n \n\n \n","sub_path":"Ben_Zuzanna/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"288245339","text":"import codecs\n\nwith codecs.open(\"/Users/liuliu/Desktop/Python/flare_down/fd-export2.csv\", 'r',encoding=\"utf-8\") as f1:\n with codecs.open(\"/Users/liuliu/Desktop/Python/flare_down/exVersion/txtFileOfCsv.txt\",\"w\",encoding=\"utf-8\") as f2:\n for line in f1:\n line=line.rstrip('\\n')\n if (line[-1] != ','):\n line+=','\n line+='\\n'\n f2.write(line)\n\n\n\n'''with open (\"txtFileOfCsv.txt\",'r') as f:\n for line in f:\n for s in line.split(','):\n if()'''","sub_path":"Version6/csv_to_txt.py","file_name":"csv_to_txt.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"618186452","text":"\n'''\nDescription: Prepares data for upload by applying proportions to prevent\n double-counting of sequelae\nNotes: Special adjustments are made to prevent double-counting of cancer sequelae.\n A select number of tumorectomy procedures, those managed by this script,\n are specific to a cancer (are only used to address cancer) AND are\n estimated elsewhere. To prevent double-counting the incidence and prevalence\n of these\n'''\nimport cancer_estimation.c_models.e_nonfatal.nonfatal_dataset as nd\nimport cancer_estimation.py_utils.data_format_tools as dft\nimport cancer_estimation.py_utils.common_utils as utils\nfrom cancer_estimation.c_models import epi_upload\nfrom cancer_estimation._database import cdb_utils as cdb\nfrom sys import argv\nimport pandas as pd\nfrom get_draws.api import get_draws\nfrom ihme_dimensions import dfutils as rs\nfrom getpass import getuser\nimport numpy as np\n\n\n\ndef decomp_prefix_cols(faux_correct): \n ''' This function will take in faux_correct boolean, and return a string that \n specifies whether 'decomp' should be added as a prefix to column names\n '''\n if faux_correct == True: \n decomp_string = 'decomp_'\n else: \n decomp_string = ''\n return(decomp_string) \n\n\ndef procedure_me_id(acause):\n me_table = (cdb.db_api('cancer_db')).get_table('cnf_model_entity')\n me_id = me_table.loc[me_table['is_active'].eq(1) & \n me_table['acause'].eq(acause) &\n me_table['me_tag'].eq('procedure_proportion'),\n 'modelable_entity_id']\n if len(me_id) == 0:\n me_id = None\n else:\n me_id = me_id.item()\n return(me_id)\n\n\ndef sequelae_fractions(acause):\n ''' Defines fractions from lit review to be used when splitting sequela\n '''\n # Set fractions of population recieving treatment according to \n # what is basically their primary disabilty (sequela)\n pros_incont_frac = 0.18 # pct. who primarily develop incontinence\n pros_impot_frac = 0.55 # pct. who primarily develop impotence\n # Define dict\n fractions = {\n 'neo_prostate': {\n # Fractions used to calculate the controlled phase\n 18781: {'fraction': pros_impot_frac}, # with impotence\n 18782: {'fraction': pros_incont_frac}, # with incontinence\n # Fractions used to calculate the metrics of sequela beyond ten years\n 18784 : {'fraction': pros_impot_frac}, \n 18785 : {'fraction': pros_incont_frac}\n }\n }\n # Add me_tags to dict (enables later linking of data to modelable_entity_id)\n me_tbl = cdb.db_api().get_table(\"cnf_model_entity\")\n meids = list(fractions['neo_prostate'].keys())\n for me in meids:\n if me_tbl.loc[me_tbl['modelable_entity_id'].eq(me), 'is_active'].item() == 0:\n del fractions['neo_prostate'][me]\n else:\n tag = me_tbl.loc[me_tbl['modelable_entity_id'].eq(me), 'me_tag'].item()\n fractions['neo_prostate'][me]['me_tag'] = tag\n if acause in fractions.keys():\n return(fractions[acause])\n else:\n return(False)\n\n\ndef load_procedure_proportions(procedure_me_id, location_id):\n ''' Downloads estimates for the proportion of the cancer population that\n recieves a given procedure\n '''\n print(\" loading procedure proportions...\")\\\n # get decomp_step \n d_step = utils.get_gbd_parameter('current_decomp_step')\n gbd_id = utils.get_gbd_parameter('current_gbd_round')\n prop_df = get_draws(gbd_id_type='modelable_entity_id', source='epi',\n measure_id=18, gbd_id=procedure_me_id,\n location_id=location_id, gbd_round_id=gbd_id, \n decomp_step=d_step)\n return(prop_df)\n\n\ndef load_estimates(metric_name, acause, location_id, faux_correct):\n ''' Loads previously-generated estimates per the metric_name\n '''\n decomp_str = decomp_prefix_cols(faux_correct)\n this_step = nd.nonfatalDataset(metric_name, acause)\n uid_cols = this_step.uid_cols\n if metric_name == \"survival\":\n type_cols = nd.get_columns('{}absolute_survival'.format(decomp_str))\n else:\n type_cols = nd.get_columns('{}{}'.format(decomp_str,metric_name))\n #\n input_file = this_step.get_output_file(location_id)\n input_data = pd.read_csv(input_file)\n return(input_data[uid_cols+type_cols])\n\n\ndef add_decade_to_age(x):\n ''' Updates an age_group_id to the id of the age group that is ten years older.\n Does this to reflect that the cohort has aged\n '''\n age_dict = {1: 6, 19: 30, 20: 31, 30: 32, 31: 33, 32: 44, 33: 45, 235: 301}\n if x >= 5 and x < 19:\n return(x + 2)\n elif x in age_dict.keys():\n return(age_dict[x])\n else:\n raise AssertionError(\n \"age group id, {}, is not in acceptable range\".format(x))\n\n\ndef calc_total_prevalence(df, uid_cols):\n ''' Calculates a prevalence \"total\" value to be uploaded for troubleshooting\n '''\n sum_df = df.loc[df['me_tag'].isin(['primary_phase', 'controlled_phase',\n 'metastatic_phase', 'terminal_phase'])]\n sum_df.loc[:, 'me_tag'] = \"computational_total\"\n sum_df = dft.collapse(sum_df, by_cols=uid_cols, stub='prev')\n return(df.append(sum_df))\n\n\ndef apply_procdedure_proportions(df, proportions, acause, metric_name, faux_correct):\n ''' Multiplies estimates by procedure proportions, adding to the dataframe\n a set of estimates for the number of cancer events that do not receive\n the given procedure\n -- Note:\n As of 2018-07-10, incidence data are adjusted after modeling\n and are not processed through this function, although the ability \n to do so remains \n\n '''\n decomp_str = decomp_prefix_cols(faux_correct)\n print(\" adjusting to avoid double-counting procedures for {}...\".format(metric_name))\n # Return if adjustment is unnecessary (if there is no rate id for the cause)\n uid_cols = nd.nonfatalDataset(metric_name, acause).uid_cols\n draw_cols = nd.get_columns(\"{}draw_cols\".format(decomp_str))\n type_cols = nd.get_columns('{}{}'.format(decomp_str,metric_name))\n mrg_cols = [c for c in uid_cols if c != 'me_tag']\n # Subset estimates to the phase wherein procedures occur\n if metric_name == 'prevalence':\n mrg_df = df.loc[df['me_tag'] == \"controlled_phase\", :].copy()\n del mrg_df['me_tag']\n elif metric_name == 'incidence':\n mrg_df = df.copy()\n # For data where sequela are a fraction of the number of procedures, multiply\n # the procedure proportion by those fractions\n if metric_name == 'prevalence' and bool(sequelae_fractions(acause)):\n # Generate dataframe to containing the fractions\n fracs = pd.DataFrame().from_dict(sequelae_fractions(acause), \n orient='index')\n fracs['acause']= acause\n fracs = fracs[~fracs['me_tag'].eq(\"procedure_sequelae\")] \n # Merge dataframe with proportions to expand\n proportions['acause'] = acause\n props = proportions.merge(fracs)\n # Adjust proportions by me\n props[draw_cols] = props[draw_cols\n ].multiply(props['fraction'], axis='index')\n del props['acause']\n else:\n # Determine fraction of population that does not recieve the procedure\n props = proportions.copy()\n props['me_tag'] = \"adjusted_controlled_phase_a\"\n # Apply proportions to estimates\n # Note: may drop some data if proportions are only for estimation years\n mrg_df = mrg_df.merge(props, on=mrg_cols, how='inner')\n adj_df = mrg_df[uid_cols]\n evnt_wo_proc = pd.DataFrame(mrg_df[type_cols].values *\n mrg_df[draw_cols].values).fillna(0)\n evnt_wo_proc.columns = type_cols\n adj_df[type_cols] = evnt_wo_proc\n assert not adj_df.isnull().any().any(), \"Error calculating procedure proportions\"\n # For prevalence, append the adjusted data to the rest of the estimates\n if metric_name == 'prevalence':\n sq_df = dft.collapse(adj_df, mrg_cols, combine_cols=type_cols\n ).sort_values(mrg_cols)\n cntrl_df = df.loc[df['me_tag'].eq(\"controlled_phase\"), :\n ].merge(mrg_df[mrg_cols].drop_duplicates(), \n on=mrg_cols, how='inner'\n ).sort_values(mrg_cols)\n nosq_df = cntrl_df[mrg_cols]\n no_proc = pd.DataFrame(cntrl_df[type_cols].values -\n sq_df[type_cols].values)\n no_proc.columns = type_cols\n nosq_df[type_cols] = no_proc\n nosq_df['me_tag'] = \"adjusted_controlled_phase\"\n adj_df = adj_df.append(nosq_df)\n output_data = df.append(adj_df)\n # Incidence of cancers with the procedure is estimated elsewhere, so there\n # is no need to preserve the unadjusted data\n else:\n output_data = adj_df\n return(output_data[uid_cols+type_cols])\n\n\ndef calc_procedure_tenplus(inc_df, proportions, acause, location_id, faux_correct):\n ''' Multiplies incidence draws by the procedure proportion and the absolute\n survival proportion at 10 years to estimate the number of cases\n surviving for at least 10 years\n '''\n # Load known values\n print(\" calculating the incidence of procedures with surv > ten years...\")\n decomp_str = decomp_prefix_cols(faux_correct)\n uid_cols = nd.nonfatalDataset().uid_cols\n type_cols = nd.get_columns('{}incidence'.format(decomp_str))\n draw_cols = nd.get_columns(\"{}draw_cols\".format(decomp_str))\n abs_surv_draw_cols = nd.get_columns('{}absolute_survival'.format(decomp_str))\n max_estimation_year = utils.get_gbd_parameter('max_year')\n max_survival_months = nd.nonfatalDataset().max_survival_months\n # Estimate incidence of procedure\n mrg_df = inc_df.merge(proportions)\n adj_df = mrg_df[uid_cols]\n num_procedures = (mrg_df[type_cols].values * mrg_df[draw_cols].values)\n adj_df[type_cols] = pd.DataFrame(num_procedures).fillna(0)\n # Estimate number of procedures resulting in survival beyond ten years\n surv_df = load_estimates('survival', acause, location_id, faux_correct)\n surv_df = surv_df.loc[surv_df['survival_month'].eq(max_survival_months), \n uid_cols + abs_surv_draw_cols]\n adj_df = adj_df.merge(surv_df)\n pbt_df = adj_df[uid_cols]\n num_procedures_10ys = adj_df[type_cols].values * \\\n adj_df[abs_surv_draw_cols].values\n pbt_df[draw_cols] = pd.DataFrame(num_procedures_10ys).fillna(0)\n # Update years and age categories\n pbt_df.loc[:, 'age_group_id'] = pbt_df['age_group_id'].apply(\n add_decade_to_age)\n pbt_df.loc[:, 'year_id'] += 10\n # drop data that are now out of scope\n pbt_df = pbt_df.loc[pbt_df['year_id'] <= max_estimation_year, :]\n # For procedures whose sequelae are fractional,\n if sequelae_fractions(acause):\n pbt_df = split_sequelae(pbt_df, acause, location_id)\n else:\n pbt_df.loc[:, 'modelable_entity_id'] = \\\n nd.get_modelable_entity_id(acause, 'procedure_sequelae')\n return(pbt_df)\n\n\ndef split_sequelae(df, acause, location_id):\n ''' Splits estimates into sequela based on proportions from literature\n '''\n print(\" splitting sequelae...\")\n uid_cols = nd.nonfatalDataset().uid_cols +['modelable_entity_id']\n draw_cols = nd.get_columns(\"draw_cols\")\n # Generate dataframe containing the procedure_sequelae fractions\n fracs = pd.DataFrame().from_dict(sequelae_fractions(acause), orient='index'\n ).reset_index().rename(columns={'index':'modelable_entity_id'})\n fracs = fracs[fracs['me_tag'].eq(\"procedure_sequelae\")] \n fracs['acause']= acause\n # Merge dataframe with data\n df['acause'] = acause\n split_df = df.merge(fracs)\n split_df[draw_cols] = split_df[draw_cols].multiply(split_df['fraction'], axis='index')\n assert split_df[draw_cols].notnull().all().all(), \"Nulls in split sequelae\"\n return(split_df)\n\n\ndef save_procedure_inputs(df, acause, location_id):\n '''' Formats and saves procedure data for upload into the epi database\n '''\n uid_cols = nd.nonfatalDataset().uid_cols +['modelable_entity_id']\n draw_cols = nd.get_columns(\"draw_cols\")\n epi_estimate_cols = ['mean', 'lower', 'upper']\n data = df.loc[:, uid_cols + draw_cols].copy()\n # apply formatting\n data.loc[df['age_group_id'].isin([33, 44, 301]), 'age_group_id'] = 235\n data = dft.collapse(data, by_cols=uid_cols, stub='draw')\n epi_df = epi_upload.format_draws_data(data)\n epi_df = epi_upload.convert_to_rate(epi_df, epi_estimate_cols, location_id)\n \n # Add metadata\n epi_df['measure'] = 'incidence'\n epi_df['unit_type'] = \"Person*year\"\n epi_df['extractor'] = getuser()\n epi_df['location_id'] = location_id\n # Finalize and export\n for me_id in epi_df['modelable_entity_id'].unique():\n print(\"me_id \" + str(me_id) + \" sequela split\")\n me_table = nd.load_me_table()\n bundle_id = int(me_table.loc[me_table['modelable_entity_id'].eq(me_id),\n 'bundle_id'].item())\n this_output = epi_df.loc[epi_df['modelable_entity_id'].eq(me_id), :]\n this_output = epi_upload.EpiUploadDataframe(this_output).data\n # Save output without testing (epi formatter has already tested data per\n # epi specs)\n # add location_id to enable save_outputs\n this_output['location_id'] = location_id\n nd.save_outputs(\"dismod_inputs\", this_output, acause,\n bundle_id, skip_testing=True)\n\n\ndef save_model_results(df, metric_name, acause, faux_correct):\n ''' Saves a separate output file for each me_tag in the dataframe\n '''\n decomp_str = decomp_prefix_cols(faux_correct)\n uid_cols = nd.nonfatalDataset(metric_name, acause).uid_cols\n data_cols = nd.get_columns('{}{}'.format(decomp_str,metric_name))\n draw_cols = nd.get_columns(\"{}draw_cols\".format(decomp_str))\n d_step = utils.get_gbd_parameter('current_decomp_step')\n if metric_name == \"incidence\":\n measure_id = utils.get_gbd_parameter('incidence_measure_id')\n df.loc[:, 'me_tag'] = 'primary_phase'\n elif metric_name == \"prevalence\":\n measure_id = utils.get_gbd_parameter('prevalence_measure_id')\n for this_tag in df['me_tag'].unique():\n me_id = nd.get_modelable_entity_id(acause, this_tag)\n if me_id is None:\n continue\n print(\"me_id \" + str(me_id) + \" \" + this_tag)\n output_data = df.loc[df['me_tag'].eq(this_tag), uid_cols + data_cols]\n output_data.columns = uid_cols + draw_cols\n output_data['modelable_entity_id'] = me_id \n output_data['upper'] = np.NaN\n output_data['lower'] = np.NaN\n output_data['uncertainty_type_value'] = np.NaN\n output_data['is_outlier'] = 0 \n output_data['step4_location_year'] = '{} updated estimates'.format(d_step)\n nd.save_outputs(\"final_results\", output_data,\n acause, me_id, measure_id,)\n\n\ndef generate_estimates(acause, location_id, faux_correct):\n ''' Applies procedure adjustments where necessary, then saves separate outputs\n by measure and cancer phase\n '''\n print(\"Begin final adjustments...\")\n faux_correct = False\n inc_df = load_estimates('incidence', acause, location_id, faux_correct)\n prev_input = load_estimates('prevalence', acause, location_id, faux_correct)\n prev_df = calc_total_prevalence(prev_input, \n uid_cols=nd.nonfatalDataset('prevalence', acause).uid_cols)\n pr_id = procedure_me_id(acause)\n if pr_id is not None:\n prop_df = load_procedure_proportions(pr_id, location_id)\n prev_df = apply_procdedure_proportions(\n prev_df, prop_df, acause, 'prevalence', faux_correct)\n proc_data = calc_procedure_tenplus(\n inc_df, prop_df, acause, location_id, faux_correct)\n save_procedure_inputs(proc_data, acause, location_id)\n \n save_model_results(inc_df, 'incidence', acause, faux_correct)\n save_model_results(prev_df, 'prevalence', acause, faux_correct)\n else:\n save_model_results(inc_df, 'incidence', acause, faux_correct)\n save_model_results(prev_df, 'prevalence', acause, faux_correct)\n success_file = nd.nonfatalDataset(\n 'final_results', acause).get_output_file(\"finalized_\"+str(location_id))\n open(success_file, 'a').close()\n print(str(success_file) + \" saved.\")\n return(True)\n\n\nif __name__ == \"__main__\":\n acause = argv[1]\n location_id = int(argv[2])\n faux_correct = (argv[3])\n faux_correct = False\n generate_estimates(acause, location_id, faux_correct)\n","sub_path":"gbd_2019/nonfatal_code/cancer/c_models/e_nonfatal/adjust_and_finalize.py","file_name":"adjust_and_finalize.py","file_ext":"py","file_size_in_byte":16927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20680362","text":"import h5py\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport icesat2_package.utils as is2_utils\n\n\nclass GroundTrack:\n '''\n Handle profile data of ALT12\n '''\n def __init__(self, profile_hdf_obj):\n self.file = profile_hdf_obj\n self._lats = None\n self._lons = None\n self._sea_surface_height = None\n\n @property\n def latitude(self):\n if self._lats is None:\n self._lats = self.file['ssh_segments/latitude']\n return self._lats\n\n @property\n def longitude(self):\n if self._lons is None:\n self._lons = self.file['ssh_segments/longitude']\n return self._lons\n\n @property\n def mean_surface_height(self):\n if self._sea_surface_height is None:\n self._sea_surface_height = self.file['ssh_segments/heights/h']\n return self._sea_surface_height\n\n\nclass ATL12:\n \"\"\"\n This class is the tools for ATL09 data.\n\n Func:\n get_layers()\n get_bsc() # back scatter\n\n Attributs:\n info: information of the alt09 dataset.\n \"\"\"\n\n\n def __init__(self, filename):\n self.filename = filename\n try:\n self.filename = filename\n self.file = h5py.File(filename, 'r')\n except :\n print(f'File read error...{self.filename}')\n self.file=None\n\n @property\n def info(self):\n return self.filename\n\n def check(self):\n def decorator(func):\n def wrapper(*args, **kw):\n if not self.exist:\n print(f'Check Error: {self.info}')\n return None\n else:\n return func(*args, **kw)\n\n return wrapper\n return decorator\n\n def ground_track_left(self,idx):\n return GroundTrack(self.file[f'gt{idx}l'])\n\n def ground_track_right(self,idx):\n return GroundTrack(self.file[f'gt{idx}r'])\n\n\ndef TEST(atl12_fn):\n atl12_file = ATL12(atl12_fn)\n ground_track_l = atl12_file.ground_track_left(1)\n ground_track_r = atl12_file.ground_track_right(1)\n height_l = ground_track_l.mean_surface_height[:]\n height_r = ground_track_r.mean_surface_height[:]\n\n is2_utils.Painter.drawCoordination(ground_track_l.longitude[:], ground_track_l.latitude[:])\n is2_utils.Painter.drawCoordination(ground_track_r.longitude[:], ground_track_r.latitude[:])\n\n plt.figure()\n plt.plot(height_l, '-r')\n plt.show()\n\n plt.figure()\n plt.plot(height_r, '--g')\n plt.show()\n\n\nif __name__ == \"__main__\":\n atl12_fn = 'L:/icesat/ATL12_201910/ATL12_20191029040948_04930501_003_01.h5'\n TEST(atl12_fn)","sub_path":"atlas/alt12.py","file_name":"alt12.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"4712222","text":"import sys\r\nimport os\r\nimport random\r\nimport collections\r\n\r\n\r\ndef is_int(x):\r\n try:\r\n int(x)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n\r\ndata_count = 1000\r\nunsorted_data_file = \"p2_data.in\" # the file to generate data in.\r\nfrequent_data_file = \"p2_data.out\" # the file where the output of code exists.\r\nrunning_time_file = \"p2.time\" # the file to write the running time.\r\ndata = []\r\n\r\nprint(\"Generating data...\")\r\nwith open(unsorted_data_file, \"w\") as file:\r\n delimiter = ''\r\n for i in range(data_count):\r\n randint = abs(int(random.normalvariate(100, 50)))\r\n data.append(randint)\r\n line = delimiter + str(randint)\r\n delimiter = '\\n'\r\n file.write(line)\r\n\r\nfrequent_data = []\r\ncounter = collections.Counter(data)\r\nsorted_tuples = counter.most_common()\r\nfor tuple in sorted_tuples:\r\n for i in range(tuple[1]):\r\n frequent_data.append(tuple[0])\r\n\r\nprint(\"Compiling source code...\")\r\nos.system(\"g++ -std=c++11 hw2_p2.cpp -o output\")\r\n# If the compilation raised an exception, try this command instead (comment the previous line and uncomment the next one)\r\n# os.system(\"g++ -o output frequencies.cpp -std=c++11\")\r\nprint(\"Running binary file...\")\r\nos.system(\"./output \" + str(unsorted_data_file) + \" \" +\r\n str(frequent_data_file) + \" \" + str(running_time_file))\r\n\r\nprint(\"Validating output...\")\r\n\r\nwith open(frequent_data_file, \"r\") as file:\r\n try:\r\n i = 0\r\n for line in file:\r\n if line == \"\\n\":\r\n continue\r\n if not is_int(line):\r\n raise ValueError(\"Wrong Submission A\")\r\n if int(line) != frequent_data[i]:\r\n raise ValueError(\"Wrong Submission B\")\r\n i = i + 1\r\n if i != data_count:\r\n raise ValueError(\"Wrong Submission C\")\r\n print(\"Correct Submission\")\r\n except ValueError as err:\r\n print(err.args[0])\r\n","sub_path":"p2/p2_test.py","file_name":"p2_test.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"582653843","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2004-2013 Mag. Christian Tanzer. All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# ****************************************************************************\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.SDG.XML.Document\n#\n# Purpose\n# Model a XML document (i.e., prolog plus root element)\n#\n# Revision Dates\n# 26-Aug-2004 (CT) Creation\n# 17-Sep-2004 (CT) Doctest changed (added `%` to document text)\n# 21-Oct-2004 (CT) Use `\"` instead of `'` in output\n# 5-Sep-2005 (CT) Derive from `XML.Node` instead of `XML.Element`\n# 5-Sep-2005 (CT) `root_element` added and `insert` redefined to delegate\n# to `root_element`\n# 5-Sep-2005 (CT) Doctest `svg` added\n# 6-Sep-2005 (CT) Doctest adapted to change of `_attr_values`\n# 20-Sep-2005 (CT) Doctest with over-long attributes added\n# 29-Nov-2007 (CT) Another doctest with over-long attributes added\n# 29-Aug-2008 (CT) Import for `Elem_Type` added to fix doctest\n# 26-Feb-2012 (MG) `__future__` imports added\n# 18-Nov-2013 (CT) Change default `encoding` to `utf-8`\n# ««revision-date»»···\n#--\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom _TFL import TFL\nfrom _TFL.pyk import pyk\n\nimport _TFL.I18N\nimport _TFL._SDG._XML.Comment\nimport _TFL._SDG._XML.Doctype\nimport _TFL._SDG._XML.Element\nimport _TFL._SDG._XML.Elem_Type\nimport _TFL._SDG._XML.Node\n\nclass Document (TFL.SDG.XML.Node) :\n \"\"\"Model a XML document (i.e., the root element)\n\n >>> nl = pyk.unichr (10)\n\n >>> d = Document ( \"Memo\", \"First line of text\"\n ... , \"& a second line of %text\"\n ... , \"A third line of %text &entity; including\"\n ... , doctype = \"memo\"\n ... , description = \"Just a test\"\n ... )\n >>> lines = list (d.formatted (\"xml_format\"))\n >>> print (nl.join (lines))\n \n \n \n \n First line of text\n & a second line of %text\n A third line of %text &entity; including\n \n >>> d = Document ( \"Memo\", \"First line of text\"\n ... , \"& a second line of %text\"\n ... , \"A third line of %text &entity; including\"\n ... , doctype = TFL.SDG.XML.Doctype\n ... (\"memo\", dtd = \"memo.dtd\")\n ... , description = \"Just a test\"\n ... )\n >>> print (nl.join (d.formatted (\"xml_format\")))\n \n \n \n \n First line of text\n & a second line of %text\n A third line of %text &entity; including\n \n >>> s = Document ( TFL.SDG.XML.Element\n ... ( \"svg\"\n ... , x_attrs = dict\n ... ( viewBox = \"10 60 450 260\"\n ... , xmlns = \"http://www.w3.org/2000/svg\"\n ... , width = \"100%\"\n ... , height = \"100%\"\n ... )\n ... )\n ... , \"...\"\n ... , encoding = \"UTF-8\"\n ... , standalone = \"no\"\n ... )\n >>> print (nl.join (s.formatted (\"xml_format\")))\n \n \n ...\n \n >>> attrs = { \"xmlns:fx\" : \"http://www.asam.net/xml/fbx\"\n ... , \"xmlns:ho\" : \"http://www.asam.net/xml\"\n ... , \"xmlns:flexray\" : \"http://www.asam.net/xml/fbx/flexray\"\n ... , \"xmlns:xsi\"\n ... : \"http://www.w3.org/2001/XMLSchema-instance\"\n ... , \"xsi:schemaLocation\"\n ... : \"http://www.asam.net/xml/fbx/all/fibex4multiplatform.xsd\"\n ... , \"VERSION\" : \"1.0.0a\"\n ... }\n >>> d = Document (TFL.SDG.XML.Element (\"fx:FIBEX\", x_attrs = attrs ))\n >>> print (nl.join (d.formatted (\"xml_format\")))\n \n \n \n\n ### Test for linebreaking in/between attribute values\n >>> Elem_Type = TFL.SDG.XML.Elem_Type\n >>> root_elem = Elem_Type (\"foo\", xmlns = \"http://foo/bar\")\n >>> elem = Elem_Type (\"bar\", baz1 = None, baz2 = None, baz3 = None)\n >>> root = root_elem ()\n >>> child = elem ( baz1 = \"This really is the value of baz1\"\n ... , baz2 = \"This really is the value of baz2\"\n ... , baz3 = \"This really is the value of baz3\"\n ... )\n >>> root.add (child)\n >>> d = Document (root)\n >>> d.write_to_xml_stream ()\n \n \n \n \n \n \"\"\"\n\n front_args = (\"root_element\", )\n init_arg_defaults = dict \\\n ( doctype = None\n , encoding = \"utf-8\"\n , root_element = None\n , standalone = \"yes\"\n , xml_version = 1.0\n )\n\n xml_format = \"\"\"\n \n %(::*doctype:)s\n %(::*description:)s\n %(::*root_element:)s\n \"\"\"\n\n _autoconvert = dict \\\n ( doctype = lambda s, k, v : s._convert (v, TFL.SDG.XML.Doctype)\n , root_element = lambda s, k, v : s._convert (v, TFL.SDG.XML.Element)\n , standalone = lambda s, k, v :\n { \"yes\" : \"yes\"\n , True : \"yes\"\n , False : \"no\"\n , \"no\" : \"no\"\n } [v]\n )\n\n def formatted (self, format_name, * args, ** kw) :\n for r in self.__super.formatted (format_name, * args, ** kw) :\n if pyk.text_type != str and isinstance (r, pyk.text_type) :\n ### Only do this for Python2\n r = r.encode (self.encoding, \"xmlcharrefreplace\")\n yield r\n # end def formatted\n\n def insert (self, child, index = None, delta = 0) :\n self.root_element.insert (child, index, delta)\n # end def insert\n\n# end class Document\n\nif __name__ != \"__main__\" :\n TFL.SDG.XML._Export (\"*\")\n### __END__ TFL.SDG.XML.Document\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/_SDG/_XML/Document.py","file_name":"Document.py","file_ext":"py","file_size_in_byte":7477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119079574","text":"# 엿팔아요\r\n# 핵심 아이디어\r\n# 나머지가 없으면 구한 (몫 - 1) 만큼 짜른 비용을 대준다\r\n# 나머지가 있으면 구한 몫 만큼 짜른 비용을 대준다\r\n# 그리고 1부터 가장 큰 값 + 1 까지(가장 큰 값 자체가 최고의 경우의 수가 될 수도 있기 때문에) 모든 경우의룰 구한다.\r\n\r\nN, C, F = map(int, input().split())\r\nvalue_li = []\r\nfor _ in range(N):\r\n value_li.append(int(input()))\r\n\r\nresult_li = []\r\nstart = 1\r\nwhile start < max(value_li) + 1:\r\n total = 0\r\n for i in value_li:\r\n if i % start == 0:\r\n # 공식을 알아내는 것 자체가 핵심\r\n total += ((i // start) * start * F) - ((i // start - 1) * C)\r\n else:\r\n total += ((i // start) * start * F) - ((i // start) * C)\r\n result_li.append(total)\r\n start += 1\r\n\r\nprint(max(result_li))\r\n\r\n\r\n","sub_path":"algorithm/week3_Q1.py","file_name":"week3_Q1.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45683435","text":"import pandas as pd\nfrom datetime import datetime, timedelta\nimport logging\nimport os\nfrom scapy.utils import rdpcap\nfrom scapy.layers.inet import IP, UDP, TCP\n\nfrom anubisflow import AnubisFG\n\n\nlogging.basicConfig(filename='logs/part_c/generate_test_data.log', \n format='%(asctime)s %(message)s', \n level=logging.DEBUG)\nlogging.info('Starting program.')\n\npcap_dir = 'data/raw/pcap/03-11'\npcap_files = os.listdir(pcap_dir)\npcap_files = [x for x in pcap_files if not '.zip' in x]\npcap_files = sorted(pcap_files, key=lambda x: int(x.split('_')[-1]))\n\nafg = AnubisFG(only_twotuple=True, bidirectional=False)\n\noutfile = f'data/interim/part_c/test_flows.csv'\nf = open(outfile,'w')\nidx = 0\nfor pcap_file in pcap_files:\n logging.info(f'memory_twotup has {len(afg.memory_twotup)} flows.')\n logging.info(f'Output file has {idx} rows.')\n logging.info(f'Reading pcap {pcap_file}')\n capture = rdpcap(f'{pcap_dir}/{pcap_file}')\n\n for packet in capture:\n if IP in packet:\n afg.update(packet)\n key = (packet[IP].src, packet[IP].dst)\n mem = afg.memory_twotup[key]\n n_packets = sum(mem.pkt_protocol_counter.values())\n if n_packets % 100 == 0:\n ftrs = afg.generate_features(key)\n f.write(f'{key};{afg.lst_timestamp};')\n f.write(';'.join([str(x) for x in ftrs]))\n f.write('\\n')\n idx += 1\n if n_packets == 5e4:\n del afg.memory_twotup[key]\nf.close()\n","sub_path":"scripts/part_c/generate_test_data.py","file_name":"generate_test_data.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"65364561","text":"class lesen():\n def __init__(self):\n pass\n def fragen_einlesen(self,string):\n try:\n fobj = open(string, \"r\")\n fragen =fobj.readlines()\n fobj.close()\n self.__Liste_Fragen=[]\n #print(fragen)\n j=0\n for zeile in fragen:\n j=j+1\n zeile = zeile.rstrip()\n liste = zeile.split('#')\n lis=[]\n if liste[0]=='normal':\n lis2=[]\n for i in range(4):\n lis2.append(liste[i+2])\n liste[6] = liste[6].replace('a',\"1\")\n liste[6] = liste[6].replace('b',\"2\")\n liste[6] = liste[6].replace('c',\"3\")\n liste[6] = liste[6].replace('d',\"4\")\n try:\n lis=[liste[0],liste[1],lis2,int(liste[6]),liste[7]]\n except:\n lis=[liste[0],liste[1],lis2,int(liste[6])]\n elif liste[0] == \"sortier\":\n lis2=[]\n lis3=[]\n for i in range(4):\n lis2.append(liste[i+2])\n for i in range(4):\n liste[i+6] = liste[i+6].replace('a',\"1\")\n liste[i+6] = liste[i+6].replace('b',\"2\")\n liste[i+6] = liste[i+6].replace('c',\"3\")\n liste[i+6] = liste[i+6].replace('d',\"4\")\n lis3.append(int(liste[i+6]))\n try:\n lis=[liste[0],liste[1],lis2,lis3,liste[10]]\n except:\n lis=[liste[0],liste[1],lis2,lis3]\n elif liste[0] == \"schaetzen\":\n try:\n lis=[liste[0],liste[1],int(liste[2]),liste[3]]\n except:\n lis=[liste[0],liste[1],int(liste[2])]\n self.__Liste_Fragen.append(lis)\n return self.__Liste_Fragen\n except:\n print(\"Einlesen Fehlgeschlagen bei Zeile \"+str(j))\n return []\n","sub_path":"fragenEinlesen.py","file_name":"fragenEinlesen.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"261682440","text":"import os\r\nimport audio_recorder\r\n\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\r\n\r\nimport io\r\nimport math\r\nimport socket\r\nimport struct\r\nimport threading\r\nimport numpy as np\r\nfrom collections import deque\r\n\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing.image import img_to_array\r\n\r\nfrom PIL import Image\r\nfrom sklearn.externals import joblib\r\nfrom motion_feature import extract_sensor_feature\r\n\r\n\r\nHOST = '166.111.139.125'\r\nMOTION_PORT, IMG_PORT, SEND_PORT, AUDIO_PORT = 8888, 8889, 8890, 8891\r\nres, last_time = 0, 0\r\nrecorder = audio_recorder.Recorder()\r\n\r\nsensor_list = ['ACCELEROMETER', 'LINEAR_ACCELERATION', 'GRAVITY', 'GYROSCOPE', 'PROXIMITY']\r\n\r\n\r\ndef work_sensor(sensor_name, queue, start_time, end_time):\r\n\tarr = [[] for i in range(len(queue[0]) - 1)]\r\n\tfor frame in queue:\r\n\t\tif frame[0] < start_time:\r\n\t\t\tcontinue\r\n\t\tif frame[0] > end_time:\r\n\t\t\tbreak\r\n\t\tfor i in range(len(frame) - 1):\r\n\t\t\tarr[i].append(frame[i+1])\r\n\treturn extract_sensor_feature(arr, sensor_name)\r\n\r\n\r\ndef work(data):\r\n\tif len(data) == 0:\r\n\t\treturn -1\r\n\tif data == 'Trigger':\r\n\t\tprint('\\n' * 3 + 'Triggered!' + '\\n' * 3)\r\n\t\treturn -1\r\n\titem = data.split(' ')\r\n\tc = -1\r\n\tfor i in range(len(sensor_list)):\r\n\t\tif sensor_list[i] == item[0]:\r\n\t\t\tc = i\r\n\t\t\tbreak\r\n\tglobal recorder\r\n\tif c == -1:\r\n\t\tif item[0] == 'START':\r\n\t\t\trecorder = audio_recorder.Recorder()\r\n\t\t\trecorder.start()\r\n\t\t\tprint('start recording: ' + data[6:])\r\n\t\t\treturn -1\r\n\t\tif item[0] == 'END':\r\n\t\t\tprint('end recording: ' + data[4:])\r\n\t\t\trecorder.stop()\r\n\t\t\trecorder.save('../record/' + data[4:].strip() + '.wav')\r\n\t\t\treturn -1\r\n\tval = []\r\n\ttry:\r\n\t\tfor i in range(len(item) - 1):\r\n\t\t\tval.append(float(item[i+1]))\r\n\texcept ValueError:\r\n\t\treturn -1\r\n\tq[c].append(val)\r\n\tt = val[0]\r\n\ts = t - 2000\r\n\twhile q[c][0][0] < s:\r\n\t\tq[c].popleft()\r\n\tglobal last_time\r\n\tif c != 0 or t - 200 < last_time:\r\n\t\treturn -1\r\n\tlast_time = t\r\n\tfeature = []\r\n\tm = (s + t) / 2\r\n\tfor i in range(len(sensor_list)):\r\n\t\tfeature.extend(work_sensor(sensor_list[i], q[i], s, m))\r\n\t\tfeature.extend(work_sensor(sensor_list[i], q[i], m, t))\r\n\tfor f in feature:\r\n\t\tif math.isnan(f) or math.isinf(f):\r\n\t\t\treturn -1\r\n\tnew_res = motion_model.predict([feature])[0]\r\n\tprob = motion_model.predict_proba([feature])[0]\r\n\t# print('feature', feature)\r\n\tprint('motion: %d %.2f' % (new_res, prob[1]))\r\n\tglobal res\r\n\r\n\tif new_res != res:\r\n\t\tres = new_res\r\n\t\tprint(res)\r\n\treturn prob[1]\r\n\r\n\r\ndef deal_img(pic):\r\n\tstream = io.BytesIO(pic)\r\n\timg = Image.open(stream)\r\n\tX = [img_to_array(img)]\r\n\tX = np.array(X)\r\n\tX /= 255\r\n\tX = X.astype(np.float32)\r\n\tres = img_model.predict(X)[0]\r\n\t# res = [0, 0]\r\n\tprint(\"img: %.2f\" % (res[1] * 100))\r\n\treturn res[1]\r\n\r\n\r\nclass SendThread(threading.Thread):\r\n\r\n\tdef run(self):\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\ttry:\r\n\t\t\ts.bind((HOST, SEND_PORT))\r\n\t\texcept socket.error as err:\r\n\t\t\tprint('Bind Failed, Error Code: ' + str(err[0]) + ' ,Message: ' + err[1])\r\n\t\tprint('Send Socket Bind Success!')\r\n\t\ts.listen(5)\r\n\t\tprint('Send Socket is now listening')\r\n\t\tglobal lock, msg\r\n\t\twhile True:\r\n\t\t\tconn, addr = s.accept()\r\n\t\t\tprint('Connect with ' + addr[0] + ':' + str(addr[1]))\r\n\t\t\twhile True:\r\n\t\t\t\tlock.acquire()\r\n\t\t\t\twhile len(msg) > 0:\r\n\t\t\t\t\tconn.send(msg.encode())\r\n\t\t\t\t\tmsg = ''\r\n\t\t\t\tlock.release()\r\n\r\n\r\nclass MotionThread(threading.Thread):\r\n\r\n\tdef run(self):\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n\t\ttry:\r\n\t\t\ts.bind((HOST, MOTION_PORT))\r\n\t\texcept socket.error as err:\r\n\t\t\tprint('Bind Failed, Error Code: ' + str(err[0]) + ' ,Message: ' + err[1])\r\n\t\tprint('Motion Socket Bind Success!')\r\n\t\ts.listen(5)\r\n\t\tprint('Motion Socket is now listening')\r\n\t\tfor i in range(len(sensor_list)):\r\n\t\t\tq.append(deque())\r\n\t\t\tq[i].append([0 for i in range(3 + 1)])\r\n\r\n\t\twhile True:\r\n\t\t\tbuffer = ''\r\n\t\t\tconn, addr = s.accept()\r\n\t\t\tprint('Connect with ' + addr[0] + ':' + str(addr[1]))\r\n\t\t\twhile True:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tdata = conn.recv(512).decode()\r\n\t\t\t\t\tif not data:\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t# print('data:' + data)\r\n\t\t\t\t\tbuffer += data\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\tsp = buffer.find('#')\r\n\t\t\t\t\t\tif sp == -1:\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tmotion_res = work(buffer[:sp])\r\n\t\t\t\t\t\tif motion_res != -1:\r\n\t\t\t\t\t\t\tmsg = format(motion_res, '.4f') + '#'\r\n\t\t\t\t\t\t\tconn.send(msg.encode())\r\n\t\t\t\t\t\tbuffer = buffer[sp + 1:]\r\n\t\t\t\texcept ConnectionResetError:\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\tconn.close()\r\n\t\t\tprint('Motion Client Disconnected')\r\n\t\ts.close()\r\n\r\n'''\r\nclass AudioThread(threading.Thread):\r\n\r\n\tdef __init__(self):\r\n\t\tsuper().__init__()\r\n\r\n\tdef run(self):\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n\t\ttry:\r\n\t\t\ts.bind((HOST, AUDIO_PORT))\r\n\t\texcept socket.error as err:\r\n\t\t\tprint('Bind Failed, Error Code: ' + str(err[0]) + ' ,Message: ' + err[1])\r\n\t\tprint('Audio Socket Bind Success!')\r\n\r\n\t\ts.listen(5)\r\n\t\tprint('Audio Socket is now listening')\r\n\r\n\t\tbuffer = ''\r\n\t\ty, z = [], []\r\n\t\twhile True:\r\n\t\t\tconn, addr = s.accept()\r\n\t\t\tprint('Connect with ' + addr[0] + ':' + str(addr[1]))\r\n\t\t\twhile True:\r\n\t\t\t\tdata = conn.recv(5120)\r\n\t\t\t\tif not data:\r\n\t\t\t\t\tbreak\r\n\t\t\t\t# print('audio:' + str(len(data)))\r\n\t\t\t\tfor i in range(len(data) // 4):\r\n\t\t\t\t\tleft, right = data[i*4+0: i*4+2], data[i*4+2:i*4+4]\r\n\t\t\t\t\ty.append(struct.unpack('h', left)[0])\r\n\t\t\t\t\tz.append(struct.unpack('h', right)[0])\r\n\r\n\t\t\t\tif len(y) >= 6400:\r\n\t\t\t\t\ty, z = np.array(y), np.array(z)\r\n\t\t\t\t\tfeature = extract_voice_features(y, z)\r\n\t\t\t\t\ty, z = [], []\r\n\t\t\t\t\tprint('audio:', audio_model.predict([feature])[0])\r\n\t\t\t\t# buffer += data\r\n\t\t\t# conn.send(('[%s] %s' % (ctime(), data)).encode())\r\n\t\t\t# print('[%s] %s' % (ctime(), data))\r\n\r\n\t\t\tconn.close()\r\n\t\t\tprint('Audio Client Disconnected')\r\n\t\ts.close()\r\n'''\r\n\r\n\r\nclass ImgThread(threading.Thread):\r\n\r\n\tdef run(self):\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\ttry:\r\n\t\t\ts.bind((HOST, IMG_PORT))\r\n\t\texcept socket.error as err:\r\n\t\t\tprint('Bind Failed, Error Code: ' + str(err[0]) + ' ,Message: ' + err[1])\r\n\t\tprint('Image Socket Bind Success!')\r\n\r\n\t\ts.listen(5)\r\n\t\tprint('Image Socket is now listening')\r\n\t\twhile True:\r\n\t\t\tconn, addr = s.accept()\r\n\t\t\tprint('Connect with ' + addr[0] + ':' + str(addr[1]))\r\n\t\t\tbuffer, pic = b'', b''\r\n\t\t\twhile True:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tdata = conn.recv(4096)\r\n\t\t\t\t\tif not data:\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tbuffer += data\r\n\t\t\t\t\twhile len(buffer) >= 4:\r\n\t\t\t\t\t\tpic_len = int.from_bytes(buffer[:4], byteorder='big')\r\n\t\t\t\t\t\tif len(buffer) - 4 >= pic_len:\r\n\t\t\t\t\t\t\tprint(pic_len)\r\n\t\t\t\t\t\t\tpic = buffer[4:pic_len+4]\r\n\t\t\t\t\t\t\tbuffer = buffer[pic_len+4:]\r\n\t\t\t\t\t\t\timg_res = deal_img(pic)\r\n\t\t\t\t\t\t\tif img_res != -1:\r\n\t\t\t\t\t\t\t\tmsg = format(img_res, '.4f') + '#'\r\n\t\t\t\t\t\t\t\tconn.send(msg.encode())\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\texcept ConnectionResetError:\r\n\t\t\t\t\tbreak\r\n\t\t\tconn.close()\r\n\t\t\tprint('Image Client Disconnected')\r\n\t\ts.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tq = []\r\n\tmotion_model = joblib.load('motion_model.m')\r\n\timg_model = load_model('ear_cnn_model.h5')\r\n\r\n\timg = Image.open('./sample.jpg')\r\n\tX = [img_to_array(img)]\r\n\tX = np.array(X)\r\n\tX /= 255\r\n\tX = X.astype(np.float32)\r\n\timg_model.predict(X)[0]\r\n\r\n\tmotion_thread = MotionThread()\r\n\timg_thread = ImgThread()\r\n\t# send_thread = SendThread()\r\n\r\n\tmotion_thread.start()\r\n\timg_thread.start()\r\n\t# send_thread.start()\r\n\r\n\tmotion_thread.join()\r\n\timg_thread.join()\r\n\t# send_thread.join()","sub_path":"Analysis/server_audio_recording.py","file_name":"server_audio_recording.py","file_ext":"py","file_size_in_byte":7255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70169165","text":"from PySide2 import QtCore\nfrom PySide2 import QtWidgets\nfrom shiboken2 import wrapInstance\n\nimport maya.OpenMayaUI as omui\nimport maya.cmds as cmds\n\n\ndef maya_main_window():\n \"\"\"\n Return the Maya main window widget as a Python object\n \"\"\"\n main_window_ptr = omui.MQtUtil.mainWindow()\n return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)\n\n\nclass ExampleDialog(QtWidgets.QDialog):\n \"\"\"\n Dialog used to demonstrates many of the standard dialogs available in Qt\n \"\"\"\n FILE_FILTERS = \"Maya (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)\"\n\n selected_filter = \"All Files (*.*)\"\n\n\n def __init__(self, parent=maya_main_window()):\n super(ExampleDialog, self).__init__(parent)\n\n self.setWindowTitle(\"Standard Qt Dialogs\")\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)\n\n self.prefs_directory = cmds.internalVar(userPrefDir=True)\n\n self.create_widgets()\n self.create_layout()\n self.create_connections()\n\n def create_widgets(self):\n self.get_color_btn = QtWidgets.QPushButton(\"getColor\")\n self.get_existing_dir_btn = QtWidgets.QPushButton(\"getExistingDirectory\")\n self.get_open_file_name_btn = QtWidgets.QPushButton(\"getOpenFileName\")\n self.get_open_file_names_btn = QtWidgets.QPushButton(\"getOpenFileNames\")\n self.get_save_file_name_btn = QtWidgets.QPushButton(\"getSaveFileName\")\n self.get_font_btn = QtWidgets.QPushButton(\"getFont\")\n self.get_double_btn = QtWidgets.QPushButton(\"getDouble\")\n self.get_int_btn = QtWidgets.QPushButton(\"getInt\")\n self.get_text_btn = QtWidgets.QPushButton(\"getText\")\n self.get_multi_line_text_btn = QtWidgets.QPushButton(\"getMultiLineText\")\n self.critical_btn = QtWidgets.QPushButton(\"critical\")\n self.warning_btn = QtWidgets.QPushButton(\"warning\")\n self.information_btn = QtWidgets.QPushButton(\"information\")\n self.question_btn = QtWidgets.QPushButton(\"question\")\n\n def create_layout(self):\n main_layout = QtWidgets.QVBoxLayout(self)\n\n grp_layout = QtWidgets.QHBoxLayout()\n grp_layout.addWidget(self.get_existing_dir_btn)\n grp_layout.addWidget(self.get_open_file_name_btn)\n grp_layout.addWidget(self.get_open_file_names_btn)\n grp_layout.addWidget(self.get_save_file_name_btn)\n grp_layout.addStretch()\n grp = QtWidgets.QGroupBox(\"QFileDialog\")\n grp.setLayout(grp_layout)\n main_layout.addWidget(grp)\n\n grp_layout = QtWidgets.QHBoxLayout()\n grp_layout.addWidget(self.critical_btn)\n grp_layout.addWidget(self.warning_btn)\n grp_layout.addWidget(self.information_btn)\n grp_layout.addWidget(self.question_btn)\n grp_layout.addStretch()\n grp = QtWidgets.QGroupBox(\"QMessageBox\")\n grp.setLayout(grp_layout)\n main_layout.addWidget(grp)\n\n grp_layout = QtWidgets.QHBoxLayout()\n grp_layout.addWidget(self.get_double_btn)\n grp_layout.addWidget(self.get_int_btn)\n grp_layout.addWidget(self.get_text_btn)\n grp_layout.addWidget(self.get_multi_line_text_btn)\n grp_layout.addStretch()\n grp = QtWidgets.QGroupBox(\"QInputDialog\")\n grp.setLayout(grp_layout)\n main_layout.addWidget(grp)\n\n grp_layout = QtWidgets.QHBoxLayout()\n grp_layout.addWidget(self.get_color_btn)\n grp_layout.addStretch()\n grp = QtWidgets.QGroupBox(\"QColorDialog\")\n grp.setLayout(grp_layout)\n main_layout.addWidget(grp)\n\n grp_layout = QtWidgets.QHBoxLayout()\n grp_layout.addWidget(self.get_font_btn)\n grp_layout.addStretch()\n grp = QtWidgets.QGroupBox(\"QFontDialog\")\n grp.setLayout(grp_layout)\n main_layout.addWidget(grp)\n\n main_layout.addStretch()\n\n def create_connections(self):\n self.get_existing_dir_btn.clicked.connect(self.get_existing_directory)\n self.get_open_file_name_btn.clicked.connect(self.get_open_file_name)\n self.get_open_file_names_btn.clicked.connect(self.get_open_file_names)\n self.get_save_file_name_btn.clicked.connect(self.get_save_file_name)\n\n self.critical_btn.clicked.connect(self.critical)\n self.warning_btn.clicked.connect(self.warning_)\n self.information_btn.clicked.connect(self.information)\n self.question_btn.clicked.connect(self.question)\n\n self.get_double_btn.clicked.connect(self.get_double)\n self.get_int_btn.clicked.connect(self.get_int)\n self.get_text_btn.clicked.connect(self.get_text)\n self.get_multi_line_text_btn.clicked.connect(self.get_multi_line_text)\n\n self.get_color_btn.clicked.connect(self.get_color)\n self.get_font_btn.clicked.connect(self.get_font)\n\n def get_existing_directory(self):\n directory = QtWidgets.QFileDialog.getExistingDirectory(self, \"Select Directory\", self.prefs_directory)\n if directory:\n print(\"Selected Directory: {0}\".format(directory))\n\n def get_open_file_name(self):\n file_path, self.selected_filter = QtWidgets.QFileDialog.getOpenFileName(self, \"Select a File\", \"\", self.FILE_FILTERS, self.selected_filter)\n if file_path:\n print(\"File path: {0}\".format(file_path))\n\n def get_open_file_names(self):\n file_paths, self.selected_filter = QtWidgets.QFileDialog.getOpenFileNames(self, \"Select File\", \"\", self.FILE_FILTERS, self.selected_filter)\n for path in file_paths:\n print(\"File path: {0}\".format(path))\n\n def get_save_file_name(self):\n file_path, self.selected_filter = QtWidgets.QFileDialog.getSaveFileName(self, \"Save File As\", \"\", self.FILE_FILTERS, self.selected_filter)\n if file_path:\n print(\"File path: {0}\".format(file_path))\n\n def critical(self):\n QtWidgets.QMessageBox.critical(self, \"Error\", \"There was an error somewhere.\")\n\n def warning_(self):\n QtWidgets.QMessageBox.warning(self, \"Warning\", \"Something odd just happened.\")\n\n def information(self):\n QtWidgets.QMessageBox.information(self, \"Info\", \"Task completed successfully.\")\n\n def question(self):\n button_pressed = QtWidgets.QMessageBox.question(self, \"Question\", \"Would you like to continue?\")\n if button_pressed == QtWidgets.QMessageBox.Yes:\n print(\"Continuing...\")\n else:\n print(\"Cancelled\")\n\n def get_double(self):\n value, ok = QtWidgets.QInputDialog.getDouble(self, \"Enter a Value\", \"Value:\")\n if ok:\n print(value)\n\n def get_int(self):\n value, ok = QtWidgets.QInputDialog.getInt(self, \"Enter a Value\", \"Value:\")\n if ok:\n print(value)\n\n def get_text(self):\n text, ok = QtWidgets.QInputDialog.getText(self, \"Enter Text\", \"Text:\")\n if ok:\n print(text)\n\n def get_multi_line_text(self):\n text, ok = QtWidgets.QInputDialog.getMultiLineText(self, \"Enter Text\", \"Text:\")\n if ok:\n print(text)\n\n def get_color(self):\n color = QtWidgets.QColorDialog.getColor(parent=self)\n if color:\n print(\"Red:{0} Green:{1} Blue:{2}\".format(color.red(), color.green(), color.blue()))\n\n def get_font(self):\n font, ok = QtWidgets.QFontDialog.getFont(parent=self)\n if ok:\n print(\"Family: {0} Point Size: {1}\".format(font.family(), font.pointSize()))\n\n\nif __name__ == \"__main__\":\n\n try:\n example_dialog.close() # pylint: disable=E0601\n example_dialog.deleteLater()\n except:\n pass\n\n example_dialog = ExampleDialog()\n example_dialog.show()\n","sub_path":"Practice_Code/different_dialogs_and_static_methods.py","file_name":"different_dialogs_and_static_methods.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373964292","text":"#!/usr/bin/env python3\n\nimport requests\nimport json\nimport base64\nimport time\nimport os\n\nheaders ={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Referer' : 'http://s.hub.hust.edu.cn/hublogin.action',\n 'Connection': 'keep-alive',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n \n}\nbaseUrl = \"http://hub.hust.edu.cn\"\nusername = 'U201517149'\npassword = '5Believe'\n\n\ndef getRandomKey(ss):\n randomKeyHeader = {}\n timeStamp = time.time()*1000\n timeStamp = str(int(timeStamp))\n print(timeStamp)\n randomKeyUrl = baseUrl + '/randomKey.action?username=' + username + '&time=' + timeStamp\n msg = ss.get(randomKeyUrl, headers=randomKeyHeader)\n keys = json.loads(msg.text)\n return (keys[0], keys[1], timeStamp)\n\ndef getRandomImg(ss):\n key1, key2, timeStamp = getRandomKey()\n imgUrl = baseUrl + '/randomImage.action?k1='+key1+'&k2='+key2+'&uno='+username+'&time='+timeStamp\n randomImgHeader = headers\n imgRes = requests.get(imgUrl, headers=randomImgHeader)\n filename = 'randomImage.jpg'\n f = open(filename, 'wb')\n f.write(imgRes.content)\n f.close()\n \ndef login(ss):\n ln = 'app65.dc.hust.edu.cn'\n loginHeader = {}\n loginHeader['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n loginHeader['content-type'] = 'application/x-www-form-urlencoded'\n loginHeader['Origin'] = 'http://s.hub.hust.edu.cn'\n loginHeader['Referer'] = 'http://s.hub.hust.edu.cn/hublogin.action'\n# key1, key2, timeStamp = getRandomKey(ss)\n# print((key1, key2))\n param = {\n #'usertype' : 'xs',\n 'username' : username,\n 'password' : base64.b64decode(password.encode('ascii')), \n #'url' : 'http://s.hub.edu.cn/',\n #'key1' : key1,\n #'key2' : key2,\n #'F_APP' : 'From kslgin. App:app65.dc.hust.edu.cn|app652|IP:10.10.10.245',\n 'ln' : 'app42.dc.hust.edu.cn'\n }\n # loginRes = ss.post('http://hub.hust.edu.cn/hublogin.action', data=param)\n #print(loginRes.headers)\n print(ss.cookies.get_dict())\n homePage = requests.get('http://s.hub.hust.edu.cn/hub.jsp', cookies=ss.cookies.get_dict())\n print(homePage.text)\n print(homePage.request.headers)\n\n\nif __name__ == '__main__' :\n ss = requests.Session()\n print(ss.cookies.get_dict())\n ss.headers.update(headers)\n ss.cookies.clear_session_cookies()\n ss.cookies.update({'username': 'U201517149', 'BIGipServerpool6_http': '369756682.20480.0000', 'JSESSIONID': '0000eHpuVBvGTElRYanpr22VZBl:167ip25ob'})\n \n\n login(ss)\n\n\n\n","sub_path":"loginhub.py","file_name":"loginhub.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110574710","text":"from mcpi.minecraft import Minecraft\nfrom mcpi import block\nfrom time import sleep\nimport random\nimport math\nimport sys\npi = math.pi\nsin = math.sin\ncos = math.cos\n\ndef init():\n\tif len(sys.argv) <= 1:\n\t\tipString = \"127.0.0.1\"\n\telse:\n\t\tipString = sys.argv[1]\n\tprint(\"IP \",ipString)\n\tmc = Minecraft.create(ipString, 4711)\n\tmc = Minecraft.create(ipString, 4711)\n\tmc.setting(\"world_immutable\",False)\n\t#x, y, z = mc.player.getPos() \n\treturn mc\n\t\t\ndef sphere(mc,x,y,z,r,inc):\n\tinc = 5\n\tfor thetaX in range (0,360,inc):\n\t\txRad = thetaX * (pi / 180) \n\t\tfor thetaY in range(0,360,inc):\n\t\t\tyRad= thetaY * (pi / 180) \n\t\t\tprint(xRad,yRad)\n\t\t\th = (r * sin(yRad) * cos(xRad))+ x \n\t\t\tk = (r * sin(yRad) * sin(xRad))+ y\n\t\t\tl = r * cos(yRad) + z\n\t\t\tmc.setBlock(h,k,l,57)\n\t\t\t#print(x,y,z,h,k,l)\n \ndef main():\n\tmc = init()\n\tx,y,z = mc.player.getPos()\n\t#createSphere(10,mc)\n\tsphere(mc,x,y,z,7,15)\n\tmc.player.setPos(x,y+8,z)\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\nAIR 0\nSTONE 1\nGRASS 2\nDIRT 3\nCOBBLESTONE 4\nWOOD_PLANKS 5\nSAPLING 6\nBEDROCK 7\nWATER_FLOWING 8\nWATER 8\nWATER_STATIONARY 9\nLAVA_FLOWING 10\nLAVA 10\nLAVA_STATIONARY 11\nSAND 12\nGRAVEL 13\nGOLD_ORE 14\nIRON_ORE 15\nCOAL_ORE 16\nWOOD 17\nLEAVES 18\nGLASS 20\nLAPIS_LAZULI_ORE 21\nLAPIS_LAZULI_BLOCK 22\nSANDSTONE 24\nBED 26\nCOBWEB 30\nGRASS_TALL 31\nWOOL 35\nFLOWER_YELLOW 37\nFLOWER_CYAN 38\nMUSHROOM_BROWN 39\nMUSHROOM_RED 40\nGOLD_BLOCK 41\nIRON_BLOCK 42\nSTONE_SLAB_DOUBLE 43\nSTONE_SLAB 44\nBRICK_BLOCK 45\nTNT 46\nBOOKSHELF 47\nMOSS_STONE 48\nOBSIDIAN 49\nTORCH 50\nFIRE 51\nSTAIRS_WOOD 53\nCHEST 54\nDIAMOND_ORE 56\nDIAMOND_BLOCK 57\nCRAFTING_TABLE 58\nFARMLAND 60\nFURNACE_INACTIVE 61\nFURNACE_ACTIVE 62\nDOOR_WOOD 64\nLADDER 65\nSTAIRS_COBBLESTONE 67\nDOOR_IRON 71\nREDSTONE_ORE 73\nSNOW 78\nICE 79\nSNOW_BLOCK 80\nCACTUS 81\nCLAY 82\nSUGAR_CANE 83\nFENCE 85\nGLOWSTONE_BLOCK 89\nBEDROCK_INVISIBLE 95\nSTONE_BRICK 98\nGLASS_PANE 102\nMELON 103\nFENCE_GATE 107\nGLOWING_OBSIDIAN 246\nNETHER_REACTOR_CORE 247\n\"\"\"\n","sub_path":"sphere_surface_cla.py","file_name":"sphere_surface_cla.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187835575","text":"import simplejson as json\nimport elasticsearch\nimport unicodecsv as csv\n\nfrom django.http import StreamingHttpResponse\nfrom django.conf import settings\n\n\ndef search_iterator(body):\n es = elasticsearch.Elasticsearch(settings.ELASTICSEARCH)\n total = None\n read = 0\n while True:\n results = es.search(\n index=settings.ES_INDEX,\n doc_type=settings.ES_DOCTYPE,\n body=body,\n from_=read,\n )\n\n hits = results['hits']\n if total is None:\n # Only read the total on the first hit to avoid infinite loops\n # in case index is growing very fast.\n total = hits['total']\n\n if read >= total:\n break\n\n for hit in hits['hits']:\n read += 1\n yield hit['_source']\n\n\nclass _Echo(object):\n def write(self, line):\n return line\n\n\ndef extract_fields(hit, fields):\n row = []\n for field in fields:\n row.append(hit.get(field, ''))\n return row\n\n\ndef download(request):\n querystr = request.POST['q']\n\n query = json.loads(querystr)\n query.pop('size', None)\n query.pop('from', None)\n fields = query.pop('fields', settings.ES_FIELDS)\n\n writer = csv.writer(_Echo(), encoding='utf-8')\n\n response = StreamingHttpResponse(\n (writer.writerow(extract_fields(hit, fields))\n for hit in search_iterator(query)),\n content_type=\"text/csv\"\n )\n\n response['Content-Disposition'] = 'attachment; filename=\"report.csv\"'\n return response\n","sub_path":"apps/qcsv/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"271810285","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nimport time\nimport math\n\n\ndef calc(x):\n return str(math.log(abs(12 * math.sin(int(x)))))\n\n\ntry:\n\n browser = webdriver.Chrome()\n browser.get(\"https://suninjuly.github.io/explicit_wait2.html\")\n\n WebDriverWait(browser, 12).until(\n EC.text_to_be_present_in_element((By.ID, \"price\"), \"$100\")\n )\n browser.find_element_by_css_selector(\"button#book.btn.btn-primary\").click()\n\n value = browser.find_element_by_css_selector('span#input_value').text\n print(value)\n\n result = calc(value)\n input_filed = browser.find_element_by_css_selector('input#answer')\n input_filed.send_keys(str(result))\n\n submit_button = browser.find_element_by_css_selector('button#solve.btn.btn-primary')\n submit_button.click()\n\n # message = browser.find_element_by_id(\"verify_message\")\n # assert \"successful\" in message.text\n\n\nfinally:\n browser.quit()","sub_path":"Automation_Python/Week_3/Lesson3_7_step8_explicit_wait.py","file_name":"Lesson3_7_step8_explicit_wait.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"229180064","text":"#! /usr/bin/env python3\n\"\"\"\n****************************************************************************\n\n Copyright (C) 2018 Datirium. LLC.\n All rights reserved.\n Contact: Datirium, LLC (datirium@datirium.com)\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 functools import lru_cache\n\n\n@lru_cache(maxsize=128)\ndef biowardrobe_settings(cursor):\n cursor.execute(\"select * from settings\")\n return {row['key']: row['value'] for row in cursor.fetchall()}\n\n\ndef remove_not_set_inputs(job_object):\n \"\"\"Remove all input parameters from job which are not set\"\"\"\n job_object_filtered ={}\n for key, value in job_object.items():\n if complete_input(value):\n job_object_filtered[key] = value\n return job_object_filtered\n\n\ndef complete_input(item):\n monitor = {\"found_none\": False}\n recursive_check(item, monitor)\n return not monitor[\"found_none\"]\n\n\ndef recursive_check(item, monitor):\n if item == 'null' or item == 'None':\n monitor[\"found_none\"] = True\n elif isinstance(item, dict):\n dict((k, v) for k, v in item.items() if recursive_check(v, monitor))\n elif isinstance(item, list):\n list(v for v in item if recursive_check(v, monitor))\n\n\ndef update_status(uid, message, code, conn, cursor, optional_column=\"\", optional_where=\"\"):\n \"\"\"Update libstatus for current uid\"\"\"\n optional_column = optional_column if optional_column.startswith(',') else ',' + optional_column\n message = str(message).replace(\"'\", '\"')\n cursor.execute(f\"\"\"update labdata set libstatustxt='{message}', \n libstatus={code} {optional_column} where uid='{uid}' \n {optional_where}\"\"\")\n conn.commit()\n","sub_path":"biowardrobe_airflow_analysis/biowardrobe/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"458762215","text":"#решение через словарь\nseasons = {\n \"Зима\": (1, 2, 12),\n 'Весна': (3, 4, 5),\n 'Лето': (6, 7, 8),\n 'Осень': (9, 10, 11)\n}\n\nmonth = int(input('Введите месяц в числовом формате: \\n'))\nfor key in seasons:\n if month in seasons[key]:\n print(key)\n else:\n print('Неправильный ввод')\n break\n\n#решение через список\nseasons = [[1, 2, 12], [3, 4, 5], [6, 7, 8], [9, 10, 11]]\n\nmonth = int(input('Введите месяц в числовом формате: \\n'))\n\nif month in seasons[0]:\n print('Зима')\nelif month in seasons[1]:\n print('Весна')\nelif month in seasons[2]:\n print('Лето')\nelif month in seasons[3]:\n print('Осень')\nelse:\n print('Непраильный ввод')","sub_path":"hw2/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465495908","text":"import sys\nimport time\nimport nacl.signing\nimport nacl.encoding\nimport binascii\nimport struct\nimport base64\nimport configparser\nimport database as db\nimport logging\n\nfrom flask import Flask, Response, request, json\nfrom flask_socketio import SocketIO, emit\nfrom flask_cors import CORS\nfrom datetime import datetime, timedelta\nfrom pyfcm import FCMNotification\n\nepoch = datetime.utcfromtimestamp(0)\nconn = db.create_connection(\"pythonsqlite.db\") # connection\ndb.create_db(conn) # create tables\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\npush_service = FCMNotification(api_key=config['DEFAULT']['API_KEY'])\n\napp = Flask(__name__)\nsio = SocketIO(app)\nCORS(app, resources={r\"*\": {\"origins\": [\"*\"]}})\n\n# Disables the default spamm logging that's caused by flask.\nlogging.getLogger(\"werkzeug\").setLevel(level=logging.ERROR)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(level=logging.DEBUG)\n\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\n \"[%(asctime)s][%(filename)s:%(lineno)s - %(funcName)s()]: %(message)s\", \"%Y-%m-%d %H:%M:%S\")\nhandler.setFormatter(formatter)\n\nlogger.addHandler(handler)\n\n\n@sio.on('connect')\ndef connect_handler():\n logger.debug(\"Connected.\")\n\n\n@sio.on('checkname')\ndef checkname_handler(data):\n logger.debug(\"Checking name %s\", data)\n sid = request.sid\n user = db.getUserByName(conn, data.get('doubleName').lower())\n\n if user:\n logger.debug(\"user %s\", user[0])\n emit('nameknown')\n else:\n logger.debug(\"user %s was not found\", data.get('doubleName').lower())\n emit('namenotknown')\n\n\n@sio.on('cancel')\ndef cancel_handler(data):\n print('')\n\n\n@sio.on('register')\ndef registration_handler(data):\n logger.debug(\"Registration %s\", data)\n doublename = data.get('doubleName').lower()\n email = data.get('email')\n sid = request.sid\n publickey = data.get('publicKey')\n user = db.getUserByName(conn, doublename)\n if (user is None):\n update_sql = \"INSERT into users (double_name, sid, email, public_key) VALUES(?,?,?,?);\"\n db.insert_user(conn, update_sql, doublename, sid, email, publickey)\n\n\n@sio.on('login')\ndef login_handler(data):\n logger.debug(\"Login %s\", data)\n data['type'] = 'login'\n\n sid = request.sid\n user = db.getUserByName(conn, data.get('doubleName').lower())\n if user:\n logger.debug(\"User found %s\", user[0])\n update_sql = \"UPDATE users SET sid=? WHERE double_name=?;\"\n db.update_user(conn, update_sql, sid, user[0])\n\n if data.get('firstTime') == False and data.get('mobile') == False:\n user = db.getUserByName(conn, data.get('doubleName').lower())\n push_service.notify_single_device(registration_id=user[4], message_title='Finish login',\n message_body='Tap to finish login', data_message=data, click_action='FLUTTER_NOTIFICATION_CLICK', tag='testLogin', collapse_key='testLogin')\n\n insert_auth_sql = \"INSERT INTO auth (double_name,state_hash,timestamp,scanned,data) VALUES (?,?,?,?,?);\"\n db.insert_auth(conn, insert_auth_sql, data.get('doubleName').lower(\n ), data.get('state'), datetime.now(), 0, json.dumps(data))\n print('')\n\n\n@sio.on('resend')\ndef resend_handler(data):\n logger.debug(\"Resend %s\", data)\n\n db.delete_auth_for_user(conn, data.get('doubleName').lower())\n\n insert_auth_sql = \"INSERT INTO auth (double_name,state_hash,timestamp,scanned,data) VALUES (?,?,?,?,?);\"\n\n db.insert_auth(conn, insert_auth_sql, data.get('doubleName').lower(\n ), data.get('state'), datetime.now(), 0, json.dumps(data))\n\n user = db.getUserByName(conn, data.get('doubleName').lower())\n data['type'] = 'login'\n push_service.notify_single_device(registration_id=user[4], message_title='Finish login',\n message_body='Tap to finish login', data_message=data, click_action='FLUTTER_NOTIFICATION_CLICK', collapse_key='testLogin')\n print('')\n\n\n@app.route('/api/forcerefetch', methods=['GET'])\ndef force_refetch_handler():\n data = request.args\n logger.debug(\"Force refetch %s\", data)\n if (data == None):\n return Response(\"Got no data\", status=400)\n logger.debug(\"Hash %s\", data['hash'])\n loggin_attempt = db.getAuthByStateHash(conn, data['hash'])\n logger.debug(\"Login attempt %s\", loggin_attempt)\n if (loggin_attempt != None):\n data = {\"scanned\": loggin_attempt[3], \"signed\": {'signedHash': loggin_attempt[4], 'data': loggin_attempt[5]}}\n response = app.response_class(\n response=json.dumps(data),\n mimetype='application/json'\n )\n logger.debug(\"Data %s\", data)\n return response\n else:\n return Response()\n\n\n@app.route('/api/flag', methods=['POST'])\ndef flag_handler():\n body = request.get_json()\n logger.debug(\"Flag %s\", body)\n login_attempt = None\n user = db.getUserByName(conn, body.get('doubleName'))\n\n try:\n login_attempt = db.getAuthByStateHash(conn, body.get('hash'))\n except Exception as e:\n pass\n\n if user:\n print(\"user found\")\n try:\n public_key = base64.b64decode(user[3])\n signed_device_id = base64.b64decode(body.get('deviceId'))\n bytes_signed_device_id = bytes(signed_device_id)\n verify_key = nacl.signing.VerifyKey(\n public_key.hex(), encoder=nacl.encoding.HexEncoder)\n verified_device_id = verify_key.verify(bytes_signed_device_id)\n if verified_device_id:\n verified_device_id = verified_device_id.decode(\"utf-8\")\n update_sql = \"UPDATE users SET device_id=? WHERE device_id=?;\"\n db.update_user(conn, update_sql, '', verified_device_id)\n\n sio.emit('scannedFlag', {'scanned': True}, room=user[1])\n return Response(\"Ok\")\n except Exception as e:\n logger.debug(\"Exception: %s\", e)\n return Response(\"Sinature invalid\", status=400)\n\n if login_attempt:\n print(\"login attempt found\")\n if verified_device_id:\n verified_device_id = verified_device_id.decode(\"utf-8\")\n update_sql = \"UPDATE users SET device_id=? WHERE device_id=?;\"\n db.update_user(conn, update_sql, '', verified_device_id)\n\n update_sql = \"UPDATE auth SET scanned=?, data=? WHERE double_name=?;\"\n db.update_auth(conn, update_sql, 1, '', login_attempt[0])\n\n update_sql = \"UPDATE users SET device_id =? WHERE double_name=?;\"\n db.update_user(conn, update_sql,\n verified_device_id, login_attempt[0])\n\n return Response(\"Ok\")\n else:\n print(\"user not found\")\n return Response('User not found', status=404)\n\n\n@app.route('/api/signRegister', methods=['POST'])\ndef signRegisterHandler():\n print('inside signRegister...')\n body = request.get_json()\n user = db.getUserByName(conn, body.get('doubleName'))\n print(user)\n if user:\n sio.emit('signed', {\n 'data': body.get('data'),\n }, room=user[1])\n return Response('Ok')\n else:\n return Response('User not found', status=404)\n\n\n@app.route('/api/sign', methods=['POST'])\ndef sign_handler():\n body = request.get_json()\n logger.debug(\"Sign: %s\", body)\n login_attempt = db.getAuthByStateHash(conn, body.get('hash'))\n if login_attempt != None:\n user = db.getUserByName(conn, login_attempt[0])\n update_sql = \"UPDATE auth SET singed_statehash =?, data=? WHERE state_hash=?;\"\n db.update_auth(conn, update_sql, body.get('signedHash'),\n json.dumps(body.get('data')), body.get('hash'))\n sio.emit('signed', {\n 'signedHash': body.get('signedHash'),\n 'data': body.get('data'),\n 'selectedImageId': body.get('selectedImageId')\n }, room=user[1])\n return Response(\"Ok\")\n else:\n return Response(\"Something went wrong\", status=500)\n\n\n@app.route('/api/attempts/', methods=['GET'])\ndef get_attempts_handler(doublename):\n doublename = doublename.lower()\n logger.debug(\"Getting attempts for %s\", doublename)\n try:\n auth_header = request.headers.get('Jimber-Authorization')\n if (auth_header is not None):\n data = verify_signed_data(doublename, auth_header)\n if data:\n data = json.loads(data.decode(\"utf-8\"))\n if(data[\"intention\"] == \"attempts\"):\n timestamp = data[\"timestamp\"]\n readable_signed_timestamp = datetime.fromtimestamp(\n int(timestamp) / 1000)\n current_timestamp = time.time() * 1000\n readable_current_timestamp = datetime.fromtimestamp(\n int(current_timestamp / 1000))\n difference = (int(timestamp) -\n int(current_timestamp)) / 1000\n if difference < 30:\n logger.debug(\"Verification succeeded.\")\n login_attempt = db.getAuthByDoubleName(\n conn, doublename)\n if (login_attempt is not None):\n logger.debug(\"Login attempt %s\", login_attempt)\n response = app.response_class(\n response=json.dumps(\n json.loads(login_attempt[5])),\n mimetype='application/json'\n )\n return response\n else:\n logger.debug(\"No login attempts found\")\n return Response(\"No login attempts found\", status=204)\n else:\n logger.debug(\n \"Signed timestamp inside the header has expired\")\n return Response(\"\", status=400)\n else:\n logger.debug(\"Intention was not correct!\")\n else:\n logger.debug(\n \"Signed timestamp inside the header could not be verified\")\n # return Response(\"Signed timestamp inside the header could not be verified\", status=400)\n else:\n logger.debug(\"Header was not present\")\n # return Response(\"Header was not present\", status=400)\n except Exception as e:\n logger.debug(\n \"Something went wrong while trying to verify the header %e\", e)\n # return Response(\"Something went wrong while trying to verify the header\", status=400)\n\n\n@app.route('/api/verify', methods=['POST'])\ndef verify_handler():\n body = request.get_json()\n logger.debug(\"Verify %s\", body)\n user = db.getUserByName(conn, body.get('username'))\n login_attempt = db.getAuthByStateHash(conn, body.get('hash'))\n try:\n if user and login_attempt:\n requested_datetime = datetime.strptime(\n login_attempt[2], '%Y-%m-%d %H:%M:%S.%f')\n max_datetime = requested_datetime + timedelta(minutes=10)\n if requested_datetime < max_datetime:\n public_key = base64.b64decode(user[3])\n signed_hash = base64.b64decode(login_attempt[4])\n original_hash = login_attempt[1]\n try:\n bytes_signed_hash = bytes(signed_hash)\n bytes_original_hash = bytes(original_hash, encoding='utf8')\n verify_key = nacl.signing.VerifyKey(\n public_key.hex(), encoder=nacl.encoding.HexEncoder)\n verify_key.verify(bytes_original_hash, bytes_signed_hash)\n return Response(\"Ok\")\n except:\n return Response(\"Sinature invalid\", status=400)\n else:\n return Response(\"You are too late\", status=400)\n\n else:\n return Response(\"Oops.. user or login attempt not found\", status=404)\n except Exception as e:\n logger.log(\"Something went wrong while trying to verify the header %e\", e)\n\n\n@app.route('/api/mobileregistration', methods=['POST'])\ndef mobile_registration_handler():\n body = request.get_json()\n double_name = body.get('doubleName').lower()\n sid = body.get('sid')\n email = body.get('email')\n public_key = body.get('public_key')\n\n if double_name == None or email == None or public_key == None or sid == None:\n return Response(\"Missing data\", status=400)\n else:\n user = db.getUserByName(conn, double_name)\n if user is None:\n update_sql = \"INSERT into users (double_name, sid, email, public_key) VALUES(?,?,?,?);\"\n db.insert_user(conn, update_sql, double_name,\n sid, email, public_key)\n return Response(\"Succes\", status=200)\n\n\n@app.route('/api/users//deviceid', methods=['PUT'])\ndef update_device_id(doublename):\n body = request.get_json()\n doublename = doublename.lower()\n logger.debug(\"Updating deviceid of user %s\", doublename)\n try:\n signed_device_id = body.get('signedDeviceId')\n\n if (signed_device_id is not None):\n device_id = verify_signed_data(\n doublename, signed_device_id).decode('utf-8')\n\n if device_id:\n logger.debug(\"Updating deviceid %s\", device_id)\n db.update_deviceid(conn, device_id, doublename)\n return device_id\n else:\n logger.debug(\n \"Signed timestamp inside the header could not be verified\")\n else:\n logger.debug(\"Header was not present\")\n except:\n logger.debug(\"Something went wrong while trying to verify the header\")\n\n\n@app.route('/api/users//deviceid', methods=['DELETE'])\ndef remove_device_id(doublename):\n doublename = doublename.lower()\n logger.debug(\"Removing device id from user %s\", doublename)\n\n try:\n auth_header = request.headers.get('Jimber-Authorization')\n logger.debug(auth_header)\n if (auth_header is not None):\n data = verify_signed_data(doublename, auth_header)\n if data:\n data = json.loads(data.decode(\"utf-8\"))\n if(data[\"intention\"] == \"delete-deviceid\"):\n timestamp = data[\"timestamp\"]\n readable_signed_timestamp = datetime.fromtimestamp(\n int(timestamp) / 1000)\n current_timestamp = time.time() * 1000\n readable_current_timestamp = datetime.fromtimestamp(\n int(current_timestamp / 1000))\n difference = (int(timestamp) -\n int(current_timestamp)) / 1000\n if difference < 30:\n db.update_deviceid(conn, \"\", doublename)\n device_id = db.get_deviceid(conn, doublename)[0]\n\n if not device_id:\n return Response(\"ok\", status=200)\n else:\n return Response(\"Device ID not found\", status=200)\n\n return Response(\"something went wrong\", status=400)\n else:\n logger.debug(\"Timestamp was expired\")\n return Response(\"Request took to long\", status=418)\n else:\n logger.debug(\n \"Signed timestamp inside the header could not be verified\")\n return Response(\"something went wrong\", status=404)\n else:\n logger.debug(\"Header was not present\")\n return Response(\"Header was not present\", status=400)\n except:\n logger.debug(\"Something went wrong while trying to verify the header\")\n return Response(\"something went wrong\", status=400)\n\n\n@app.route('/api/users/', methods=['GET'])\ndef get_user_handler(doublename):\n doublename = doublename.lower()\n logger.debug(\"Getting user %s\", doublename)\n user = db.getUserByName(conn, doublename)\n if (user is not None):\n data = {\n \"doublename\": doublename,\n \"publicKey\": user[3]\n }\n response = app.response_class(\n response=json.dumps(data),\n mimetype='application/json'\n )\n logger.debug(\"User found\")\n return response\n else:\n logger.debug(\"User not found\")\n return Response('User not found', status=404)\n\n\n@app.route('/api/users//cancel', methods=['POST'])\ndef cancel_login_attempt(doublename):\n user = db.getUserByName(conn, doublename.lower())\n db.delete_auth_for_user(conn, doublename.lower())\n\n sio.emit('cancelLogin', {'scanned': True}, room=user[1])\n return Response('Canceled by User')\n\n\n@app.route('/api/users//emailverified', methods=['post'])\ndef set_email_verified_handler(doublename):\n logger.debug(\"Verified email from user %s\", doublename.lower())\n user = db.getUserByName(conn, doublename.lower())\n logger.debug(user)\n logger.debug(user[4])\n push_service.notify_single_device(registration_id=user[4], message_title='Email verified', message_body='Thanks for verifying your email', data_message={\n 'type': 'email_verification'}, click_action='EMAIL_VERIFIED')\n return Response('Ok')\n\n\n@app.route('/api/savederivedpublickey', methods=['POST'])\ndef save_derived_public_key():\n body = request.get_json()\n double_name = body['doubleName']\n logger.debug(body)\n try:\n auth_header = request.headers.get('Jimber-Authorization')\n logger.debug(auth_header)\n if (auth_header is not None):\n data = verify_signed_data(double_name, auth_header)\n logger.debug(data)\n if data:\n data = json.loads(data.decode(\"utf-8\"))\n logger.debug(data)\n if(data[\"intention\"] == \"post-savederivedpublickey\"):\n timestamp = data[\"timestamp\"]\n readable_signed_timestamp = datetime.fromtimestamp(\n int(timestamp) / 1000)\n current_timestamp = time.time() * 1000\n readable_current_timestamp = datetime.fromtimestamp(\n int(current_timestamp / 1000))\n difference = (int(timestamp) -\n int(current_timestamp)) / 1000\n if difference < 30:\n # here code\n derived_public_key = verify_signed_data(double_name, body.get(\n 'signedDerivedPublicKey')).decode(encoding='utf-8')\n app_id = verify_signed_data(double_name, body.get(\n 'signedAppId')).decode(encoding='utf-8')\n\n if double_name and derived_public_key and app_id:\n logger.debug(\"Signed data has been verified\")\n insert_statement = \"INSERT into userapps (double_name, user_app_id, user_app_derived_pk) VALUES(?,?,?);\"\n db.insert_app_derived_public_key(\n conn, insert_statement, double_name, app_id, derived_public_key)\n\n result = db.select_from_userapps(\n conn, \"SELECT * from userapps WHERE double_name=? and user_app_id=?;\", double_name, app_id)\n logger.debug(result)\n return Response('', status=200)\n else:\n logger.debug(\"Signed data is not verified\")\n\n return Response(\"something went wrong\", status=400)\n else:\n logger.debug(\"Timestamp was expired\")\n return Response(\"Request took to long\", status=418)\n else:\n logger.debug(\n \"Signed timestamp inside the header could not be verified\")\n return Response(\"something went wrong\", status=404)\n else:\n logger.debug(\"Header was not present\")\n return Response(\"Header was not present\", status=400)\n except Exception as e:\n logger.debug(\n \"Something went wrong while trying to verify the header %s\", e)\n return Response(\"something went wrong\", status=400)\n\n\n@app.route('/api/showapps', methods=['get'])\ndef show_apps_handler():\n return Response('True')\n\n\n@app.route('/api/minversion', methods=['get'])\ndef min_version_handler():\n return Response('45')\n\n\ndef verify_signed_data(double_name, data):\n # print('/n### --- data verification --- ###')\n # print(\"Verifying data: \", data)\n\n decoded_data = base64.b64decode(data)\n # print(\"Decoding data: \", decoded_data)\n\n bytes_data = bytes(decoded_data)\n\n public_key = base64.b64decode(db.getUserByName(conn, double_name)[3])\n # print('Retrieving public key from: ', double_name)\n\n verify_key = nacl.signing.VerifyKey(\n public_key.hex(), encoder=nacl.encoding.HexEncoder)\n # print('verify_key: ', verify_key)\n\n verified_signed_data = verify_key.verify(bytes_data)\n # print('verified_signed_data: ', verified_signed_data)\n # print('### --- END data verification --- ###/n')\n\n return verified_signed_data\n\n\napp.run(host='0.0.0.0', port=5000)\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":21531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"374689755","text":"from django.urls import path\nfrom .views import *\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('', home, name='home'),\n path('logs/', delivery_logs, name='logs'),\n path('accounts/login/', auth_views.LoginView.as_view(), name='login'),\n path('accounts/logout/', logout_request, name=\"logout\"),\n path('accounts/signup/', signup, name='signup'),\n]\n","sub_path":"deliveries/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"545379473","text":"# -*- coding: utf-8 -*-\n\n#頂点ごとに色を指定する\n\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GL import *\nimport sys\nimport os\n\n\ndef display():\n # ウィンドウを塗りつぶす 0.0~1.0を指定\n # 引数には塗りつぶすバッファを指定\n # バッファの種類は下記\n # GL_COLOR_BUFFER_BIT\n # GL_DEPTH_BUFFER_BIT\n # GL_ACCUM_BUFFER_BIT\n # GL_STENCIL_BUFFER_BIT\n glClear(GL_COLOR_BUFFER_BIT)\n\n #glBegin()〜glEnd()の間でコマンドを指定して図形を描く\n #glBegin()の引数には描画する図形のタイプを指定\n #このタイプ次第で処理速度などが決まる\n glBegin(GL_POLYGON)\n\n #図形の各頂点の座標値を設定する関数を置く\n #(-0.9, -0.9), (0.9, -0.9), (0.9, 0.9), (-0.9, 0.9)\n #の順に線を引く\n #座標系は-1.0 ~ 1.0に正規化されている\n\n glColor3d(1.0, 0.0, 0.0)\n glVertex2d(-0.9, -0.9)\n\n glColor3d(0.0, 1.0, 0.0)\n glVertex2d(0.9, -0.9)\n\n glColor3d(0.0, 0.0, 1.0)\n glVertex2d(0.9, 0.9)\n\n glColor3d(1.0, 1.0, 0.0)\n glVertex2d(-0.9, 0.9)\n\n glEnd()\n\n # まだ実行されていない OpenGL の命令を全部実行\n # OpenGLは関数呼び出し��都度実行ではなくある程度命令が溜まったら一気に実行する仕様のため\n # ただしglFlushを呼びすぎると処理が遅くなる\n glFlush()\n\n\ndef init():\n # ウィンドウを塗りつぶす際の色を指定\n glClearColor(1.0, 1.0, 1.0, 1.0)\n\n\ndef main():\n # GLUT OpenGLの初期化\n glutInit(sys.argv)\n # ディスプレイの表示モードを設定\n # mode に GLUT_RGBA を指定した場合, 色の指定をRGBAで行えるようにする\n glutInitDisplayMode(GLUT_RGBA)\n # ファイル名をフォルダ名にしてwindowを生成\n window_id = glutCreateWindow(os.path.basename(__file__))\n # window再描画時に呼び出すメソッドを設定\n glutDisplayFunc(display)\n # (自作)初期化メソッド\n init()\n # 無限ループでイベントを待つ\n glutMainLoop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"GLUT_OPenGL/5_4_2.py","file_name":"5_4_2.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"520259324","text":"import os\nimport boto3\n\nfrom datetime import datetime\nfrom cmo_trading_strategy.config import LOGICAL_PARAMS, INFRASTRUCTURE_PARAMS\nfrom trading_tools.poloniex_wrapper_bwentzloff import Poloniex\nfrom trading_tools.cmo_calculation import cmo_logic_no_pandas\n\n\ndef close_positions(poloniex_wrapper, base_currency, quote_currency):\n\n ticker = poloniex_wrapper.returnTicker()[quote_currency+'_'+base_currency]\n\n # if we have any of our base currency\n if poloniex_wrapper.returnBalances()[base_currency] > 0 and LOGICAL_PARAMS[\"DRY_RUN\"] is False:\n # sell the entire balance of our base currency\n response = poloniex_wrapper.sell(\n currencyPair=LOGICAL_PARAMS['PAIR'],\n rate=ticker['highestBid'],\n amount=poloniex_wrapper.returnBalances()[base_currency]\n )\n elif LOGICAL_PARAMS[\"DRY_RUN\"] is True:\n print(f\"closing {LOGICAL_PARAMS['PAIR']}\\nsale price: {ticker['highestBid']}\")\n response = {'orderNumber': '514845991795',\n 'resultingTrades': [\n {'amount': '3.0',\n 'date': '2018-10-25 23:03:21',\n 'rate': '0.0002',\n 'total': '0.0006',\n 'tradeID': '251834',\n 'type': 'sell'}\n ],\n 'fee': '0.01000000',\n 'clientOrderId': '12345',\n 'currencyPair': 'BTC_ETH'}\n else:\n response = None\n\n print(f\"{base_currency} balance: {poloniex_wrapper.returnBalances()[base_currency]}\")\n return response\n\n\ndef enter_position(poloniex_wrapper, base_currency, quote_currency):\n ticker = poloniex_wrapper.returnTicker()[quote_currency+'_'+base_currency]\n entry_amount = ticker['lowestAsk']/(LOGICAL_PARAMS['INITIAL_CAPITAL'] * LOGICAL_PARAMS['ENTRY_SIZE'])\n if LOGICAL_PARAMS[\"DRY_RUN\"] is False:\n response = poloniex_wrapper.buy(\n currencyPair=LOGICAL_PARAMS['PAIR'],\n rate=ticker['lowestAsk'],\n amount=entry_amount\n )\n else:\n print(f\"opening: {LOGICAL_PARAMS['PAIR']}\\nsize: {entry_amount}\\npurchase price: {ticker['lowestAsk']} \")\n response = {'orderNumber': '514845991795',\n 'resultingTrades': [\n {'amount': '3.0',\n 'date': '2018-10-25 23:03:21',\n 'rate': '0.0002',\n 'total': '0.0006',\n 'tradeID': '251834',\n 'type': 'buy'}\n ],\n 'fee': '0.01000000',\n 'clientOrderId': '12345',\n 'currencyPair': 'BTC_ETH'}\n\n return response\n\n\ndef s3_logger(message):\n if message is not None:\n s3 = boto3.resource(\n 's3',\n region_name=INFRASTRUCTURE_PARAMS['AWS_REGION'],\n aws_access_key_id=os.getenv('AWS_KEY'),\n aws_secret_access_key=os.getenv('AWS_SECRET')\n )\n object = s3.Object(\n INFRASTRUCTURE_PARAMS['S3_BUCKET_NAME'],\n f'{datetime.strftime(datetime.now(),\"%m%d%y_%H%M\")}_cmo_trading_strategy_audit.txt'\n )\n response = object.put(Body=message)\n else:\n response = 'no trades'\n return response\n\n\ndef lambda_handler(event, context):\n\n poloniex_wrapper = Poloniex(\n APIKey=os.getenv('POLONIEX_API_KEY'),\n Secret=os.getenv('POLONIEX_SECRET_KEY')\n )\n\n base_currency = LOGICAL_PARAMS['PAIR'].split('_')[0]\n quote_currency = LOGICAL_PARAMS['PAIR'].split('_')[1]\n assert base_currency+'_'+quote_currency == LOGICAL_PARAMS['PAIR']\n\n cmo = cmo_logic_no_pandas()\n\n # asset oversold\n if cmo < LOGICAL_PARAMS[\"OVERSOLD_VALUE\"]:\n response = enter_position(poloniex_wrapper, base_currency, quote_currency)\n # asset overbought\n elif cmo > LOGICAL_PARAMS[\"OVERBOUGHT_VALUE\"]:\n response = close_positions(poloniex_wrapper, base_currency)\n else:\n response = None\n\n s3_response = s3_logger(message=response)\n print(f'CMO: {cmo}')\n print(f's3_response: {s3_response}')\n for key in LOGICAL_PARAMS:\n print(f'{key}: {LOGICAL_PARAMS[key]}')\n\n\nif __name__ == '__main__':\n lambda_handler(0, 0)\n","sub_path":"poloniex_cmo_trading_strategy/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"374608367","text":"import os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# region input parameters\n# 0: 1st, 1: , 2: , 3: , 4:\nconditions_list_i=0\n\n\n\n\nplot_context = 'talk'\n# plot_context = 'notebook'\nfont_scale=1.5\nsave_plots=1\n\ncontrol_condition='Control_DMSO'\nframe=1\n\n# endregion\n\n\n# 1st Condition list\n# conditions_1=['Control_DMSO', 'NS1643_50uM_TMZ_50uM', 'Pantoprazole_100uM_Lamotrigine_100uM', 'Pantoprazole_100uM','Pantoprazole_100uM_NS1643_20uM',\n# 'Pantoprazole_100uM_Rapamycin_100nM','Pantoprazole_100uM_Retigabine_10uM','Pantoprazole_100uM_TMZ_50uM','Pantoprazole_100uM_NS1643_50uM',\n# 'NS1643_20uM_TMZ_50uM']\n\nconditions_1=['Control_DMSO', 'Pantoprazole_100uM','NS1643_50uM', 'TMZ_50uM',\n 'Retigabine_10uM', 'Pantoprazole_100uM_NS1643_50uM','Pantoprazole_100uM_Retigabine_10uM',\n 'Pantoprazole_100uM_TMZ_50uM','NS1643_50uM_TMZ_50uM']\n\n\nconditions_list=[conditions_1]\n\nconditions=conditions_list[conditions_list_i]\n\nconditions_reduced=conditions[1:]\n\nfilepath = filedialog.askopenfilename(\n # initialdir=\"/\",\n initialdir=r\"E:\\U87_LiveDead_analysis_NEWEST\\Day6_combined\\_prism_data_format\",\n title=\"Select file\",\n filetypes=((\"csv\", \"*.csv\"),)\n)\n\nbase_directory = os.path.dirname(os.path.dirname(filepath))\n\n\nnormalize_search = filepath.find(\"_normalized_\")\nif normalize_search>0:\n analyze_method='fold_change' # 'fold_change' or ''\nelse:\n analyze_method=''\n\nPercent_search = filepath.find(\"_Percent_\")\nif Percent_search>0:\n normalization='_Percent_' # 'Percent_' or ''\nelse:\n normalization=''\n\nschroedinger_search = filepath.find(\"_Dead_\")\n\nif Percent_search>0:\n schroedinger='_Dead'\nelse:\n schroedinger='_Alive'\n\nfname= normalization + schroedinger + '_Cells'\nylabel_string=fname.replace('_',' ')\n\nbox_dir = os.path.join(\n base_directory, 'boxplots'\n)\n\n\n\nif not os.path.exists(box_dir):\n os.makedirs(box_dir)\n\n# ax_title_boxplot = f'Day {box_day} Normalized Cell Counts Compared to {control_condition} - frame m{frame}'\n\nGroupt_title = ['1st List']\n\n\nboxplot_fname = os.path.join(box_dir, f'{Groupt_title[conditions_list_i]} {fname} .png')\n\nprint('Producing Combined Boxplot')\n\nmi_box = pd.read_csv(filepath)\n\n# mi_box = mi_box.loc[mi_box['Condition'].isin(conditions)]\n# sorterIndex = dict(zip(conditions, range(len(conditions))))\n\n\n# mi_box = mi_box.reset_index(drop=True)\n\nif analyze_method == 'fold_change':\n mi_box=mi_box[conditions_reduced]\nelse:\n mi_box=mi_box[conditions]\n\nmi_box=mi_box*100\n\nswarmplot_size = 10\nswarmplot_offset = 0 # offset to left of boxplot\n\n# ax = sns.swarmplot(x=\"Condition\", y=norm_colname, data=mi_box, hue=\"Date\", size=swarmplot_size,\n# edgecolor=\"white\", linewidth=1, dodge=True)\n# g = mi_box.groupby(by=[\"Condition\"])[norm_colname].median()\nmedians=mi_box.median(axis=0)\n\nmy_order = medians.nlargest(len(medians))\nmy_order = my_order.index.tolist()\n\nsns.set(context=plot_context,font_scale=font_scale,style=\"whitegrid\")\n\n# ax = sns.swarmplot(data=mi_box, size=swarmplot_size, order=my_order,\n# edgecolor=\"black\", linewidth=0.5)\nax = sns.stripplot(data=mi_box, size=swarmplot_size,\n edgecolor=\"black\", linewidth=1)#, order=my_order)\n\n\npath_collections = [child for child in ax.get_children()\n if isinstance(child, matplotlib.collections.PathCollection)]\n\nfor path_collection in path_collections:\n x, y = np.array(path_collection.get_offsets()).T\n xnew = x + swarmplot_offset\n offsets = list(zip(xnew, y))\n path_collection.set_offsets(offsets)\n\nmypalette = {\"Control_DMSO\": \"black\",\n \"Pantoprazole_100uM\": \"#949494\",\n \"Retigabine_10uM\": \"#029e73\",\n \"Pantoprazole_100uM_Retigabine_10uM\": \"mediumaquamarine\",\n \"Pantoprazole_100uM_NS1643_50uM\": \"lightskyblue\",\n \"Pantoprazole_100uM_TMZ_50uM\": \"chocolate\",\n \"NS1643_50uM_TMZ_50uM\": \"mediumorchid\",\n # \"TMZ_50uM\":\"firebrick\",\n \"TMZ_50uM\": \"saddlebrown\",\n \"NS1643_50uM\": \"#0173b2\"}\n\n# ax = sns.boxplot(data=mi_box, order=my_order, linewidth=2, fliersize=0, showmeans=True,\n# meanprops={\"marker\": \"D\",\n# \"markeredgecolor\": \"white\",\n# \"markerfacecolor\": \"black\",\n# \"markersize\": \"14\"})\nmi_box['emtpy_column']=''\n\nax = sns.barplot(x=mi_box.index.to_list(),y=mi_box.columns.to_list(), data=mi_box, capsize=0.01, palette=mypalette, hue=mi_box.columns.to_list())\n\nax.grid(True)\n\nbottom, top = ax.get_ylim()\n\nax.set(ylim=(bottom, top+0.1*np.abs(top)))\n\n\n# if analyze_method == \"fold_change\":\n# ax.set(ylim=(bottom-0.25, 0.25))\n# else:\n# ax.set(ylim=(bottom, top+0.2*np.abs(top)))\n\nfig = plt.gcf()\nfig.set_size_inches(30, 15)\nplt.gcf().subplots_adjust(bottom=0.3)\n\n# ax.set_xticklabels(conditions, rotation=90)\n# ax.set(xticks=ttest_pvalues.columns, rotation=90)\nif analyze_method == \"fold_change\":\n tick_list = np.r_[0:len(conditions_reduced)]\nelse:\n tick_list = np.r_[0:len(conditions)]\n# ax.set_xticks(tick_list)\n#\n# con_list = [item.get_text() for item in ax.get_xticklabels()]\n#\n# conditions_labels = [w.replace('_', ' ') for w in con_list]\n#\n# conditions_labels = [w.replace('uM', 'μM\\n') for w in conditions_labels]\n#\n# conditions_labels = [w.replace('mM', 'mM\\n') for w in conditions_labels]\n# conditions_labels = [w.replace('nM', 'nM\\n') for w in conditions_labels]\n# conditions_labels = [w.replace('per', '%') for w in conditions_labels]\n\nplt.gcf().subplots_adjust(right=0.7)\nhandles, labels = ax.get_legend_handles_labels()\nlabels = [w.replace('_', ' ') for w in labels]\n\nlabels = [w.replace('uM', 'μM') for w in labels]\n\nlabels = [w.replace('mM', 'mM') for w in labels]\nlabels = [w.replace('nM', 'nM') for w in labels]\nlabels = [w.replace('per', '%') for w in labels]\n\nax.legend(handles=handles[0:], labels=labels[0:],loc='center left', bbox_to_anchor=(1, 0.5))\n\nplt.tick_params(\n axis='x', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n bottom=False, # ticks along the bottom edge are off\n top=False, # ticks along the top edge are off\n labelbottom=False) # labels along the bottom edge are off\n# plt.legend()\n\nax.set_xlabel('')\n#\n#\n# if len(conditions)<6:\n# dx = 0.\n# dy = 0.\n# rotation=0\n# tick_orientation='center'\n#\n# elif len(conditions)>15:\n# rotation=37\n# dx = 24 / 72.\n# dy = 0.\n# conditions_labels = [w.replace('\\n', ' ') for w in conditions_labels]\n# # tick_orientation='center'\n# tick_orientation='right'\n#\n# else:\n# rotation=37\n# dx = 50 / 72.\n# dy = 0.\n# # tick_orientation='center'\n# tick_orientation='right'\n\n\n\n# Con_list = mi_box['Condition'].to_numpy()\n# con_list = np.unique(Con_list)\n# con_list = con_list.tolist()\n\n\n\n\n# conditions_label_reduced = [w.replace('_', ' \\n ') for w in conditions_reduced]\n# conditions_label_reduced = [w.replace('uM', 'μM') for w in conditions_label_reduced]\n\n# ax.set_xticklabels(conditions_labels, rotation=rotation,\n# ha=tick_orientation) # , rotation_mode=\"anchor\")\n# if analyze_method == \"fold_change\":\n# # ax.set_xticklabels(conditions_label_reduced, rotation=rotation, ha=tick_orientation) # , rotation_mode=\"anchor\")\n# if normalization == '_Percent_':\n# ax.set_ylabel('Percent (Fold Change to Control)')\n# else:\n# ax.set_ylabel('Cell Count (Fold Change to Control)')\n# # plt.axhline(y=0)\n# else:\n# ax.set_xticklabels(conditions_labels, rotation=rotation, ha=tick_orientation) # , rotation_mode=\"anchor\")\n# # for tick in ax.xaxis.get_majorticklabels():\n# # tick.set_horizontalalignment(\"right\")\n# if normalization == '_Percent_':\n# ax.set_ylabel('Percent')\n# else:\n# ax.set_ylabel('Cell Count')\n\n\nax.set_ylabel(ylabel_string)\n\n#\n# offset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)\n#\n# # apply offset transform to all x ticklabels.\n# for label in ax.xaxis.get_majorticklabels():\n# label.set_transform(label.get_transform() + offset)\n\n# ax.set_xlabel('Conditions')\nax.set_xlabel('')\n\n# ax.set_title(ax_title_boxplot)\nax.set_title('')\n\n# ax.xaxis.set_ticks_position('none')\n# ax.yaxis.set_ticks_position('none')\n# ax.tick_params(direction='in')\n\n\nif save_plots:\n plt.savefig(boxplot_fname)\n plt.clf()\n plt.close()\nelse:\n plt.show()","sub_path":"Box_plot_Toxscreen_data_from_Prism_data.py","file_name":"Box_plot_Toxscreen_data_from_Prism_data.py","file_ext":"py","file_size_in_byte":8546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"10816298","text":"#ex 1 chapter 4 ABSWP\n'''Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your func- tion should be able to work with any list value passed to it.'''\n\nspam = ['apples','bananas','tofu','cats']\nham = ['Jano','Pippo','Saro']\neggs = ['Ciccio', 'Melo', 'Tano','Puppettu', 'Scicchigno']\n\n\ndef foo(listValue): #definiamo la funzione\n\tfor p in listValue[0:-1]: #creiamo un for loop che stampa i singoli valori che sono nella lista, dal primo al penultimo\n\t\tprint(p, end=', ')#e separiamo i vari valori con una vorgola, tenendoli sulla stessa riga\n\tprint('and ' + listValue[-1] + '.') #aggiungiamo 'and' e l'ultimo valore della lista seguito dal punto per avere il risultato corretto.\nfoo(spam)\nfoo(ham)\nfoo(eggs)\n#la lista deve essere di ALMENO due elementi; in alternativa si potrebbe inserire un if per controllare che la lista rispetti certi criteri\n\n","sub_path":"commaCode.py","file_name":"commaCode.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"503848040","text":"\n\n\ndef try_all_matches(subject, query, score_limit):\n for subject_start in range(0,len(subject)):\n for query_start in range(0,len(query)):\n for length in range(0,len(query)):\n if (subject_start + length < len(subject) and query_start + length < len(query)):\n score = score_match(subject, query, subject_start, query_start, length)\n # only print a line of output if the score is better than some limie\n if (score >= score_limit):\n print(subject_start, query_start, length, score)\n\ntry_all_matches('one_sequence', 'another_sequence', 6)","sub_path":"server/.history/score_20200307211237.py","file_name":"score_20200307211237.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"448385219","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, 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\"\"\" Finetuning the library models for question-answering on SQuAD (DistilBERT, Bert, XLM, XLNet).\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport argparse\nimport logging\nimport os\nimport random\nimport glob\nimport timeit\nimport time\nfrom datetime import datetime\n\nimport json\nimport numpy as np\nimport torch\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\n TensorDataset)\nfrom torch.utils.data.distributed import DistributedSampler\nimport torch.nn.functional as F\n\ntry:\n from torch.utils.tensorboard import SummaryWriter\nexcept:\n from tensorboardX import SummaryWriter\n\nfrom tqdm import tqdm, trange\n\nfrom transformers import (WEIGHTS_NAME, BertConfig,\n BertForQuestionAnswering, BertTokenizer,)\n\nfrom transformers import AdamW, get_linear_schedule_with_warmup\n\nfrom utils_squad import (read_squad_examples, convert_examples_to_features,\n RawResult, write_predictions,\n RawResultExtended, write_predictions_extended)\n\n# The follwing import is the official SQuAD evaluation script (2.0).\n# You can remove it from the dependencies if you are using this script outside of the library\n# We've added it here for automated tests (see examples/test_examples.py file)\nfrom utils_squad_evaluate import EVAL_OPTS, main as evaluate_on_squad\n# logging.disable(logging.CRITICAL)\nlogger = logging.getLogger(__name__)\n\nALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) \\\n for conf in (BertConfig, )), ())\n\nMODEL_CLASSES = {\n 'bert': (BertConfig, BertForQuestionAnswering, BertTokenizer),\n}\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\ndef to_list(tensor):\n return tensor.detach().cpu().tolist()\n\n\n# For GA\nclass Question(object):\n def __init__(self, q_len, q_vocab):\n self.q_len = q_len\n self.q_vocab = q_vocab\n self.data = create_random_question(q_len, q_vocab)\n self.value = 0\n\n def fitness(self, outputs, boundary):\n s_logits = outputs[0]\n e_logits = outputs[1]\n\n s_conf, s_idx = F.softmax(s_logits, dim=-1).max(-1)\n e_conf, e_idx = F.softmax(e_logits[:, s_idx:], dim=-1).max(-1)\n e_idx += s_idx\n\n conf = (s_conf + e_conf) / 2\n\n self.s_idx = s_idx\n self.e_idx = e_idx\n\n if s_idx.item() > boundary or e_idx.item() > boundary:\n self.value = 0\n else:\n self.value = conf.item()\n\n def get_answer(self, context_tokens):\n tokens = [\"[CLS]\"] + self.data + [\"[SEP]\"] + context_tokens + [\"[SEP]\"]\n while len(tokens) < 512:\n tokens.append(\"[PAD]\")\n answer = tokens[self.s_idx:self.e_idx+1]\n answer = ' '.join(answer).replace(\" ##\", \"\").replace(\"##\", \"\")\n return answer\n\n def copy(self):\n clone = Question(self.q_len, self.q_vocab)\n clone.data = self.data.copy()\n return clone\n\n def mutate(self, _prob_mutate):\n for i in range(len(self.data)):\n if random.random() < _prob_mutate:\n self.data[i] = random.sample(self.q_vocab, 1)[0]\n\n def __str__(self):\n s = ' '.join(self.data)\n return s\n\n def __eq__(self, other):\n return self.data == other.data\n\nclass Pool:\n # prob = (prob_co, prob_mu)\n def __init__(self, model, population, prob, er, q_len, q_vocab, \\\n context_tokens, tokenizer, device):\n self.model = model\n self.generation = 0\n self.prob = prob\n self.er = er\n self.population = population\n self.q_len = q_len\n self.q_vocab = q_vocab\n self.context_tokens = context_tokens\n self.tokenizer = tokenizer\n self.device = device\n\n # Init population\n self.parents = [Question(q_len, q_vocab) for _ in range(population)]\n self.offsprings = []\n\n def fitness_bulk(self, qs):\n for i, q in enumerate(qs):\n tokens = [\"[CLS]\"] + q.data + [\"[SEP]\"] + self.context_tokens + [\"[SEP]\"]\n input_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n boundary = len(input_ids)\n while len(input_ids) < 512:\n input_ids.append(0)\n input_mask.append(0)\n\n input_ids = torch.tensor(input_ids, dtype=torch.long).to(self.device)\n input_mask = torch.tensor(input_mask, dtype=torch.long).to(self.device)\n\n inputs = {'input_ids': input_ids.unsqueeze(0),\n 'attention_mask': input_mask.unsqueeze(0)}\n outputs = self.model(**inputs)\n q.fitness(outputs, boundary)\n\n def roulette(self):\n roulette = [self.parents[0].value]\n for q in self.parents[1:]:\n roulette.append(q.value + roulette[-1])\n\n a = random.uniform(0, roulette[-1])\n for i in range(len(roulette)):\n if roulette[i] > a:\n return i\n\n def crossover(self):\n # select parent with FPS & roulette strategy\n prob_cross = self.prob[0]\n\n while len(self.offsprings) < len(self.parents):\n parent1 = self.parents[self.roulette()]\n parent2 = parent1\n while parent1 == parent2:\n parent2 = self.parents[self.roulette()]\n\n if random.random() < prob_cross:\n # one point crossover\n point = random.randint(0, len(parent1.data)-1)\n off1 = parent1.copy()\n off2 = parent2.copy()\n off1.data[point:], off2.data[point:] = off2.data[point:], off1.data[point:]\n\n self.offsprings.append(off1)\n self.offsprings.append(off2)\n\n def mutate(self):\n prob_mutate = self.prob[1]\n for q in self.offsprings:\n q.mutate(prob_mutate)\n\n def select(self):\n # elitism\n N = int(self.population * self.er)\n new_parents = self.parents[:N] + self.offsprings[:(self.population-N)]\n self.parents = new_parents\n self.offsprings = []\n\n def simulate(self, _iter):\n print('GA Simulation Started...')\n print('Evaluating first parents fitness...')\n self.fitness_bulk(self.parents)\n print('end')\n\n for i in range(_iter):\n print('-------------------------------------')\n print(f'{i}th generation started')\n print('Sorting parents...')\n self.parents.sort(key=lambda i: i.value, reverse=True)\n print('end')\n print([q.value for q in self.parents][:5])\n for q in self.parents[:5]:\n print(' '.join(q.data))\n print('-------------------------------------')\n\n print('Crossover...')\n self.crossover()\n print('end')\n\n print('Mutation...')\n self.mutate()\n print('end')\n\n print('Evaluating offspring fitness and sorting...')\n self.fitness_bulk(self.offsprings)\n self.offsprings.sort(key=lambda i: i.value, reverse=True)\n print('end')\n\n print('Select next generation...')\n self.select()\n print('end')\n\n print('--------------------------------------')\n print(f'{i}th generation end!')\n print('--------------------------------------')\n self.generation += 1\n\n for q in self.parents:\n print(q.data)\n\n def save(self, _rank, context, gold_qas_tuple):\n now = '-'.join(str(datetime.now()).split())\n output = \"result_{}.txt\".format(now)\n print(\"Save Results to {}...\".format(output))\n self.fitness_bulk(self.parents)\n former_qs = []\n with open(output, 'w') as f:\n f.write(\"Context:\\n**************************************************\\n\")\n f.write(context + '\\n\\n')\n f.write(\"Questions:\\n**************************************************\\n\")\n # for i in range(_rank):\n i = 0\n while len(former_qs) < _rank:\n q = self.parents[i]\n i += 1\n if len(former_qs) > 0 and former_qs[-1] == q:\n continue\n question = ' '.join(q.data).replace(\" ##\", \"\").replace(\"##\", \"\")\n f.write(\"%0.2f %s\\n\" % (q.value*100, question))\n answer = q.get_answer(self.context_tokens)\n f.write(\"Answer: {}\\n\\n\".format(answer))\n former_qs.append(q)\n\n f.write(\"\\nGold QAs:\\n*************************************************\\n\")\n for qa in gold_qas_tuple:\n f.write(qa[0] + '\\n')\n f.write(\"Answer: {}\\n\\n\".format(qa[1]))\n\n\ndef create_random_question(q_len, q_vocab):\n # q_head_words = [\"when\", \"where\", \"why\", \"how\", \"who\", \"what\", \"which\"]\n # question_tokens = tokenizer.convert_ids_to_tokens(torch.randint(len(tokenizer), (q_len,), dtype=torch.long).tolist())\n question_tokens = random.sample(q_vocab, q_len)\n # question_tokens = random.sample(q_head_words, 1) + question_tokens\n return question_tokens\n\n\ndef build_q_vocab(data, tokenizer):\n start = time.time()\n\n qs = []\n for d in data:\n for paragraph in d['paragraphs']:\n for qas in paragraph['qas']:\n qs.append(qas['question'])\n q_vocab = []\n total_len = 0\n for q in qs:\n q_tokens = tokenizer.tokenize(q)\n q_vocab += q_tokens\n total_len += len(q_tokens)\n\n q_len = int(total_len / len(qs))\n q_vocab = list(set(q_vocab))\n print(\"Extracting Q Vocab: {}\".format(time.time() - start))\n return q_vocab, q_len\n\ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--train_file\", default=\"train-v1.1.json\", type=str,\n help=\"SQuAD json for training. E.g., train-v1.1.json\")\n parser.add_argument(\"--model_type\", default='bert', type=str,\n help=\"Model type selected in the list: \" + \", \".join(MODEL_CLASSES.keys()))\n parser.add_argument(\"--model_name_or_path\",\n default='bert-large-uncased-whole-word-masking-finetuned-squad', type=str,\n help=\"Path to pre-trained model or shortcut name selected in the list: \" + \", \".join(ALL_MODELS))\n parser.add_argument(\"--output_dir\", default=\"output\", type=str,\n help=\"The output directory where the model checkpoints and predictions will be written.\")\n\n ## Other parameters\n parser.add_argument(\"--config_name\", default=\"\", type=str,\n help=\"Pretrained config name or path if not the same as model_name\")\n parser.add_argument(\"--tokenizer_name\", default=\"\", type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\")\n parser.add_argument(\"--cache_dir\", default=\"\", type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\")\n\n parser.add_argument('--version_2_with_negative', action='store_true',\n help='If true, the SQuAD examples contain some that do not have an answer.')\n parser.add_argument('--null_score_diff_threshold', type=float, default=0.0,\n help=\"If null_score - best_non_null is greater than the threshold predict null.\")\n\n parser.add_argument(\"--do_lower_case\", action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument('--seed', type=int, default=2019,\n help=\"random seed for initialization\")\n\n parser.add_argument(\"--local_rank\", type=int, default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument(\"--valid_mode\", action='store_true')\n args = parser.parse_args()\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir:\n raise ValueError(\"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.\".format(args.output_dir))\n\n\n # Setup CUDA, GPU & distributed training\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.n_gpu = torch.cuda.device_count()\n else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend='nccl')\n args.n_gpu = 1\n args.device = device\n\n # Setup logging\n logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO if args.local_rank in [-1, 0] else logging.WARN)\n\n # Set seed\n set_seed(args)\n\n # Load pretrained model and tokenizer\n\n args.model_type = args.model_type.lower()\n config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\n config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path,\n cache_dir=args.cache_dir if args.cache_dir else None)\n tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,\n do_lower_case=args.do_lower_case,\n cache_dir=args.cache_dir if args.cache_dir else None)\n model = model_class.from_pretrained(args.model_name_or_path,\n from_tf=bool('.ckpt' in args.model_name_or_path),\n config=config,\n cache_dir=args.cache_dir if args.cache_dir else None)\n\n\n model.to(args.device)\n model.eval()\n\n logger.info(\"Training/evaluation parameters %s\", args)\n\n with open('train-v1.1.json', 'r') as f:\n data = json.load(f)\n\n data = data['data']\n\n d = random.sample(data, 1)[0]\n paragraph = random.sample(d['paragraphs'], 1)[0]\n context = paragraph['context']\n qas = paragraph['qas']\n\n gold_qas_tuple = []\n for qa in qas:\n gold_qas_tuple.append((qa['question'], qa['answers'][0]['text']))\n\n context_tokens = tokenizer.tokenize(context.lower())\n q_vocab, q_len = build_q_vocab(data, tokenizer)\n # 17470...\n\n # Random sample context from context pool\n# with open(\"squad_train.txt\" ,'r') as f:\n# context_corpus = f.readlines()\n# context = random.sample(context_corpus, 1)[0]\n# context_tokens = tokenizer.tokenize(context)\n\n print(\"Context: {}\".format(context))\n\n if args.valid_mode:\n while True:\n print(\"\\nType your question related to given context:\\n\")\n question = input()\n if len(question) < 1:\n break\n data = tokenizer.tokenize(question.lower())[:10]\n q = Question(q_len, q_vocab)\n q.data = data\n tokens = [\"[CLS]\"] + q.data + [\"[SEP]\"] + context_tokens + [\"[SEP]\"]\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n while len(input_ids) < 512:\n input_ids.append(0)\n input_mask.append(0)\n\n input_ids = torch.tensor(input_ids, dtype=torch.long).to(device)\n input_mask = torch.tensor(input_mask, dtype=torch.long).to(device)\n\n inputs = {'input_ids': input_ids.unsqueeze(0),\n 'attention_mask': input_mask.unsqueeze(0)}\n outputs = model(**inputs)\n q.fitness(outputs, 512)\n answer = q.get_answer(context_tokens)\n print(\"Answer: {}\".format(answer))\n print(\"Confidence: {}\".format(q.value))\n\n else:\n # Now Generation Start\n # Selection -> Breeding -> Mutating...\n POPULATION = 500\n PROB_MUTATE = 0.01\n PROB_CROSSOVER = 0.95\n ELITISM_RATE = 0.1\n ITER = 100\n\n p = Pool(model, POPULATION, (PROB_CROSSOVER, PROB_MUTATE), ELITISM_RATE, \\\n q_len, q_vocab, context_tokens, tokenizer, device)\n p.simulate(ITER)\n p.save(10, context, gold_qas_tuple)\n\n import pdb; pdb.set_trace()\nif __name__ == \"__main__\":\n main()\n","sub_path":"project_nlp/run_squad.py","file_name":"run_squad.py","file_ext":"py","file_size_in_byte":17506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"158932768","text":"import torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport os\nfrom torchvision import datasets\nfrom train import interrupt, train\nfrom logger import Logger\nimport time\nimport random\nimport csv\n\npath = os.path.abspath(__file__)\ndir_path = os.path.dirname(path)\n\ndef winner(x1,x2,dataset):\n (_, c1), (_, c2) = dataset[x1], dataset[x2]\n classes = dataset.classes\n\n if c1 == c2:\n return 0 #SAME CLASS\n\n c1 = classes[c1]\n c2 = classes[c2]\n\n if c1 == \"paper\":\n if c2 == \"rock\":\n return 1\n if c2 == \"scissors\":\n return 2\n\n if c1 == \"scissors\":\n if c2 == \"paper\":\n return 1\n if c2 == \"rock\":\n return 2\n\n if c1 == \"rock\":\n if c2 == \"scissors\":\n return 1\n if c2 == \"paper\":\n return 2\n\n raise Exception(\"label not recognized\")\n\ndef split_examples(examples,TRAIN_RATIO,TEST_RATIO):\n size = round(len(examples) * TRAIN_RATIO)\n train_data = examples[:size]\n test_data = examples[size:]\n return train_data,test_data\n\n\ndef neural_predicate(network, i):\n i = int(i.args[0])\n d, l = dataset[i]\n d = Variable(d.unsqueeze(0))\n output = network.net(d)\n return output.squeeze(0)\n\n\ntransformations = transforms.Compose([\n transforms.ToTensor(),\n transforms.Grayscale(num_output_channels=1)\n])\n\ndataset = datasets.ImageFolder(root='../../../data/RPSLS/rock-paper-scissors',transform = transformations)\n\ndef format_string(string):\n string = string.replace('rps', '')\n string = string.replace('test', '')\n string = string.replace('train', '')\n string = string.replace('(', '')\n string = string.replace(')', '')\n string = string.replace('.', '')\n string = string.replace(',', ' ')\n return string\n\ndef write(file,first_coll,second_coll):\n return 0\n\n","sub_path":"examples/RPSLS/RPS/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"609774055","text":"import os\nimport pandas as pd\nimport time\nimport sys\nimport glob\nfrom datetime import datetime, timedelta\n\n\ndef create_sql_file(template_text, site_name, property_id, start_date, end_date):\n filename = site_name + \"_\" + str(property_id) + \".sql\"\n contents = template_text.replace(\"{site_name}\", site_name) \\\n .replace(\"{property_id}\", str(property_id)) \\\n .replace(\"{start_date}\", start_date) \\\n .replace(\"{end_date}\", end_date)\n f = open(\"sql_files/\"+filename ,\"w+\")\n f.write(contents)\n f.close\n \ndef process_line(strg):\n print(\"Submitting query to bq via the cli:\\n\", strg)\n os.system(strg)\n time.sleep(15)\n\n\nyesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y%m%d')\nstart_date = \"20180701\"\n\nos.chdir(sys.path[0])\n\nif not (os.path.exists(os.path.join(os.getcwd(), 'sql_files'))):\n os.makedirs((os.path.join(os.getcwd(), 'sql_files')))\n\nwith open(\"config/template_1.sql\", \"r\") as myfile:\n sql_text=myfile.read().replace('\\n', '')\n\n# read config data and create a list of sites\ndf = pd.read_csv(\"config/config.csv\")\nsite_list = list(df.itertuples(index=False, name=None))\n\nfiles = glob.glob('sql_files/*.sql')\nfor f in files:\n os.remove(f)\n\n# create static sql files for each site\n[create_sql_file(sql_text, i[0], i[1], start_date, yesterday) for i in site_list]\n\n# set the account using the cli\nos.system(\"gcloud config set account analytics@clearhead.me\")\n\n# deletes the summary table\nos.system(\"bq rm --table --force CH_Test.summary_table\")\n\nfile_list = list(os.listdir(\"sql_files\"))\n\n# submits query to cli for each file in the sql_files folder\n# create summary_table with the result from the 0th query\nprocess_line(\"cat sql_files/\" + file_list[0] + \" | bq query --allow_large_results --use_legacy_sql=False \\\n --destination_table=CH_Test.summary_table\")\n\n# run queries 1-N and append to summary table\n[process_line(\"cat sql_files/\" + file + \" | bq query --allow_large_results --use_legacy_sql=False \\\n --append_table=True --destination_table=CH_Test.summary_table\") for file in file_list[1:]]","sub_path":"ETL Examples/Big Query Cron Job Script/cli_approach.py","file_name":"cli_approach.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"121563108","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 3 23:11:10 2015\n\n@author: FinArb\n\"\"\"\n#declare libraries\nimport pandas as pd\nimport sys\nimport numpy as np\nimport itertools\n\n#declare variables...later to be taken as command line arguments\n#Var1=full path of csv file\n#Var2=step size of interpolation\n#Var3=type of interpolation \n#Var4=oder of spline or ploynomial interpolation\n#Var5=if time series formatting is required....Useless at this stage\nVar1=str(sys.argv[1])\nVar2=float(sys.argv[2])\nVar3=str(sys.argv[3])\nVar4=int(sys.argv[4])\nVar5=str(sys.argv[5])\n\n#define loopiong function\ndef seq(start, end, step):\n assert(step != 0)\n sample_count = abs(end - start) / step\n return itertools.islice(itertools.count(start, step), sample_count)\n\n#read csv\ndf=pd.read_csv(Var1,sep=',')\n#create full series\nMax=max(df.iloc[:,0])\nMin=min(df.iloc[:,0])\nTime=[]\nValue=[]\nfor i in seq(Min,Max+1,Var2):\n Time.append(i)\n if (sum(df.iloc[:,0].isin([i]))>0):\n Value.append(df[df.iloc[:,0].isin([i])].iloc[0,1])\n else:\n Value.append(np.nan)\n \nTime=np.array(Time) \nValue=np.array(Value)\n\n#COnvert arrays to pandas data\ndf2=pd.DataFrame(Value,index=Time)\n\n#convert to time series if required\nif (Var5=='TimeSeries'):\n df2.index = pd.to_datetime(df2.index)\n\n#calculate interpolation\nif any([Var3=='polynomial',Var3=='spline']):\n df3=df2.interpolate(method=Var3,order=Var4)\nelif (Var3=='growth'):\n df2=pd.DataFrame(np.log(df2))\n df3=df2.interpolate(method='linear')\n df3=pd.DataFrame(np.exp(df3))\nelse:\n df3=df2.interpolate(method=Var3)\n \n#write to csv\ndf3.to_csv(Var1[:-4]+\"_interpolated_\"+Var3+\".csv\",sep=',',index=True)\n\n\n","sub_path":"scripts/utils/interpolation.py","file_name":"interpolation.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328885341","text":"# Copyright 2019 Stanislav Pidhorskyi\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\n\nclass Encoder(nn.Module):\n def __init__(self, input_channels=1, hiden_size=128, output_channels=64):\n super(Encoder, self).__init__()\n # input parameters\n self.input_channels = input_channels\n self.output_channels = output_channels\n\n self.features = nn.Sequential(\n # 1 x 128 x 128\n nn.Conv2d(self.input_channels, output_channels, 4, stride=2, padding=1),\n nn.BatchNorm2d(output_channels),\n nn.ReLU(),\n # 64 x 64 x 64\n nn.Conv2d(output_channels, output_channels * 2, 4, stride=2, padding=1),\n nn.BatchNorm2d(output_channels * 2),\n nn.ReLU(),\n # 128 x 32 x 32\n nn.Conv2d(output_channels * 2, output_channels * 4, 4, stride=2, padding=1),\n nn.BatchNorm2d(output_channels * 4),\n nn.ReLU(),\n # 256 x 16 x 16\n nn.Conv2d(output_channels * 4, output_channels * 8, 4, stride=2, padding=1),\n nn.BatchNorm2d(output_channels * 8),\n nn.ReLU(),\n # 512 x 8 x 8\n nn.Conv2d(output_channels * 8, output_channels * 16, 4, stride=2, padding=1),\n nn.BatchNorm2d(output_channels * 16),\n nn.ReLU())\n # 1024 x 4 x 4\n\n self.mean = nn.Sequential(\n nn.Linear(output_channels * 16 * 4 * 4, 2048),\n nn.BatchNorm1d(2048),\n nn.ReLU(),\n nn.Linear(2048, hiden_size))\n\n self.logvar = nn.Sequential(\n nn.Linear(output_channels * 16 * 4 * 4, 2048),\n nn.BatchNorm1d(2048),\n nn.ReLU(),\n nn.Linear(2048, hiden_size))\n\n def forward(self, x):\n batch_size = x.size()[0]\n\n hidden_representation = self.features(x)\n\n mean = self.mean(hidden_representation.view(batch_size, -1))\n logvar = self.logvar(hidden_representation.view(batch_size, -1))\n\n return mean, logvar\n\n def hidden_layer(self, x):\n batch_size = x.size()[0]\n output = self.features(x)\n return output\n\n\nclass Decoder(nn.Module):\n def __init__(self, input_size, representation_size):\n super(Decoder, self).__init__()\n self.input_size = input_size\n self.representation_size = representation_size\n dim = representation_size[0] * representation_size[1] * representation_size[2]\n\n self.preprocess = nn.Sequential(\n nn.Linear(input_size, dim),\n nn.BatchNorm1d(dim),\n nn.ReLU())\n\n\n # 1024x4x4\n self.deconv0 = nn.ConvTranspose2d(representation_size[0], 512, 4, stride=2, padding=1)\n self.act0 = nn.Sequential(nn.BatchNorm2d(512),\n nn.ReLU())\n\n # 512 x 8 x 8\n self.deconv1 = nn.ConvTranspose2d(512, 256, 4, stride=2, padding=1)\n self.act1 = nn.Sequential(nn.BatchNorm2d(256),\n nn.ReLU())\n # 256 x 16 x 16\n self.deconv2 = nn.ConvTranspose2d(256, 128, 4, stride=2, padding=1)\n self.act2 = nn.Sequential(nn.BatchNorm2d(128),\n nn.ReLU())\n # 128 x 32 x 32\n self.deconv3 = nn.ConvTranspose2d(128, 64, 4, stride=2, padding=1)\n self.act3 = nn.Sequential(nn.BatchNorm2d(64),\n nn.ReLU())\n # 64 x 64 x 64\n self.deconv4 = nn.ConvTranspose2d(64, 1, 4, stride=2, padding=1)\n # 1 x 128 x 128\n #self.activation = nn.Sigmoid()\n\n def forward(self, code):\n bs = code.size()[0]\n preprocessed_codes = self.preprocess(code)\n preprocessed_codes = preprocessed_codes.view(-1,\n self.representation_size[0],\n self.representation_size[1],\n self.representation_size[2])\n\n output = self.deconv0(preprocessed_codes, output_size=(bs, 512, 8, 8))\n output = self.act0(output)\n output = self.deconv1(output, output_size=(bs, 256, 16, 16))\n output = self.act1(output)\n output = self.deconv2(output, output_size=(bs, 128, 32, 32))\n output = self.act2(output)\n output = self.deconv3(output, output_size=(bs, 64, 64, 64))\n output = self.act3(output)\n output = self.deconv4(output, output_size=(bs, 1, 128, 128))\n output = torch.sigmoid(output)\n\n\n # output = self.deconv1(preprocessed_codes, output_size=(bs, 256, 16, 16))\n #\n # output = self.act1(output)\n # output = self.deconv2(output, output_size=(bs, 128, 32, 32))\n # output = self.act2(output)\n # output = self.deconv3(output, output_size=(bs, 64, 64, 64))\n # output = self.act3(output)\n # output = self.deconv4(output, output_size=(bs, 1, 128, 128))\n # output = self.activation(output)\n return output\n\n\nclass VAE_GAN_Generator(nn.Module):\n def __init__(self, input_channels=1, hidden_size=128, representation_size=[1024,4,4],output_channels=64):\n super(VAE_GAN_Generator, self).__init__()\n self.input_channels = input_channels\n self.hidden_size = hidden_size\n self.representation_size = representation_size\n\n self.encoder = Encoder()\n self.decoder = Decoder(hidden_size, representation_size)\n\n def forward(self, x):\n batch_size = x.size()[0]\n mean, logvar = self.encoder(x)\n std = logvar.mul(0.5).exp_()\n\n reparametrized_noise = Variable(torch.randn((batch_size, self.hidden_size))).cuda()\n #reparametrized_noise = Variable(torch.randn((batch_size, self.hidden_size)))\n reparametrized_noise = mean + std * reparametrized_noise\n\n rec_images = self.decoder(reparametrized_noise)\n\n return mean, logvar, rec_images\n\n\nclass Discriminator(nn.Module):\n def __init__(self, input_channels=1, representation_size=(1024, 4, 4)):\n super(Discriminator, self).__init__()\n self.representation_size = representation_size\n dim = representation_size[0] * representation_size[1] * representation_size[2]\n\n self.main = nn.Sequential(\n # 1 x 128 x 128\n nn.Conv2d(input_channels, 64, 4, stride=2, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(0.2),\n nn.Conv2d(64, 128, 4, stride=2, padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2),\n nn.Conv2d(128, 256, 4, stride=2, padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2),\n nn.Conv2d(256, 512, 4, stride=2, padding=1),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2),\n nn.Conv2d(512, 1024, 4, stride=2, padding=1),\n nn.BatchNorm2d(1024),\n nn.LeakyReLU(0.2)\n )\n\n self.lth_features = nn.Sequential(\n nn.Linear(dim, 2048),\n nn.LeakyReLU(0.2))\n\n self.sigmoid_output = nn.Sequential(\n nn.Linear(2048, 1),\n nn.Sigmoid())\n\n def forward(self, x):\n batch_size = x.size()[0]\n features = self.main(x)\n lth_rep = self.lth_features(features.view(batch_size, -1))\n output = self.sigmoid_output(lth_rep)\n return output\n\n def similarity(self, x):\n batch_size = x.size()[0]\n features = self.main(x)\n lth_rep = self.lth_features(features.view(batch_size, -1))\n return lth_rep\n\n\nif __name__ == '__main__':\n x=torch.rand(64*1*128*128)\n x=x.view(64,1,128,128)\n enc=Encoder(1,1024,64)\n mu,var=enc(x)\n print(mu.shape,var.shape)\n gan=VAE_GAN_Generator(input_channels=1, hidden_size=1024, representation_size=[1024,4,4],output_channels=64)\n a,b,c=gan(x)\n dis=Discriminator()\n d=dis.forward(x)\n e=dis.similarity(x)\n","sub_path":"model/VAE_DCGAN/vae_gan_net.py","file_name":"vae_gan_net.py","file_ext":"py","file_size_in_byte":8558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"401586132","text":"import sys\nsys.path.insert(0, \"../\")\nsys.path.insert(0, \"./\")\nfrom scipy.io import netcdf as nc\nimport subprocess\n\nimport parcel as pc\n\n#checking if chemistry is indeed switched on/off \ndef test_chem_off():\n outfile_on = \"test_on.nc\"\n pc.parcel(outfile=outfile_on, chem_dsl = True, chem_dsc = True, chem_rct = True,\n SO2_g_0 = 200e-12, O3_g_0 = 50e-9, H2O2_g_0 = 500e-12\n )\n nc_on = nc.netcdf_file(outfile_on)\n\n outfile_off = \"test_off.nc\"\n pc.parcel(outfile=outfile_off, chem_dsl = False, chem_dsc = False, chem_rct = False)\n nc_off = nc.netcdf_file(outfile_off)\n\n assert(nc_on.SO2_g_0 > 0)\n assert(nc_off.SO2_g_0 == 0)\n assert(nc_on.variables.has_key(\"SO2_g\"))\n assert(nc_on.variables.has_key(\"SO2_a\"))\n assert(not nc_off.variables.has_key(\"SO2_g\"))\n assert(not nc_off.variables.has_key(\"SO2_a\"))\n\n subprocess.call([\"rm\", outfile_on])\n subprocess.call([\"rm\", outfile_off])\n","sub_path":"unit_test/test_chem_off.py","file_name":"test_chem_off.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"430249218","text":"# 按照Kirk Kaiser的教程 自己敲出来的源码\r\n# 理解了其中思路\r\n# 原文 https://www.makeartwithpython.com/blog/deal-with-it-generator-face-recognition/\r\n# GitHub https://github.com/burningion/automatic-memes\r\n# 需要 ffmpeg\r\n# We'll first import all our tools, and take in an image from the command line\r\n\r\nimport dlib\r\n# a replacement for PIL, the Python Image Library,\r\n# which provides image processing functionality and supports many file formats.\r\n# Use `from PIL import Image` instead of `import Image`.\r\n# 已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。\r\nfrom PIL import Image\r\n# 用于命令行选项,参数和子命令的解析器\r\nimport argparse\r\nfrom imutils import face_utils\r\nimport numpy as np\r\nimport moviepy.editor as mpy\r\n\r\n# 创建解析器\r\nparser = argparse.ArgumentParser()\r\n# 添加参数\r\nparser.add_argument(\"-image\", required=True, help=\"path to input image\")\r\n# 解析参数\r\nargs = parser.parse_args()\r\n\r\n# With this in place, we can then resize our images to fit a smaller width,\r\n# so our gif don't turn out massive, and import our face detector and shape predictors.\r\n#\r\n# We can also open the glasses and text we'll be pasting on to our image.\r\n#\r\n# At this point, we should also detect if there are even any faces detected in the image.\r\n# If not, we should exit immediately.\r\n\r\n# Pycharm 一直找不到引用 但是程序可以正常运行\r\n\r\n# 利用dlib的特征提取器,进行人脸 矩形框 的提取\r\ndetector = dlib.get_frontal_face_detector()\r\n# 利用dlib的68点特征预测器,进行人脸面部轮廓特征提取: \r\npredictor = dlib.shape_predictor('shape_predictor_68.dat')\r\n# resize to a max_width to keep gif size small\r\nmax_width = 500\r\n# open our image, convert to rgba\r\n# 返回此图像的转换副本\r\nimg = Image.open(args.image).convert('RGBA')\r\n# two image we'll need, glasses and deal with it text\r\n# 支持Alpha通道的透明/半透明特性 可以很好的将图像添加到其它图像上面\r\ndeal = Image.open(\"deals.png\")\r\ntext = Image.open(\"text.png\")\r\nif img.size[0] > max_width:\r\n scaled_height = int(max_width * img.size[1] / img.size[0])\r\n # 将此图像制作成缩略图。此方法修改图像以包含其本身的缩略图版本,其大小不超过给定大小。\r\n # 此方法计算适当的缩略图大小以保留图像的方面,调用draft()配置文件阅读器的 方法(适用时),最后调整图像的大小。\r\n # 注意这个函数修改了这个Image 对象。如果您还需要使用全分辨率图像,请将此方法应用于copy()原始图像。\r\n img.thumbnail((max_width, scaled_height))\r\n# need grayscale for dlib face detection\r\nimg_gray = np.array(img.convert('L'))\r\nrects = detector(img_gray, 0)\r\nif len(rects) == 0:\r\n print(\"No faces found,exiting.\")\r\n exit(1)\r\nprint(\"%i faces found in source image. processing into gif now.\" % len(rects))\r\n\r\n# Great! Now we can loop over each of the faces detected,\r\n# and build up a list of scaled and rotated glasses, along with their final positions.\r\nfaces = []\r\nfor rect in rects:\r\n face = {}\r\n print(rect.top(), rect.right(), rect.bottom(), rect.left())\r\n shades_width = rect.right() - rect.left()\r\n # predictor used to detect orientation in place where current face is\r\n shape = predictor(img_gray, rect)\r\n shape = face_utils.shape_to_np(shape)\r\n # grab the outlines of each eye from the input image\r\n leftEye = shape[36:42]\r\n rightEye = shape[42:48]\r\n # compute the center of mass for each eye\r\n leftEyeCenter = leftEye.mean(axis=0).astype(\"int\")\r\n rightEyeCenter = rightEye.mean(axis=0).astype(\"int\")\r\n # compute the angle between by eye centroids\r\n dY = leftEyeCenter[1] - rightEyeCenter[1]\r\n dX = leftEyeCenter[0] - rightEyeCenter[0]\r\n angle = np.rad2deg(np.arctan2(dY, dX))\r\n # resize glasses to fit face width\r\n current_deal = deal.resize((shades_width, int(shades_width * deal.size[1] / deal.size[0])), resample=Image.LANCZOS)\r\n # rotate and flip to fit eye centers\r\n current_deal = current_deal.rotate(angle, expand=True)\r\n current_deal = current_deal.transpose(Image.FLIP_TOP_BOTTOM)\r\n # add the scaled image to list, shift the final position to the left of the leftmost eye\r\n face['glasses_image'] = current_deal\r\n left_eye_x = leftEye[0, 0] - shades_width // 4\r\n left_eye_y = leftEye[0, 1] - shades_width // 6\r\n face['final_pos'] = (left_eye_x, left_eye_y)\r\n faces.append(face)\r\n\r\n# With our final positions in place along with our scaled and rotated glasses,\r\n# we can then put together our movie. We'll set a duration for the whole gif,\r\n# along with a time to stop the glasses coming down, so we can put the deal with it text on the screen.\r\n\r\nduration = 4\r\n\r\n\r\ndef make_frame(t):\r\n # returns copy of original image\r\n draw_img = img.convert('RGBA')\r\n\r\n # no glasses first image\r\n if t == 0:\r\n return np.array(draw_img)\r\n\r\n for face in faces:\r\n if t <= duration - 2: # leave 2 seconds for text\r\n current_x = int(face['final_pos'][0]) # start from proper x\r\n current_y = int(face['final_pos'][1] * t / (duration - 2)) # move to position w/2 secs to spare\r\n draw_img.paste(face['glasses_image'], (current_x, current_y), face['glasses_image'])\r\n else: # draw the text for last 2 seconds\r\n draw_img.paste(face['glasses_image'], face['final_pos'], face['glasses_image'])\r\n draw_img.paste(text, (75, draw_img.height // 2 - 32), text)\r\n\r\n return np.asarray(draw_img)\r\n\r\n\r\n# You'll notice I used an image for the text overlay,\r\n# and not Pillow's built in Text drawing functions.\r\n# I did this because Pillow doesn't have a built in Stroke function for text.\r\n# Without the stroke, the text becomes illegible on brighter images.\r\n#\r\n# Finally, we need to create a VideoClip object in MoviePy, and pass in our animation generating frame along with a fps.\r\nanimation = mpy.VideoClip(make_frame, duration=duration)\r\nanimation.write_gif(\"deal.gif\", fps=4)\r\n\r\n# With this, we're done!\r\n\r\n# Now that we've got a base set for generating our gifs,\r\n# it isn't too difficult to adapt our code to work with the webcam in real time.\r\n#\r\n# Instead of loading our source image from the command line,\r\n# we can use OpenCV as our source images, and keep track of the animations with a counter.\r\n# The new code to do this is pretty straightforward, the real meat being:\r\n","sub_path":"generate_gif.py","file_name":"generate_gif.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"122849682","text":"from django.conf.urls import patterns, url, include\n# from django import forms\n# from prescription.forms import Patientform\n# from django.views.generic.edit import FormView\n\nfrom healthixApp import views\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/$', include(admin.site.urls)),\n url(r'^patient_list/$', views.patientlist, name='patient_list'),\n url(r'^patientcreate$', views.patient, name='patient'),\n url(r'^specialistlist$', views.specialistlist, name='specialistlist'),\n url(r'^createspecialist$', views.specialist, name='createspecialist'),\n url(r'^createcompany$', views.company, name='createcompany'),\n url(r'^companylist$', views.companylist, name='companylist'),\n url(r'^makeappointment$', views.appointment, name='makeappointment'),\n url(r'^appointmentlist$', views.appointmentlist, name='appointmentlist'),\n \n)\n","sub_path":"healthix/healthixApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"502842757","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-02-05 16:36:03\n# @Author : Yan Liu & Zhi Liu (zhiliu.mind@gmail.com)\n# @Link : http://iridescent.ink\n# @Version : $1.0$\n\nimport numpy as np\n\n\ndef nextpow2(x):\n if x == 0:\n y = 0\n else:\n y = np.ceil(np.log2(x))\n\n return y\n","sub_path":"radar/iprs/iprs/dsp/math.py","file_name":"math.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"642910880","text":"'''\r\n3.\tWrite a program that takes a number (1-100) and determines whether this is a product of two Prime numbers.\r\nIf yes, print the two Prime numbers, otherwise print a “try again” message. Allow the user 3 tries.\r\n'''\r\nprimenum = []\r\n\r\ndef findPrime(until):\r\n for num in range(until+1):\r\n isPrime = True\r\n for i in range(num):\r\n if i != 0 and i != 1 and num % i == 0:\r\n isPrime = False\r\n if isPrime and i == num-1:\r\n primenum.append(num)\r\n\r\nfindPrime(100)\r\n\r\ndef checkProduct(product):\r\n product = int(product)\r\n for num in range(len(primenum)):\r\n value = int(product) / int(primenum[num])\r\n for numb in primenum:\r\n if value == numb:\r\n print(str(primenum[num])+\" \"+str(numb))\r\n return True\r\n\r\n\r\n return False\r\n\r\n\r\n\r\nattempts = 3\r\n\r\n\r\nwhile attempts>0:\r\n number = input(str(attempts) + \" Enter a product: \")\r\n if checkProduct(number) == False:\r\n print(\"try again\")\r\n\r\n\r\n\r\n attempts -=1\r\n","sub_path":"Aarsh_Patel_Python/Question_3.py","file_name":"Question_3.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"636248985","text":"from pprint import pprint\n\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.urls import reverse\n\nfrom fo2.connections import db_cursor_so\n\nfrom utils.views import group_rowspan\n\nimport cd.forms\nfrom cd.queries.novo_modulo.grade_cd import grade_estoque\nfrom cd.queries.novo_modulo.lotes_em_estoque import LotesEmEstoque\n\n\nclass Grade(PermissionRequiredMixin, View):\n\n def __init__(self):\n self.permission_required = 'cd.can_view_grades_estoque'\n self.Form_class = cd.forms.AskReferenciaForm\n self.template_name = 'cd/grade_estoque.html'\n self.title_name = 'Seleção de grade de estoque'\n\n def tipo(self, ref):\n if ref[0].isdigit():\n value = ('PA', 1, 'PA/PG')\n elif ref[0] in ('A', 'B'):\n value = ('PG', 2, 'PA/PG')\n elif ref[0] in ('F', 'Z'):\n value = ('MP', 4, 'MP')\n else:\n value = ('MD', 3, 'MD')\n return dict(zip(('tipo', 'ordem', 'grade'), value))\n\n def mount_context(self, request, ref, exec, limpo, page=1, detalhe=False):\n modelos_pagina = 5\n sel_modelos = []\n\n if ref == '':\n exec = 'busca'\n else:\n if ref[0] == '_':\n sel_modelos = ref[1:].split('_')\n ref = 'totais'\n todas = ref == 'todas'\n if todas:\n ref = ''\n exec = 'grade'\n totais = ref == 'totais'\n if totais:\n ref = ''\n exec = 'totais'\n\n refnum_digitos = \"\".join([c for c in ref if c in \"0123456789\"])\n refnum = int(f'0{refnum_digitos}')\n context = {\n 'ref': ref,\n 'refnum': refnum,\n 'detalhe': detalhe,\n 'exec': exec,\n }\n if limpo:\n context['limpo'] = True\n\n # cursor_def = connection.cursor()\n\n if totais:\n self.template_name = 'cd/grade_estoque_totais.html'\n\n if len(ref) == 5: # Referência\n context.update({\n 'link_tot': 1,\n 'link_num': 1,\n 'title_tipo': 1,\n 'link_ref': 1,\n })\n tipo = self.tipo(ref)\n referencias = [{\n 'referencia': ref,\n 'modelo': refnum,\n 'tipo': tipo['tipo'],\n 'ordem_tipo': tipo['ordem'],\n 'grade_tipo': tipo['grade'],\n }]\n modelos = [refnum]\n exec = 'grade'\n else: # Todos ou Modelo ou Totais\n # data_rec = lotes.models.Lote.objects\n # data_rec = data_rec.exclude(\n # local__isnull=True\n # ).exclude(\n # local__exact=''\n # ).exclude(\n # qtd__lte=0)\n\n referencias = LotesEmEstoque(self.cursor_s, get='ref').dados()\n # referencias = data_rec.distinct().values(\n # 'referencia').order_by('referencia')\n for row in referencias:\n row['referencia'] = row['ref']\n row['modelo'] = int(\n ''.join([c for c in row['referencia'] if c.isdigit()]))\n\n if len(sel_modelos) > 0:\n refs_copy = referencias[:]\n referencias = [row for row in refs_copy\n if str(row['modelo']) in sel_modelos]\n\n if refnum == 0: # Todos ou Totais ou busca vazio\n for row in referencias:\n row['referencia|LINK'] = reverse(\n 'cd:grade_estoque', args=[row['referencia']])\n row['modelo|LINK'] = reverse(\n 'cd:grade_estoque', args=[row['modelo']])\n tipo = self.tipo(row['referencia'])\n row['tipo'] = tipo['tipo']\n row['ordem_tipo'] = tipo['ordem']\n row['grade_tipo'] = tipo['grade']\n referencias = sorted(\n referencias, key=lambda k: (\n k['modelo'], k['ordem_tipo'], k['referencia']))\n if exec == 'busca':\n context.update({\n 'link_tot': 1,\n })\n group = ['modelo']\n group_rowspan(referencias, group)\n context.update({\n 'headers': ['Grades por referência numérica', 'Tipo',\n 'Grade de referência'],\n 'fields': ['modelo', 'tipo', 'referencia'],\n 'group': group,\n 'data': referencias,\n })\n else: # exec == 'grade'\n context.update({\n 'link_tot': 1,\n 'link_num': 1,\n 'link_num_hr': 1,\n 'title_tipo': 1,\n 'title_tipo_hr': 1,\n 'link_ref': 1,\n })\n modelos = []\n for ref in referencias:\n if ref['modelo'] not in modelos:\n modelos.append(ref['modelo'])\n else: # Modelo ou busca\n referencias = [\n {'referencia': row['referencia'],\n 'modelo': refnum,\n }\n for row in referencias\n if row['modelo'] == refnum]\n for row in referencias:\n row['referencia|LINK'] = reverse(\n 'cd:grade_estoque', args=[row['referencia']])\n tipo = self.tipo(row['referencia'])\n row['tipo'] = tipo['tipo']\n row['ordem_tipo'] = tipo['ordem']\n row['grade_tipo'] = tipo['grade']\n referencias = sorted(\n referencias, key=lambda k: (\n k['ordem_tipo'], k['referencia']))\n\n if exec == 'busca':\n context.update({\n 'link_tot': 1,\n 'link_num': 1,\n })\n context.update({\n 'headers': ['Tipo', 'Grade de referência'],\n 'fields': ['tipo', 'referencia'],\n 'data': referencias,\n })\n else: # exec == 'grade'\n context.update({\n 'link_tot': 1,\n 'link_num': 1,\n 'title_tipo': 1,\n 'title_tipo_hr': 1,\n 'link_ref': 1,\n })\n modelos = [refnum]\n\n if exec in ['grade', 'totais']:\n if not totais:\n paginator = Paginator(modelos, modelos_pagina)\n try:\n modelos = paginator.page(page)\n except PageNotAnInteger:\n modelos = paginator.page(1)\n except EmptyPage:\n modelos = paginator.page(paginator.num_pages)\n grades_ref = []\n for modelo in modelos:\n refnum_ant = -1\n tipo_ant = '##'\n mod_referencias = [\n ref for ref in referencias if ref['modelo'] == modelo]\n if totais:\n mod_referencias_todos = []\n else: # todos ou modelo\n mod_referencias_todos = mod_referencias\n for row in mod_referencias_todos:\n ref = row['referencia']\n\n invent_ref = grade_estoque(self.cursor_s, tipo='i', ref=ref)\n # invent_ref = queries.grade_solicitacao(\n # cursor_def, ref, tipo='i', grade_inventario=True)\n grade_ref = {\n 'ref': ref,\n 'inventario': invent_ref,\n }\n if refnum_ant != row['modelo']:\n grade_ref.update({'refnum': row['modelo']})\n refnum_ant = row['modelo']\n tipo_ant = '##'\n\n if tipo_ant != row['grade_tipo']:\n grade_ref.update({'tipo': row['grade_tipo']})\n tipo_ant = row['grade_tipo']\n\n pedido_ref = grade_estoque(self.cursor_s, tipo='p', ref=ref)\n total_pedido = pedido_ref['total']\n # sum_pedido = [{'qtd': 2}]\n # sum_pedido = queries.sum_pedido(cursor_def, ref)\n # total_pedido = sum_pedido[0]['qtd']\n if total_pedido is None:\n total_pedido = 0\n\n solped_ref = grade_estoque(self.cursor_s, tipo='sp', ref=ref)\n # solped_ref = queries.grade_solicitacao(\n # cursor_def, ref, tipo='sp', grade_inventario=True)\n if solped_ref['total'] != 0:\n if total_pedido == 0:\n link_detalhe = False\n solped_titulo = 'Solicitações'\n elif solped_ref['total'] == total_pedido:\n link_detalhe = False\n solped_titulo = 'Pedidos'\n else:\n link_detalhe = True\n solped_titulo = 'Solicitações+Pedidos'\n dispon_ref = grade_estoque(self.cursor_s, tipo='i-sp', ref=ref)\n # dispon_ref = queries.grade_solicitacao(\n # cursor_def, ref, tipo='i-sp',\n # grade_inventario=True)\n grade_ref.update({\n 'solped_titulo': solped_titulo,\n 'link_detalhe': link_detalhe,\n 'solped': solped_ref,\n 'disponivel': dispon_ref,\n })\n if detalhe:\n solic_ref = grade_estoque(self.cursor_s, tipo='s', ref=ref)\n # solic_ref = queries.grade_solicitacao(\n # cursor_def, ref, tipo='s',\n # grade_inventario=True)\n if solic_ref['total'] != 0:\n grade_ref.update({\n 'solicitacoes': solic_ref,\n })\n # pedido_ref = grade_estoque(self.cursor_s, tipo='p', ref=ref) # está calculado acima\n # pedido_ref = queries.grade_solicitacao(\n # cursor_def, ref, tipo='p',\n # grade_inventario=True)\n if pedido_ref['total'] != 0:\n grade_ref.update({\n 'pedido': pedido_ref,\n })\n\n grades_ref.append(grade_ref)\n\n refs = []\n if totais:\n totaliza_mais_que = 0\n else:\n totaliza_mais_que = 1\n if len(mod_referencias) > totaliza_mais_que:\n refs = [row['referencia'] for row in mod_referencias\n if row['grade_tipo'] == 'PA/PG']\n\n if len(refs) > totaliza_mais_que:\n dispon_modelo = grade_estoque(self.cursor_s, tipo='i-sp', ref=refs)\n # dispon_modelo = queries.grade_solicitacao(\n # cursor_def, refs, tipo='i-sp')\n if dispon_modelo['total'] != 0:\n\n if totais: # se for totais add borda entre as colunas\n for i in range(1, len(dispon_modelo['fields'])):\n i_column = i + 1\n ori_style = ''\n if i_column in dispon_modelo['style']:\n ori_style = dispon_modelo[\n 'style'][i_column]\n dispon_modelo['style'][i_column] = \\\n ori_style + \\\n 'border-left-style: solid;' \\\n 'border-left-width: thin;'\n\n grade_ref = {\n 'ref': '',\n 'refnum': row['modelo'],\n 'tipo': 'PA/PG',\n 'titulo': 'Total disponível',\n 'inventario': dispon_modelo,\n }\n if totais:\n grade_ref.update({'titulo': '-'})\n grade_ref.update({'refnum': modelo})\n grades_ref.append(grade_ref)\n\n if totais:\n refs = [row['referencia'] for row in referencias\n if row['grade_tipo'] == 'PA/PG']\n dispon_sel_modelo = grade_estoque(self.cursor_s, tipo='i-sp', ref=refs)\n # dispon_sel_modelo = queries.grade_solicitacao(\n # cursor_def, refs, tipo='i-sp')\n\n for i in range(1, len(dispon_sel_modelo['fields'])):\n i_column = i + 1\n ori_style = ''\n if i_column in dispon_sel_modelo['style']:\n ori_style = dispon_sel_modelo[\n 'style'][i_column]\n dispon_sel_modelo['style'][i_column] = \\\n ori_style + \\\n 'border-left-style: solid;' \\\n 'border-left-width: thin;'\n grade_ref = {\n 'ref': '',\n 'tipo': 'PA/PG',\n 'titulo': '-',\n 'inventario': dispon_sel_modelo,\n }\n grade_ref.update({'refnum': 'TOTAL'})\n grades_ref.append(grade_ref)\n\n context.update({\n 'grades': grades_ref,\n 'modelos': modelos,\n 'modelos_pagina': modelos_pagina,\n })\n\n return context\n\n def get(self, request, *args, **kwargs):\n self.cursor_s = db_cursor_so(request)\n page = request.GET.get('page', 1)\n limpo = request.GET.get('limpo', 'N') == 'S'\n if 'referencia' in kwargs and kwargs['referencia'] is not None:\n ref = kwargs['referencia']\n else:\n ref = ''\n if 'detalhe' in kwargs and kwargs['detalhe'] is not None:\n detalhe = kwargs['detalhe'] == 'detalhe'\n else:\n detalhe = False\n context = {'titulo': self.title_name}\n data = self.mount_context(request, ref, 'grade', limpo, page, detalhe)\n context.update(data)\n form = self.Form_class()\n context['form'] = form\n return render(request, self.template_name, context)\n\n def post(self, request, *args, **kwargs):\n self.cursor_s = db_cursor_so(request)\n context = {'titulo': self.title_name}\n form = self.Form_class(request.POST)\n if form.is_valid():\n ref = form.cleaned_data['ref']\n data = self.mount_context(request, ref, 'busca', False)\n context.update(data)\n context['form'] = form\n return render(request, self.template_name, context)\n","sub_path":"src/cd/views/grade_estoque.py","file_name":"grade_estoque.py","file_ext":"py","file_size_in_byte":15795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"206733188","text":"import pygame\n\nW = 800\nH = 600\nBLACK = (0, 0, 0)\nWHITE = (225, 225, 225)\nYELLOW = (225, 225, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 50)\n\npygame.init()\npygame.display.set_caption('Текст')\nscreen = pygame.display.set_mode((W, H))\n\n\nfont = pygame.font.SysFont('Arial', 50, True, False)\nfont_box = pygame.Surface((W - font.get_height(), font.get_height()))\nfont_rect = font_box.get_rect(center=(W - 200, H // 2))\nfont1 = pygame.font.SysFont('Arial', 26, True, False)\nfont1_box = pygame.Surface((W - font1.get_height(), font1.get_height()))\nfont1_rect = font1_box.get_rect(center=(W - 200, H // 2))\n\nscreen.fill(BLUE)\npygame.draw.rect(screen, (RED), (370, 180, 50, 50))\nscreen.blit(font.render('Всем привет', True, WHITE),(font_rect))\nscreen.blit(font1.render('задание на урок', True, YELLOW), (300, 350))\n\n\nprint (font_rect)\n\npygame.display.update()\nrun = True\nwhile run:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n run = False","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"269168316","text":"from aglyph.binder import Binder\nfrom aglyph.component import Reference\n\nfrom movies.lister import MovieLister\nfrom movies.finder import MovieFinder, SQLMovieFinder\n\n\nclass MoviesBinder(Binder):\n\n def __init__(self):\n super(MoviesBinder, self).__init__(\"movies-binder\")\n (self.bind(\"delim-finder\",\n to=\"movies.finder.ColonDelimitedMovieFinder\",\n strategy=\"singleton\").\n init(\"movies.txt\"))\n (self.bind(MovieFinder, to=SQLMovieFinder, strategy=\"borg\").\n init(\"movies.db\"))\n self.bind(MovieLister).init(MovieFinder)\n\n","sub_path":"example/movielisterapp-aglyph/movies/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"238301767","text":"#!/usr/bin/env python\n\n# python-gphoto2 - Python interface to libgphoto2\n# http://github.com/jim-easterbrook/python-gphoto2\n# Copyright (C) 2014-17 Jim Easterbrook jim@jim-easterbrook.me.uk\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\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport logging\nimport os\nimport sys\n\nimport gphoto2 as gp\n\nPHOTO_DIR = os.path.expanduser('~/images/photopoof')\n\ndef get_target_dir(timestamp):\n return os.path.join(PHOTO_DIR)\n\ndef list_computer_files():\n result = []\n for root, dirs, files in os.walk(os.path.expanduser(PHOTO_DIR)):\n for name in files:\n if '.thumbs' in dirs:\n dirs.remove('.thumbs')\n if name in ('.directory',):\n continue\n ext = os.path.splitext(name)[1].lower()\n if ext in ('.db',):\n continue\n result.append(os.path.join(root, name))\n return result\n\ndef list_camera_files(camera, context, path='/'):\n result = []\n # get files\n gp_list = gp.check_result(\n gp.gp_camera_folder_list_files(camera, path, context))\n for name, value in gp_list:\n result.append(os.path.join(path, name))\n # read folders\n folders = []\n gp_list = gp.check_result(\n gp.gp_camera_folder_list_folders(camera, path, context))\n for name, value in gp_list:\n folders.append(name)\n # recurse over subfolders\n for name in folders:\n result.extend(list_camera_files(\n camera, context, os.path.join(path, name)))\n return result\n\ndef get_camera_file_info(camera, context, path):\n folder, name = os.path.split(path)\n return gp.check_result(\n gp.gp_camera_file_get_info(camera, folder, name, context))\n\ndef main():\n logging.basicConfig(\n format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)\n gp.check_result(gp.use_python_logging())\n computer_files = list_computer_files()\n camera = gp.check_result(gp.gp_camera_new())\n context = gp.gp_context_new()\n gp.check_result(gp.gp_camera_init(camera, context))\n print('Getting list of files from camera...')\n camera_files = list_camera_files(camera, context)\n if not camera_files:\n print('No files found')\n return 1\n print('Copying files...')\n for path in camera_files:\n info = get_camera_file_info(camera, context, path)\n timestamp = datetime.fromtimestamp(info.file.mtime)\n folder, name = os.path.split(path)\n dest_dir = get_target_dir(timestamp)\n dest = os.path.join(dest_dir, name)\n if dest in computer_files:\n continue\n print('%s -> %s' % (path, dest_dir))\n if not os.path.isdir(dest_dir):\n os.makedirs(dest_dir)\n camera_file = gp.check_result(gp.gp_camera_file_get(\n camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context))\n gp.check_result(gp.gp_file_save(camera_file, dest))\n gp.check_result(gp.gp_camera_exit(camera, context))\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"mini/camera_downloader.py","file_name":"camera_downloader.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"492606265","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n所有的tensor都要命名便于索引和使用,所有的程序都可以放在session中设计,\r\n计算图可以保存和继续训练的关键在于变量tensor的命名始终保持一致,\r\n因为最终也是为了获得更合适的变量。\r\n\r\n版本3的改进地方:1、参数初始化改为正太分布(0,1);2、采用正则化方法增加泛化性能;\r\n3、采用随步数而减小的学习率;4、适当引入tf的高层API;5、是否可以采用抽样降低\r\n训练数据的不对称性造成的损失失衡?。【2、4、5】留着在下一版本中探索研究.\r\n6、AdaGrad,一种先进的梯度下降法,用于重新调整每个参数的梯度,以便有效地为每个参数\r\n指定独立的学习速率;7、特征组合 (feature cross)通过将单独的特征进行组合(相乘或\r\n求笛卡尔积)而形成的合成特征。特征组合有助于表示非线性关系;8、梯度裁剪 (gradient \r\nclipping)在应用梯度值之前先设置其上限,梯度裁剪有助于确保数值稳定性以及防止梯度爆炸;\r\n9、合页损失函数 (hinge loss)一系列用于分类的损失函数,旨在找到距离每个训练样本都\r\n尽可能远的决策边界,从而使样本和边界之间的裕度最大化, KSVM 使用合页损失函数(或\r\n相关函数,例如平方合页损失函数);10、L1 损失函数 (L₁ loss)一种损失函数,\r\n基于模型预测的值与标签的实际值之差的绝对值,与 L2 损失函数相比,L1 损失函数对\r\n离群值的敏感性弱一些,L1 正则化 (L₁ regularization)一种正则化,根据权重的绝对值的\r\n总和来惩罚权重。在依赖稀疏特��的模型中,L1 正则化有助于使不相关或几乎不相关的特征的\r\n权重正好为 0,从而将这些特征从模型中移除,与 L2 正则化相对。L2 损失函数 (L₂ loss)请\r\n参阅平方损失函数。L2 正则化 (L₂ regularization)一种正则化,根据权重的平方和来\r\n惩罚权重。L2 正则化有助于使离群值(具有较大正值或较小负值)权重接近于 0,但又\r\n不正好为 0。(与 L1 正则化相对。)在线性模型中,L2 正则化始终可以改进泛化。\r\n11、对数损失函数 (Log Loss)二元逻辑回归中使用的损失函数。12、Metrics API (\r\ntf.metrics)一种用于评估模型的 TensorFlow API。例如,tf.metrics.accuracy 用于\r\n确定模型的预测与标签匹配的频率。在编写自定义 Estimator 时,您可以调用 Metrics API\r\n 函数来指定应如何评估您的模型。13、小批次随机梯度下降法 (SGD, mini-batch \r\n stochastic gradient descent)会根据一小部分训练数据来估算梯度。13、动量 (Momentum)\r\n一种先进的梯度下降法,其中学习步长不仅取决于当前步长的导数,还取决于之前一步或多步的\r\n步长的导数。动量涉及计算梯度随时间而变化的指数级加权移动平均值,与物理学中的动量类似\r\n。动量有时可以防止学习过程被卡在局部最小的情况。14、时间序列分析 (time series \r\nanalysis);15、宽度模型 (wide model)一种线性模型,通常有很多稀疏输入特征。我们\r\n之所以称之为“宽度模型”,是因为这是一种特殊类型的神经网络,其大量输入均直接与\r\n输出节点相连。与深度模型相比,宽度模型通常更易于调试和检查。虽然宽度模型无法通过\r\n隐藏层来表示非线性关系,但可以利用特征组合、分桶等转换以不同的方式为非线性关系建模。\r\n与深度模型相对。16、Estimator (tf.estimator)\t高级 OOP API。\r\ntf.layers/tf.losses/tf.metrics\t用于常见模型组件的库。\r\nTensorFlow\t低级 API\r\n17、先映射到可视化空间、再分类;\r\n\"\"\"\r\n\r\nimport pymysql as pdb\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.special import comb\r\n#import statsmodels.api as sm #导入统计模型,可以和numpy、pandas紧密搭配使用\r\n\r\n\r\ndef to_db(db=\"fund_train\"):\r\n return pdb.connect(host=\"localhost\",\r\n port=3306,\r\n user=\"root\",\r\n passwd=\"123456\",\r\n db=db,\r\n charset=\"utf8\")\r\n\r\nft=to_db(\"wangkaibiao\")\r\nft_cursor=ft.cursor()\r\n\r\nft_cursor.execute(\"show tables\")\r\ntrain_table=ft_cursor.fetchall()[0][0]\r\nprint(train_table)\r\n \r\n\r\ndef visual_bp_fund(X,Y,x_size=60,k1=1,k11=2,step=200*100,log_dir_n=\"aaa\",\r\n lr=0.001,save=\"y\",g_name=\"visual_bp_fund\"):\r\n with tf.Graph().as_default() as g_name:\r\n samp_size=len(Y)\r\n Xtrain= tf.placeholder(tf.float32,[samp_size,x_size],\r\n name=\"Xtrain\") \r\n Ytrain= tf.placeholder(tf.float32,[samp_size,1],name=\"Ytrain\")\r\n \r\n \r\n #①处理数据、先映射到二维空间\r\n weights1=tf.Variable(tf.truncated_normal(\r\n [x_size,x_size+1+k1],stddev=1.0),name=\"weights1\")\r\n #切刀至高维面\r\n tf.summary.histogram(\"h_weights1\",weights1)\r\n biass1=tf.Variable(tf.truncated_normal(\r\n [1,x_size+1+k1],stddev=1.0),name=\"biass1\")\r\n tf.summary.histogram(\"h_biass1\",biass1)\r\n\r\n neural_num=int(comb(x_size+1+k1,x_size+1))\r\n\r\n weights2=tf.Variable(tf.truncated_normal(\r\n [x_size+1+k1,neural_num],stddev=1.0),name=\"weights2\")\r\n #组合高维面到高维体\r\n tf.summary.histogram(\"h_weights2\",weights2)\r\n biass2=tf.Variable(tf.truncated_normal(\r\n [1,neural_num],stddev=1.0),name=\"biass2\")\r\n tf.summary.histogram(\"h_biass2\",biass2)\r\n \r\n weights3=tf.Variable(tf.truncated_normal(\r\n [neural_num,2],stddev=1.0),name=\"weights3\")\r\n #高维体组合映射到二维空间\r\n tf.summary.histogram(\"h_weights3\",weights3)\r\n biass3=tf.Variable(tf.truncated_normal(\r\n [1,2],stddev=1.0),name=\"biass3\")\r\n tf.summary.histogram(\"h_biass3\",biass3)\r\n \r\n \r\n #②再从二维空间划分(原理仍是重复上面)\r\n weights11=tf.Variable(tf.truncated_normal(\r\n [2,2+1+k11],stddev=1.0),name=\"weights11\")\r\n tf.summary.histogram(\"h_weights11\",weights11)\r\n biass11=tf.Variable(tf.truncated_normal(\r\n [1,2+1+k11],stddev=1.0),name=\"biass11\")\r\n tf.summary.histogram(\"h_biass11\",biass11)\r\n\r\n neural_num2=int(comb(2+1+k11,2+1))\r\n\r\n weights21=tf.Variable(tf.truncated_normal(\r\n [2+1+k11,neural_num2],stddev=1.0),name=\"weights21\")\r\n tf.summary.histogram(\"h_weights21\",weights21)\r\n biass21=tf.Variable(tf.truncated_normal(\r\n [1,neural_num2],stddev=1.0),name=\"biass21\")\r\n tf.summary.histogram(\"h_biass21\",biass21)\r\n \r\n weights31=tf.Variable(tf.truncated_normal(\r\n [neural_num2,1],stddev=1.0),name=\"weights31\")\r\n tf.summary.histogram(\"h_weights31\",weights31)\r\n biass31=tf.Variable(tf.truncated_normal(\r\n [1,1],stddev=1.0),name=\"biass31\")\r\n tf.summary.histogram(\"h_biass31\",biass31) \r\n\r\n\r\n #③开始设计具体网络结构,首尾不变、变的只是中间的结构,也不影响数据结构\r\n l1_out=tf.tanh(tf.matmul(Xtrain,weights1)+biass1,name=\"l1_out\")\r\n #tf.nn.relu tf.sigmoid # relu是激励函数的一种\r\n l2_out=tf.tanh(tf.matmul(l1_out,weights2)+biass2,name=\"l2_out\")\r\n visual_predic_op=tf.nn.relu(tf.matmul(l2_out,weights3)+biass3,\r\n name=\"visual_predic_op\")\r\n tf.summary.histogram(\"visual_predic_op\",visual_predic_op)\r\n \r\n l11_out=tf.tanh(tf.matmul(visual_predic_op,weights11)+biass11,\r\n name=\"l11_out\")\r\n l21_out=tf.tanh(tf.matmul(l11_out,weights21)+biass21,name=\"l21_out\")\r\n predic_op=tf.sigmoid(tf.matmul(l21_out,weights31)+biass31,\r\n name=\"predic_op\")#加上这条才能在预测时调用\r\n tf.summary.histogram(\"predic_op\",predic_op)\r\n \r\n loss = tf.reduce_mean(tf.square(Ytrain-predic_op),\r\n name=\"loss_reduce_mean\")\r\n tf.summary.scalar(\"s_loss\",loss)\r\n tf.summary.histogram(\"h_loss\",loss)\r\n \r\n# train=tf.train.MomentumOptimizer(lr,0.9).minimize(loss)\r\n train=tf.train.AdamOptimizer(\r\n learning_rate=lr,beta1=0.9,\r\n beta2=0.999, epsilon=1e-08).minimize(loss)\r\n \r\n merged = tf.summary.merge_all()\r\n #收集数据但也需要数据来计算,也是图的元素之一\r\n \r\n model_dir=\"a_fund_trade/tf_continue_train/\"+log_dir_n\r\n saver = tf.train.Saver()#模型建立之后再定义saver\r\n with tf.Session() as sess:\r\n try:\r\n run=\"try\"\r\n saver.restore(sess,model_dir+\"/bp_fund-200\")\r\n print(\"该步执行的是try加载参数模型\")\r\n except:#★★★非常关键的一步:决定模型能否持续★★★\r\n run=\"except\"\r\n tf.global_variables_initializer().run()\r\n print(\"该步执行的是except新建参数\")\r\n \r\n writer = tf.summary.FileWriter(model_dir+\"/\",graph=sess.graph)\r\n \r\n for i in range(step):\r\n# lr_t=lr*(1-i/step)#学习率随步数减少,这种损失呈现线性递减\r\n# #还一种学习率是:lr/sqrt(i),这种损失应该呈现非线性递减\r\n# train=tf.train.GradientDescentOptimizer(lr_t).minimize(loss) \r\n# # 选择梯度下降法 \r\n sess.run(train,feed_dict={Xtrain:X,Ytrain:Y}) \r\n if (i+1)%200 == 0:\r\n print(i,\"步:学习率为 %s\"%\"lr_t\",\r\n \" ;损失为 %s\"%sess.run(loss,\r\n feed_dict={Xtrain:X,Ytrain:Y}))\r\n rs=sess.run(merged,feed_dict={Xtrain:X,Ytrain:Y}) \r\n writer.add_summary(rs,(i+1))\r\n #writer必须配合独立新Graph使用,否则会报错没有给占位符传入数据 \r\n if run==\"try\" and save==\"y\":\r\n saver.save(sess,model_dir+\"/bp_fund\",\r\n global_step=200,write_meta_graph=False)\r\n #此处的路径不能用占位符来替换、但能用加号连接字符串\r\n #\"+log_dir_n+\",否则运行之后会报错,也可能是write_meta_graph\r\n #每次都操作的原因,所以加上if判断。此外文件夹名字不能太短\r\n if run==\"except\" and save==\"y\":\r\n saver.save(sess,model_dir+\"/bp_fund\",\r\n global_step=200,write_meta_graph=True)\r\n \r\n #训练结束,执行一次预测过程,如果结果太大就要避免计算占用过多内存 \r\n print(\"predic:\",\"sess.run(predic_op,{Xtrain:X,Ytrain:Y})\"\r\n ,\"__loss:\",sess.run(loss,feed_dict={Xtrain:X,Ytrain:Y})) \r\n #sess.close()#with情况下不需要\r\n\r\n\r\n#运行上面的代码,在当前目录下新生成一个名为logs的文件夹,里边有汇总的记录\r\n#打开cmd,���载D:\\pymoney\\DeepLearn35,输入tensorboard --logdir logs\r\n#生成一个链接http://LAPTOP-CF0R75NC:6006,复制在google浏览器(火狐也行)粘贴显示\r\n\r\n\r\n#实际训练学习\r\ndef average_continue_train(tb=\"1mon_ave_aft_2week_divided_3day_ave\",smp=200000,\r\n avg_rate=0.05,raten=\"3\",\r\n x_size=60,k1=1,k11=2,step=200*5,log_dir_n=\"aaa\",lr=0.001,\r\n save=\"y\",g_name=\"visual_bp_fund\"):\r\n count_sql='select count(*) from %s'%tb\r\n ft_cursor.execute(count_sql)\r\n count_train=ft_cursor.fetchall()\r\n batchs=count_train[0][0] // smp#整除是往上取,实际上是多出一部分的\r\n \r\n for i in range(batchs+1):\r\n #slsql=\"select * from grow_rate1 limit 7,6 \"#从第8条开始取,取6条\r\n if i == batchs:\r\n break#不要尾巴数据了\r\n# samp_num=count_train[0][0]-smp*i \r\n else:\r\n samp_num=smp\r\n slsql=\"select * from %s limit %d,%d \"%(tb,smp*i,samp_num)\r\n print(slsql) \r\n ft_cursor.execute(slsql)#16613\r\n res=np.array(ft_cursor.fetchall())\r\n #准备训练的Y数据\r\n if raten==\"3\":#使用1个月比3个月的数据\r\n rate3_1=[eval(rate) for rate in res[:,1]]\r\n# max(rate3_1),min(rate3_1)# (0.63950136964548, -0.358762528334373)\r\n if raten==\"2\":#使用1个月比2个月的数据\r\n rate3_1=[eval(rate) for rate in res[:,2]]\r\n if raten==\"1\":#使用1个月比1个月的数据\r\n rate3_1=[eval(rate) for rate in res[:,3]]\r\n samples=len(rate3_1)##16613\r\n# plt.scatter(np.arange(0,samples,1),rate3_1)\r\n# plt.hist(rate3_1,bins=np.arange(-0.3,0.4,0.05)) \r\n Ytrain=np.zeros((samples,1))\r\n for i in range(samples):\r\n if rate3_1[i]>avg_rate:\r\n Ytrain[i]=1\r\n# plt.hist(Ytrain,bins=np.arange(-1,3,0.5))#1占25%左右 \r\n #准备训练的X数据\r\n nets=[eval(net)[0:x_size] for net in res[:,2]]\r\n# nets[0]\r\n Xtrain=np.array(nets)\r\n #开始训练\r\n visual_bp_fund(Xtrain,Ytrain,x_size=x_size,k1=k1,k11=k11,step=step,\r\n g_name=g_name,log_dir_n=log_dir_n,lr=lr,save=save)\r\n\r\n \r\ndef del_str_x(x_train,y_train):\r\n# tt=np.array([\"1\",\"2\",\"我\",\"4\",\"5\"]).astype(\"float32\")\r\n# #ValueError: could not convert string to float: '我'\r\n# type(tt[0])#numpy.float32\r\n# type(x_train[0][0])#numpy.str_\r\n# x_train[0].astype(\"float32\")#可以执行\r\n# np.shape(y_train)#(123170,)\r\n# np.shape(x_train)#(123170, 60)\r\n# test=np.delete(x_train,[1,2,3])\r\n# np.shape(test)#(7390197,)\r\n# test1=np.delete(x_train,[1,2,3],axis=0)#axis=0表示行,axis=1表示列\r\n# np.shape(test1)#(123167, 60)\r\n contain_str_index=[]\r\n i=0\r\n for x in x_train:\r\n try:\r\n x.astype(\"float32\")\r\n except:\r\n contain_str_index.append(i) \r\n i+=1\r\n new_x_train=np.delete(x_train,contain_str_index,axis=0).astype(\"float32\")\r\n new_y_train=np.delete(y_train,contain_str_index,axis=0)\r\n return new_x_train,new_y_train,len(contain_str_index)\r\n \r\ndef max_continue_train(tb=\"grow_rate_randorder\",smp=200000,max_rate=0.04,\r\n raten=\"1\",x_size=60,k1=1,k11=2,step=200*5,\r\n log_dir_n=\"qqq\",lr=0.001,save=\"y\",g_name=\"bp_fund_max\"):\r\n count_sql='select count(*) from %s'%tb\r\n ft_cursor.execute(count_sql)\r\n count_train=ft_cursor.fetchall()\r\n batchs=count_train[0][0] // smp#整除是往上取,实际上是多出一部分的\r\n \r\n for i in range(batchs+1):\r\n #slsql=\"select * from grow_rate1 limit 7,6 \"#从第8条开始取,取6条\r\n if i == batchs:\r\n break#不要尾巴数据了\r\n# samp_num=count_train[0][0]-smp*i \r\n else:\r\n samp_num=smp\r\n# i=0\r\n slsql=\"select * from %s limit %d,%d \"%(tb,smp*i,samp_num)\r\n print(slsql) \r\n ft_cursor.execute(slsql)#16613\r\n res=np.array(ft_cursor.fetchall())\r\n #ValueError: could not convert string to float: \r\n #说明里边肯定有字符串\r\n# type(float(res[:,1:2][0][0])-1)\r\n if raten==\"3\":#使用1个月比3个月的数据\r\n y_train=res[:,3:4]\r\n# max(rate3_1),min(rate3_1)# (0.63950136964548, -0.358762528334373)\r\n if raten==\"2\":#使用1个月比2个月的数据\r\n y_train=res[:,2:3]\r\n if raten==\"1\":#使用1个月比1个月的数据\r\n y_train=res[:,1:2] \r\n x_train=res[:,4:] \r\n# print(np.shape(x_train),np.shape(y_train))#(200000, 60) (200000, 1)\r\n #删除无效数据\r\n new_x_train,new_y_train,dels=del_str_x(x_train,y_train)\r\n# float(new_y_train[0])\r\n# type(new_x_train[0])\r\n print(np.shape(new_x_train),np.shape(new_y_train))\r\n #(199997, 60) (199997, 1)\r\n# print(len(new_x_train[0:1,0:][0]))#60\r\n #准备训练的Y数据\r\n samples=samp_num-dels#199997\r\n# plt.scatter(np.arange(0,samples,1),rate3_1)\r\n# plt.hist(rate3_1,bins=np.arange(-0.3,0.4,0.05)) \r\n Ytrain=np.zeros((samples,1))\r\n for i in range(samples):\r\n if float(new_y_train[i])>max_rate:\r\n Ytrain[i]=1\r\n# plt.hist(Ytrain,bins=np.arange(-1,3,0.5))#1占25%左右 \r\n #开始训练\r\n visual_bp_fund(new_x_train,Ytrain,x_size=x_size,k1=k1,k11=k11,\r\n step=step,g_name=g_name,log_dir_n=log_dir_n,lr=lr,\r\n save=save)\r\n \r\n \r\naverage_continue_train(smp=20000,avg_rate=0.01,raten=\"3\",x_size=60,\r\n g_name=\"visual_bp_fund\",k1=1,k11=3,step=200*70,\r\n log_dir_n=\"vaaa\",lr=0.001,save=\"y\")\r\n\r\nmax_continue_train(smp=200000,max_rate=0.04,raten=\"3\",x_size=60,\r\n g_name=\"bp_fund_max\",k1=1,k11=6,step=200*70,\r\n log_dir_n=\"vbbb\",lr=0.001,save=\"y\") \r\n\r\n\r\ndef average_test_predict(tb=\"grow_rand\",raten=\"3\",x_size=20,smp=200000,\r\n avg_rate=0.03,standard=0.95,log_dir_n=\"fff\"):\r\n #用剩下的尾巴数据测试准确率\r\n count_sql='select count(*) from %s'%tb\r\n ft_cursor.execute(count_sql)\r\n count_train=ft_cursor.fetchall()\r\n batchs=count_train[0][0] // smp#整除是往上取,实际上是多出一部分的。=7 \r\n samp_num=count_train[0][0]-smp*batchs \r\n\r\n slsql=\"select * from %s limit %d,%d \"%(tb,smp*batchs,samp_num)\r\n print(slsql) \r\n ft_cursor.execute(slsql)#36613\r\n res=np.array(ft_cursor.fetchall())\r\n print(\"test样本数量为:%s\"%len(res))#36613\r\n #准备测试的Y数据\r\n rate1=[eval(rate) for rate in res[:,1]]\r\n rate2=[eval(rate) for rate in res[:,1]]\r\n rate3=[eval(rate) for rate in res[:,1]]\r\n if raten==\"3\":#使用1个月比3个月的数据\r\n rate3_1=rate1\r\n# max(rate3_1),min(rate3_1)# (0.63950136964548, -0.358762528334373)\r\n if raten==\"2\":#使用1个月比2个月的数据\r\n rate3_1=rate2\r\n if raten==\"1\":#使用1个月比1个月的数据\r\n rate3_1=rate3\r\n samples=len(rate3_1)##16613\r\n# plt.scatter(np.arange(0,samples,1),rate3_1)\r\n# plt.hist(rate3_1,bins=np.arange(-0.3,0.4,0.05)) \r\n Ytest=np.zeros((samples,1))\r\n for i in range(samples):\r\n if rate3_1[i]>avg_rate:\r\n Ytest[i]=1\r\n# plt.hist(Ytrain,bins=np.arange(-1,3,0.5))#1占25%左右 \r\n #准备测试的X数据\r\n nets=[eval(net)[0:x_size] for net in res[:,2]]\r\n# nets[0]\r\n Xtest=np.array(nets)\r\n #检验算法的正确性\r\n try:\r\n nets_remain=[eval(net)[x_size:x_size+20] for net in res[:,2]]\r\n sum_nets_remain=np.array(\r\n [np.sum(nets_remain[i]) for i in range(samples)])\r\n sum_nets=np.array([np.sum(nets[i]) for i in range(samples)])\r\n cal_false=np.sum(np.sqrt(np.square(\r\n sum_nets_remain/sum_nets*x_size/20-1-rate3_1)))\r\n print(\"x维度为%s、样本量为%s时的总算法失误为:%s\"%(x_size,\r\n samples,cal_false))\r\n except:\r\n print(\"try必须配合except使用,当前x_size=60\") \r\n #开始测试 \r\n Ypre=np.zeros((samples,1)) \r\n with tf.Graph().as_default() as bp_fund:#这条必须得加\r\n with tf.Session() as sess:\r\n #先加载图和参数变量\r\n model = tf.train.import_meta_graph(\r\n \"a_fund_trade/tf_continue_train/\"+log_dir_n+\"/bp_fund-200.meta\")\r\n model.restore(sess, tf.train.latest_checkpoint(\r\n \"a_fund_trade/tf_continue_train/\"+log_dir_n))\r\n graph = tf.get_default_graph()\r\n # 访问placeholders变量,并且创建feed-dict来作为placeholders的新值\r\n weights1=graph.get_tensor_by_name(\"weights1:0\") \r\n biass1=graph.get_tensor_by_name(\"biass1:0\") \r\n weights2=graph.get_tensor_by_name(\"weights2:0\") \r\n biass2=graph.get_tensor_by_name(\"biass2:0\")\r\n weights3=graph.get_tensor_by_name(\"weights3:0\")\r\n biass3=graph.get_tensor_by_name(\"biass3:0\") \r\n# X_test = graph.get_tensor_by_name(\"Xtrain:0\")#这样必须同原模型的参数\r\n X_test= tf.placeholder(tf.float32,[samples,x_size])\r\n Y_test= tf.placeholder(tf.float32,[samples,1])\r\n #接下来,访问你想要执行的op\r\n l1_out=tf.tanh(tf.matmul(X_test,weights1)+biass1)\r\n #tf.nn.relu # relu是激励函数的一种\r\n l2_out=tf.tanh(tf.matmul(l1_out,weights2)+biass2)\r\n predic_op=tf.sigmoid(tf.matmul(l2_out,weights3)+biass3)\r\n loss = tf.reduce_mean(tf.square(Ytest-predic_op))\r\n \r\n pre_loss=sess.run(loss,feed_dict ={X_test:Xtest,Y_test:Ytest} )\r\n print(\"测试损失为:%s\"%pre_loss)\r\n\r\n pre=sess.run(predic_op,feed_dict ={X_test:Xtest} )\r\n plt.hist(pre,bins=np.arange(0,1,0.05))\r\n for i in range(samples):\r\n if pre[i]>standard:\r\n Ypre[i]=1\r\n plt.scatter(Ytest,Ypre)#有4个分布的点就说明预测不是百分之百的准确\r\n# plt.hist(Ypre,bins=np.arange(-1,2,0.05))\r\n# plt.hist(Ytest,bins=np.arange(-1,2,0.05))\r\n #计算预测准确率:预测为1中实际为1的占比\r\n Ypre_1_count=0\r\n YY_1_count=0 \r\n for i in range(samples):\r\n if Ypre[i]==1:\r\n Ypre_1_count +=1\r\n if Ytest[i]==1:\r\n YY_1_count +=1\r\n print(\"预测准确率为:%s%%\"%round(YY_1_count/Ypre_1_count*100,2))\r\n ft.close()\r\n \r\n \r\ndef max_test_predict(tb=\"grow_rate_randorder\",raten=\"1\",x_size=60,\r\n smp=200000,max_rate=0.04,standard=0.95,\r\n log_dir_n=\"qqq\",g_name=\"bp_fund_max\"):\r\n #用剩下的尾巴数据测试准确率\r\n count_sql='select count(*) from %s'%tb\r\n ft_cursor.execute(count_sql)\r\n count_train=ft_cursor.fetchall()\r\n batchs=count_train[0][0] // smp#整除是往上取,实际上是多出一部分的。=7 \r\n samp_num=count_train[0][0]-smp*batchs \r\n\r\n slsql=\"select * from %s limit %d,%d \"%(tb,smp*batchs,samp_num)\r\n print(slsql) \r\n ft_cursor.execute(slsql)\r\n res=np.array(ft_cursor.fetchall())\r\n print(\"test样本数量为:%s\"%len(res))#123170\r\n #准备测试的数据\r\n if raten==\"3\":#使用1个月比3个月的数据\r\n y_test=res[:,3:4]\r\n if raten==\"2\":#使用1个月比2个月的数据\r\n y_test=res[:,2:3]\r\n if raten==\"1\":#使用1个月比1个月的数据\r\n y_test=res[:,1:2] \r\n x_test=res[:,4:] \r\n #删除无效数据\r\n new_x_test,new_y_test,dels=del_str_x(x_test,y_test)\r\n print(np.shape(new_x_test),np.shape(new_y_test))\r\n samples=samp_num-dels#123170\r\n# plt.scatter(np.arange(0,samples,1),y_test)\r\n# plt.hist(y_test,bins=np.arange(-0.3,0.4,0.05)) \r\n Ytest=np.zeros((samples,1))\r\n for i in range(samples):\r\n if float(new_y_test[i])>max_rate:\r\n Ytest[i]=1\r\n# plt.hist(Ytest,bins=np.arange(-1,3,0.5))#1占33%左右 \r\n #检验数据整理的正确性\r\n# try:\r\n# nets_remain=[eval(net)[x_size:x_size+20] for net in res[:,4]]\r\n# sum_nets_remain=np.array(\r\n# [np.sum(nets_remain[i]) for i in range(samples)])\r\n# sum_nets=np.array([np.sum(nets[i]) for i in range(samples)])\r\n# cal_false=np.sum(np.sqrt(np.square(\r\n# sum_nets_remain/sum_nets*x_size/20-1-rate3_1)))\r\n# print(\"x维度为%s、样本量为%s时的总算法失误为:%s\"%(x_size,\r\n# samples,cal_false))\r\n# except:\r\n# print(\"try必须配合except使用,当前x_size=60\") \r\n #开始测试 \r\n Ypre=np.zeros((samples,1)) \r\n with tf.Graph().as_default() as g_name:#这条必须得加\r\n with tf.Session() as sess:\r\n #先加载图和参数变量\r\n model = tf.train.import_meta_graph(\r\n \"fundlogs/\"+log_dir_n+\"/bp_fund-200.meta\")\r\n model.restore(sess, tf.train.latest_checkpoint(\r\n \"fundlogs/\"+log_dir_n))\r\n graph = tf.get_default_graph()\r\n # 访问placeholders变量,并且创建feed-dict来作为placeholders的新值\r\n weights1=graph.get_tensor_by_name(\"weights1:0\") \r\n biass1=graph.get_tensor_by_name(\"biass1:0\") \r\n weights2=graph.get_tensor_by_name(\"weights2:0\") \r\n biass2=graph.get_tensor_by_name(\"biass2:0\")\r\n weights3=graph.get_tensor_by_name(\"weights3:0\")\r\n biass3=graph.get_tensor_by_name(\"biass3:0\") \r\n# X_test = graph.get_tensor_by_name(\"Xtrain:0\")#这样必须同原模型的参数\r\n X_test= tf.placeholder(tf.float32,[samples,x_size])\r\n Y_test= tf.placeholder(tf.float32,[samples,1])\r\n #接下来,访问你想要执行的op\r\n l1_out=tf.tanh(tf.matmul(new_x_test,weights1)+biass1)\r\n #tf.nn.relu # relu是激励函数的一种\r\n l2_out=tf.tanh(tf.matmul(l1_out,weights2)+biass2)\r\n predic_op=tf.sigmoid(tf.matmul(l2_out,weights3)+biass3)\r\n loss = tf.reduce_mean(tf.square(Ytest-predic_op))\r\n \r\n pre_loss=sess.run(loss,feed_dict ={X_test:new_x_test,Y_test:Ytest} )\r\n print(\"测试损失为:%s\"%pre_loss)\r\n\r\n pre=sess.run(predic_op,feed_dict ={X_test:new_x_test} )\r\n plt.hist(pre,bins=np.arange(0,1,0.05))\r\n for i in range(samples):\r\n if pre[i]>standard:\r\n Ypre[i]=1\r\n plt.scatter(Ytest,Ypre)#有4个分布的点就说明预测不是百分之百的准确\r\n# plt.hist(Ypre,bins=np.arange(-1,2,0.05))\r\n# plt.hist(Ytest,bins=np.arange(-1,2,0.05))\r\n #计算预测准确率:预测为1中实际为1的占比\r\n Ypre_1_count=0\r\n YY_1_count=0 \r\n for i in range(samples):\r\n if Ypre[i]==1:\r\n Ypre_1_count +=1\r\n if Ytest[i]==1:\r\n YY_1_count +=1\r\n print(\"预测准确率(而不是完整率)为:%s%%\"%round(\r\n YY_1_count/Ypre_1_count*100,2))\r\n\r\naverage_test_predict(tb=\"1mon_ave_aft_2week_divided_3day_ave\",\r\n raten=\"3\",x_size=60,smp=20000,\r\n avg_rate=0.01,standard=0.95,log_dir_n=\"vaaa\")\r\n\r\nmax_test_predict(tb=\"grow_rate_randorder\",raten=\"1\",x_size=60,\r\n smp=200000,max_rate=0.04,standard=0.99,\r\n log_dir_n=\"qqq\",g_name=\"bp_fund_max\")\r\n \r\n\r\n\r\n\r\n\r\n\r\n ","sub_path":"service/wkb/tf_continue_train/train_fund.py","file_name":"train_fund.py","file_ext":"py","file_size_in_byte":27521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"459836124","text":"#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\nimport os\nimport argparse\n\nfrom young_tools.argument import Argument\n\nclass DeTokenizerArgument(Argument):\n def _add_items(self):\n group = self._argument_parser.add_argument_group('DeTokenizer Scripts!\\n')\n group.add_argument('-i', '--input-file', type=str, required=True)\n group.add_argument('-o', '--output-file', type=str, required=True)\n group.add_argument('-l', '--language', type=str, required=True)\n \n\nMosesRoot='~/3PartyTools/MosesDecoder_v4.0'\nMosesScripts='{}/scripts'.format(MosesRoot)\nMosesDeTokenizer='{}/tokenizer/detokenizer.perl'.format(MosesScripts)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n argument = DeTokenizerArgument(parser)\n arguments = argument.items\n language = arguments.language\n input_file = arguments.input_file\n output_file = arguments.output_file\n os.system('{} -l {} < {} > {}'.format(MosesDeTokenizer, language, input_file, output_file))\n \nif __name__ == \"__main__\" :\n main()\n","sub_path":"DeTokenizer.py","file_name":"DeTokenizer.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"645953085","text":"from Ray import Ray\nfrom Engine import Object, ToolCollection\nfrom pygame import Surface, K_d, K_a, K_s, K_w, K_LSHIFT, Vector2, draw\n\n\ndef create_sprite():\n image = Surface((32, 32))\n rect = image.get_rect()\n draw.circle(image, (255, 0, 0), rect.center, 16, 2)\n draw.line(image, (0, 255, 0), rect.center, rect.midtop, 2)\n return image\n\n\nclass Actor(Object):\n\n def update(self, Tools: ToolCollection):\n\n self.speed = 100\n move = Vector2(0.0, 0.0)\n\n if Tools.Input.is_pressed(K_LSHIFT):\n self.speed *= 1.5\n\n if Tools.Input.is_pressed(K_d):\n self.rotate(-self.rotation_speed * Tools.Time.delta_time)\n\n if Tools.Input.is_pressed(K_a):\n self.rotate(self.rotation_speed * Tools.Time.delta_time)\n\n if Tools.Input.is_pressed(K_w):\n move.y = -1\n\n if Tools.Input.is_pressed(K_s):\n move.y = 1\n\n if move.length() > 0:\n move = move.rotate(-self.rotation).normalize()\n self.move(move * self.speed * Tools.Time.delta_time)\n\n def __init__(self):\n Object.__init__(self, create_sprite())\n self.speed = 100.0\n self.rotation_speed = 270\n self.rays = set(Ray(self.pos, -angle) for angle in range(45, 135))\n","sub_path":"Actor.py","file_name":"Actor.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"628287140","text":"import cv2\nimport numpy as np\nimport json\nimport os\n\n\n#classify two categories manually\ndef classify(path_ofjson,nameofimg,pathofimg):\n\n #read the img from path\n img = cv2.imread(pathofimg)\n\n #open json file\n with open(path_ofjson, 'r') as f:\n josn_file = json.load(f)\n\n #from dictionary get 'shapes'\n dir = josn_file['shapes']\n\n #get through all the points in the josnfile\n length = len(dir)\n for i in range(length):\n\n #get four vertices of a quad\n topleft = dir[i]['points'][0]\n bottomleft = dir[i]['points'][1]\n topright = dir[i]['points'][3]\n bottomright = dir[i]['points'][2]\n\n #get the Roi from quadrilateral to rectangle\n pts1 = np.float32([topleft, topright, bottomleft, bottomright])\n pts2 = np.float32([[0, 0], [254, 0], [0, 400], [254, 400]])\n\n #transform matrix\n M = cv2.getPerspectiveTransform(pts1, pts2)\n\n #get output image\n dst = cv2.warpPerspective(img, M, (254, 400))\n\n #use keyboard for classfy\n cv2.imshow(\"dst\", dst)\n k = cv2.waitKey(0) & 0xFF\n\n # Identify if 'e' or 'E' is pressed, put the picture into Empty\n if (k == 101 or k == 69):\n cv2.imwrite(\"F:\\SS2021\\Opencv\\Code\\Free-space-detection-4\\RAW_data\\Empty\" + str(i) + nameofimg, dst)\n cv2.destroyAllWindows()\n\n # Identify if 'z' or 'Z' is pressed, put the picture into Full\n if (k == 102 or k == 70):\n cv2.imwrite(\"F:\\SS2021\\Opencv\\Code\\Free-space-detection-4\\RAW_data\\Full\" + str(i) + nameofimg, dst)\n cv2.destroyAllWindows()\n\n\n#path of josn\npathofjson = \"F:\\SS2021\\Opencv\\Code\\Free-space-detection-4\\RAW_data\\josn_file_foto\\c5001.json\"\n\n#path of images\npath = \"F:\\SS2021\\Opencv\\Code\\Free-space-detection-4\\RAW_data\\images\"\n\n#images name\ndir = os.listdir(path)\n\nfor d in dir:\n path_img = path + \"/\" + d\n classify(pathofjson, d, path_img)\n\n\n\n\n\n\n","sub_path":"Code/Free-space-detection-4/Two-Categories.py","file_name":"Two-Categories.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"104873910","text":"from espnff import League \n\nleague_id = 926261\nyear = 2018\nleague = League(league_id,year)\n# teams = league.teams\n\nteam_dict = {}\nall_teams = []\nfor team in league.teams:\n\tteam_dict[team.team_abbrev] = team.scores\n\t# all_teams.append()\n\nprint(\"\\nChoose a team:\")\ni = 0\nfor key in team_dict.keys():\n\tprint(\"{}\\t\".format(key),end='')\n\ti += 1\n\tif (i % 4 == 0):\n\t\tprint()\n\n# print(team_dict)\n\nprint()\nteam1 = input(\"Team 1: \")\nteam2 = input(\"Team 2: \")\nprint()\n\nteam1_wins = 0\nteam2_wins = 0\nall_teams = team_dict.keys()\nfor i in range(0,13):\n\tteam1_score = team_dict[team1][i]\n\tteam2_score = team_dict[team2][i]\n\n\tif team1_score > team2_score:\n\t\twinner = team1\n\t\tteam1_wins += 1\n\telse:\n\t\twinner = team2\n\t\tteam2_wins += 1\n\n\tprint(\"Week {:2}: {}-{}\\t{} wins\".format(i+1,team1_score,team2_score,winner))\n\nprint()\nprint(\"{} would be {}-{} if they played {} every week\".format(team1,team1_wins,team2_wins,team2))","sub_path":"fantasy_football.py","file_name":"fantasy_football.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"613649694","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\ndef gen():\n for x in range(10):\n yield x\n\n\nf = gen()\n\nwhile 1:\n try:\n x = f.__next__()\n except StopIteration:\n print(\"over\")\n break\n else:\n print(x)\n","sub_path":"languages/little_code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"216518808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 7 15:15:14 2021\n\n@author: farrospide\n\"\"\"\nimport os\nimport geopandas as gpd\nimport contextily as ctx\nfrom matplotlib import pyplot as plt\nfrom matplotlib.patches import Patch\n\n\ndef import_shapes(file):\n folder = os.path.join('..', 'SIG', \n 'COBERTURAS INFRAESTRUCTURA Y ÁREAS DE RIEGO',\n 'infraest_ariego_etapa2')\n fp = os.path.join(folder, file)\n gdf = gpd.read_file(fp)\n print(gdf.crs)\n return gdf\n\ndef import_hidroMAV(file):\n folder = os.path.join('..', 'SIG', \n 'COBERTURAS INFRAESTRUCTURA Y ÁREAS DE RIEGO',\n 'infraest_ariego_etapa2')\n fp = os.path.join(folder, file)\n gdf = gpd.read_file(fp)\n gdf = gdf.to_crs('EPSG:32719')\n print(gdf.crs)\n return gdf\n\ndef import_catchments():\n folder = os.path.join('..', 'Etapa 1 y 2', 'GIS', 'Cuencas_DARH')\n f1 = os.path.join(folder, 'Cuencas', 'Cuencas_DARH_2015_AOHIA_ZC.geojson')\n f2 = os.path.join(folder, 'Subcuencas',\n 'SubCuencas_DARH_2015_AOHIA_ZC.geojson')\n cuencas = gpd.read_file(f1)\n scuencas = gpd.read_file(f2)\n \n return cuencas, scuencas\n\ndef import_hidrografia():\n folder = os.path.join('..', 'Etapa 1 y 2', 'GIS', 'Hidrografia')\n file = 'RedHidrograficaUTM19S_AOHIA_ZC.geojson'\n fp = os.path.join(folder, file)\n gdf = gpd.read_file(fp)\n print(gdf.crs)\n return gdf\n\ndef set_ax(ax, title):\n ax.set_xlabel('Coordenada UTM Este (m)')\n ax.set_ylabel('Coordenada UTM Norte (m)')\n ax.set_title(title)\n\ndef plot_gdf(gdf, title, contextshp=None, hgf=None):\n kwargs = {'ec': 'green', 'fc': 'green', 'alpha': 0.7}\n fs = (8.5,11)\n src = ctx.providers.Esri.WorldTerrain\n \n \n fig, ax = plt.subplots(figsize=fs)\n \n if contextshp is not None:\n gdf = gpd.sjoin(gdf, contextshp, how='inner')\n contextshp.plot(ax=ax, fc = 'none', ec = 'red')\n else:\n pass\n \n if hgf is not None:\n hgf = gpd.sjoin(hgf,contextshp,how='inner')\n hgf.plot(ax=ax, color='blue', ls='--', lw = 0.5)\n else:\n pass\n \n \n gdf.plot(ax=ax, **kwargs)\n ctx.add_basemap(ax=ax, zoom=9, source=src, crs='EPSG:32719')\n set_ax(ax, title)\n plt.show()\n\n \nfiles = ['AR_Maipo_20210430.shp',\n 'AR_Rapel_20210414.shp',\n 'AR_Mataquito20210507.shp',\n 'AR_Maule_20210507.shp']\n\ngdf = import_shapes(files[0])\n\nhidrografiaMAV = import_hidroMAV('Hidro_Maipo_filtro.shp')\nhidrografia = import_hidrografia()\ncuencas, subcuencas = import_catchments()\n\nmaipo = cuencas[cuencas['COD_CUENCA'].isin(['1300'])]\n\nplot_gdf(gdf, 'Areas de Riego\\n Cuenca Rio Maipo',contextshp=maipo, hgf=hidrografiaMAV)\n ","sub_path":"Hydrology/CIREN/areas_riego_MAV.py","file_name":"areas_riego_MAV.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409795563","text":"# -*- coding: utf-8 -*-\n\"\"\"\nЗадание 5.4\n\nНапример, для списка num_list, число 10 последний раз встречается с индексом 4; в\nсписке word_list, слово 'ruby' последний раз встречается с индексом 6.\nСделать решение общим (то есть, не привязываться к конкретному элементу в\nконкретном списке) и проверить на двух списках, которые указаны и на разных\nэлементах.\n\nДля этого надо запросить у пользователя сначала ввод числа из списка num_list и\nзатем вывести индекс его последнего появления в списке. А затем аналогично для\nсписка word_list.\n\nP.S. пример работает для всех списков, однако их требуется вносить вручную\n\"\"\"\n\nnum_list = [10, 2, 30, 100, 10, 50, 11, 30, 15, 7]\n\nword_list = ['python', 'ruby', 'perl',\n 'ruby', 'perl', 'python', 'ruby', 'perl']\n\nnew_num_list = [(len(num_list) - num_list[::-1].index(i) - 1) for i in num_list]\n\nnew_word_list = [(len(word_list) - word_list[::-1].index(i) - 1) for i in word_list]\n\nnum_dict = dict(zip(num_list, new_num_list))\nword_dict = dict(zip(word_list, new_word_list))\n\nprint(num_dict, '\\n', word_dict)\n","sub_path":"Python for Network Engineers/Chapter 5 - Basic Scripts/task_5_4.py","file_name":"task_5_4.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"520796410","text":"import logging\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django_twilio.client import twilio_client\nfrom twilio.rest.exceptions import TwilioRestException\n\nfrom apostello.models import Keyword, Recipient, SmsInbound, SmsOutbound\n\nlogger = logging.getLogger('apostello')\n\n\ndef handle_incoming_sms(msg):\n \"\"\"Add incoming sms to log.\"\"\"\n sms, created = SmsInbound.objects.get_or_create(sid=msg.sid)\n if created:\n sender, s_created = Recipient.objects.get_or_create(number=msg.from_)\n if s_created:\n sender.first_name = 'Unknown'\n sender.last_name = 'Person'\n sender.save()\n\n sms.content = msg.body\n sms.time_received = timezone.make_aware(\n msg.date_created, timezone.get_current_timezone()\n )\n sms.sender_name = str(sender)\n sms.sender_num = msg.from_\n matched_keyword = Keyword.match(msg.body)\n sms.matched_keyword = str(matched_keyword)\n sms.matched_colour = Keyword.lookup_colour(msg.body)\n sms.matched_link = Keyword.get_log_link(matched_keyword)\n sms.save()\n\n\ndef handle_outgoing_sms(msg):\n \"\"\"Add outgoing sms to log.\"\"\"\n try:\n sms, created = SmsOutbound.objects.get_or_create(sid=msg.sid)\n if created:\n recip, r_created = Recipient.objects.get_or_create(number=msg.to)\n if r_created:\n recip.first_name = 'Unknown'\n recip.last_name = 'Person'\n recip.save()\n\n sms.content = msg.body\n sms.time_sent = timezone.make_aware(\n msg.date_sent, timezone.get_current_timezone()\n )\n sms.sent_by = \"[Imported]\"\n sms.recipient = recip\n sms.save()\n except Exception:\n logger.error(\n 'Could not import sms.', exc_info=True, extra={'msg': msg}\n )\n\n\ndef fetch_generator(direction):\n \"\"\"Fetch generator from twilio.\"\"\"\n if direction == 'in':\n return twilio_client.messages.iter(to_=settings.TWILIO_FROM_NUM)\n if direction == 'out':\n return twilio_client.messages.iter(from_=settings.TWILIO_FROM_NUM)\n return []\n\n\ndef check_log(direction):\n \"\"\"Abstract check log function.\"\"\"\n if direction == 'in':\n sms_handler = handle_incoming_sms\n elif direction == 'out':\n sms_handler = handle_outgoing_sms\n\n # we want to iterate over all the incoming messages\n sms_page = fetch_generator(direction)\n\n for msg in sms_page:\n sms_handler(msg)\n\n\ndef check_incoming_log():\n \"\"\"Check Twilio's logs for messages that have been sent to our number.\"\"\"\n check_log('in')\n\n\ndef check_outgoing_log():\n \"\"\"Check Twilio's logs for messages that we have sent.\"\"\"\n check_log('out')\n","sub_path":"apostello/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"112702733","text":"import functools\n\nimport networkx as nx\n\nfrom nw2vec import layers\n\n\ndef _collect_node_filtered_children_dict(dag, node, func, collected):\n assert isinstance(collected, dict)\n\n if node in collected:\n raise ValueError(\"Was already called on node '{}'\".format(node))\n\n children = set()\n for child in dag.successors(node):\n if child not in collected:\n _collect_node_filtered_children_dict(dag, child, func, collected)\n children.update([child] if func(child) else collected[child])\n\n collected[node] = children\n\n\ndef _collect_node_descendants_dict(dag, node, collected):\n assert isinstance(collected, dict)\n\n if node in collected:\n raise ValueError(\"Was already called on node '{}'\".format(node))\n\n descendants = set()\n for child in dag.successors(node):\n if child not in collected:\n _collect_node_descendants_dict(dag, child, collected)\n descendants.update([child], collected[child])\n\n collected[node] = descendants\n\n\n@functools.lru_cache()\ndef subdag_GC(dag):\n return subdag(dag, lambda n: isinstance(n, layers.GC))\n\n\ndef subdag(dag, func):\n assert nx.is_directed_acyclic_graph(dag)\n\n roots = [n for n in dag.nodes if len(list(dag.predecessors(n))) == 0]\n filtered_children = {}\n for root in roots:\n _collect_node_filtered_children_dict(dag, root, func, filtered_children)\n\n subdag_dict = dict((n, children) for n, children in filtered_children.items() if func(n))\n return nx.from_dict_of_lists(subdag_dict, create_using=nx.DiGraph())\n\n\ndef _collect_layer_dag_dict(layer, collected):\n assert isinstance(collected, dict)\n\n if layer in collected:\n raise ValueError(\"Was already called on layer '{}'\".format(layer))\n\n children = [outnode.outbound_layer for outnode in layer._outbound_nodes]\n for child in children:\n if child not in collected:\n _collect_layer_dag_dict(child, collected)\n\n collected[layer] = children\n\n\ndef restrict(dag, roots):\n assert nx.is_directed_acyclic_graph(dag)\n\n descendants = {}\n for root in roots:\n if root not in descendants:\n _collect_node_descendants_dict(dag, root, descendants)\n\n roots_descendants = set().union(roots, *[descendants[root] for root in roots])\n return nx.from_dict_of_lists(nx.to_dict_of_lists(dag, nodelist=roots_descendants),\n create_using=nx.DiGraph())\n\n\n@functools.lru_cache()\ndef model_dag(model):\n dag_dict = {}\n for input_layer in model.input_layers:\n _collect_layer_dag_dict(input_layer, dag_dict)\n\n # Restrict the dag to what is reachable from the model inputs and outputs\n dag = nx.from_dict_of_lists(dag_dict, create_using=nx.DiGraph())\n dag = restrict(dag, model.input_layers)\n dag = nx.reverse(dag)\n dag = restrict(dag, model.output_layers)\n dag = nx.reverse(dag)\n\n # Check that each of the model's output layers is in the dag collected,\n # and that each dag leaf is in the model's output layers (but there can be\n # output layers that are not leaves).\n model_outputs = set(model.output_layers)\n for output in model_outputs:\n assert output in dag.nodes\n leaves = set([n for n in dag.nodes if len(list(dag.successors(n))) == 0])\n for leaf in leaves:\n assert leaf in model_outputs\n\n return dag\n","sub_path":"nw2vec/dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"397001184","text":"import matplotlib\n#matplotlib.use('agg')\n\nimport random\nimport numpy as np\nimport matplotlib.pylab as plt\n\nfrom copy import copy\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom grid import regridXYZ\nfrom simulateSignal import zernikePoly\nfrom utils.utils import midPoint, sampleXYZData\n\n\nclass MidpointNormalize(matplotlib.colors.Normalize):\n \"\"\"\n Normalise the colorbar so that diverging bars work \n their way either side from a prescribed midpoint value.\n\n\n Examples\n --------\n\n >>> import pylab as plt\n >>> array = [[50,100,50],[-100,-50,-100],[50,100,50]]\n >>> im = plt.imshow(array, norm=MidpointNormalize(midpoint=0., vmin=-100, vmax=100))\n \"\"\"\n\n def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):\n self.midpoint = midpoint\n matplotlib.colors.Normalize.__init__(self, vmin, vmax, clip)\n\n\n def __call__(self, value, clip=None):\n\n if clip is None:\n clip = self.clip\n\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n\n result, is_scalar = self.process_value(value)\n\n result = np.ma.array(np.interp(value, x, y), mask=result.mask, fill_value=np.nan, copy=False)\n\n if is_scalar:\n result = result[0]\n\n return result \n\n\ndef surfacePlot(x, y, z, title=None, midPoint=0, vMin=-5e-3, vMax=5e-3, colorbarLabel=None, filename=None):\n \"\"\"\n Plot a surface using `imshow`. The data should be a 2-D ndarray with square pixels.\n\n Parameters\n ----------\n x : 2-D ndarray\n Array with x coordinates of the surface.\n Used to set the labels of the x ticks.\n It assumes the units are meters.\n y : 2-D ndarray\n Array with y coordinates of the surface.\n Used to set the labels of the y ticks.\n It assumes the units are meters.\n z : 2-D ndarray\n Array with z coordinates of the surface.\n title : string, optional\n Text to display as plot title.\n midPoint : float, optional\n Value used as middle of the colorbar.\n vMin : float, optional\n Value used as minimum of the colorbar.\n vMax : float, optional\n Value used as maximum of the colorbar.\n colorbarLabel : string, optional\n Text for the colorbar.\n filename : string, optional\n Save the plot to this file.\n \"\"\"\n\n cmap = plt.matplotlib.cm.coolwarm\n cmap.set_bad(color='white')\n\n extent = [np.nanmin(x), np.nanmax(x), np.nanmin(y), np.nanmax(y)]\n\n fig = plt.figure(figsize=(6, 5), dpi=150, frameon=False)\n ax = fig.add_subplot(111)\n\n norm = MidpointNormalize(midpoint=midPoint, vmin=vMin, vmax=vMax)\n im = ax.imshow(z, extent=extent, vmin=vMin, vmax=vMax, norm=norm, cmap=cmap, origin='lower')\n\n cb = plt.colorbar(im, fraction=0.046, pad=0.04)\n if colorbarLabel is not None:\n cb.ax.set_ylabel(colorbarLabel)\n\n ax.minorticks_on()\n ax.tick_params('both', which='both', direction='in', top=True, right=True, bottom=True, left=True)\n\n ax.set_xlabel('x axis (m)')\n ax.set_ylabel('y axis (m)')\n if title is not None:\n plt.title(title)\n\n if filename is not None:\n plt.savefig(filename, bbox_inches='tight', pad_inches=0.06)\n \n\ndef barChartPlot(index, coefficients, expected=[]):\n \"\"\"\n Plots a bar chart with Zernike coefficients, `:math: C_{i}`.\n \n Parameters\n ----------\n index : list of ints\n Indices of the polynomial coefficients.\n coefficients : array\n Coefficients of the Zernike polynomials.\n expected : array, optional\n Expected values of the coefficients.\n \"\"\"\n\n fig = plt.figure(figsize=(9, 6), dpi=80)\n xticklist = []\n width = 0.6\n # Prepare the labels of the x ticks.\n for i in index:\n xticklist.append('Z'+str(i))\n barfigure = plt.bar(index, coefficients, width, color='#2E9AFE', edgecolor='#2E9AFE', label='Measured')\n if len(expected) > 0:\n plt.bar(index-width/3, expected, width, color='#882255', edgecolor='#882255', label='Input', alpha=0.5)\n\n # Add a legend.\n plt.legend(loc=0, fancybox=True)\n\n # Set the ticks and their labels.\n plt.xticks(index+width//2, xticklist, rotation=90)\n plt.xlabel('Zernike polynomials', fontsize=18)\n plt.ylabel('Coefficient', fontsize=18)\n plt.title('Fitted Zernike polynomial coefficients', fontsize=18)\n\n plt.gca().minorticks_on()\n plt.gca().tick_params('both', direction='in', top=True, right=True)\n plt.gca().tick_params('y', which='minor', direction='in', left=True, right=True)\n plt.gca().tick_params('x', which='minor', bottom=False)\n\n\ndef zernikeResiduals2DPlot(xx, yy, zz):\n \"\"\"\n Plots the residuals of a Zernike fit.\n \"\"\"\n\n fig = plt.figure(figsize=(9, 6), dpi=80)\n ax = fig.gca()\n im = plt.pcolormesh(xx, yy, zz, cmap=plt.get_cmap('RdYlGn'))\n plt.colorbar()\n plt.title('Remaining Aberration', fontsize=18)\n ax.set_aspect('equal', 'datalim')\n\n\n#def linePlot(y, title):\n# fig = plt.figure()\n# ax = fig.gca()\n# ax.plot(range(len(y)), y)\n# plt.title(title)\n\n\ndef imagePlot(z, title):\n \"\"\"\n \"\"\"\n \n fig = plt.figure()\n ax = fig.gca()\n cax = ax.imshow(z)\n fig.colorbar(cax)\n plt.title(title)\n\n\ndef surface3dPlot(x, y, z, title=None, xlim=None, ylim=None, sample=None):\n \"\"\"\n Plot a surface in 3D using a mesh.\n\n Parameters\n ----------\n x : 2-D array\n y : 2-D array\n z : 2-D array\n sample : float between 0 and 1, optional\n Percentage of the data to be displayed.\n \"\"\"\n\n fig = plt.figure()\n ax = Axes3D(fig)\n\n # plot all the data, or just some?\n if sample is not None:\n print(\"Plotting %5.2f percent of data\" % sample)\n x, y, z = sampleXYZData(x, y, z, sample)\n\n ax.plot_surface(x, y, z)\n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n \n if title is not None:\n plt.title(title)\n\n if xlim is not None:\n plt.xlim(xlim)\n \n if ylim is not None:\n plt.ylim(ylim)\n\n\ndef scatter3dPlot(x, y, z, title=None, xlim=None, ylim=None, sample=None, fig=None, axes=None, color=None):\n \"\"\"\n Plot a surface in 3D using points.\n\n Parameters\n ----------\n x : 2-D array\n y : 2-D array\n z : 2-D array\n xlim : tuple, optional\n Limits for the display in the x coordinate.\n ylim L tuple, optional\n Limits for the display in the y coordinate.\n sample : float between 0 and 1, optional\n Percentage of the data to be displayed.\n fig : figure object, optional\n Display the points in this Figure.\n axes : axes object, optional\n Display the points in this Axes.\n color : color, sequence, or sequence of colors, optional\n\n Returns\n -------\n tuple\n Tuple with the Figure and Axes objects used for the plot.\n \"\"\"\n\n # plot all the data, or just some?\n if sample is not None:\n print(\"Plotting %5.2f percent of data\" % sample)\n x, y, z = sampleXYZData(x, y, z, sample)\n print(\"Now length of data is %d\" % len(x))\n\n if fig is None:\n fig = plt.figure()\n \n if axes is None:\n axes = Axes3D(fig)\n if color is None:\n color = 'b'\n\n axes.scatter(x, y, z, c=color)\n \n axes.set_xlabel(\"x\")\n axes.set_ylabel(\"y\")\n \n if title is not None:\n plt.title(title)\n \n if xlim is not None:\n axes.set_xlim(xlim)\n \n if ylim is not None:\n axes.set_ylim(ylim) \n \n return fig, axes\n\n\ndef scatterPlot(x, y, z=None, title=None, xlim=None, ylim=None, sample=None):\n \"\"\"\n Display a surface using a scatter plot in 2D.\n\n Parameters\n ----------\n \n \"\"\"\n if z is None:\n z = np.ones(x.shape, dtype=np.int)\n\n # plot all the data, or just some?\n if sample is not None:\n print(\"Plotting %5.2f percent of data\" % sample)\n x, y, z = sampleXYZData(x, y, z, sample)\n print(\"Now length of data is %d\" % len(x))\n\n fig = plt.figure()\n \n ax = fig.gca()\n \n sc = ax.scatter(x, y, c=z)\n plt.colorbar(sc)\n \n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n\n if title is not None:\n plt.title(title)\n \n if xlim is not None:\n plt.xlim(xlim)\n \n if ylim is not None:\n plt.ylim(ylim)\n\n\ndef sampleXYZData(x, y, z, samplePercentage, seed=None):\n \"\"\"\n Return a percentage of the data using a random sample.\n\n Parameters\n ----------\n x : 1-D array\n y : 1-D array\n x : 1-D array\n samplePercentage : float between 0 and 1\n Percentage of the data to return.\n seed : int, optional\n Initialize the random number generator.\n Use a fixed value for reproducible results.\n \n Returns\n -------\n tuple\n Tuple with a random sample of x, y and z.\n \"\"\"\n\n assert len(x) == len(y)\n assert len(y) == len(z)\n\n if seed is not None:\n random.seed(seed)\n\n lenx = len(x)\n\n sampleSize = int((lenx * samplePercentage) / 100.)\n\n idx = random.sample(range(lenx), sampleSize)\n\n return copy(x[idx]), copy(y[idx]), copy(z[idx])\n\n\ndef plotZernikes(x, y, zernCoeffs, n=512, title=None, filename=None):\n \"\"\"\n Plot Zernike polynomials with coefficients `zernCoeffs` over a square grid.\n\n Parameters\n ----------\n x : array\n Array with x coordinates.\n Used to evaluate the Zernike polynomials.\n y : array\n Array with y coordinates.\n Used to evaluate the Zernike polynomials.\n zernCoeffs : array\n Array with the coefficients of a Zernike polynomial.\n n : int, optional\n Number of pixels per side of the square grid used to\n display the Zernike polynomial.\n title : string, optional\n filename : string, optional\n Save the plot to this disk location.\n \"\"\"\n\n # Create the linear combination of the Zernike polynomials.\n zPoly = zernikePoly(x, y, midPoint(x), midPoint(y), zernCoeffs)\n \n # Grid it to a regularly sampled cartesian grid.\n xx, yy, zz = regridXYZ(x, y, zPoly, n=n)\n\n # Make it look like the dish of the GBT by selecting a circular area.\n mask = (((xx - midPoint(xx))**2. + (yy - midPoint(yy))**2.) < 49.**2.)\n zz[~mask] = np.nan\n\n # To get meaningful plot tick labels.\n extent = [np.nanmin(xx), np.nanmax(xx), np.nanmin(yy), np.nanmax(yy)]\n\n fig = plt.figure(figsize=(12, 8), dpi=80)\n ax = fig.gca()\n im = ax.imshow(zz.T, cmap=cm.RdYlGn, extent=extent)\n plt.colorbar(im)\n\n # Add minor ticks and make them point inwards.\n ax.minorticks_on()\n ax.tick_params('both', which='both', direction='in', top=True, right=True, bottom=True, left=True)\n \n # Set a title.\n if title is not None:\n plt.title(title)\n\n # Set axis label names.\n ax.set_xlabel('x axis (m)')\n ax.set_ylabel('y axis (m)')\n\n # Save the figure to disk.\n if filename is not None:\n plt.savefig(filename)\n\n\ndef nicePlotDates(labels, i0=0):\n \"\"\"\n Given a list of text labels representing dates with the format %m/%d %H:%M\n it will update the list to keep only the month and day portion when it\n changes.\n\n Parameters\n ----------\n labels : list \n List with the text labels formatted as %m/%d %H:%M.\n i0 : int, optional\n Index of the first text label to keep in full.\n Useful when the index 0 text label does not appear in the plot\n \n Examples\n --------\n\n >>> labels = ['06/11 15:00', '06/11 18:00']\n >>> new_labels = nicePlotDates(labels)\n >>> new_labels\n ['06/11 15:00', '18:00']\n \"\"\"\n\n new_labels = []\n month_ = None\n day_ = None\n for i,label in enumerate(labels):\n date, time = label.split(' ')\n month, day = date.split('/')\n if i == i0:\n month_ = month\n day_ = day\n new_labels.append(label)\n if i != i0:\n if month != month_:\n month_ = month\n new_labels.append(label)\n elif day != day_:\n day_ = day\n new_labels.append(label)\n else:\n new_labels.append(time)\n\n return new_labels\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":12067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449634312","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('/home/pi/Pictures/peoples.jpeg')\ncv2.imshow('Original', img)\nwidth= img.shape[1]\nheight = img.shape[0]\nproportion = float(height/width)\nnew_width = 320 #pixels\nnew_height = int(new_width*proportion)\nnew_size = (new_width, new_height)\n\nimg_resized = cv2.resize(img, new_size, interpolation = cv2.INTER_AREA)\n\ncv2.imshow('Result', img_resized)\ncv2.waitKey(0)\n","sub_path":"simple-resize-img.py","file_name":"simple-resize-img.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"438470796","text":"import os\nimport pytest\n\nimport testinfra.utils.ansible_runner\n\ntestinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(\n os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')\n\n\n@pytest.mark.parametrize('pkg', [\n 'kubelet',\n 'kubeadm'\n])\ndef test_pkg(host, pkg):\n package = host.package(pkg)\n\n assert package.is_installed\n\n\n@pytest.mark.parametrize('svc', [\n 'docker',\n 'kubelet'\n])\ndef test_svc(host, svc):\n service = host.service(svc)\n\n assert service.is_running\n assert service.is_enabled\n\n\ndef test_kubectl(host):\n if host.ansible.get_variables()['inventory_hostname'] == 'worker':\n return\n\n cmd = host.run('kubectl --kubeconfig=/etc/kubernetes/admin.conf get nodes')\n\n assert cmd.rc == 0\n assert 'worker' in cmd.stdout\n assert 'controller' in cmd.stdout\n assert 'Ready' in cmd.stdout\n","sub_path":"ansible/roles/kubernetes/molecule/default/tests/test_default.py","file_name":"test_default.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"569105534","text":"import string\n\ntranslation_dict = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-', 'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..', ' ':'', '/':'-..-.', '-':'-....-', '.':'.-.-.-', ',':'--..--', \"1\":\".----\", \"2\":\"..---\", \"3\":\"...--\", \"4\":\"....-\", \"5\":\".....\", \"6\":\"-....\", \"7\":\"--...\", \"8\":\"---..\", \"9\":\"----.\", \"0\":\"-----\"}\n\n#alphabet = {}\nmorse = {}\n\nfor key, value in translation_dict.items():\n morse[value] = key\n #alphabet[key] = value\n\ndef encode(plaintext):\n plaintext = plaintext.lower()\n morse_text = \"\"\n for char in plaintext:\n morse_text += translation_dict[char] + \"/\"\n morse_text += \"//\"\n return morse_text\n\ndef decode(morse_text):\n morse_array = morse_text.split(\"/\")\n plain_text = \"\"\n for i in range(len(morse_array)):\n current_element = morse_array[i]\n plain_text += morse[current_element]\n return plain_text\n\nprint(decode(encode(\"tezke troleni\")))\nprint(decode(encode(\"garant rocniku se predem omlouva za zpusobene psychicke potize.\")))\nprint(decode(encode(\"do translation dict jsou pridany vsechny specialni znaky a cisla, ktera budete potrebovat.\")))\nprint(encode(\"ab c\")) # .-/-...//-.-.///","sub_path":"KSI_18-19/morseCode.py","file_name":"morseCode.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"42481314","text":"from flask import Flask, request, abort\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import *\nimport requests\nimport random\nimport time\n\napp = Flask(__name__)\n\n# Channel Access Token\nline_bot_api = LineBotApi('TJOUtiMcGAQ6/zNSJtCC0EycuCpTBKawb9FK9Ohdyr80o+Co18kKHf4tqdrfzeEZrZ+4ybnyxBjnKkjcPvWVJVQpEiEyfFyzhOGTupp0EBeVczTIUrjKqZQqYoKTPlzxzWgjSyQJerwPDndu3NSvtwdB04t89/1O/w1cDnyilFU=')\n# Channel Secret\nhandler = WebhookHandler('25892f81ac6e4f45a73f24cee150150e')\n\n# 監聽所有來自 /callback 的 Post Request\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n return 'OK'\n\n#user類別\nclass user:\n def __init__(self,ID,Q):\n self.ID = ID\n self.Q = Q\n\n#讀取成員名單\ndef GetUserList():\n url = \"https://script.google.com/macros/s/AKfycbwVs2Si91yKz6m3utpaPtsttbh_lUQ8LOQM3Zud2hPFxXCgW3u1/exec\"\n payload = {\n 'sheetUrl':\"https://docs.google.com/spreadsheets/d/1mlxmS0MYfBHSqiRLjaKyqNBvYZZHIGLwsbxr6FENdn4/edit#gid=0\",\n 'sheetTag':\"成員列表\",\n 'row': 1,\n 'col': 1,\n 'endRow' : 51,\n 'endCol' : 2\n }\n resp = requests.get(url, params=payload)\n temp = resp.text.split(',')\n userlist = []\n i = 0\n while i < len(temp):\n if temp[i] != \"\":\n userlist.append(user(temp[i],temp[i+1]))\n i+=2\n else:\n break\n return userlist\n\n#登入\ndef Login(user_id,userlist):\n for user in userlist:\n if user.ID == user_id:\n return userlist.index(user)\n return -1\n\n#註冊\ndef Signup(user_id):\n url = \"https://script.google.com/macros/s/AKfycbxn7Slc2_sKHTc6uEy3zmm3Bh_4duiGCXLavUM3RB0a3yzjAxc/exec\"\n payload = {\n 'sheetUrl':\"https://docs.google.com/spreadsheets/d/1mlxmS0MYfBHSqiRLjaKyqNBvYZZHIGLwsbxr6FENdn4/edit#gid=0\",\n 'sheetTag':\"成員列表\",\n 'data':user_id+',-1'\n }\n requests.get(url, params=payload)\n \ndef Write(x,data):\n url = \"https://script.google.com/macros/s/AKfycbyBbQ1lsq4GSoKE0yiU5d6x0z2EseeBNZVTewWlSZhQ6EVrizo/exec\"\n payload = {\n 'sheetUrl':\"https://docs.google.com/spreadsheets/d/1mlxmS0MYfBHSqiRLjaKyqNBvYZZHIGLwsbxr6FENdn4/edit#gid=0\",\n 'sheetTag':\"成員列表\",\n 'data':data,\n 'x':str(x+1),\n 'y':'2'\n }\n requests.get(url, params=payload)\n \n#對答案\ndef Ans(Q, ans):\n if Q == 0:\n if ans.find('芝麻街') >= 0:\n return \"答對了\"\n else:\n return \"錯,答案是「芝麻街」,因為芝麻街美語(沒雨)\"\n elif Q == 1:\n if ans.find('冰淇淋') >= 0:\n return \"答對了\"\n else:\n return \"錯,答案是「冰淇淋(麒麟)」\"\n elif Q == 2:\n if ans.find('平行線') >= 0:\n return \"答對了\"\n else:\n return \"錯,答案是「平行線」,因為沒有相交(香蕉)\"\n elif Q == 3:\n if ans.find('虱目魚') >= 0 or ans.find('濕木魚') >= 0:\n return \"答對了\"\n else:\n return \"錯,答案是「虱目魚」(濕木魚)\"\n elif Q == 4:\n if ans.find('布丁狗') >= 0 or ans.find('不叮狗') >= 0:\n return \"答對了\"\n else:\n return \"錯,答案是「布丁狗」(不叮狗)\"\n\n# 處理訊息\n@handler.add(MessageEvent, message=None)\ndef handle_message(event):\n try:\n userlist = GetUserList()\n clientindex = Login(event.source.user_id,userlist)\n if clientindex == -1:\n Signup(event.source.user_id)\n userlist = GetUserList()\n clientindex = Login(event.source.user_id,userlist)\n Q = int(userlist[clientindex].Q)\n #開始使用功能\n if Q < 0:\n ran = random.randint(0,9)\n if ran == 0:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"哪一條街永遠不下雨?\"))\n elif ran == 1:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"麒麟飛到北極會變成什麼?\"))\n elif ran == 2:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"猴子最討厭哪一種線?\"))\n elif ran == 3:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"木魚掉進海裡會變成什麼?\"))\n elif ran == 4:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"有一隻蚊子牠只叮[鼠牛虎兔龍蛇馬羊猴雞豬],請問這隻蚊子叫什麼名字?\"))\n elif ran == 5:\n line_bot_api.reply_message(\n event.reply_token,TemplateSendMessage(\n alt_text='猜題面板(手機限定)',\n template=ButtonsTemplate(\n thumbnail_image_url='https://truth.bahamut.com.tw/s01/201709/e9c87c887640edf475d96f171eb8834f.PNG',\n title='題目',\n text='狼、老虎和獅子誰玩遊戲一定會被淘汰?',\n actions=[\n PostbackTemplateAction(\n label='狼',\n data='1`t'\n ),\n PostbackTemplateAction(\n label='老虎',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='獅子',\n data='1`f'\n )\n ]\n )\n )\n )\n elif ran == 6:\n line_bot_api.reply_message(event.reply_token,\n TemplateSendMessage(\n alt_text='猜題面板(手機限定)',\n template=ButtonsTemplate(\n thumbnail_image_url='https://truth.bahamut.com.tw/s01/201709/e9c87c887640edf475d96f171eb8834f.PNG',\n title='題目',\n text='孔子有三位徒弟子貢、子路、和子游,請問哪一位不是人?',\n actions=[\n PostbackTemplateAction(\n label='子貢',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='子路',\n data='1`t'\n ),\n PostbackTemplateAction(\n label='子游',\n data='1`f'\n )\n ]\n )\n )\n )\n elif ran == 7:\n line_bot_api.reply_message(event.reply_token,\n TemplateSendMessage(\n alt_text='猜題面板(手機限定)',\n template=ButtonsTemplate(\n thumbnail_image_url='https://truth.bahamut.com.tw/s01/201709/e9c87c887640edf475d96f171eb8834f.PNG',\n title='題目',\n text='獅子、狼、熊,哪一隻的牙齒最好?',\n actions=[\n PostbackTemplateAction(\n label='獅子',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='狼',\n data='1`t'\n ),\n PostbackTemplateAction(\n label='熊',\n data='1`f'\n )\n ]\n )\n )\n )\n elif ran == 8:\n line_bot_api.reply_message(event.reply_token,\n TemplateSendMessage(\n alt_text='猜題面板(手機限定)',\n template=ButtonsTemplate(\n thumbnail_image_url='https://truth.bahamut.com.tw/s01/201709/e9c87c887640edf475d96f171eb8834f.PNG',\n title='題目',\n text='喵喵、吱吱 、旺旺誰會最先被叫起來背書?',\n actions=[\n PostbackTemplateAction(\n label='喵喵',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='吱吱',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='旺旺',\n data='1`t'\n )\n ]\n )\n )\n )\n elif ran == 9:\n line_bot_api.reply_message(event.reply_token,\n TemplateSendMessage(\n alt_text='猜題面板(手機限定)',\n template=ButtonsTemplate(\n thumbnail_image_url='https://truth.bahamut.com.tw/s01/201709/e9c87c887640edf475d96f171eb8834f.PNG',\n title='題目',\n text='蝴蝶, 蜘蛛, 蜈蚣, 哪一個沒有領到酬勞?',\n actions=[\n PostbackTemplateAction(\n label='蝴蝶',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='蜘蛛',\n data='1`f'\n ),\n PostbackTemplateAction(\n label='蜈蚣',\n data='1`t'\n )\n ]\n )\n )\n )\n Write(clientindex,ran)\n elif Q < 5:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=Ans(Q ,event.message.text)))\n Write(clientindex,-1)\n else:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"要回答請點擊題目下方的按鈕喔\"))\n except Exception as e:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=str(e)))\n\n@handler.add(PostbackEvent)\ndef handle_postback(event):\n userlist = GetUserList()\n clientindex = Login(event.source.user_id,userlist)\n data = event.postback.data.split('`')\n #註冊用\n if data[0] == '0' and clientindex < 0:\n if data[1] == 't':\n Signup(event.source.user_id,data[2])\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"註冊成功,歡迎來到LineBot世界\"))\n elif data[1] == 'f':\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"請再次輸入您的姓名\"))\n elif data[0] == '1':\n userlist = GetUserList()\n clientindex = Login(event.source.user_id,userlist)\n Q = int(userlist[clientindex].Q)\n if data[1] == 't' and Q > 4:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"答對了\"))\n else:\n if Q == 5:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"錯,答案是「狼」,因為「桃太郎」(淘汰狼)\"))\n elif Q == 6:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"錯,答案是「子路」,因為「指鹿(子路)為馬」\"))\n elif Q == 7:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"錯,答案是「狼」,因為「狼牙棒」\"))\n elif Q == 8:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"錯,答案是「旺旺」,因為「旺旺仙貝(先背)」\"))\n elif Q == 9:\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"錯,答案是「蜈蚣」,因為「無功(蜈蚣)不受祿」\"))\n if Q > 4:\n Write(clientindex,-1)\nimport os\nif __name__ == \"__main__\":\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"529550016","text":"def read_grades(gradefile):\r\n \"\"\" (file open for reading) -> list of floats\r\n \r\n Read and return the list of grades from the gradefile\r\n\r\n Precondition: gradefile starts with a header that contains no blank lines,\r\n then has a blank line, and then lines containing student number and a grade\r\n \"\"\"\r\n work_file=gradefile.readlines()\r\n grates=[]\r\n buff=\"\"\r\n for i in work_file:\r\n j=0\r\n while j != -1:\r\n if i[j] is \":\" and i[j+1] is \" \":\r\n j=j+2\r\n if i[j] is \" \":\r\n j=j+1\r\n while i[j] is not \"\\n\":\r\n buff = buff+i[j]\r\n j=j+1\r\n if buff is not \"\":\r\n grates.append(buff)\r\n buff=\"\"\r\n break\r\n if i[j] is \"\\n\":\r\n break\r\n j=j+1\r\n return grates\r\n\r\ndef count_grade_ranges(grades):\r\n \"\"\"(list of float) -> list of int\r\n\r\n Return a list of int where every index indicates how many grades are in these ranges:\r\n \r\n 0-9: 0\r\n 10-19: 1\r\n 20-29: 2\r\n :\r\n 90-99: 9\r\n 100: 10\r\n\r\n >>> grade_ranges([77.5, 37.5, 0.5, 9.5, 72.5, 100.0, 55.0, 70.0, 79.5])\r\n [2, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]\r\n \"\"\"\r\n grates=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n for i in grades:\r\n if float(i)<10:\r\n grates[0]=grates[0]+1\r\n if float(i)<20 and float(i)>=10:\r\n grates[1]=grates[1]+1\r\n if float(i)<30 and float(i)>=20:\r\n grates[2]=grates[2]+1\r\n if float(i)<40 and float(i)>=30:\r\n grates[3]=grates[3]+1\r\n if float(i)<50 and float(i)>=40:\r\n grates[4]=grates[4]+1\r\n if float(i)<60 and float(i)>=50:\r\n grates[5]=grates[5]+1\r\n if float(i)<70 and float(i)>=60:\r\n grates[6]=grates[6]+1\r\n if float(i)<80 and float(i)>=70:\r\n grates[7]=grates[7]+1\r\n if float(i)<90 and float(i)>=80:\r\n grates[8]=grates[8]+1\r\n if float(i)<100 and float(i)>=90:\r\n grates[9]=grates[9]+1\r\n if float(i)==100:\r\n grates[10]=grates[10]+1\r\n return grates\r\n\r\ndef write_histogram(range_counts, hist_file):\r\n \"\"\"(list of int, file open for writing) -> NoneType\r\n\r\n Write a *'s histogram based on the number of grades in every range\r\n\r\n The output format:\r\n 0-9: *\r\n 10-19: **\r\n 20-29: *****\r\n :\r\n 90-99: **\r\n 100: *\r\n\r\n \"\"\"\r\n i=0\r\n string=\"\"\r\n string=string+\"0-9: \"\r\n for index in range(0, range_counts[0]):\r\n string=string+\"*\"\r\n string=string+\"\\n\"\r\n hist_file.write(string)\r\n string=\"\"\r\n\r\n for i in range(9):\r\n string=str(i*10)+\"-\"+str(i*10+9)+\": \"\r\n for index in range(0, range_counts[1]):\r\n string=string+\"*\"\r\n string=string+\"\\n\"\r\n hist_file.write(string)\r\n string=\"\"\r\n\r\n\r\n string=string+\"100: \"\r\n for index in range(0, range_counts[10]):\r\n string=string+\"*\"\r\n string=string+\"\\n\"\r\n hist_file.write(string)\r\n string=\"\" \r\n return None\r\n","sub_path":"grade_template.py","file_name":"grade_template.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"185370505","text":"\ndef recurdict(d, f, depth = 0):\n # f()\n for a in d:\n if type(d[a]) is dict:\n f('['+a+']', depth)\n recurdict(d[a],f, depth+1)\n else:\n f(a, depth)\nstuff = eval (open(\"C:\\\\_code\\\\temporary\\\\list_readable2.txt\").read())\n\nlined = []\nrecurdict(stuff, lambda x, n: lined.append(n*4*' '+str(x)))\n\nprint('\\n'.join(lined[:50]))","sub_path":"test-ftp.py","file_name":"test-ftp.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328098146","text":"import pytest\nimport responses\nimport json\nfrom pycronofy import Client\nfrom pycronofy import settings\nfrom pycronofy.tests import common_data\n\nTEST_EVENT = {\n 'event_id': 'test-1',\n 'summary': 'Test Event',\n 'description': 'Talk about how awesome cats are.',\n 'start': '2014-10-01T08:00:00Z',\n 'end': '2014-10-01T09:00:00Z',\n 'tzid': 'Etc/UTC',\n 'location': {\n 'description': 'Location!',\n },\n}\n\nREAL_TIME_SCHEDULING_RESPONSE = {'url': 'http://www.example.com'}\n\n\n@pytest.fixture(scope=\"module\")\ndef client():\n \"\"\"Setup Client instance with test values.\"\"\"\n return Client(**common_data.AUTH_ARGS)\n\n\n@responses.activate\ndef test_real_time_scheduling(client):\n \"\"\"Test Client.availability().\n\n :param Client client: Client instance with test data.\n \"\"\"\n\n def request_callback(request):\n payload = json.loads(request.body)\n\n availability = payload['availability']\n assert availability['required_duration'] == {'minutes': 30}\n assert availability['available_periods'] == [\n {'start': '2017-01-03T09:00:00Z', 'end': '2017-01-03T18:00:00Z'},\n {'start': '2017-01-04T09:00:00Z', 'end': '2017-01-04T18:00:00Z'}\n ]\n assert availability['participants'] == [\n {\n 'required': 'all',\n 'members': [\n {'sub': 'acc_567236000909002'},\n {'sub': 'acc_678347111010113'}\n ]\n }\n ]\n\n assert payload['event'] == TEST_EVENT\n assert payload['oauth'] == oauth\n assert request.headers['Authorization'] == \"Bearer %s\" % client.auth.client_secret\n\n return (200, {}, json.dumps(REAL_TIME_SCHEDULING_RESPONSE))\n\n responses.add_callback(\n responses.POST,\n url='%s/%s/real_time_scheduling' % (settings.API_BASE_URL, settings.API_VERSION),\n callback=request_callback,\n content_type='application/json',\n )\n\n periods = (\n {'start': \"2017-01-03T09:00:00Z\", 'end': \"2017-01-03T18:00:00Z\"},\n {'start': \"2017-01-04T09:00:00Z\", 'end': \"2017-01-04T18:00:00Z\"}\n )\n example_participants = ({\n 'members': [\n \"acc_567236000909002\",\n \"acc_678347111010113\",\n ],\n })\n\n availability = {\n 'participants': example_participants,\n 'available_periods': periods,\n 'required_duration': 30\n }\n\n oauth = {\n 'scope': 'foo',\n 'redirect_uri': 'http://www.example.com',\n 'state': 'bar'\n }\n\n result = client.real_time_scheduling(availability, oauth, TEST_EVENT)\n assert result == REAL_TIME_SCHEDULING_RESPONSE\n","sub_path":"pycronofy/tests/test_real_time_scheduling.py","file_name":"test_real_time_scheduling.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"276861142","text":"import os\nfrom typing import List\nfrom setuptools import find_packages, setup # type: ignore\n\n\ndef readme():\n \"\"\"Read the README file and use it as long description.\"\"\"\n with open(os.path.join(os.path.dirname(__file__), \"README.md\")) as readme_file:\n return readme_file.read()\n\n\nVERSION = \"0.0.0\"\nREQUIRES: List[str] = []\nDESCRIPTION = (\n \"pcluster-autocompleter enables auto completion of the `pcluster` CLI commands for the bash, \"\n \"zsh, and fish shells. The `pcluster` CLI is used to interact with AWS ParallelCluster, an \"\n \"AWS supported Open Source cluster management tool to deploy and manage HPC clusters in the \"\n \"AWS cloud.\"\n)\n\nsetup(\n name=\"pcluster-autocompleter\",\n version=VERSION,\n author=\"Tim Lane\",\n description=DESCRIPTION,\n url=\"https://github.com/tilne/pcluster-autocompleter\",\n license=\"Apache License 2.0\",\n packages=find_packages(),\n python_requires=\">=3.6\",\n install_requires=REQUIRES,\n entry_points={\n \"console_scripts\": [\n \"pcluster_autocompleter = pcluster_autocompleter.get_pcluster_completion_candidates:main\"\n ]\n },\n include_package_data=True,\n zip_safe=False,\n package_data={\"pcluster_autocompleter\": [\"py.typed\", \"util.pyi\"]},\n long_description=readme(),\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"Programming Language :: Python\",\n \"Topic :: Scientific/Engineering\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272671412","text":"#\n# @lc app=leetcode.cn id=714 lang=python\n#\n# [714] 买卖股票的最佳时机含手续费\n#\n\n# @lc code=start\nclass Solution(object):\n def maxProfit(self, prices, fee):\n \"\"\"\n :type prices: List[int]\n :type fee: int\n :rtype: int\n \"\"\"\n return self.helpDP(prices, fee)\n \n # Solution_1 —— 动态规划\n def helpDP(self, prices, fee):\n m = len(prices)\n dp_0, dp_1 = 0, -float('inf')\n for i in range(1, m + 1):\n dp_0 = max(dp_0, dp_1 + prices[i - 1] - fee)\n dp_1 = max(dp_0 - prices[i - 1], dp_1)\n return dp_0\n# @lc code=end\n\n","sub_path":"Week06/714.买卖股票的最佳时机含手续费.py","file_name":"714.买卖股票的最佳时机含手续费.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"456657529","text":"def flip(currstring):\n\tfor i in range(len(currstring)):\n\t\tif currstring[i]=='+':\n\t\t\tcurrstring[i]='-'\n\t\telse:\n\t\t\tcurrstring[i]='+'\n\n\n\n\n\nT=int(input())\n\nfor i in range(T):\n\tcurrstring=list(input())\n\tcurrstring.reverse()\n\tflips=0\n\n\n\t#find the smallest down pancake\n\t#remove pancakes before that\n\t#flip all the pancakes \n\t#repeat\n\n\twhile True:\n\t\ttry:\n\t\t\tnewtop=currstring.index('-')\n\t\texcept ValueError:\n\t\t\tbreak\n\t\t\n\t\tcurrstring=currstring[newtop:]\n\t\tflips+=1\n\t\tflip(currstring)\n\n\tprint(\"Case #%d: %d\" %(i+1,flips) )","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_hyyl_p2.py","file_name":"16_0_2_hyyl_p2.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"529830902","text":"import logging\r\nimport os\r\nimport subprocess\r\n\r\n\r\ndef replace_file_ext(file: str, ext: str):\r\n base = os.path.splitext(file)[0]\r\n return f'{base}.{ext}'\r\n\r\n\r\ndef encode_utf8(txt: str) -> str:\r\n if txt is None:\r\n return ''\r\n\r\n return str(txt.encode('utf-8'), 'utf-8')\r\n\r\n\r\ndef encode_b_utf8(txt: bytes) -> str:\r\n if txt is None:\r\n return ''\r\n\r\n s = ''\r\n try:\r\n s = str(txt, 'utf-8')\r\n except UnicodeDecodeError as err:\r\n logging.error(f'UnicodeDecodeError: {err}')\r\n return s\r\n\r\n\r\ndef file_ext(file: str, ext) -> bool:\r\n if file:\r\n return file.lower().endswith(ext)\r\n\r\n\r\ndef clean_dir(folder: str):\r\n for the_file in os.listdir(folder):\r\n\r\n file_path = os.path.join(folder, the_file)\r\n\r\n try:\r\n if os.path.isfile(file_path):\r\n os.unlink(file_path)\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ndef run_cmd(cmd: str or list, shell=False, wait=True, timeout=None) -> tuple or None:\r\n if not cmd:\r\n return None\r\n\r\n info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)\r\n\r\n if wait:\r\n if timeout:\r\n info.wait(timeout)\r\n else:\r\n info.wait()\r\n\r\n std, err = info.communicate()\r\n\r\n if std:\r\n logging.info(std)\r\n\r\n if err:\r\n logging.error(err)\r\n\r\n return std.decode('utf-8'), err or None\r\n","sub_path":"mailprinter/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"52210804","text":"import json\n\nLOGS = \"loggly_events_2015-01-28 18-53-19.652608.json\"\n\nCFG = \"agencywolf.json\"\n\ndef find_ntids_in_log(log, cfg):\n missing_ntids = set()\n with open(log) as log_file:\n log_json = json.load(log_file)\n for event in log_json[\"events\"]:\n bad_alc = event[\"logmsg\"].rsplit(\"/\", 1)[1]\n if bad_alc.startswith(\"e\") and bad_alc.endswith(\"t\"):\n missing_ntids.add(bad_alc[1:-1])\n \n print(len(missing_ntids))\n actually_missing_ntids = set()\n with open(cfg) as cfg_file:\n cfg_json = json.load(cfg_file)\n for ntid in missing_ntids:\n if ntid in cfg_json[\"config\"][\"ntid_alc_mapping\"]:\n print(\"Actually, {} was in the config already!\".format(ntid))\n else:\n actually_missing_ntids.add(ntid)\n\n print(actually_missing_ntids)\n \n\nif __name__ == \"__main__\":\n find_ntids_in_log(LOGS, CFG)\n \n","sub_path":"misc/DO-550/find_ntids.py","file_name":"find_ntids.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270329592","text":"\"\"\"\r\n950. 按递增顺序显示卡牌\r\n\r\n牌组中的每张卡牌都对应有一个唯一的整数。你可以按你想要的顺序对这套卡片进行排序。\r\n最初,这些卡牌在牌组里是正面朝下的(即,未显示状态)。\r\n现在,重复执行以下步骤,直到显示所有卡牌为止:\r\n\r\n从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。\r\n如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。\r\n如果仍有未显示的牌,那么返回步骤 1。否则,停止行动。\r\n返回能以递增顺序显示卡牌的牌组顺序。\r\n\r\n答案中的第一张牌被认为处于牌堆顶部。\r\n\r\n示例:\r\n输入:[17,13,11,2,3,5,7]\r\n输出:[2,13,3,11,5,17,7]\r\n解释:\r\n我们得到的牌组顺序为 [17,13,11,2,3,5,7](这个顺序不重要),然后将其重新排序。\r\n重新排序后,牌组以 [2,13,3,11,5,17,7] 开始,其中 2 位于牌组的顶部。\r\n我们显示 2,然后将 13 移到底部。牌组现在是 [3,11,5,17,7,13]。\r\n我们显示 3,并将 11 移到底部。牌组现在是 [5,17,7,13,11]。\r\n我们显示 5,然后将 17 移到底部。牌组现在是 [7,13,11,17]。\r\n我们显示 7,并将 13 移到底部。牌组现在是 [11,17,13]。\r\n我们显示 11,然后将 17 移到底部。牌组现在是 [13,17]。\r\n我们展示 13,然后将 17 移到底部。牌组现在是 [17]。\r\n我们显示 17。\r\n由于所有卡片都是按递增顺序排列显示的,所以答案是正确的。\r\n\r\n提示:\r\n1 <= A.length <= 1000\r\n1 <= A[i] <= 10^6\r\n对于所有的 i != j,A[i] != A[j]\r\n\"\"\"\r\n\r\n\r\nclass Solution:\r\n def deckRevealedIncreasing(self, deck):\r\n \"\"\"\r\n :type deck: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n\r\n deck.sort(reverse=True)\r\n result = []\r\n\r\n for d in deck:\r\n result.insert(0, d)\r\n result.insert(1, result.pop())\r\n # print(result)\r\n return (result)\r\n\r\n\r\ns = Solution()\r\ns.deckRevealedIncreasing([17, 13, 11, 2, 3, 5, 7])\r\ns.deckRevealedIncreasing(list(range(1000)))\r\n\r\n\"\"\"\r\n此题解法:\r\n* 采用逆向操作即可\r\n* 首先将数组排序(大 到 小)\r\n* 遍历数组,将数字插入到result的0位,然后尾部数字弹出,插入到1位即可。\r\n\r\n\"\"\"\r\n","sub_path":"LeetCode/950.py","file_name":"950.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"381126421","text":"import sys\r\nimport os.path\r\nimport shutil\r\nimport logging\r\nimport dicognito.__main__\r\nfrom .data_for_tests import load_dcm\r\n\r\ndata_dir = None\r\n\r\n\r\ndef setup_module(module):\r\n base_dir = os.path.dirname(__file__)\r\n orig_dir = os.path.join(base_dir, \"orig_data\")\r\n\r\n global data_dir\r\n data_dir = os.path.join(base_dir, \"..\", \"build\", \"data\")\r\n if os.path.isdir(data_dir):\r\n shutil.rmtree(data_dir)\r\n shutil.copytree(orig_dir, data_dir)\r\n\r\n\r\ndef test_overwrite_files():\r\n test_name = get_test_name()\r\n orig_dataset = read_original_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert \"CompressedSamples^MR1\" == orig_dataset.PatientName\r\n\r\n run_dicognito(path_to(\"p*\"))\r\n\r\n anon_dataset = read_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert anon_dataset.PatientName != orig_dataset.PatientName\r\n\r\n\r\ndef test_ignores_file_that_do_not_match_glob():\r\n test_name = get_test_name()\r\n orig_dataset = read_original_file(test_name, \"np01_s01_s01_i01.dcm\")\r\n assert \"CompressedSamples^MR1\" == orig_dataset.PatientName\r\n\r\n run_dicognito(path_to(\"p*\"))\r\n\r\n anon_dataset = read_file(test_name, \"np01_s01_s01_i01.dcm\")\r\n assert anon_dataset.PatientName == orig_dataset.PatientName\r\n\r\n\r\ndef test_summary_mixed_files_reports_on_each_study(capsys):\r\n expected_output = \"\"\"\\\r\nAccession Number Patient ID Patient Name\r\n---------------- ---------- ------------\r\nHGED6DXQTO1F DQFZ0HDKPYUX JENSEN^KELLIE^PATRICK\r\nXV266HDCGIOH DQFZ0HDKPYUX JENSEN^KELLIE^PATRICK\r\nUUM68P1IJHBE LXO0DMOPN7PV BUCHANAN^ALBA^MADGE\r\n\"\"\"\r\n run_dicognito(path_to(\"p*\"))\r\n (actual_output, actual_error) = capsys.readouterr()\r\n\r\n assert expected_output == actual_output\r\n\r\n\r\ndef test_summary_with_quiet_no_report(capsys):\r\n expected_output = \"\"\r\n\r\n run_dicognito(path_to(\"p*\"), \"--quiet\")\r\n (actual_output, actual_error) = capsys.readouterr()\r\n\r\n assert expected_output == actual_output\r\n\r\n\r\ndef test_summary_no_accession_number(capsys):\r\n expected_output = \"\"\"\\\r\nAccession Number Patient ID Patient Name\r\n---------------- ---------- ------------\r\n LXO0DMOPN7PV BUCHANAN^ALBA^MADGE\r\n\"\"\"\r\n run_dicognito(path_to(\"p*\"))\r\n (actual_output, actual_error) = capsys.readouterr()\r\n\r\n assert expected_output == actual_output\r\n\r\n\r\ndef test_directory_is_recursed():\r\n test_name = get_test_name()\r\n orig_dataset1 = read_original_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n orig_dataset2 = read_original_file(test_name, \"a\", \"b\", \"p01_s02_s01_i01.dcm\")\r\n assert \"CompressedSamples^MR1\" == orig_dataset1.PatientName\r\n assert \"CompressedSamples^MR1\" == orig_dataset2.PatientName\r\n\r\n run_dicognito(path_to(\"\"))\r\n\r\n anon_dataset1 = read_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n anon_dataset2 = read_file(test_name, \"a\", \"b\", \"p01_s02_s01_i01.dcm\")\r\n assert orig_dataset1.PatientName != anon_dataset1.PatientName\r\n assert orig_dataset2.PatientName != anon_dataset2.PatientName\r\n\r\n\r\ndef test_non_dicom_files_ignored(capsys):\r\n expected_error = \"\"\r\n\r\n test_name = get_test_name()\r\n orig_dataset = read_original_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert \"CompressedSamples^MR1\" == orig_dataset.PatientName\r\n\r\n run_dicognito(path_to(\"\"))\r\n (actual_output, actual_error) = capsys.readouterr()\r\n\r\n anon_dataset = read_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert orig_dataset.PatientName != anon_dataset.PatientName\r\n assert expected_error == actual_error\r\n\r\n\r\ndef test_non_dicom_files_logged_at_info(caplog):\r\n expected_error = \"not_a_dicom_file.txt appears not to be DICOM. Skipping.\"\r\n\r\n test_name = get_test_name()\r\n orig_dataset = read_original_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert \"CompressedSamples^MR1\" == orig_dataset.PatientName\r\n\r\n # py.test configures the logs itself, so setting the log level in the command\r\n # doesn't work. Instead, use caplog to set the level.\r\n caplog.set_level(logging.INFO)\r\n run_dicognito(path_to(\"\"))\r\n\r\n anon_dataset = read_file(test_name, \"p01_s01_s01_i01.dcm\")\r\n assert orig_dataset.PatientName != anon_dataset.PatientName\r\n\r\n log_record = caplog.records[0]\r\n assert log_record.levelname == \"INFO\"\r\n assert log_record.getMessage().endswith(expected_error)\r\n\r\n\r\ndef test_creates_output_directory_when_missing():\r\n run_dicognito(path_to(\"\"), \"--output-dir\", path_to(\"new_dir\"))\r\n\r\n assert os.path.isdir(path_to(\"new_dir\"))\r\n\r\n\r\ndef test_preserves_existing_source_files_when_writing_to_output_directory():\r\n run_dicognito(path_to(\"p01_s01_s01_i01.dcm\"), \"--output-dir\", path_to())\r\n\r\n orig_dataset = read_original_file(get_test_name(), \"p01_s01_s01_i01.dcm\")\r\n assert orig_dataset.SOPInstanceUID == \"1.3.6.1.4.1.5962.20040827145012.5458.1.1.1.1\"\r\n\r\n\r\ndef test_writes_file_as_sop_instance_uid_in_output_directory():\r\n run_dicognito(path_to(\"p01_s01_s01_i01.dcm\"), \"--output-dir\", path_to(\"new_dir\"))\r\n\r\n all_output_files = os.listdir(path_to(\"new_dir\"))\r\n assert len(all_output_files) == 1\r\n\r\n dataset = read_file(get_test_name(), \"new_dir\", all_output_files[0])\r\n assert all_output_files[0] == dataset.SOPInstanceUID + \".dcm\"\r\n\r\n\r\ndef test_retains_existing_files_in_output_directory():\r\n run_dicognito(path_to(\"p01_s01_s01_i01.dcm\"), \"--output-dir\", path_to())\r\n\r\n all_output_files = os.listdir(path_to())\r\n assert len(all_output_files) == 2\r\n assert \"p01_s01_s01_i01.dcm\" in all_output_files\r\n\r\n\r\ndef test_writes_deflated_file_correctly():\r\n run_dicognito(path_to(\"CT_small_deflated.dcm\"), \"--output-dir\", path_to(\"new_dir\"))\r\n\r\n output_file_name = os.listdir(path_to(\"new_dir\"))[0]\r\n\r\n read_file(get_test_name(), \"new_dir\", output_file_name)\r\n\r\n\r\ndef get_test_name():\r\n depth = 1\r\n while True:\r\n frame = sys._getframe(depth)\r\n if frame.f_code.co_name.startswith(\"test\"):\r\n return frame.f_code.co_name\r\n depth += 1\r\n\r\n\r\ndef path_to(*end_of_path):\r\n return os.path.join(data_dir, get_test_name(), *end_of_path)\r\n\r\n\r\ndef run_dicognito(*extra_args):\r\n dicognito.__main__.main((\"--seed\", \"\") + extra_args)\r\n\r\n\r\ndef read_file(*directory_parts):\r\n return load_dcm(data_dir, *directory_parts)\r\n\r\n\r\ndef read_original_file(*directory_parts):\r\n return load_dcm(\"orig_data\", *directory_parts)\r\n","sub_path":"tests/test_commandline.py","file_name":"test_commandline.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"498046138","text":"import os\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\nmessage = Mail(\n from_email='from-email@some-domain.com',\n to_emails='to-email@some-domain.com',\n subject='Subject for the message',\n html_content='Some message')\ntry:\n # Save the API key from sendgrid as env variable with the\n # key name as SENDGRID_API_KEY.\n key = os.environ.get('SENDGRID_API_KEY')\n sg = SendGridAPIClient(key)\n response = sg.send(message)\n print(response.status_code)\nexcept Exception as e:\n print(str(e))\n","sub_path":"Python/email-using-sendgrid.py","file_name":"email-using-sendgrid.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"579042516","text":"import datetime\n\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.core.mail import mail_admins\nfrom django.core.urlresolvers import reverse_lazy, reverse\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models.signals import pre_delete\nfrom django.db.models import F\nfrom mptt.models import MPTTModel, TreeForeignKey\n\nfrom apps.users.models import Company\nfrom awecounting.utils.helpers import zero_for_none, none_for_zero\n\n\nclass Node(object):\n def __init__(self, model, parent=None, depth=0, company=None):\n self.children = []\n self.model = model\n self.name = self.model.name\n self.type = self.model.__class__.__name__\n self.dr = 0\n self.cr = 0\n self.url = None\n self.depth = depth\n self.parent = parent\n self.company = company or str(self.model.company)\n if self.type == 'Category':\n for child in self.model.children.all():\n self.add_child(Node(child, parent=self, depth=self.depth + 1, company=self.company))\n for account in self.model.accounts.all():\n self.add_child(Node(account, parent=self, depth=self.depth + 1, company=self.company))\n if self.type == 'Account':\n self.dr = self.model.current_dr or 0\n self.cr = self.model.current_cr or 0\n self.url = self.model.get_absolute_url()\n if self.parent:\n self.parent.dr += self.dr\n self.parent.cr += self.cr\n\n def add_child(self, obj):\n self.children.append(obj.get_data())\n\n def get_data(self):\n data = {\n 'name': self.name,\n 'type': self.type,\n 'dr': round(self.dr, 2),\n 'cr': round(self.cr, 2),\n 'nodes': self.children,\n 'depth': self.depth,\n 'url': self.url,\n 'company': self.company,\n }\n return data\n\n def __str__(self):\n return self.name\n\n\nclass Category(MPTTModel):\n name = models.CharField(max_length=50)\n description = models.CharField(max_length=254, null=True, blank=True)\n code = models.CharField(max_length=20, null=True, blank=True)\n default = models.BooleanField(default=False)\n parent = TreeForeignKey('self', blank=True, null=True, related_name='children')\n company = models.ForeignKey(Company, related_name='categories')\n\n def __unicode__(self):\n return self.name\n\n def get_data(self):\n node = Node(self)\n return node.get_data()\n\n def get_descendant_ledgers(self):\n ledgers = self.accounts.all()\n for descendant in self.get_descendants():\n ledgers = ledgers | descendant.accounts.all()\n return ledgers\n\n class Meta:\n verbose_name_plural = u'Categories'\n unique_together = ('company', 'name')\n\n\nclass Account(models.Model):\n code = models.CharField(max_length=20, blank=True, null=True)\n name = models.CharField(max_length=100)\n company = models.ForeignKey(Company)\n current_dr = models.FloatField(null=True, blank=True)\n current_cr = models.FloatField(null=True, blank=True)\n parent = models.ForeignKey('self', blank=True, null=True, related_name='children')\n category = models.ForeignKey(Category, related_name='accounts', blank=True, null=True)\n tax_rate = models.FloatField(blank=True, null=True)\n opening_dr = models.FloatField(default=0)\n opening_cr = models.FloatField(default=0)\n default = models.BooleanField(default=False)\n fy = models.PositiveSmallIntegerField(blank=True, null=True)\n\n _original_opening_dr = 0\n _original_opening_cr = 0\n\n def __init__(self, *args, **kwargs):\n super(Account, self).__init__(*args, **kwargs)\n self._original_opening_dr = self.opening_dr\n self._original_opening_cr = self.opening_cr\n\n def get_absolute_url(self):\n # return '/ledger/' + str(self.id)\n return reverse('view_ledger', kwargs={'pk': self.pk})\n\n # def get_last_day_last_transaction(self):\n # transactions = Transaction.objects.filter(account=self, date__lt=date.today()).order_by('-id', '-date')[:1]\n # if len(transactions) > 0:\n # return transactions[0]\n #\n # def get_last_transaction_before(self, before_date):\n # transactions = Transaction.objects.filter(account=self, date__lt=before_date).order_by('-id', '-date')[:1]\n # if len(transactions) > 0:\n # return transactions[0]\n #\n\n def suggest_code(self):\n if self.category:\n cat_code = self.category.code or ''\n max = 0\n for account in self.category.accounts.all():\n code = account.code.strip(cat_code + '-')\n if code.isdigit() and int(code) > max:\n max = int(code)\n if cat_code:\n self.code = cat_code + '-' + str(max + 1)\n else:\n self.code = str(max + 1)\n\n @property\n def balance(self):\n return self.get_balance()\n\n def get_balance(self):\n return zero_for_none(self.current_dr) - zero_for_none(self.current_cr)\n\n def get_day_opening_dr(self, before_date=None):\n if not before_date:\n before_date = datetime.date.today()\n transactions = Transaction.objects.filter(account=self, journal_entry__date__lt=before_date).order_by(\n '-journal_entry__id', '-journal_entry__date')[:1]\n if len(transactions) > 0:\n return transactions[0].current_dr\n return self.current_dr\n\n def get_day_opening_cr(self, before_date=None):\n if not before_date:\n before_date = datetime.date.today()\n transactions = Transaction.objects.filter(account=self, journal_entry__date__lt=before_date).order_by(\n '-journal_entry__id', '-journal_entry__date')[:1]\n if len(transactions) > 0:\n return transactions[0].current_cr\n return self.current_cr\n\n def get_day_opening(self, before_date=None):\n if not before_date:\n before_date = datetime.date.today()\n transactions = Transaction.objects.filter(account=self, journal_entry__date__lt=before_date).order_by(\n '-journal_entry__id', '-journal_entry__date')[:1]\n if len(transactions) > 0:\n return zero_for_none(transactions[0].current_dr) - zero_for_none(transactions[0].current_cr)\n return self.opening_dr - self.opening_cr\n\n def add_category(self, category):\n # all_categories = self.get_all_categories()\n category_instance, created = Category.objects.get_or_create(name=category, company=self.company)\n # self.categories.add(category_instance)\n self.category = category_instance\n\n def get_all_categories(self):\n return self.category.get_ancestors(include_self=True)\n\n categories = property(get_all_categories)\n\n def get_cr_amount(self, day):\n # journal_entry= JournalEntry.objects.filter(date__lt=day,transactions__account=self).order_by('-id','-date')[:1]\n transactions = Transaction.objects.filter(journal_entry__date__lt=day, account=self).order_by(\n '-journal_entry__id', '-journal_entry__date')[:1]\n if len(transactions) > 0:\n return transactions[0].current_cr\n return 0\n\n def get_dr_amount(self, day):\n # journal_entry= JournalEntry.objects.filter(date__lt=day,transactions__account=self).order_by('-id','-date')[:1]\n transactions = Transaction.objects.filter(journal_entry__date__lt=day, account=self).order_by(\n '-journal_entry__id', '-journal_entry__date')[:1]\n if len(transactions) > 0:\n return transactions[0].current_dr\n return 0\n\n def get_voucher_no(self):\n # Use code as voucher number in ledger view when \n # an account is the source of journal entry for opening balance transactions\n return self.code\n\n def save(self, *args, **kwargs):\n if not self.pk:\n queryset = Account.objects.filter(company=self.company)\n original_name = self.name\n nxt = 2\n while queryset.filter(**{'name': self.name}):\n self.name = original_name\n end = '%s%s' % ('-', nxt)\n if len(self.name) + len(end) > 100:\n self.name = self.name[:100 - len(end)]\n self.name = '%s%s' % (self.name, end)\n nxt += 1\n opening_balance_equity = None\n super(Account, self).save(*args, **kwargs)\n if self.opening_dr != self._original_opening_dr:\n entries = []\n opening_balance_equity = Account.objects.get(name='Opening Balance Equity', category__name='Equity', company=self.company)\n entries.append(['cr', opening_balance_equity, self.opening_dr])\n entries.append(['dr', self, self.opening_dr])\n self._original_opening_dr = self.opening_dr\n set_transactions(self, datetime.date.today(), *entries)\n if self.opening_cr != self._original_opening_cr:\n entries = []\n if not opening_balance_equity:\n opening_balance_equity = Account.objects.get(name='Opening Balance Equity', category__name='Equity', company=self.company)\n entries.append(['dr', opening_balance_equity, self.opening_cr])\n entries.append(['cr', self, self.opening_cr])\n self._original_opening_cr = self.opening_cr\n set_transactions(opening_balance_equity, datetime.date.today(), *entries)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n unique_together = ('name', 'company')\n\n\nclass JournalEntry(models.Model):\n date = models.DateField()\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n source = GenericForeignKey('content_type', 'object_id')\n\n def __str__(self):\n return str(self.content_type) + ': ' + str(self.object_id) + ' [' + str(self.date) + ']'\n\n class Meta:\n verbose_name_plural = u'Journal Entries'\n\n\nclass Transaction(models.Model):\n account = models.ForeignKey(Account)\n dr_amount = models.FloatField(null=True, blank=True)\n cr_amount = models.FloatField(null=True, blank=True)\n current_dr = models.FloatField(null=True, blank=True)\n current_cr = models.FloatField(null=True, blank=True)\n journal_entry = models.ForeignKey(JournalEntry, related_name='transactions')\n\n def get_balance(self):\n return zero_for_none(self.current_dr) - zero_for_none(self.current_cr)\n\n def __str__(self):\n return str(self.account) + ' [' + str(self.dr_amount) + ' / ' + str(self.cr_amount) + ']'\n\n\ndef alter(account, date, dr_difference, cr_difference):\n Transaction.objects.filter(journal_entry__date__gt=date, account=account).update(\n current_dr=none_for_zero(zero_for_none(F('current_dr')) + zero_for_none(dr_difference)),\n current_cr=none_for_zero(zero_for_none(F('current_cr')) + zero_for_none(cr_difference)))\n\n\ndef set_transactions(submodel, date, *args):\n if isinstance(date, unicode):\n date = datetime.datetime.strptime(date, '%Y-%m-%d')\n journal_entry, created = JournalEntry.objects.get_or_create(\n content_type=ContentType.objects.get_for_model(submodel), object_id=submodel.id,\n defaults={\n 'date': date\n })\n dr_total = 0\n cr_total = 0\n for arg in args:\n # transaction = Transaction(account=arg[1], dr_amount=arg[2])\n matches = journal_entry.transactions.filter(account=arg[1])\n val = round(float(zero_for_none(arg[2])), 2)\n if not matches:\n transaction = Transaction()\n transaction.account = arg[1]\n if arg[0] == 'dr':\n transaction.dr_amount = val\n transaction.cr_amount = None\n transaction.account.current_dr = none_for_zero(zero_for_none(transaction.account.current_dr) + val)\n alter(arg[1], date, val, 0)\n dr_total += val\n if arg[0] == 'cr':\n transaction.cr_amount = val\n transaction.dr_amount = None\n transaction.account.current_cr = none_for_zero(zero_for_none(transaction.account.current_cr) + val)\n alter(arg[1], date, 0, float(arg[2]))\n cr_total += val\n transaction.current_dr = none_for_zero(\n round(zero_for_none(transaction.account.get_dr_amount(date + datetime.timedelta(days=1)))\n + zero_for_none(transaction.dr_amount), 2)\n )\n transaction.current_cr = none_for_zero(\n round(zero_for_none(transaction.account.get_cr_amount(date + datetime.timedelta(days=1)))\n + zero_for_none(transaction.cr_amount), 2)\n )\n else:\n transaction = matches[0]\n transaction.account = arg[1]\n\n # cancel out existing dr_amount and cr_amount from current_dr and current_cr\n # if transaction.dr_amount:\n # transaction.current_dr -= transaction.dr_amount\n # transaction.account.current_dr -= transaction.dr_amount\n #\n # if transaction.cr_amount:\n # transaction.current_cr -= transaction.cr_amount\n # transaction.account.current_cr -= transaction.cr_amount\n\n # save new dr_amount and add it to current_dr/cr\n if arg[0] == 'dr':\n dr_difference = val - zero_for_none(transaction.dr_amount)\n cr_difference = zero_for_none(transaction.cr_amount) * -1\n alter(arg[1], transaction.journal_entry.date, dr_difference, cr_difference)\n transaction.dr_amount = val\n transaction.cr_amount = None\n dr_total += transaction.dr_amount\n else:\n cr_difference = val - zero_for_none(transaction.cr_amount)\n dr_difference = zero_for_none(transaction.dr_amount) * -1\n alter(arg[1], transaction.journal_entry.date, dr_difference, cr_difference)\n transaction.cr_amount = val\n transaction.dr_amount = None\n cr_total += transaction.cr_amount\n\n transaction.current_dr = none_for_zero(zero_for_none(transaction.current_dr) + dr_difference)\n transaction.current_cr = none_for_zero(zero_for_none(transaction.current_cr) + cr_difference)\n transaction.account.current_dr = none_for_zero(\n zero_for_none(transaction.account.current_dr) + dr_difference)\n transaction.account.current_cr = none_for_zero(\n zero_for_none(transaction.account.current_cr) + cr_difference)\n\n # the following code lies outside if,else block, inside for loop\n transaction.account.save()\n try:\n journal_entry.transactions.add(transaction, bulk=False)\n except TypeError: # for Django <1.9\n journal_entry.transactions.add(transaction)\n if dr_total != cr_total:\n mail_admins('Dr/Cr mismatch!',\n 'Dr/Cr mismatch from {0}, ID: {1}, Dr: {2}, Cr: {3}'.format(str(submodel), submodel.id, dr_total, cr_total))\n raise RuntimeError('Dr/Cr mismatch!')\n\n\ndef delete_rows(rows, model):\n for row in rows:\n if row.get('id'):\n instance = model.objects.get(id=row.get('id'))\n try:\n JournalEntry.objects.get(content_type=ContentType.objects.get_for_model(model),\n model_id=instance.id).delete()\n except:\n pass\n instance.delete()\n\n\n# @receiver(pre_delete, sender=Transaction)\ndef _transaction_delete(sender, instance, **kwargs):\n transaction = instance\n # cancel out existing dr_amount and cr_amount from account's current_dr and current_cr\n if transaction.dr_amount:\n transaction.account.current_dr = zero_for_none(transaction.account.current_dr)\n transaction.account.current_dr -= transaction.dr_amount\n\n if transaction.cr_amount:\n transaction.account.current_cr = zero_for_none(transaction.account.current_cr)\n transaction.account.current_cr -= transaction.cr_amount\n\n alter(transaction.account, transaction.journal_entry.date, float(zero_for_none(transaction.dr_amount)) * -1,\n float(zero_for_none(transaction.cr_amount)) * -1)\n\n transaction.account.save()\n\n\npre_delete.connect(_transaction_delete, Transaction, dispatch_uid=\"apps.ledgers.models\")\n\nfrom apps.users.signals import company_creation\n\n\ndef handle_company_creation(sender, **kwargs):\n company = kwargs.get('company')\n\n # CREATE DEFAULT CATEGORIES AND LEDGERS FOR EQUITY\n\n equity = Category.objects.create(name='Equity', code='E', company=company, default=True)\n Account.objects.create(name='Paid in Capital', category=equity, code='E-PC', company=company, default=True)\n Account.objects.create(name='Retained Earnings', category=equity, code='E-RE', company=company, default=True)\n # Account.objects.create(name='Profit and Loss Account', category=equity, code='E-PL', company=company, default=True)\n Account.objects.create(name='Opening Balance Equity', category=equity, code='E-OBE', company=company, default=True)\n\n # CREATE DEFAULT CATEGORIES AND LEDGERS FOR ASSETS\n\n assets = Category.objects.create(name='Assets', code='A', company=company, default=True)\n Category.objects.create(name='Other Receivables', code='A-OR', parent=assets, company=company, default=True)\n Category.objects.create(name='Tax Receivables', code='A-TR', parent=assets, company=company, default=True)\n Category.objects.create(name='Deferred Assets', code='A-DA', parent=assets, company=company, default=True)\n Category.objects.create(name='Fixed Assets', code='A-FA', parent=assets, company=company, default=True)\n Category.objects.create(name='Loans and Advances Given', code='A-L', parent=assets, company=company, default=True)\n Category.objects.create(name='Deposits Made', code='A-D', parent=assets, company=company, default=True)\n Category.objects.create(name='Employee', code='A-E', parent=assets, company=company, default=True)\n\n cash_account = Category.objects.create(name='Cash Accounts', code='A-C', parent=assets, company=company, default=True)\n Account.objects.create(company=company, default=True, name='Cash', category=cash_account, code='A-C-C')\n Account.objects.create(name='Merchandise', category=assets, code='A-M', company=company, default=True)\n cash_equivalent_account = Category.objects.create(name='Cash Equivalent Account', code='A-CE', parent=assets, company=company, default=True)\n Account.objects.create(name='Cheque Account', category=cash_equivalent_account, code='A-CE-CQ', company=company, default=True)\n\n bank_account = Category.objects.create(name='Bank Account', code='A-B', parent=assets, company=company, default=True)\n # Account(name='ATM Account', category=bank_account, code='A-B-A', company=company, default=True).save()\n # Account(name='Bank Account', category=bank_account, code='A-B-B', company=company, default=True).save()\n # Account(name='Card Account', category=bank_account, code='A-B-Ca', company=company, default=True).save()\n\n account_receivables = Category.objects.create(name='Account Receivables', code='A-AR', parent=assets, company=company, default=True)\n Category.objects.create(name='Customers', code='A-AR-C', parent=account_receivables, company=company, default=True)\n\n employee_deductions = Category.objects.create(name='Employee Deductions', code='A-ED', parent=assets, company=company, default=True)\n Account.objects.create(name='Advances', category=employee_deductions, code='A-ED-AD', company=company, default=True)\n Account.objects.create(name='Loans', category=employee_deductions, code='A-ED-L', company=company, default=True)\n Account.objects.create(name='Payroll Taxes', category=employee_deductions, code='A-ED-T', company=company, default=True)\n Account.objects.create(name='Employees\\' Contribution to Retirement Fund', category=employee_deductions, code='A-ED-RF',\n company=company, default=True)\n Account.objects.create(name='Compulsory Deductions', category=employee_deductions, code='A-ED-CD', company=company, default=True)\n\n # CREATE DEFAULT CATEGORIES AND LEDGERS FOR LIABILITIES\n\n liabilities = Category.objects.create(name='Liabilities', code='L', company=company, default=True)\n account_payables = Category.objects.create(name='Account Payables', code='L-AP', parent=liabilities, company=company, default=True)\n Category.objects.create(name='Suppliers', parent=account_payables, code='L-AP-S', company=company, default=True)\n other_payables = Category.objects.create(name='Other Payables', code='L-OP', parent=liabilities, company=company, default=True)\n Account.objects.create(name='Utility Bills Account', category=other_payables, code='L-OP-U', company=company, default=True)\n Category.objects.create(name='Provisions', code='L-P', parent=liabilities, company=company, default=True)\n secured_loans = Category.objects.create(name='Secured Loans', code='L-SL', parent=liabilities, company=company, default=True)\n Account.objects.create(name='Bank OD', category=secured_loans, code='L-SL-OD', company=company, default=True)\n Account.objects.create(name='Bank Loans', category=secured_loans, code='L-SL-BL', company=company, default=True)\n Category.objects.create(name='Unsecured Loans', code='L-US', parent=liabilities, company=company, default=True)\n Category.objects.create(name='Deposits Taken', code='L-DT', parent=liabilities, company=company, default=True)\n Category.objects.create(name='Loans & Advances Taken', code='L-L&A', parent=liabilities, company=company, default=True)\n duties_and_taxes = Category.objects.create(name='Duties & Taxes', code='L-T', parent=liabilities, company=company, default=True)\n Account.objects.create(name='Sales Tax', category=duties_and_taxes, code='L-T-S', company=company, default=True)\n Account.objects.create(name='Payroll Tax', category=duties_and_taxes, code='L-T-P', company=company, default=True)\n Account.objects.create(name='Income Tax', category=duties_and_taxes, code='L-T-I', company=company, default=True)\n\n # CREATE DEFAULT CATEGORIES FOR INCOME\n\n income = Category.objects.create(name='Income', code='I', company=company, default=True)\n Category.objects.create(name='Sales', code='I-S', parent=income, company=company, default=True)\n direct_income = Category.objects.create(name='Direct Income', code='I-D', parent=income, company=company, default=True)\n Category.objects.create(name='Transfer and Remittance', code='I-D-T&R', parent=direct_income, company=company, default=True)\n Category.objects.create(name='Indirect Income', code='I-II', parent=income, company=company, default=True)\n\n # CREATE DEFAULT CATEGORIES FOR EXPENSES\n\n expenses = Category.objects.create(name='Expenses', code='E', company=company, default=True)\n Category.objects.create(name='Purchase', code='E-P', parent=expenses, company=company, default=True)\n\n direct_expenses = Category.objects.create(name='Direct Expenses', code='E-DE', parent=expenses, company=company, default=True)\n Category.objects.create(name='Purchase Expenses', code='E-DE-PE', parent=direct_expenses, company=company, default=True)\n indirect_expenses = Category.objects.create(name='Indirect Expenses', code='E-IE', parent=expenses, company=company, default=True)\n Category.objects.create(name='Pay Head', code='E-IE-P', parent=indirect_expenses, company=company, default=True)\n\n # Opening Balance Difference\n\n # opening_balance_difference = Category.objects.create(name='Opening Balance Difference', code='O', company=company, default=True)\n # Account.objects.create(name='Opening Balance Difference', code='O-OBD', category=opening_balance_difference, company=company, default=True)\n\n handle_fy_creation(sender, company=company, default=True, fy=company.fy)\n\n\ndef handle_fy_creation(sender, **kwargs):\n company = kwargs.get('company')\n fy = kwargs.get('fy')\n\n # CREATE DEFAULT LEDGERS FOR INCOME FOR THE FY\n\n income = Category.objects.get(name='Income', company=company, default=True)\n sales = Category.objects.get(name='Sales', parent=income, company=company, default=True)\n indirect_income = Category.objects.get(name='Indirect Income', code='I-II', parent=income, company=company, default=True)\n Account.objects.create(name='Discount Income', category=indirect_income, code='I-II-DI', company=company, default=True, fy=fy)\n Account.objects.create(name='Non-tax Sales', category=sales, code='I-S-NT', company=company, default=True, fy=fy)\n Account.objects.create(name='Sales', category=sales, code='I-S-S', company=company, default=True, fy=fy)\n direct_income = Category.objects.get(name='Direct Income', parent=income, company=company, default=True)\n transfer_remittance = Category.objects.get(name='Transfer and Remittance', parent=direct_income, company=company, default=True)\n Account.objects.create(name='Bill Payments', code='I-DI-T&R-BP', category=transfer_remittance, company=company, default=True, fy=fy)\n indirect_income = Category.objects.get(name='Indirect Income', parent=income, company=company, default=True)\n Account.objects.create(name='Commission In', code='I-II-CI', category=indirect_income, company=company, default=True, fy=fy)\n\n # CREATE DEFAULT LEDGERS FOR EXPENSE FOR THE FY\n\n expenses = Category.objects.get(name='Expenses', company=company, default=True)\n purchase = Category.objects.get(name='Purchase', parent=expenses, company=company, default=True)\n Account.objects.create(name='Purchases', code='E-P-P', category=purchase, company=company, default=True, fy=fy)\n\n direct_expenses = Category.objects.get(name='Direct Expenses', parent=expenses, company=company, default=True)\n Account.objects.create(name='Wages', category=direct_expenses, code='E-DE-W', company=company, default=True, fy=fy)\n\n indirect_expenses = Category.objects.get(name='Indirect Expenses', parent=expenses, company=company, default=True)\n Account.objects.create(name='Payroll Expenses', category=indirect_expenses, code='E-IE-P', company=company, default=True, fy=fy)\n Account.objects.create(name='Rent Expenses', category=indirect_expenses, code='E-IE-R', company=company, default=True, fy=fy)\n Account.objects.create(name='Commission Out', category=indirect_expenses, code='E-IE-CO', company=company, default=True, fy=fy)\n Account.objects.create(name='Bank Charges Expenses', category=indirect_expenses, code='E-IR-BC', company=company, default=True, fy=fy)\n Account.objects.create(name='Bank Interest Expenses', category=indirect_expenses, code='E-IE-BI', company=company, default=True, fy=fy)\n Account.objects.create(name='Electricity Expenses', category=indirect_expenses, code='E-IE-E', company=company, default=True, fy=fy)\n Account.objects.create(name='Telecommunication Expenses', category=indirect_expenses, code='E-IE-T', company=company, default=True, fy=fy)\n\n Account.objects.create(name='Travelling and Conveyance Expenses', category=indirect_expenses, code='E-IE-T&C',\n company=company, default=True, fy=fy)\n Account.objects.create(name='Lunch and Refreshment Expenses', category=indirect_expenses, code='E-IE-L&R',\n company=company, default=True, fy=fy)\n Account.objects.create(name='Cleaning Expenses', category=indirect_expenses, code='E-IE-C', company=company, default=True, fy=fy)\n Account.objects.create(name='Discount Expenses', category=indirect_expenses, code='E-IE-D', company=company, default=True, fy=fy)\n Account.objects.create(name='Repairs and Maintenance Expenses', category=indirect_expenses, code='E-IE-R&M', company=company, default=True,\n fy=fy)\n Account.objects.create(name='Drainage/Garbage Collection Expenses', category=indirect_expenses, code='E-IE-D&G',\n company=company, default=True, fy=fy)\n Account.objects.create(name='Water Supply Expenses', category=indirect_expenses, code='E-IE-W', company=company, default=True, fy=fy)\n Account.objects.create(name='City/Municipal Expenses', category=indirect_expenses, code='E-IE-C&M', company=company, default=True, fy=fy)\n\n purchase_expenses = Category.objects.get(name='Purchase Expenses', parent__name='Direct Expenses', company=company, default=True)\n Account.objects.create(name='Carriage Inwards', category=purchase_expenses, code='E-DE-PE-CI', company=company, default=True, fy=fy)\n Account.objects.create(name='Customs Duty', category=purchase_expenses, code='E-DE-PE-CD', company=company, default=True, fy=fy)\n\n pay_head = Category.objects.get(name='Pay Head', parent=indirect_expenses, company=company, default=True)\n Account.objects.create(name='Salary', category=pay_head, code='E-IE-P-S', company=company, default=True, fy=fy)\n Account.objects.create(name='Allowances', category=pay_head, code='E-IE-P-A', company=company, default=True, fy=fy)\n Account.objects.create(name='Benefits', category=pay_head, code='E-IE-P-B', company=company, default=True, fy=fy)\n Account.objects.create(name='Employees\\' Insurance', category=pay_head, code='E-IE-P-I', company=company, default=True, fy=fy)\n Account.objects.create(name='Travelling Allowance', category=pay_head, code='E-IE-P-TA', company=company, default=True, fy=fy)\n Account.objects.create(name='Daily Allowance', category=pay_head, code='E-IE-P-DA', company=company, default=True, fy=fy)\n\n\ncompany_creation.connect(handle_company_creation)\n\n\nclass Party(models.Model):\n name = models.CharField(max_length=254)\n address = models.TextField(blank=True, null=True)\n phone_no = models.CharField(max_length=100, blank=True, null=True)\n pan_no = models.CharField(max_length=50, blank=True, null=True, verbose_name='Tax Reg. No.')\n account = models.ForeignKey(Account, null=True)\n TYPES = [('Customer', 'Customer'), ('Supplier', 'Supplier'), ('Customer/Supplier', 'Customer/Supplier')]\n type = models.CharField(choices=TYPES, max_length=17, default='Customer/Supplier')\n supplier_account = models.OneToOneField(Account, null=True, related_name='supplier_detail')\n customer_account = models.OneToOneField(Account, null=True, related_name='customer_detail')\n company = models.ForeignKey(Company, related_name='parties')\n related_company = models.ForeignKey(Company, blank=True, null=True, related_name='related_party')\n email = models.EmailField(verbose_name='email address', blank=True, null=True, max_length=254, unique=True, db_index=True)\n\n def get_absolute_url(self):\n return reverse_lazy('party_edit', kwargs={'pk': self.pk})\n\n @property\n def balance(self):\n return zero_for_none(self.customer_account.current_dr) - zero_for_none(\n self.customer_account.current_cr) + zero_for_none(\n self.supplier_account.current_cr) - zero_for_none(self.supplier_account.current_dr)\n\n def save(self, *args, **kwargs):\n self.post = kwargs.pop('post', True)\n super(Party, self).save(*args, **kwargs)\n\n if self.post:\n self.post_save()\n\n def post_save(self):\n account = Account(name=self.name)\n account.company = self.company\n if self.type == 'Customer':\n if not self.customer_account:\n try:\n account.category = Category.objects.get(name='Customers', company=self.company)\n account.suggest_code()\n account.save()\n self.customer_account = account\n except Category.DoesNotExist:\n pass\n if self.supplier_account:\n self.supplier_account.delete()\n self.supplier_account = None\n elif self.type == 'Supplier':\n if not self.supplier_account:\n try:\n account.category = Category.objects.get(name='Suppliers', company=self.company)\n account.suggest_code()\n account.save()\n self.supplier_account = account\n except Category.DoesNotExist:\n pass\n if self.customer_account:\n self.customer_account.delete()\n self.customer_account = None\n else:\n if not self.customer_account:\n account.name += ' (Receivable)'\n try:\n account.category = Category.objects.get(name='Customers', company=self.company)\n account.suggest_code()\n account.save()\n self.customer_account = account\n except Category.DoesNotExist:\n pass\n if not self.supplier_account:\n try:\n account2 = Account(name=self.name + ' (Payable)')\n account2.company = self.company\n account2.category = Category.objects.get(name='Suppliers', company=self.company)\n account2.suggest_code()\n account2.save()\n self.supplier_account = account2\n except Category.DoesNotExist:\n pass\n self.save(post=False)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = 'Parties'\n unique_together = ('company', 'related_company')\n\n # @receiver(branch_creation)\n # def handle_branch_creation(sender, **kwargs):\n # Party.objects.create(name=kwargs['name'], company=kwargs['company'])\n # print \"Handle branch\"\n # pass\n\n\ndef get_account(request_or_company, name):\n if not request_or_company.__class__.__name__ == 'Company':\n company = request_or_company.company\n else:\n company = request_or_company\n if name in ['Purchase', 'Purchases']:\n return Account.objects.get(name='Purchase', category__name='Purchase', company=company)\n if name in ['Cash', 'Cash Account']:\n return Account.objects.get(name='Cash', category__name='Cash Accounts', company=company)\n","sub_path":"apps/ledger/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":34384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"270651212","text":"\"\"\"Converts 'transcription' (or 'entity' if available) from spacy Doc to RTTM file via pyannote Annotation\nAlso maps speaker identifier to their most common name if requested.\nNote that only speech segments will be considered as annotated (i.e. discarded from the UEM).\n\nUsage: transcription_to_rttm.py [--common_name --confidence=]\n\nOptions:\n--common_name Map speaker identifier to their most common name\n using hand-crafted mapping.\n If speaker identifier is not in the mapping it will be discarded from the UEM\n--confidence= Discard words with a confidence lower than from the UEM\n Defaults to keep all words [Recommended: 0.5]\n\"\"\"\n\nfrom docopt import docopt\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport json\n\nfrom pyannote.core import Segment, Timeline, Annotation\nfrom pyannote.database import get_protocol\nimport Plumcot as PC\n\nDATA_PATH = Path(PC.__file__).parent / 'data'\nTRANSCRIPT = 'annotated_transcripts'\n\n\ndef transcription_to_annotation(transcription, uri=None, mapping=None, confidence=0.0):\n annotation = Annotation(uri=uri, modality='speaker')\n annotated = Timeline(uri=uri)\n for word in transcription:\n segment = Segment(word._.time_start, word._.time_end)\n # map speaker identifier to common name if mapping else keep identifier\n speaker = mapping.get(word._.speaker) if mapping else word._.speaker\n if speaker and word._.confidence >= confidence:\n annotation[segment, speaker] = speaker\n annotated.add(segment)\n return annotation, annotated\n\n\ndef protocol_to_rttm(protocol, rttm_out, uem_out, mapping=None, confidence=0.0):\n for current_file in tqdm(protocol.files(), desc='Converting transcriptions'):\n transcription = current_file.get('entity', current_file['transcription'])\n uri = current_file['uri']\n annotation, annotated = transcription_to_annotation(transcription, uri,\n mapping, confidence)\n with open(rttm_out, 'a') as file:\n annotation.write_rttm(file)\n with open(uem_out, 'a') as file:\n annotated.write_uem(file)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n protocol_name = args['']\n confidence = float(args['--confidence']) if args['--confidence'] else 0.\n protocol = get_protocol(protocol_name)\n serie, _, _ = protocol_name.split('.')\n output_path = DATA_PATH / serie / TRANSCRIPT\n rttm_out = output_path / f'{protocol_name}.rttm'\n uem_out = output_path / f'{protocol_name}.uem'\n for path in [rttm_out, uem_out]:\n if path.exists():\n raise ValueError(f\"'{path}' already exists, you probably don't want \"\n f\"to append any more data to it\")\n if args['--common_name']:\n # load mapping\n with open(DATA_PATH / serie / TRANSCRIPT / 'names_dict.json') as file:\n mapping = json.load(file)\n else:\n mapping = None\n protocol_to_rttm(protocol, rttm_out, uem_out, mapping, confidence)\n\n","sub_path":"scripts/transcription_to_rttm.py","file_name":"transcription_to_rttm.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"610699594","text":"import numpy as np\n\nbest = 0\n\n\ndef product(num):\n if len(num) == 1:\n return num[0]\n return num[0] * product(num[1:])\n\n\ndef amounts():\n for i in range(101):\n for j in range(101 - i):\n for k in range(101 - (i + j)):\n l = 100 - (i + j + k)\n yield np.array([i, j, k, l], dtype=np.int32)\n\n\nwith open(\"input15.txt\", encoding=\"utf-8\") as file:\n raw_data = [line.split() for line in file.readlines()]\n\n# The data has colons and commas on some lines, we strip them away here\ndata = [[word.strip(':,') for word in line] for line in raw_data]\n\n# The numbers that we need are still strings, so we pick them out and convert them\nnumbers = np.array([[int(x) for x in group[2::2]] for group in data], dtype=np.int32)\n\nfor group in amounts():\n numbers_copy = np.copy(numbers)\n for i, (pair) in enumerate(zip(numbers_copy, group)):\n # print(pair)\n # print(pair[0] * pair[1])\n numbers_copy[i] = pair[0] * pair[1]\n\n summed = []\n for column in numbers_copy.T:\n temp = np.sum(column)\n if temp < 0:\n temp = 0\n summed.append(temp)\n score = product(summed[:-1])\n if summed[-1] == 500 and score > best:\n best = score\n # print(score)\n # print(numbers_copy)\nprint(best)\n\n# for pair in zip(numbers_array, test):\n# print(pair)\n# print(pair[0] * pair[1])\n","sub_path":"advent_of_code/2015/Day_15/Part2.py","file_name":"Part2.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"150631741","text":"import json\n\ninfile = open('eq_data_30_day_m1.json', 'r')\noutfile = open('readable_eq_data.json', 'w')\n\neqdata = json.load(infile)\n\njson.dump(eqdata, outfile, indent=4)\n\n# print(len(eqdata[\"features\"]))\n\nlist_of_eqs = eqdata[\"features\"]\n\nmags = []\nlats = []\nlons = []\n\nfor eq in list_of_eqs:\n mag = (eq[\"properties\"][\"mag\"])\n lat = (eq['geometry']['coordinates'][1])\n lon = (eq['geometry']['coordinates'][0])\n mags.append(mag)\n lats.append(lat)\n lons.append(lon)\n\nprint(mags[:5])\n#:5 means it's grabbing the first 5 elements\nprint(lats[:5])\nprint(lons[:5])\n\nfrom plotly.graph_objs import Scattergeo, Layout\nfrom plotly import offline\n\ndata = [Scattergeo(lon=lons,lat=lats)]\n\nmy_layout = Layout(title=\"Global Earthquak 1 Day\")\n\nfig = {'data':data,'layout':my_layout}\n\noffline.plot(fig,filename='globalearthquakes1day.html')\n","sub_path":"json1.py","file_name":"json1.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"546068788","text":"\"\"\"Build an index mapping word -> list of occurrences\"\"\"\n\nimport sys\nimport re\n\nWORD_RE = re.compile('\\w+')\n\nindex = {}\nwith open(sys.argv[1], encoding='utf-8') as fp:\n for line_no, line in enumerate(fp, 1):\n for match in WORD_RE.finditer(line):\n word = match.group()\n column_no = match.start() + 1\n location = (line_no, column_no)\n index.setdefault(word, []).append(location)\t# Get the list of occurrences for word, or set it to [] if not found; setdefault returns the value, so it can be updated without requiring a second search. It's the same as follows (but the following code performs at least two searches for key -- three if it's not found -- while setdefault does it all with a single lookup):\n \"\"\"\n if key not in my_dict:\n \tmy_dict[key] = []\n my_dict[key].append(new_value)\n \"\"\"\n # print in alphabetical order\n for word in sorted(index, key=str.upper):\t# Pass the str.upper as reference so the sorted function can use it to normalize the words for sorting\n print(word, index[word])\n","sub_path":"02_data_structures/02_dictionaries_and_sets/04_handling_missing_keys_with_dict_dot_setdefault.py","file_name":"04_handling_missing_keys_with_dict_dot_setdefault.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"459259337","text":"def search(lis,a):\r\n print(lis)\r\n if a in lis:\r\n return True\r\n else:\r\n return False\r\nlis=[]\r\nwhile True:\r\n a=int(input(\"Enter the list elements\"))\r\n if a!=-1:\r\n lis.append(a)\r\n else:\r\n break\r\nb=int(input(\"enter teh element to search\"))\r\nres=search(lis,b)\r\nif res:\r\n print(\"Element is present\")\r\nelse:\r\n print(\"element is not present\")\r\n","sub_path":"lab2a.py","file_name":"lab2a.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"581193463","text":"import pprint\n\nfrom pymongo import MongoClient\n\nfrom bson import _ENCODERS as bson_encoders\nfrom nudgebot.settings import CurrentProject\n\n\nclass DatabaseClient(MongoClient): # noqa\n \"\"\"A Database client for MongoDB\"\"\"\n bson_types = tuple(bson_encoders.keys())\n HOST = CurrentProject().config.config.database.mongo_client.host\n PORT = CurrentProject().config.config.database.mongo_client.port\n\n def __init__(\n self,\n host=None,\n port=None,\n document_class=dict,\n tz_aware=None,\n connect=None,\n **kwargs):\n MongoClient.__init__(self, host=host, port=port, document_class=document_class,\n tz_aware=tz_aware, connect=connect, **kwargs)\n\n @classmethod\n def bson_encode(cls, node):\n \"\"\"Verifying that all the objects in the dict node are bson encodable.\n Those that are not converted to an `str`.\n @param node: Either a node of the json tree or a value.\n \"\"\"\n if isinstance(node, dict):\n result = {}\n for key, value in node.items():\n result[key] = cls.bson_encode(value)\n elif isinstance(node, (list, tuple)):\n result = []\n for item in node:\n result.append(cls.bson_encode(item))\n elif isinstance(node, cls.bson_types):\n result = node\n else:\n result = str(node)\n return result\n\n def dump(self, databasename, collection_name=None, query=None, filepath=None, dismiss_id=True):\n \"\"\"Dumping the database content.\n @param databasename: `str` The name of the database to dump.\n @keyword collection_name: `str` filter by collection name to dump a specific collection.\n @keyword query: `dict` filter by a query in the collection.\n @keyword filepath: `str` The path of the file to dump.\n @keyword dismiss_id: `bool` Whether to dismiss the '_id' property.\n \"\"\"\n assert isinstance(databasename, str)\n assert collection_name is None or isinstance(collection_name, str)\n assert query is None or isinstance(query, dict)\n assert filepath is None or isinstance(filepath, str)\n db = getattr(self, databasename)\n if collection_name:\n collections = [getattr(db, collection_name)]\n else:\n collections = [getattr(db, name) for name in db.collection_names()\n if name != 'system.indexes']\n data = {}\n for collection in collections:\n dismiss_id = {'_id': False} if dismiss_id else {}\n data[collection.name] = list(collection.find(query, dismiss_id))\n if filepath:\n with open(filepath, 'w') as f:\n f.write(pprint.pformat(data, width=20) + '\\n')\n return data\n\n def clear_db(self, i_really_want_to_do_this=False):\n \"\"\"Clearing all the database content. This is unrevertable danger operation.\n @param i_really_want_to_do_this: `bool` Whether I really want to perform this operation.\n if false - it'll raise exception.\n \"\"\"\n if not i_really_want_to_do_this:\n raise Exception('You are performing a really danger operation. if you really want to do this - '\n 'please call clear_db(i_really_want_to_do_this=True).')\n for dbname in self.database_names():\n if dbname not in ('local', 'admin'):\n self.drop_database(dbname)\n\n\nclass DataCollection(object):\n \"\"\"\n Define the inherit class as data collection and provides access into it\n Should be defined in subclass:\n * DATABSE_NAME: `str` The name of the database.\n * COLLECTION_NAME: `str` The name of the COLLECTION_NAME in that database.\n \"\"\"\n DATABASE_NAME = None\n COLLECTION_NAME = None\n\n def upsert(self, query: dict, work: dict):\n \"\"\"Update a document with the matched query, if no such document, insert.\n @see: https://docs.mongodb.com/manual/reference/method/db.collection.work/#upsert-option\n \"\"\"\n return self.db_collection.update(query, work, {'upsert': True})\n\n @classmethod\n def get_db_collection(cls):\n \"\"\"Returns the database collection\"\"\"\n assert cls.DATABASE_NAME is not None\n assert cls.COLLECTION_NAME is not None\n db = getattr(CurrentProject().db_client, cls.DATABASE_NAME)\n return getattr(db, cls.COLLECTION_NAME)\n\n @property\n def db_collection(self):\n return self.get_db_collection()\n\n\nclass CachedStack(DataCollection):\n \"\"\"\n A cached LIFO stack that cache itself in the database.\n \"\"\"\n DATABASE_NAME = 'metadata'\n COLLECTION_NAME = 'cached_stacks'\n\n def __init__(self, name: str, length: int = 1000):\n \"\"\"\n @param name: `str` The name of the cached stack.\n @keyword length: `int` the length of the cached stack. if length = -1: length is unlimited.\n \"\"\"\n self._i = 0\n self._name = name\n self._length = length\n self._length_exeeded = False\n\n def __repr__(self):\n return '<{} {}>'.format(self.__class__.__name__, self.stack)\n\n def __eq__(self, other):\n return self.stack == getattr(other, 'stack', None)\n\n def __getitem__(self, index):\n return self.stack[index]\n\n def __contains__(self, item):\n return item in self.stack\n\n def __len__(self):\n return len(self.stack)\n\n @property\n def stack(self):\n \"\"\"Returns the stack.\"\"\"\n doc = self.db_collection.find_one({'name': self._name}, {'_id': False})\n if doc:\n return doc['stack']\n else:\n self.db_collection.insert_one({'name': self._name, 'stack': []})\n return []\n\n @property\n def length_exeeded(self):\n \"\"\"\n Checking whether the length exceeded. once it exceeded, it continue to be exceeded.\n That in order to reduce DB calls.\"\"\"\n if not self._length_exeeded:\n self._length_exeeded = (False if self._length == -1 else self._length <= len(self.stack))\n return self._length_exeeded\n\n def pop(self):\n \"\"\"Pop the first item\"\"\"\n return self.db_collection.update_one({'name': self._name}, {'$pop': {'stack': -1}})\n\n def push(self, item):\n \"\"\"\n Push a new item to the stack, pop the first.\n @param item: The item to push.\"\"\"\n if self.length_exeeded:\n self.pop()\n self.db_collection.update_one({'name': self._name}, {'$addToSet': {'stack': item}})\n\n def clear(self):\n \"\"\"Clearing the stack\"\"\"\n while self.stack:\n self.pop()\n","sub_path":"nudgebot/db/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":6714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111755353","text":"import vk_api\nimport time\nimport random\nimport commands\nimport json\nimport requests\nimport grouptest\nimport speech\nimport fx\nimport apiai\n\ndef convert_base(num, from_base = 10, to_base = 10):\n # first convert to decimal number\n print(from_base)\n n = int(str(num), int(from_base))\n # now convert decimal to 'to_base' base\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n print(n)\n if n < to_base:\n print(n,1)\n return alphabet[n]\n else:\n print(alphabet[n% to_base], 'alpabet %')\n return convert_base(n // to_base, 10, to_base) + alphabet[n % to_base]\n\nfrom yandex import Translater\n\ntoken = 'trnsl.1.1.20180822T035034Z.c4e6b0734a1501db.3c10535039452db4d70963681df09234674e4b33'\nall_lang = ['az','sq','am','en','ar','hy','af','eu','ba','be','bn','my',\n 'bg','bs','cy','hu','vi','ht','gl','nl','mrj','el','ka','gu',\n 'da','he','yi','id','ga','it','is','es','kk','kn','ca','ky',\n 'zh','ko','xh','km','lo','la','lv','lt','lb','mg','ms','ml',\n 'mt','mk','mi','mr','mhr','mn','de','ne','no','pa','pap','fa',\n 'pl','pt','ro','ru','ceb','sr','si','sk','sl','sw','su','tg',\n 'th','tl','ta','tt','te','tr','udm','uz','uk','ur','fi','fr',\n 'hi','hr','cs','sv','gd','et','eo','jv','ja']\n\n\ndef replace_line(file_name, line_num, text):\n lines = open(file_name, 'r').readlines()\n lines[line_num] = text\n out = open(file_name, 'w')\n out.writelines(lines)\n out.close()\ndef replace_line_bu(file_name, line_num, text):\n lines = open(file_name, 'r').readlines()\n lines[line_num] += text\n out = open(file_name, 'w')\n out.writelines(lines)\n out.close()\n\ndef replacer_line(file_name, line_num, text):\n lines = open(file_name, 'r', encoding=\"utf-8\").readlines()\n lines[line_num] = text\n out = open(file_name, 'w',encoding=\"utf-8\")\n out.writelines(lines)\n out.close()\n\n\n\n\nvk = vk_api.VkApi(token='9348c5fa44e74d04840ce92338aa10d7dc9784d626756f952ad8d2266a2e5417965ee306181c58111a75b')\nvk._auth_token()\n# vk = vk_api.VkApi(login='89605187783', password='N1524360798n')\n# vk.auth()\n\n\ndef get_button(label, color, payload=\"\"):\n return {\n \"action\": {\n \"type\": \"text\",\n \"payload\": json.dumps(payload),\n \"label\": label\n },\n \"color\": color\n }\n\nkeyboard = {\n \"one_time\": False,\n \"buttons\": [\n [get_button(label=\"Помощь\", color=\"primary\")],\n [get_button(label=\"Казино всё\", color=\"negative\")],\n [get_button(label=\"Баланс\", color=\"primary\"),get_button(label=\"Профиль\", color=\"default\")],\n [get_button(label=\"Работать\", color=\"positive\"),get_button(label=\"Бонус\", color=\"positive\")],\n [get_button(label=\"Есть\", color=\"default\")]\n\n\n ]\n}\n\nkeyboard = json.dumps(keyboard, ensure_ascii=False).encode('utf-8')\nkeyboard = str(keyboard.decode('utf-8'))\nprint(keyboard)\n\nuser = open('users.txt', 'r')\nidss = open('allids.txt', 'r')\nidc = open('allids.txt', 'a')\nuserc = open('users.txt', 'a')\nids = idss.read().split()\nusers = user.read()\nusers = users.split('\\n')\nusers = [i.split(',') for i in users]\nprint(users)\nprint(ids)\n\n\ndef typer(arg):\n if arg == '0':\n return 'id'\n elif arg == '1':\n return 'money'\n elif arg == '2':\n return 'рейтинг'\n elif arg == '3':\n return 'время до бонуса'\n elif arg == '4':\n return 'время до окончания выходных'\n elif arg == '5':\n return 'привилегия'\n elif arg == '6':\n return 'Как скоро повышение(1 - нескоро, 10 - прямо сейчас)'\n elif arg == '7':\n return 'зарплата'\n elif arg == '8':\n return 'деньги в банке'\n elif arg == '9':\n return 'пока что ничего'\n elif arg == '10':\n return 'работал ли игрок вообще'\n\n elif arg == '11':\n return 'выпадало ли игроку х50'\n elif arg == '12':\n return 'вводил ли игрок хоть один читкод'\n elif arg == '13':\n return 'рейтинг множитель'\n\n elif arg == '14':\n return 'голод'\n elif arg == '15':\n return 'имя'\n\n\n\nclass CommandsGenerate:\n def __init__(self):\n pass\n\n def random(self, name, list):\n ch = open('Commands_bot.py', 'a')\n replacer_line('gbot.py', 200,\n \"\\n\\n\\t\\t\\telif body.lower()=='\" + name + \"':\\n\\t\\t\\t\\tvk.method('messages.send', {'peer_id': id, 'message': random.choice(\" + list + \")})\\n\\n\\n\")\n\n def halfchance(self, name, list):\n ch = open('Commands_bot.py', 'a')\n replacer_line('gbot.py', 200,\n \"\\n\\n\\t\\t\\telif body.lower().split()[0]=='\" + name + \"': \\n\\n\\t\\t\\t\\t\\tif body.lower().split()[1].isdigit and int(body.lower().split()[1]) <= float(users[n][1]): \\n\\t\\t\\t\\t\\tusers[n][1] = str(float(users[n][1])-int(body.lower().split()[1]))\\n\\t\\t\\t\\t\\trnd = random.choice(\" + list + \")\\n\\t\\t\\t\\t\\tif rnd == body.lower().split()[2]:\\n\\t\\t\\t\\t\\t\\tusers[n][1] = str(float(users[n][1])+(int(body.lower().split()[1])*2))\\n\\t\\t\\t\\t\\t\\tvk.method('messages.send', {'peer_id': id, 'message': 'You are win ' + str(int(body.lower().split()[1])) + '\\\\nYour balance: ' + commands.bt(int(float(users[n][1])))})\\n\\t\\t\\t\\t\\telse: \\n\\t\\t\\t\\t\\t\\tvk.method('messages.send', {'peer_id': id, 'message': 'You are lose ' + str(int(body.lower().split()[1])) + '\\\\nYour balance: ' + commands.bt(int(float(users[n][1])))})\\n\\n\\n\\n\")\n\n\ncg = CommandsGenerate()\ncc = 0\nwh = False\ngs = False\n\nwhile True:\n ans = False\n try:\n cc += 1\n\n # bis = open('bisnes.json','r+',encoding='utf-8')\n\n user = open('users.txt', 'r')\n idss = open('allids.txt', 'r')\n idc = open('allids.txt', 'a')\n userc = open('users.txt', 'a')\n\n # dat = json.loads(bis.read())\n # print(dat)\n ids = idss.read().split()\n users = user.read()\n users = users.split('\\n')\n users = [i.split(',') for i in users]\n for us in range(len(users)):\n if len(users[us]) > 1:\n if int(users[us][3]) > -10:\n users[us][3] = str(int(users[us][3]) - 1)\n if int(users[us][4]) > -10:\n users[us][4] = str(int(users[us][4]) - 1)\n replace_line('users.txt', us, ','.join(users[us]) + '\\n')\n\n\n if gs == False:\n print('\\nBot get started')\n gs = True\n\n messages = vk.method('messages.getConversations', {'out': 0, 'time_offset': 60, 'count': 100, 'filter': \"unread\"})\n if messages['count'] >= 1:\n\n\n id = messages['items'][0]['last_message']['from_id']\n usid = messages['items'][0]['last_message']['peer_id']\n body = messages['items'][0]['last_message']['text']\n\n\n if not str(id) in ids:\n wh = False\n if wh == False:\n if body.lower() == 'hello':\n vk.method('messages.send', {'peer_id': id, 'message': 'User' + ',' + ' ''hi!' + str(usid)})\n if body.lower().split()[0] == 'регистрация':\n name = body.split()[1:]\n name = ' '.join(name)\n idc.write(' ' + str(usid)) #15\n userc.write(str(usid) + ',' + '0' + ',' + '0' + ',' + '10,' + '10,' + 'User,0,1000,0,0,0,0,0,1,10,' + name + '\\n')\n # dat['\"'+str(id)+'\"'] = {\n # \"bis_lvl\":\"0\",\n # \"bis_type\":\"none\"\n # }\n # bis.writelines(str(dat))\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Аккаунт создан. Теперь я буду обращаться к вам, как ' + name + '\\nНапишите \"помощь\" для списка команд'})\n else:\n vk.method('messages.send', {'peer_id': id,\n 'message': 'Необходимо завести аккаунт. Для этого напишите: \"регистрация <Ваше имя>\"'})\n\n elif str(usid) in ids:\n\n\n print(body + '\\n' + 'by: ' + users[ids.index(str(usid))][-1])\n wh = True\n n = ids.index(str(usid))\n # if str(id) == '502004139' or str(id) == '155118230':\n # users[ids.index('502004139')][5] = 'Admin'\n # users[ids.index('155118230')][5] = 'Admin'\n # replace_line('users.txt', n, ','.join(users[n]) + '\\n')\n users[n][1] = str(round(float(users[n][1]), 2))\n users[n][8] = str(round(float(users[n][8]), 2))\n users[n][13] = str(round(float(users[n][13]),2))\n users[n][7] = str(round(float(users[n][7]),2))\n if float(users[n][1]) >= 99999999999999:\n users[n][1] = '99999999999999'\n if float(users[n][8]) >= 99999999999999:\n users[n][8] = '99999999999999'\n\n if 'все' in body.lower().split() and not 'снять' in body.lower().split():\n print(body.lower())\n body = body.lower().split()\n body[body.index('все')] = str(int(float(users[n][1])))\n body = ' '.join(body)\n print(body,1)\n\n\n elif 'всё' in body.lower().split() and not 'снять' in body.lower().split():\n print(body.lower())\n body = body.lower().split()\n body[body.index('всё')] = str(int(float(users[n][1])))\n body = ' '.join(body)\n print(body, 1)\n\n\n\n if body.lower() == 'hello':\n vk.method('messages.send', {'peer_id': id, 'message': users[n][-1] + ',' + ' ''hi!'})\n ans = True\n\n\n elif body.lower() == 'баланс':\n vk.method('messages.send', {'peer_id': id, 'message': users[n][-1] + ', Ваш баланс: ' + commands.bt(\n int(float(users[n][1]))) + '\\nВ банке: ' + commands.bt(\n int(float(users[n][8])))})\n\n ans = True\n\n\n\n\n\n\n\n\n elif len(body.split()) > 1 and body.lower().split()[0] == 'казино':\n ans = True\n summ = body.split()[1]\n if (str(summ) != 'все' and str(summ) != 'всё') and not str(summ).isdigit():\n vk.method('messages.send', {'peer_id': id, 'message': 'Так нельзя'})\n else:\n if not str(summ).isdigit():\n summ = float(users[n][1])\n\n summ = float(summ)\n if summ > float(users[n][1]):\n vk.method('messages.send', {'peer_id': id, 'message': 'Недостаточно денеГ'})\n else:\n if summ > 0:\n users[n][1] = str(float(users[n][1]) - summ)\n ch = random.choice(range(1, 51))\n if ch == 1:\n m = 0\n summ *= m\n elif ch >= 2 and ch <= 10:\n m = 0.25\n summ *= m\n elif ch <= 25 and ch > 10:\n m = 0.5\n summ *= m\n elif ch <= 35 and ch > 25:\n m = 0.75\n summ *= m\n elif ch <= 45 and ch > 35:\n m = 2\n summ *= m\n elif ch < 50 and ch > 45:\n m = 5\n summ *= m\n elif ch == 50:\n if users[n][11] == '0':\n users[n][11] = '1'\n users[n][2] = str((int(float(users[n][2])) + 50))\n vk.method('messages.send', {'peer_id': id, 'message': 'Ура, вы первый раз выбили х50, награда 50 рейтинга!'})\n m = 50\n summ *= m\n users[n][1] = str(float(users[n][1]) + summ)\n vk.method('messages.send', {'peer_id': id, 'message': 'Вам попался (х' + str(m) + ')' + '\\n' + 'Ваш баланс: ' + commands.bt(int(float(users[n][1])))})\n\n\n elif body.lower() == 'работать':\n ans = True\n if int(users[n][14]) <= 2:\n vk.method('messages.send', {'peer_id': id,\n 'message': 'Вам нужно срочно поесть'})\n else:\n if int(users[n][4]) <= 0 and int(float(users[n][6])) == 10:\n vk.method('messages.send', {'peer_id': id, 'message': 'Вы устроились на новую работу. Награда ' + str(float(users[n][13])*10) + ' рейтинга'})\n users[n][2] = str(float(users[n][2]) + float(users[n][13])*10)\n users[n][7] = str((int(float(users[n][7])) * 2.5))\n if float(users[n][13]) < 50:\n users[n][13] = str(float(users[n][13]) * 2.5)\n users[n][6] = '0'\n elif int(float(users[n][6])) != 10 and int(users[n][4]) <= 0:\n users[n][6] = str((int(float(users[n][6])) + 1))\n users[n][14] = str((int(float(users[n][14])) - 1))\n users[n][1] = str(int(float(users[n][1])) + int(float(users[n][7])))\n users[n][2] = str(float(users[n][2]) + float(users[n][13]))\n vk.method('messages.send', {'peer_id': id, 'message': 'Вы заработали ' + users[n][7] + '$ ' + 'и ' + users[n][13] + ' рейтинга'})\n users[n][4] = str(60)\n if users[n][10] == '0':\n users[n][10] = '1'\n users[n][2] = str((int(float(users[n][2])) + 20))\n vk.method('messages.send', {'peer_id': id, 'message': 'Ура, вы поработали 1-ый раз.\\nНаграда 20 рейтинга'})\n elif int(users[n][4]) > 0:\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Выходные кончатся через ' + str(int(users[n][4]))})\n elif body.lower() == 'бонус':\n ans = True\n if int(users[n][3]) <= 0:\n if random.choice('mmmr') == 'm':\n p = random.choice([100,100000,100000,500000000,500000000,500000000,25000000000])\n users[n][1] = str(float(users[n][1]) + p)\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Вы получили '+commands.bt(p) + \" $\" + '\\n' + 'Ваш баланс: ' + commands.bt(\n int(float(users[n][1])))})\n\n\n else:\n p = random.choice([2,2,10,10,10,50,50,100])\n users[n][2] = str(float(users[n][2]) + p)\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Вы получили '+commands.bt(p) + \" рейтинга\" + '\\n' + 'Ваш рейтинг ' + commands.bt(\n int(float(users[n][2])))})\n users[n][3] = str(60)\n else:\n vk.method('messages.send',{'peer_id': id, 'message': 'До бонуса остал��сь:' + str(int(users[n][3]))})\n\n elif body.lower() == 'помощь':\n ans = True\n vk.method('messages.send', {'peer_id': id,\n 'message': 'Вот что я могу: \\nКлава (клавиатура с некоторыми командами)\\nПередать <сумма>\\n' + 'Казино <сумма>\\n' + 'Баланс \\nБанк\\nБанк положить\\n Банк снять\\nперевести \\nязыки(список языков для переводчика)' + '\\nРаботать \\n' + 'Бонус \\n' + 'имя <имя>\\nскажи <слова(<=500)>(будет отправлена ссылка на документ)\\n' + 'топ (топ игроков)\\nнаписать админу <сообщение>\\nГраф <массив> (Пример: [[1,4],[0,3],[4],[1],[0,2]])' + '\\nсс(по-русски) <число> <системы счисления из которой нужно перевести> <в которую>\\n\\n(Version: 0.2)'})\n if users[n][5] == 'Admin':\n vk.method('messages.send', {'peer_id': id,\n 'message': 'Доп команды для админов:\\nПолучить <сумма>\\nСоздать команду\\nпомощь создать\\nget_all_ids\\nget_all_users\\nюзеры(как get_all_users, красивее и проще)\\nget_me (инфо о тебе)'})\n if users[n][0] == '502004139' or users[n][0] == '155118230':\n vk.method('messages.send', {'peer_id': id,\n 'message': 'Доп команды для меня: \\nprefix\\nedit_profile <значение>'})\n\n elif len(body.split()) > 1 and body.split()[0].lower() == 'имя':\n ans = True\n users[n][-1] = str(' '.join(body.split()[1:]))\n vk.method('messages.send',{'peer_id': id, 'message': 'Имя изменено. Теперь я буду обращаться к вам, как ' + ' '.join(body.split()[1:])})\n\n\n elif body.lower() == 'топ':\n ans = True\n new_per = users[:]\n new_per = [i[:] for i in new_per[:]]\n\n for i in range(len(new_per)):\n for j in range(len(new_per) - 1, i, -1):\n if len(new_per[j]) > 1:\n if int(float(new_per[j][2])) > int(float(new_per[j - 1][2])):\n new_per[j], new_per[j - 1] = new_per[j - 1], new_per[j]\n\n new_per = [i for i in new_per if i[0] != '155118230' and str(i[0]) != '502004139']\n new_per = new_per[:-1]\n if len(new_per) > 5:\n new_per = new_per[:5]\n if users[n][5] == 'Admin':\n top = [str(new_per.index(i) + 1) + \". \" + \"[id\" + i[0] + \"|\" + i[-1] + \"]\" + \", money \" + i[1]+\", rating \"+i[2] + \", id \" + i[0] for i in new_per]\n top = [i + '\\n' for i in top]\n top = ''.join(top)\n else:\n top = [str(new_per.index(i) + 1) + \". \" + \"[id\"+i[0]+\"|\"+i[-1]+\"]\"+ \", money \" + i[1] + \", rating \" + i[2] for i in new_per]\n top = [i + '\\n' for i in top]\n top = ''.join(top)\n vk.method('messages.send', {'peer_id': id,'message': '0. [id155118230|Admin], money ∞, rating ∞\\n'+top})\n\n elif body.lower() == 'помощь создать':\n ans = True\n if users[n][5] == 'Admin':\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Нужно написать: создать команду \\n\\n'\n 'Параметры:\\n'\n '1. рандом <первый рандомный элемент, ... , n-ый рандомный элемент>\\n'\n '2. 50%50 <1st, 2nd> (Типа трейда вверх/вниз)'})\n\n elif body.lower() == 'профиль':\n ans = True\n vk.method('messages.send', {'peer_id': id,'message': 'Ваш профиль, '+users[n][-1]+':\\n1. Ваш id: '+users[n][0] +'\\n2. Баланс:' + commands.bt(str(int(float(users[n][1])))) + '\\n3. В банке '+commands.bt(str(int(float(users[n][8]))))+'\\n4. Рейтинг: ' + users[n][2] + '\\n5. Привилегия: '+users[n][5] + '\\n6. Голод: '+users[n][14]})\n\n\n\n\n\n\n elif body.lower().split()[:2] == ['с��здать', 'команду']:\n ans = True\n vk.method('messages.send', {'peer_id': id, 'message': 'Данная функция находится в активной разработке'})\n # if users[n][5] == 'Admin':\n # all = body.lower().split()\n # if all[2] == 'рандом':\n # cg.random(all[3], all[4])\n # vk.method('messages.send', {'peer_id': id, 'message': 'Готово'})\n # elif all[2] == '50%50':\n # cg.halfchance(all[3], all[4])\n # vk.method('messages.send', {'peer_id': id, 'message': 'Готово'})\n\n\n elif len(body.split()) > 1 and body.lower().split()[0] == 'получить':\n ans = True\n if users[n][5] == 'Admin' and body.lower().split()[1].isdigit():\n users[n][1] = str(float(users[n][1]) + int(body.lower().split()[1].strip(\n 'asdfghjklqwertyuiopzxcvbnmфывапролдйцукенгшщзхъячсмитьбю?\"}][;.>:{/!@#$%^&*()_+-=~`')))\n vk.method('messages.send', {'peer_id': id, 'message': 'Готово'})\n\n\n elif len(body.split()) > 1 and body.lower().split()[0] == 'передать':\n ans = True\n g = body.lower().split()\n if len(g) == 3 and g[2].isdigit() and int(float(users[n][1])) >= int(g[2]) and g[1] in ids and int(g[2]) > 0:\n users[n][1] = str(int(float(users[n][1])) - int(g[2]))\n users[ids.index(g[1])][1] = str(int(float(users[ids.index(g[1])][1]))+int(g[2]))\n replace_line('users.txt', ids.index(str(g[1])), ','.join(users[ids.index(g[1])]) + '\\n')\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Вы передали игроку ' + users[ids.index(g[1])][-1] + ' ' + g[2] + ' $'})\n vk.method('messages.send',{'peer_id': g[1], 'message': 'Вам передал ' + users[n][-1] + ' ' + g[2] + ' $'})\n elif g[2].isdigit() and int(float(users[n][1])) < int(g[2]):\n vk.method('messages.send',\n {'peer_id': id, 'message': 'Недостаточно денег'})\n elif not g[1] in ids:\n vk.method('messages.send',\n {'peer_id': id, 'message': 'ID не существует'})\n else:\n vk.method('messages.send',\n {'peer_id': id, 'message': 'В боте это не предусмотренно'})\n\n\n elif body.lower() == 'банк':\n ans = True\n vk.method('messages.send',\n {'peer_id': id, 'message': 'В банке ' + commands.bt(str(int(float(users[n][8]))))})\n\n elif body.lower().split()[:2] == ['банк','положить'] and len(body.lower().split()) >= 3 and body.lower().split()[2].isdigit():\n ans = True\n\n if int(float(users[n][1])) >= int(float(body.lower().split()[2])):\n users[n][8] = str(int(float(users[n][8])) + int(float(body.lower().split()[2])))\n users[n][1] = str(int(float(users[n][1])) - int(float(body.lower().split()[2])))\n vk.method('messages.send', {'peer_id': id, 'message': 'Готово'})\n else:\n vk.method('messages.send', {'peer_id': id, 'message': 'Недостаточно денег'})\n\n\n elif body.lower().split()[:2] == ['банк', 'снять'] and len(body.lower().split()) >= 3:\n ans = True\n summ = body.split()[2]\n # print(summ)\n if (str(summ) != 'все' and str(summ) != 'всё') and not str(summ).isdigit():\n vk.method('messages.send', {'peer_id': id, 'message': 'Так нельзя'})\n else:\n if not str(summ).isdigit():\n summ = float(users[n][8])\n summ = int(summ)\n print(summ)\n if summ <= int(float(users[n][8])):\n users[n][8] = str(int(float(users[n][8])) - int(summ))\n users[n][1] = str(int(float(users[n][1])) + int(summ))\n vk.method('messages.send', {'peer_id': id, 'message': 'Готово'})\n else:\n vk.method('messages.send', {'peer_id': id, 'message': 'Недостаточно денег в банке'})\n\n\n elif len(body.split()) > 1 and body.split()[0].lower() == 'edit_profile' and len(body.split()) == 4 and (users[n][0] == '502004139' or users[n][0] == '155118230'):\n ans = True\n args = body.split()[1:]\n\n users[ids.index(args[0])][int(args[1])] = args[2]\n vk.method('messages.send', {'peer_id': id,\n 'message': '[id'+users[ids.index(args[0])][0]+'|'+users[ids.index(args[0])][-1]+']' + ' теперь имеет ' + args[\n 2] + ' ' + typer(args[1])})\n replace_line('users.txt', ids.index(str(args[0])), ','.join(users[ids.index(args[0])]) + '\\n')\n\n\n elif body.lower() == 'prefix' and (users[n][0]=='502004139' or users[n][0] == '155118230'):\n ans = True\n pref = [str(i) + ' - ' + typer(str(i)) for i in range(len(users[0]))]\n vk.method('messages.send', {'peer_id': id, 'message': '\\n'.join(pref)})\n\n elif body.lower() == 'get_all_ids' and users[n][5] == 'Admin':\n ans = True\n vk.method('messages.send', {'peer_id':id, 'message': ' '.join(ids)})\n elif body.lower() == 'get_all_users' and users[n][5] == 'Admin':\n ans = True\n uss = [','.join(i) for i in users]\n uss = '\\n'.join(uss)\n vk.method('messages.send', {'peer_id': id, 'message': uss})\n\n elif body.lower() == 'юзеры' and users[n][5] == 'Admin':\n ans = True\n uss = [\"[id\"+i[0]+\"|\"+i[-1]+\"] \\n\" + 'id: ' + i[0] + '\\n' + 'привилегия: '+i[5]+'\\nденьги,рейтинг:' + i[1] + ',\\t' + i[2] + '\\n\\n' for i in users if len(i) > 1]\n uss = '\\n'.join(uss)\n vk.method('messages.send', {'peer_id': id, 'message': uss})\n\n elif body.lower() == 'get_all_admins' and users[n][5] == 'Admin':\n ans = True\n adm = [\"[id\"+i[0]+\"|\"+i[-1]+\"] \" + i[0] for i in users if len(i) > 1 and i[5] == 'Admin']\n adm = '\\n'.join(adm)\n vk.method('messages.send', {'peer_id': id, 'message': adm})\n\n elif body.lower() == 'yayangi':\n ans = True\n if users[n][12] == '0':\n users[n][12] = '1'\n users[n][2] = str(float(users[n][2]) + 50)\n vk.method('messages.send', {'peer_id': id, 'message': 'Воу, вы нашли читкод, награда 50 рейтинга'})\n else:\n vk.method('messages.send', {'peer_id': id, 'message': 'Ты уже вводил этот читкод'})\n\n elif body.lower() == 'get_me' and users[n][5] == 'Admin':\n ans = True\n getting = [typer(str(i)) + ' ' + str(users[n][i]) + '\\n' for i in range(len(users[n]))]\n vk.method('messages.send', {'peer_id': id, 'message': ''.join(getting)})\n\n elif body.lower().split()[:2] == ['написать', 'админу']:\n ans = True\n message = body.split()[2:]\n di = str(users[n][0])\n di = \"[id\"+users[n][0]+\"|\"+users[n][-1]+\" \"+users[n][0]+\"]\"\n # print(di)\n\n vk.method('messages.send', {'peer_id': '155118230', 'message': ' '.join(message) + \"\\nby: \"+di})\n vk.method('messages.send', {'peer_id': id,'message': 'Готово'})\n\n\n\n elif body.lower().split()[:1] == ['перевести']:\n ans = True\n eng_text = body.split()[1:]\n langs = [eng_text[0], eng_text[1]]\n eng_text = body.split()[3:]\n\n eng_text = ' '.join(eng_text)\n # print(eng_text, langs)\n if langs[0] in all_lang and langs[1] in all_lang:\n url_trans = 'https://translate.yandex.net/api/v1.5/tr.json/translate'\n trans_option = {'key': token, 'lang': langs[0]+\"-\"+langs[1], 'text': eng_text}\n # trans_option = {'key': token, 'lang': \"en-ru\", 'text': eng_text}\n webRequest = requests.get(url_trans, params=trans_option)\n rus_text = webRequest.text\n srez = 32+len(langs[0])+len(langs[1])\n rus_text = rus_text[srez:(len(rus_text) - 3)]\n\n vk.method('messages.send', {'peer_id': id, 'message': rus_text+ '\\n\\nПереведено сервисом «Яндекс.Переводчик»\\nhttp://translate.yandex.ru/'})\n elif body.lower() == 'языки':\n ans = True\n vk.method('messages.send', {'peer_id': id, 'message': 'азерб��йджанский\taz\t\\nмалаялам\tml\\n\\\n албанский\tsq\t\\nмальтийский\tmt\\n\\\n амхарский\tam\t\\nмакедонский\tmk\\n\\\n английский\ten\t\\nмаори\tmi\\n\\\n арабский\tar\t\\nмаратхи\tmr\\n\\\n армянский\thy\t\\nмарийский\tmhr\\n\\\n африкаанс\taf\t\\nмонгольский\tmn\\n\\\n баскский\teu\t\\nнемецкий\tde\\n\\\n башкирский\tba\t\\nнепальский\tne\\n\\\n белорусский\tbe\t\\nнорвежский\tno\\n\\\n бенгальский\tbn\t\\nпанджаби\tpa\\n\\\n бирманский\tmy\t\\nпапьяменто\tpap\\n\\\n болгарский\tbg\t\\nперсидский\tfa\\n\\\n боснийский\tbs\t\\nпольский\tpl\\n\\\n валлийский\tcy\t\\nпортугальский\tpt\\n\\\n венгерский\thu\t\\nрумынский\tro\\n\\\n вьетнамский\tvi\t\\nрусский\tru\\n\\\n гаитянский (креольский)\tht\t\\nсебуанский\tceb\\n\\\n галисийский\tgl\t\\nсербский\tsr\\n\\\n голландский\tnl\t\\nсингальский\tsi\\n\\\n горномарийский\t\\nmrj\tсловацкий\tsk\\n\\\n греческий\tel\t\\nсловенский\tsl\\n\\\n грузинский\tka\t\\nсуахили\tsw\\n\\\n гуджарати\tgu\t\\nсунданский\tsu\\n\\\n датский\tda\t\\nтаджикский\ttg\\n\\\n иврит\the\t\\nтайский\tth\\n\\\n идиш\tyi\t\\nтагальский\ttl\\n\\\n индонезийский\tid\t\\nтамильский\tta\\n\\\n ирландский\tga\t\\nтатарский\ttt\\n\\\n итальянский\tit\t\\nтелугу\tte\\n\\\n исландский\tis\t\\nтурецкий\ttr\\n\\\n испанский\tes\t\\nудмуртский\tudm\\n\\\n казахский\tkk\t\\nузбекский\tuz\\n\\\n каннада\tkn\t\\nукраинский\tuk\\n\\\n каталанский\tca\t\\nурду\tur\\n\\\n киргизский\tky\t\\nфинский\tfi\\n\\\n китайский\tzh\t\\nфранцузский\tfr\\n\\\n корейский\tko\t\\nхинди\thi\\n\\\n коса\txh\t\\nхорватский\thr\\n\\\n кхмерский\tkm\t\\nчешский\tcs\\n\\\n лаосский\tlo\t\\nшведский\tsv\\n\\\n латынь\tla\t\\nшотландский\tgd\\n\\\n латышский\tlv\t\\nэстонский\tet\\n\\\n литовский\tlt\t\\nэсперанто\teo\\n\\\n люксембургский\tlb\t\\nяванский\tjv\\n\\\n малагасийский\tmg\t\\nяпонский\tja\\n\\\n малайский\tms\t'})\n\n\n elif len(body.split()) == 2 and body.lower().split()[0] == 'граф':\n ans = True\n print('graph')\n if body.lower().split()[1] == 'рандом':\n nums = random.choice(range(1,15))\n # print(nums)\n points = [i for i in range(nums)]\n # print(points)\n comps = random.choice(range(nums,nums+5))\n # print(nums)\n cord = [[random.choice(points) for i in range(random.choice(range(1,5)))] for i in range(nums)]\n # print(''.join(str(cord).split()))\n\n try:\n # cord = json.loads(cord)\n grouptest.graph(cord)\n a = vk.method(\"photos.getMessagesUploadServer\")\n b = requests.post(a['upload_url'], files={'photo': open('test.png', 'rb')}).json()\n c = vk.method('photos.saveMessagesPhoto',\n {'photo': b['photo'], 'server': b['server'], 'hash': b['hash']})[0]\n d = \"photo{}_{}\".format(c[\"owner_id\"], c[\"id\"])\n vk.method('messages.send', {'peer_id': id, \"attachment\": d, \"message\": 'Вот граф ' + ''.join(str(cord).split())})\n except:\n vk.method('messages.send', {'peer_id': id, \"message\": 'Ошибка'})\n elif body.lower().split()[1] != 'рандом':\n ans = True\n print(123)\n try:\n cord = body.split()[1:]\n cord = ''.join(cord)\n\n cord = json.loads(cord)\n grouptest.graph(cord)\n a = vk.method(\"photos.getMessagesUploadServer\")\n b = requests.post(a['upload_url'], files={'photo': open('test.png', 'rb')}).json()\n c = vk.method('photos.saveMessagesPhoto',\n {'photo': b['photo'], 'server': b['server'], 'hash': b['hash']})[0]\n d = \"photo{}_{}\".format(c[\"owner_id\"], c[\"id\"])\n vk.method('messages.send', {'peer_id': id, \"attachment\": d, \"message\": 'Вот граф'})\n except:\n vk.method('messages.send', {'peer_id': id, \"message\": 'Неверный формат'})\n\n elif body.lower().split()[0] == 'f(x)':\n ans = True\n pass\n\n elif body.lower() == 'клава':\n ans = True\n vk.method(\"messages.send\", {\"peer_id\": id, \"message\": \"Клавиатура выведена\", \"keyboard\": keyboard})\n\n elif body.lower() == 'есть':\n ans = True\n if float(users[n][1]) < 500:\n vk.method(\"messages.send\", {\"peer_id\": id, \"message\": \":( недостаточно денег, вы можете начать игру сначала, написав заново <ваш id>\"})\n else:\n users[n][1] = str(float(users[n][1]) - 500)\n users[n][14] = str(10)\n vk.method(\"messages.send\", {\"peer_id\": id, \"message\": \"Вы поели на 500$\"})\n\n elif body.lower() == 'заново '+users[n][0]:\n ans = True\n print(users[n][5])\n\n users[n][1],users[n][2],users[n][3],users[n][4],users[n][6],users[n][7],users[n][8] = '0', '0', '10', '10', '0', '1000', '0'\n users[n][9], users[n][10],users[n][11], users[n][12], users[n][13], users[n][14] = '0','0', '0', '0', '1','10'\n vk.method(\"messages.send\", {\"peer_id\": id, \"message\": \"Ваш аккаунт сброшен. Сохранено: привилегия, имя\"})\n\n\n\n elif body.split()[0].lower() == 'скажи' or body.split()[0].lower() == 'tts' or body.split()[0].lower() == 'ттс':\n ans = True\n words = ' '.join(body.split()[1:])\n\n hr = speech.speech(words,id,'ru')\n\n\n vk.method('messages.send', {'peer_id': id, 'message': 'https://vk.com/'+hr}) # отправляю сообщение\n\n\n elif len(body.lower().split()) == 1:\n ans = True\n # print(body.lower().split('e'))\n if len(''.join(body.lower().split('е'))) == 0:\n vk.method('messages.send', {'peer_id': id, 'message': 'Б'+'О'*len(body)+'Й'})\n\n elif len(''.join(body.lower().split('e'))) == 0:\n vk.method('messages.send', {'peer_id': id, 'message': 'B'+'O'*len(body)+'Y'})\n\n\n elif len(body.lower().split()) == 4 and body.lower().split()[0] == 'сс':\n ans = True\n body = body.lower().split()\n print(body)\n try:\n vk.method('messages.send', {'peer_id': id, 'message': str(convert_base(str(body[1]), int(body[2]), int(body[3])))})\n\n except:\n vk.method('messages.send', {'peer_id': id, 'message': 'Error!\\n\\n Возможно указано неверное значение системы из который нужно переводить.\\nИли в числе используются не англ символы.\\nЕсли все условия соблюдены - повторите попытку.'})\n\n # vk.method('messages.send', {'peer_id': id, 'message': '123'})\n # Обработка команд\n def textMessage(update):\n request = apiai.ApiAI('6a64d8a88c164253990049e41c5c4f06').text_request() # Токен API к Dialogflow\n request.lang = 'ru' # На каком языке будет послан запрос\n request.session_id = 'BatlabAIBot' # ID Сессии диалога (нужно, чтобы потом учить бота)\n request.query = update # Посылаем запрос к ИИ с сообщением от юзера\n responseJson = json.loads(request.getresponse().read().decode('utf-8'))\n response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ\n # Если есть ответ от бота - присылаем юзеру, если нет - бот его не понял\n if response:\n vk.method('messages.send', {'peer_id': id, 'message': response})\n else:\n vk.method('messages.send', {'peer_id': id, 'message': 'Не понял вас'})\n print(123456789)\n textMessage(body)\n replace_line('users.txt', ids.index(str(usid)), ','.join(users[n]) + '\\n')\n\n\n\n\n\n\n # print(cc)\n if cc % 3600 == 0:\n cc = 0\n for i in range(len(users)):\n if len(users[i]) > 1:\n users[i][8] = str(float(users[i][8])*1.1)\n replace_line('users.txt', i, ','.join(users[i]) + '\\n')\n\n\n time.sleep(1)\n except:\n time.sleep(2)","sub_path":"TelegramBot/tip(so lazy to create new project).py","file_name":"tip(so lazy to create new project).py","file_ext":"py","file_size_in_byte":41977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"508197116","text":"# @Time : 2021/4/14 19:52\n# @Author : Monlter\n# @FileName: segfunction.py\n# @Software: PyCharm\nimport numpy as np\n\n\ndef iterThresh(img_gray):\n img_gray = np.array(img_gray)\n zmax = np.max(img_gray)\n zmin = np.min(img_gray)\n ith_old = 0\n ith_new = (zmax + zmin) / 2\n while ith_old != ith_new:\n zo = np.mean(img_gray[np.where(img_gray > ith_new)])\n zb = np.mean(img_gray[np.where(img_gray < ith_new)])\n ith_old = ith_new\n ith_new = (zo + zb) / 2\n print(\"old:\",ith_old,\"new:\",ith_new)\n print('iter th:', ith_new)\n\n return ith_new\n\n\ndef threshSegImg(img_gray, thresh):\n img_bool = img_gray > thresh\n img_gray = np.array(img_gray)\n img_gray[img_bool] = 255\n img_gray[~img_bool] = 0\n return img_gray\n\n\ndef delete_contours(contours, delete_list):\n delta = 0\n for i in range(len(delete_list)):\n # print(\"i= \", i)\n del contours[delete_list[i] - delta]\n delta = delta + 1\n return contours\n","sub_path":"rock segmentation and oil extraction/test_code/segfunction.py","file_name":"segfunction.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"83968536","text":"# -*- coding: utf-8 -*-\nimport os\n\ndef Google_desired_capabilities(path=os.getcwd()):\n return {\"switches\": [\"-silent\", \"--disable-logging\", \"--disable-extensions\"],\n \"chromeOptions\": {\n \"args\": [\"-silent\", \"--disable-logging\", \"--disable-extensions\"],\n \"prefs\": {\n \"download.default_directory\": path,\n 'plugins.plugins_disabled': ['Chrome PDF Viewer'],\n \"download.prompt_for_download\": False,\n \"profile.default_content_settings.popups\": False\n },\n },\n 'browserName': 'chrome',\n 'javascriptEnabled': True,\n 'platform': 'ANY',\n 'version': ''}\n\ndef create_folder(name):\n\ttry:\n\t\tos.mkdir(name)\n\texcept OSError:\n\t\tpass","sub_path":"addition_functions.py","file_name":"addition_functions.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"283100794","text":"from django.contrib import admin\nfrom appointments.models import Appointment\n\n# Register your models here.\nclass ApptAdmin(admin.ModelAdmin):\n fieldsets = [\n ('Who?', {\n 'fields': [\n 'customer',\n ]\n }),\n ('What/Why?', {\n 'fields': [\n 'title',\n 'description',\n 'duration',\n ]\n }),\n ('When?', {\n 'fields': [\n 'date',\n 'time',\n ]\n }),\n ('Where?', {\n 'fields': [\n 'garage',\n ]\n })\n ]\n\nadmin.site.register(Appointment, ApptAdmin)\n\n","sub_path":"HirenAuto/appointments/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"638421621","text":"\"\"\"pk 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 django.conf import settings\nfrom django.views.static import serve\nfrom django.conf.urls import url\n\nurlpatterns = [\n path('backend/admin/', admin.site.urls),\n path('backend/client/' , include('clientlist.api.urls')),\n path('backend/homepage/' , include('homepage.api.urls')),\n path('backend/queries/' , include('Queries.api.urls')),\n path('backend/news/' , include('news.api.urls')),\n path('backend/summernote/', include('django_summernote.urls')),\n path('backend/whatwedo/', include('whatwedo.api.urls')),\n path('backend/career/', include('career.api.urls')),\n]\n\n\nif settings.DEBUG:\n urlpatterns += [\n url(r'^media/(?P.*)$', serve, {\n 'document_root': settings.MEDIA_ROOT,\n }),\n ]\n","sub_path":"pk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"415618600","text":"import json\n\nimport pymysql\nimport pandas as pd\nimport jieba\nfrom gensim import corpora, models\n\nconn = pymysql.connect(host=\"localhost\", port=3306, user=\"root\",\n password=\"123456\", database=\"wuhu\", charset=\"utf8\")\ndata3 = [[\"城市建设\", \"拆迁工程\", \"孩子学校\", \"工作工资\", \"生活政策\"], [\"房屋拆迁\", \"经济发展\", \"补贴政策\", \"工作生活\", \"居民安置\"],\n [\"工作\", \"物业\", \"拆迁\", \"环境\", \"买房\"], [\"物业\", \"拆迁\", \"工程影响\", \"居民安置\", \"工作\"], [\"农业\", \"环境\", \"物业\", \"交通\", \"拆迁\"],\n [\"工程修建\", \"医疗疫情\", \"政策补贴\", \"教育\", \"工作\"]]\n\n\ndef year_yu_qing(date):\n sql = f'select * from bottom_car where year_day like \"{date}%\"'\n sql1 = f'select * from shizhang where year_day like \"{date}%\"'\n df = pd.read_sql(sql, conn)\n df1 = pd.read_sql(sql1, conn)\n df = pd.concat([df, df1], axis=0)\n data2 = df[\"message\"].tolist()\n seg_words = []\n for word in data2:\n seg_word = [w for w in jieba.cut(word, cut_all=False) if len(w) > 1]\n seg_words.append(seg_word)\n df_seg = pd.DataFrame({\"content\": seg_words})\n return df_seg\n\n\ndef drop_stopwords(stopwords1, date1):\n contents = year_yu_qing(date1).content.values.tolist()\n stopwords1 = stopwords1.stopword.values.tolist()\n contents_clean1 = []\n all_words1 = []\n for line in contents:\n line_clean = []\n for word in line:\n if word in stopwords1:\n continue\n line_clean.append(word)\n all_words1.append(word)\n contents_clean1.append(line_clean)\n return contents_clean1, all_words1\n\n\nfor year in range(2015, 2021):\n data6 = []\n data4 = data3[year - 2015]\n if year == 2020:\n lda = models.LdaModel.load(f\"./{year}与{year + 1}主题分类\")\n for s in range(1, 16):\n stopwords = pd.read_csv(\"tyc.csv\")\n stopwords = stopwords[\"word\"].tolist()\n stopwords = pd.DataFrame({\"stopword\": stopwords})\n if 9 < s < 13:\n d = float(str(year) + \".\" + str(s))\n elif s < 10:\n d = float(str(year) + \".0\" + str(s))\n else:\n d = float(str(year + 1) + \".0\" + str(s - 12))\n contents_clean, all_words = drop_stopwords(stopwords, d)\n data = pd.read_pickle(f\"{year}与{year + 1}content.pickle\")\n data1 = [data for data in data[\"contents_clean\"]]\n dictionary = corpora.Dictionary(data1) # 为当年的语料库\n bow = dictionary.doc2bow(all_words)\n a = lda.get_document_topics(bow)\n b = [i[1] for i in a]\n b.sort(reverse=True)\n zhu_ti = []\n gai_lv = b[0:len(b)]\n for i in range(len(b)):\n if i < 3:\n for z in a:\n if b[i] == z[1]:\n zhu_ti.append(z[0])\n datas = []\n for i in range(len(zhu_ti)):\n temp_dict = {'name': data4[zhu_ti[i]], 'value': gai_lv[i]}\n datas.append(temp_dict)\n # print(datas)\n data6.append(datas)\n if s > 12:\n print(f\"{year + 1}第{s - 12}月完成\")\n else:\n print(f\"{year}第{s}月完成\")\n else:\n lda = models.LdaModel.load(f\"./{year}主题分类\")\n for s in range(1, 13):\n stopwords = pd.read_csv(\"tyc.csv\")\n stopwords = stopwords[\"word\"].tolist()\n stopwords = pd.DataFrame({\"stopword\": stopwords})\n if s > 9:\n d = float(str(year) + \".\" + str(s))\n else:\n d = float(str(year) + \".0\" + str(s))\n contents_clean, all_words = drop_stopwords(stopwords, d)\n if len(contents_clean) == 0:\n data6.append([])\n continue\n data = pd.read_pickle(f\"{year}content.pickle\")\n data1 = [data for data in data[\"contents_clean\"]]\n dictionary = corpora.Dictionary(data1) # 为当年的语料库\n bow = dictionary.doc2bow(all_words)\n a = lda.get_document_topics(bow)\n b = [i[1] for i in a]\n b.sort(reverse=True)\n zhu_ti = []\n gai_lv = b[0:len(b)]\n for i in range(len(b)):\n if i < 3:\n for z in a:\n if b[i] == z[1]:\n zhu_ti.append(z[0])\n datas = []\n for i in range(len(zhu_ti)):\n temp_dict = {'name': data4[zhu_ti[i]], 'value': gai_lv[i]}\n datas.append(temp_dict)\n # print(datas)\n print(f\"{year}第{s}月完成\")\n data6.append(datas)\n# print(len(data5[5]))\n # 写入json格式\n year_month1 = []\n year_month2 = []\n for i in range(len(data6)):\n dic1 = {\"name\": f\"{i+1}月\", \"children\": data6[i]}\n if i > 11:\n dic2 = {\"name\": f\"{i-11}月\", \"children\": data6[i]}\n year_month2.append(dic2)\n dic2 = {\"name\": year + 1, \"children\": year_month2}\n with open(f'第{year + 1}.json', 'w') as f:\n f.write(json.dumps({\"datas\": str(dic2)}))\n year_month1.append(dic1)\n dic = {\"name\": year, \"children\": year_month1}\n with open(f'第{year}.json', 'w') as f:\n f.write(json.dumps({\"datas\": str(dic)}))\n","sub_path":"LDA模型训练/每月分类当年训练.py","file_name":"每月分类当年训练.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375255561","text":"import numpy as np \nimport os\nimport paddle.fluid as fluid\nimport logging\nfrom collections import defaultdict\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(\"fluid\")\nlogger.setLevel(logging.INFO)\n\nall_field_id = ['101', '109_14', '110_14', '127_14', '150_14', '121', '122', '124', '125', '126', '127', '128', '129',\n '205', '206', '207', '210', '216', '508', '509', '702', '853', '301']\nall_field_id_dict = defaultdict(int)\nfor i,field_id in enumerate(all_field_id):\n all_field_id_dict[field_id] = [False,i]\n\ndef get_dataset(inputs,files,batch_size,cpu_num):\n dataset = fluid.DatasetFactory().create_dataset()\n dataset.set_use_var(inputs)\n dataset.set_pipe_command(\"python dataset_generator.py\")\n dataset.set_batch_size(batch_size)\n dataset.set_thread(int(cpu_num))\n file_list = [\n os.path.join(files, x) for x in os.listdir(files)\n ]\n logger.info(\"file list: {}\".format(file_list))\n return dataset, file_list\n \ndef get_vocab_size(vocab_path):\n with open(vocab_path, \"r\") as rf:\n line = rf.readline()\n return int(line.strip()) + 1\n\n\nclass CriteoDataset(object):\n\n def _reader_creator(self, file):\n def reader():\n with open(file, 'r') as f:\n for line in f:\n features = line.strip().split(',')\n ctr = features[1]\n cvr = features[2]\n \n padding = '0'\n output = [(field_id,[]) for field_id in all_field_id_dict]\n \n for elem in features[4:]:\n field_id,feat_id = elem.strip().split(':')\n if field_id not in all_field_id_dict:\n continue\n all_field_id_dict[field_id][0] = True\n index = all_field_id_dict[field_id][1]\n output[index][1].append(feat_id) \n \n for field_id in all_field_id_dict:\n visited,index = all_field_id_dict[field_id]\n if visited:\n all_field_id_dict[field_id][0] = False\n else:\n output[index][1].append(padding) \n output.append(('ctr',ctr))\n output.append(('cvr',cvr))\n yield output\n\n return reader\n\n def train(self, file):\n return self._reader_creator(file)\n\n def test(self, file):\n return self._reader_creator(file)\n\n\n\n\n ","sub_path":"PaddleRec/multi_task/esmm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"465733362","text":"#!/usr/bin/env python3\n'''\nAuthor: Brendan Byrne\nDescription: Useful functions from chapter3 of the text book.\n'''\n\nfrom ..macros import nCr\n\n# binom: calculates the probably of \"k\" events happening given \"n\" chances\n# and \"p\" probability of a single success. This assumes independence\n# or with replacement\n#\n# n: total number of attempts\n# k: desired number of successes\n# p: probability of a single success\ndef binom (n, k, p):\n P = nCr(n,k) * (p**k) * ((1-p)**(n-k))\n return P\n\n# hyperGeo: calculates the probably of \"k\" events happening \"n\" chances\n# assuming no replacement and no independence\n#\n# N: total number of items\n# n: number of chances to have a success (n <= N)\n# K: total number of items that are a success (K <= N)\n# k: desired number of successes\ndef hypergeo (N, n, K, k):\n \n # check inputs for feasibility\n if N < K:\n msg = \"Can't have more possible successes ({}) than total items ({}).\".format(K, N)\n raise SyntaxError(msg)\n \n elif n > N:\n msg = \"Can't have more chances ({}) than total items ({}).\".format(n,N)\n raise SyntaxError(msg)\n \n else:\n P = ( nCr(K, k) * nCr(N - K, n - k) ) / nCr(N, n)\n return P\n","sub_path":"chapters/chapter3.py","file_name":"chapter3.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"479404884","text":"class Node:\n def __init__(self, parent, left, right, key):\n self.parent = parent\n self.left = left\n self.right = right\n self.key = key\n\n def __iter__(self): # for method extend in list\n yield self.key\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n self.size = 0\n\n def add(self, key):\n if not self.root: # if we have no node yet\n self.root = Node(None, None, None, key)\n self.size += 1\n else:\n current = self.root\n while True:\n if key == current.key: # if key already exist\n return\n elif key < current.key: # traversing to left side\n if current.left:\n current = current.left\n else:\n new = Node(current, None, None, key) # adding to left side\n current.left = new\n self.size += 1\n return\n else: # traversing to right side\n if current.right:\n current = current.right\n else:\n new = Node(current, None, None, key) # adding to right side\n current.right = new\n self.size += 1\n return\n\n def find_median(self):\n result = self.traverse([], self.root)\n if self.size % 2 != 0: # if odd\n return result[self.size // 2]\n return (result[self.size // 2] + result[self.size // 2 - 1]) / 2\n\n def traverse(self, l, n):\n if n.left:\n self.traverse(l, n.left)\n l.append(n.key)\n if n.right:\n self.traverse(l, n.right)\n return l\n\n def union_tree(self, T2): # assuming no duplicate key in union\n li1 = self.get_tree(self.root, [])\n li2 = T2.get_tree(T2.root, [])\n li1.extend(li2)\n return li1\n\n def get_tree(self, cursor, li=[]):\n if cursor is None:\n return\n if cursor.left:\n self.get_tree(cursor.left, li)\n li.extend(cursor)\n if cursor.right:\n self.get_tree(cursor.right, li)\n return li\n\n\nt1 = BinarySearchTree()\nt1.add(3)\nt1.add(1)\nt1.add(5)\n\nt2 = BinarySearchTree()\nt2.add(10)\nt2.add(9)\nt2.add(15)\n\nt3 = t1.union_tree(t2)\nprint(t3)\n\n","sub_path":"Data/src/lab_10/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"170574140","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask import redirect\n\n\napp = Flask(__name__)\n\n\n@app.route('/story')\ndef create_page():\n \"\"\" Gets input through the user through the browser\n then adds them to the database\n \"\"\"\n selected_story = []\n selected = ['', '', '', '', '']\n title = \"Super Sprinter 3000 - Add new Story\"\n id = \"\"\n desc_text = \"Add new Story\"\n return render_template('form.html', sel_list=selected_story, id=id,\n selected=selected, title=title, desc_text=desc_text)\n\n\n@app.route(\"/story\", methods=['POST'])\ndef create_save():\n \"\"\" Gets several input from the user through the browser\n then writes them back to the datebase into a new line, with the next ID in line\n \"\"\"\n title = request.form['title']\n story = request.form['story'].replace(\"\\r\\n\", \" \")\n criteria = request.form['criteria'].replace(\"\\r\\n\", \" \")\n business = request.form['business']\n estimation = request.form['estimation']\n progress = request.form['progress']\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n next_id = \"\"\n if len(data_list) > 0:\n next_id = str(int(data_list[-1][0]) + 1)\n else:\n next_id = 0\n with open('database.csv', 'a') as file:\n file.write(str(next_id) + \"ߤ\")\n file.write(str(title + \"ߤ\"))\n file.write(str(story + \"ߤ\"))\n file.write(str(criteria + \"ߤ\"))\n file.write(str(business + \"ߤ\"))\n file.write(str(estimation + \"ߤ\"))\n file.write(str(progress + \"\\n\"))\n return redirect(\"/list\")\n\n\n@app.route(\"/story/\", methods=[\"GET\"])\ndef update_show(id):\n \"\"\"Receives an ID from the user through the browser, then find the\n correct the story and returns all the values from the database to the html form\n \"\"\"\n title = \"Super Sprinter 3000 - Edit Story\"\n desc_text = \"Edit Story\"\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n selected_story = []\n for item in data_list:\n if int(item[0]) == int(id):\n selected_story = item\n\n options = [\"1. Planning\", \"2. TODO\", \"3. In Progress\", \"4. Review\", \"5. Done\"]\n selected_status = ['', '', '', '', '']\n for i in range(len(selected_status)):\n if selected_story[6] == options[i]:\n selected_status[i] = \"selected\"\n return render_template('form.html', sel_list=selected_story, id=('/' + str(id)),\n selected=selected_status, title=title, desc_text=desc_text)\n\n\n@app.route(\"/story/\", methods=['POST'])\ndef update_save(id):\n \"\"\" Receives several inputs from the user through the browser then\n finds the correct row with the ID then changes the values and writes it back, updates it\n then returns the user back to the list page\n \"\"\"\n title = request.form['title']\n story = request.form['story'].replace(\"\\r\\n\", \" \")\n criteria = request.form['criteria'].replace(\"\\r\\n\", \" \")\n business = request.form['business']\n estimation = request.form['estimation']\n progress = request.form['progress']\n new_list = [str(id), title, story, criteria, business, estimation, progress]\n selected_row = []\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n for item in data_list:\n if int(item[0]) == int(id):\n selected_row.append(new_list)\n else:\n selected_row.append(item)\n\n with open('database.csv', 'w') as file:\n for item in selected_row:\n file.write(\"ߤ\".join(item) + \"\\n\")\n return redirect(\"/list\")\n\n\n@app.route(\"/\", methods=['GET'])\n@app.route(\"/list\", methods=['GET'])\ndef main_list():\n \"\"\" Reads the database into list of lists then returns them to the html template\n \"\"\"\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n title = \"Super Sprinter 3000\"\n return render_template('list.html', data_list=data_list, title=title)\n\n\n@app.route(\"/delete/\", methods=[\"POST\"])\ndef delete(id):\n \"\"\"Receives an ID from the user through the browser, then searches the database\n for said ID, if it finds it then it deletes it, then returns the user back to the\n list page\n \"\"\"\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n for item in data_list:\n if int(item[0]) == int(id):\n data_list.remove(item)\n\n with open('database.csv', 'w') as file:\n for item in data_list:\n datas = \"ߤ\".join(item)\n file.write(str(datas) + \"\\n\")\n return render_template('list.html', data_list=data_list, id=('/' + str(id)))\n\n\n@app.route(\"/search\", methods=['POST'])\ndef search():\n \"\"\" Receives a string from the user through forms then\n searches the database if the string is in any row item,\n it it is then returns the whole row, if not then goes back to the main page\n \"\"\"\n title = \"Super Sprinter 3000\"\n searched_word = request.form['search']\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n searched_row = []\n for row in data_list:\n for item in row:\n if str(searched_word) in item:\n searched_row.append(row)\n if len(searched_word) > 0:\n return render_template('list.html', data_list=searched_row, title=title)\n else:\n return redirect(\"/list\")\n\n\n@app.route(\"/sortby\", methods=['POST'])\ndef sortby():\n \"\"\" gets input from the user through the browser, then\n shows the database based on that rule\n \"\"\"\n title = \"Super Sprinter 3000\"\n search_key = str(request.form['sortby'])\n with open('database.csv') as data:\n data_list = data.read().splitlines()\n data_list = [item.split(\"ߤ\") for item in data_list]\n if search_key == 'ID':\n data_list = sorted(data_list, key=lambda x: int(x[0]))\n elif search_key == 'Title':\n data_list = sorted(data_list, key=lambda x: str(x[1]))\n elif search_key == 'User Story':\n data_list = sorted(data_list, key=lambda x: str(x[2]))\n elif search_key == 'Acceptance Criteria':\n data_list = sorted(data_list, key=lambda x: str(x[3]))\n elif search_key == 'Business Value':\n data_list = sorted(data_list, key=lambda x: int(x[4]))\n elif search_key == 'Estimation (h)':\n data_list = sorted(data_list, key=lambda x: float(x[5]))\n elif search_key == 'Status':\n data_list = sorted(data_list, key=lambda x: str(x[6]))\n return render_template('list.html', data_list=data_list, title=title)\n\n\nif __name__ == \"__main__\":\n app.run(debug=None)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"627942869","text":"# vim: fileencoding=utf-8:\n'''\n\nFormat\n---------------------\n\nSources:\n\n.. _Swift for corporates: http://www.sepaforcorporates.com/\\\n swift-for-corporates/account-statement-mt940-file-format-overview/\n.. _Rabobank MT940: https://www.rabobank.nl/images/\\\n formaatbeschrijving_swift_bt940s_1_0_nl_rib_29539296.pdf\n\n - `Swift for corporates`_\n - `Rabobank MT940`_\n\n::\n\n [] = optional\n ! = fixed length\n a = Text\n x = Alphanumeric, seems more like text actually. Can include special\n characters (slashes) and whitespace as well as letters and numbers\n d = Numeric separated by decimal (usually comma)\n c = Code list value\n n = Numeric\n'''\nfrom __future__ import print_function\nimport re\nimport logging\n\ntry:\n import enum\nexcept ImportError: # pragma: no cover\n import sys\n print('MT940 requires the `enum34` package', file=sys.stderr)\n\n class enum(object):\n @staticmethod\n def unique(*args, **kwargs):\n return []\n\n Enum = object\n\nfrom . import models\n\nlogger = logging.getLogger(__name__)\n\n\nclass Tag(object):\n id = 0\n RE_FLAGS = re.IGNORECASE | re.VERBOSE | re.UNICODE\n scope = models.Transactions\n\n def __init__(self):\n self.re = re.compile(self.pattern, self.RE_FLAGS)\n\n def parse(self, transactions, value):\n match = self.re.match(value)\n if match: # pragma: no branch\n self.logger.debug(\n 'matched (%d) %r against %r, got: %s',\n len(value), value, self.pattern,\n match.groupdict())\n else: # pragma: no cover\n self.logger.error(\n 'matching (%d) %r against %r', len(value), value,\n self.pattern)\n\n part_value = value\n for pattern in self.pattern.split('\\n'):\n match = re.match(pattern, part_value, self.RE_FLAGS)\n if match:\n self.logger.info('matched %r against %r, got: %s',\n pattern, match.group(0),\n match.groupdict())\n part_value = part_value[len(match.group(0)):]\n else:\n self.logger.error('no match for %r against %r',\n pattern, part_value)\n\n raise RuntimeError(\n 'Unable to parse %r from %r' % (self, value),\n self, value)\n return match.groupdict()\n\n def __call__(self, transactions, value):\n return value\n\n def __new__(cls, *args, **kwargs):\n cls.name = cls.__name__\n\n words = re.findall('([A-Z][a-z]+)', cls.__name__)\n cls.slug = '_'.join(w.lower() for w in words)\n cls.logger = logger.getChild(cls.name)\n\n return object.__new__(cls, *args, **kwargs)\n\n def __hash__(self):\n return self.id\n\n\nclass DateTimeIndication(Tag):\n '''Date/Time indication at which the report was created\n\n Pattern: 6!n4!n1! x4!n\n '''\n id = 13\n pattern = r'''^\n (?P\\d{2})\n (?P\\d{2})\n (?P\\d{2})\n (?P\\d{2})\n (?P\\d{2})\n (\\+(?P\\d{4})|)\n '''\n\n def __call__(self, transactions, value):\n data = super(DateTimeIndication, self).__call__(transactions, value)\n return {\n 'date': models.DateTime(**data)\n }\n\n\nclass TransactionReferenceNumber(Tag):\n\n '''Transaction reference number\n\n Pattern: 16x\n '''\n id = 20\n pattern = r'(?P.{0,16})'\n\n\nclass RelatedReference(Tag):\n\n '''Related reference\n\n Pattern: 16x\n '''\n id = 21\n pattern = r'(?P.{0,16})'\n\n\nclass AccountIdentification(Tag):\n\n '''Account identification\n\n Pattern: 35x\n '''\n id = 25\n pattern = r'(?P.{0,35})'\n\n\nclass StatementNumber(Tag):\n\n '''Statement number / sequence number\n\n Pattern: 5n[/5n]\n '''\n id = 28\n pattern = r'''\n (?P\\d{1,5}) # 5n\n (?:/?(?P\\d{1,5}))? # [/5n]\n $'''\n\n\nclass FloorLimitIndicator(Tag):\n '''Floor limit indicator\n indicates the minimum value reported for debit and credit amounts\n\n Pattern: :34F:GHSC0,00\n '''\n id = 34\n pattern = r'''^\n (?P[A-Z]{3}) # 3!a Currency\n (?P[DC ]?) # 2a Debit/Credit Mark\n (?P[0-9,]{0,16}) # 15d Amount (includes decimal sign, so 16)\n $'''\n\n def __call__(self, transactions, value):\n data = super(FloorLimitIndicator, self).__call__(transactions, value)\n if data['status']:\n return {\n data['status'].lower() + '_floor_limit': models.Amount(**data)\n }\n\n data_d = data.copy()\n data_c = data.copy()\n data_d.update({'status': 'D'})\n data_c.update({'status': 'C'})\n return {\n 'd_floor_limit': models.Amount(**data_d),\n 'c_floor_limit': models.Amount(**data_c)\n }\n\n\nclass NonSwift(Tag):\n\n '''Non-swift extension for MT940 containing extra information. The\n actual definition is not consistent between banks so the current\n implementation is a tad limited. Feel free to extend the implementation\n and create a pull request with a better version :)\n\n It seems this could be anything so we'll have to be flexible about it.\n\n Pattern: `2!n35x | *x`\n '''\n\n class scope(models.Transaction, models.Transactions):\n pass\n id = 'NS'\n\n pattern = r'''\n (?P\n (\n (\\d{2}.{0,})\n (\\n\\d{2}.{0,})*\n )|(\n [^\\n]*\n )\n )\n $'''\n sub_pattern = r'''\n (?P\\d{2})(?P.{0,})\n '''\n sub_pattern_m = re.compile(sub_pattern,\n re.IGNORECASE | re.VERBOSE | re.UNICODE)\n\n def __call__(self, transactions, value):\n text = []\n data = value['non_swift']\n for line in data.split('\\n'):\n frag = self.sub_pattern_m.match(line)\n if frag and frag.group(2):\n ns = frag.groupdict()\n value['non_swift_' + ns['ns_id']] = ns['ns_data']\n text.append(ns['ns_data'])\n elif len(text) and text[-1]:\n text.append('')\n elif line.strip():\n text.append(line.strip())\n value['non_swift_text'] = '\\n'.join(text)\n value['non_swift'] = data\n return value\n\n\nclass BalanceBase(Tag):\n\n '''Balance base\n\n Pattern: 1!a6!n3!a15d\n '''\n pattern = r'''^\n (?P[DC]) # 1!a Debit/Credit\n (?P\\d{2}) # 6!n Value Date (YYMMDD)\n (?P\\d{2})\n (?P\\d{2})\n (?P.{3}) # 3!a Currency\n (?P[0-9,]{0,16}) # 15d Amount (includes decimal sign, so 16)\n '''\n\n def __call__(self, transactions, value):\n data = super(BalanceBase, self).__call__(transactions, value)\n data['amount'] = models.Amount(**data)\n data['date'] = models.Date(**data)\n return {\n self.slug: models.Balance(**data)\n }\n\n\nclass OpeningBalance(BalanceBase):\n id = 60\n\n\nclass FinalOpeningBalance(BalanceBase):\n id = '60F'\n\n\nclass IntermediateOpeningBalance(BalanceBase):\n id = '60M'\n\n\nclass Statement(Tag):\n\n '''Statement\n\n Pattern: 6!n[4!n]2a[1!a]15d1!a3!c23x[//16x]\n '''\n id = 61\n scope = models.Transaction\n pattern = r'''^\n (?P\\d{2}) # 6!n Value Date (YYMMDD)\n (?P\\d{2})\n (?P\\d{2})\n (?P\\d{2})? # [4!n] Entry Date (MMDD)\n (?P\\d{2})?\n (?P[A-Z]?[DC]) # 2a Debit/Credit Mark\n (?P[A-Z])? # [1!a] Funds Code (3rd character of the currency\n # code, if needed)\n \\n? # apparently some banks (sparkassen) incorporate newlines here\n (?P[\\d,]{1,15}) # 15d Amount\n (?P[A-Z][A-Z0-9 ]{3})? # 1!a3!c Transaction Type Identification Code\n (?P.{0,16}) # 16x Customer Reference\n (//(?P.{0,23}))? # [//23x] Bank Reference\n (\\n?(?P.{0,34}))? # [34x] Supplementary Details\n $'''\n\n def __call__(self, transactions, value):\n data = super(Statement, self).__call__(transactions, value)\n data.setdefault('currency', transactions.currency)\n\n data['amount'] = models.Amount(**data)\n date = data['date'] = models.Date(**data)\n\n if data.get('entry_day') and data.get('entry_month'):\n entry_date = data['entry_date'] = models.Date(\n day=data.get('entry_day'),\n month=data.get('entry_month'),\n year=str(data['date'].year),\n )\n\n if date > entry_date and (date - entry_date).days >= 330:\n year = 1\n elif entry_date > date and (entry_date - date).days >= 330:\n year = -1\n else:\n year = 0\n\n data['guessed_entry_date'] = models.Date(\n day=entry_date.day,\n month=entry_date.month,\n year=entry_date.year + year,\n )\n\n return data\n\n\nclass StatementASNB(Statement):\n '''StatementASNB\n\n From: https://www.sepaforcorporates.com/swift-for-corporates\n\n Pattern: 6!n[4!n]2a[1!a]15d1!a3!c16x[//16x]\n [34x]\n\n But ASN bank puts the IBAN in the customer reference, which is acording to\n Wikipedia at most 34 characters.\n\n So this is the new pattern:\n\n Pattern: 6!n[4!n]2a[1!a]15d1!a3!c34x[//16x]\n [34x]\n '''\n pattern = r'''^\n (?P\\d{2}) # 6!n Value Date (YYMMDD)\n (?P\\d{2})\n (?P\\d{2})\n (?P\\d{2})? # [4!n] Entry Date (MMDD)\n (?P\\d{2})?\n (?P[A-Z]?[DC]) # 2a Debit/Credit Mark\n (?P[A-Z])? # [1!a] Funds Code (3rd character of the currency\n # code, if needed)\n \\n? # apparently some banks (sparkassen) incorporate newlines here\n (?P[\\d,]{1,15}) # 15d Amount\n (?P[A-Z][A-Z0-9 ]{3})? # 1!a3!c Transaction Type Identification Code\n (?P.{0,34}) # 34x Customer Reference\n (//(?P.{0,16}))? # [//16x] Bank Reference\n (\\n?(?P.{0,34}))? # [34x] Supplementary Details\n $'''\n\n def __call__(self, transactions, value):\n return super(StatementASNB, self).__call__(transactions, value)\n\n\nclass ClosingBalance(BalanceBase):\n id = 62\n\n\nclass FinalClosingBalance(ClosingBalance):\n id = '62F'\n\n\nclass IntermediateClosingBalance(ClosingBalance):\n id = '62M'\n\n\nclass AvailableBalance(BalanceBase):\n id = 64\n\n\nclass ForwardAvailableBalance(BalanceBase):\n id = 65\n\n\nclass TransactionDetails(Tag):\n\n '''Transaction details\n\n Pattern: 6x65x\n '''\n id = 86\n scope = models.Transaction\n pattern = r'''\n (?P(([\\s\\S]{0,65}\\r?\\n?){0,8}[\\s\\S]{0,65}))\n '''\n\n\nclass SumEntries(Tag):\n '''Number and Sum of debit Entries\n\n '''\n\n id = 90\n pattern = r'''^\n (?P\\d*)\n (?P.{3}) # 3!a Currency\n (?P[\\d,]{1,15}) # 15d Amount\n '''\n\n def __call__(self, transactions, value):\n data = super(SumEntries, self).__call__(transactions, value)\n\n data['status'] = self.status\n return {\n self.slug: models.SumAmount(**data)\n }\n\n\nclass SumDebitEntries(SumEntries):\n status = 'D'\n id = '90D'\n\n\nclass SumCreditEntries(SumEntries):\n status = 'C'\n id = '90C'\n\n\n@enum.unique\nclass Tags(enum.Enum):\n DATE_TIME_INDICATION = DateTimeIndication()\n TRANSACTION_REFERENCE_NUMBER = TransactionReferenceNumber()\n RELATED_REFERENCE = RelatedReference()\n ACCOUNT_IDENTIFICATION = AccountIdentification()\n STATEMENT_NUMBER = StatementNumber()\n OPENING_BALANCE = OpeningBalance()\n INTERMEDIATE_OPENING_BALANCE = IntermediateOpeningBalance()\n FINAL_OPENING_BALANCE = FinalOpeningBalance()\n STATEMENT = Statement()\n CLOSING_BALANCE = ClosingBalance()\n INTERMEDIATE_CLOSING_BALANCE = IntermediateClosingBalance()\n FINAL_CLOSING_BALANCE = FinalClosingBalance()\n AVAILABLE_BALANCE = AvailableBalance()\n FORWARD_AVAILABLE_BALANCE = ForwardAvailableBalance()\n TRANSACTION_DETAILS = TransactionDetails()\n FLOOR_LIMIT_INDICATOR = FloorLimitIndicator()\n NON_SWIFT = NonSwift()\n SUM_ENTRIES = SumEntries()\n SUM_DEBIT_ENTRIES = SumDebitEntries()\n SUM_CREDIT_ENTRIES = SumCreditEntries()\n\n\nTAG_BY_ID = {t.value.id: t.value for t in Tags}\n\n\n\n","sub_path":"mt940/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":12490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429965757","text":"#---------------------------------------------------------------------------------------------------#\n#1.grafica\n#------------MESAJES-----------------#\n\nPREGUNTA_NOMBRE = \"Ingrese el archivo que quieres graficar \\n \"\n\n#------------CODIGO------------------#\nimport matplotlib.pyplot as plt\nimport pandas as p \ndef validador_archivo(PREGUNTA_NOMBRE):\n assert (open (archivoUsuario) )\n return False\nvalidador = True\nwhile (validador):\n archivoUsuario = input (PREGUNTA_NOMBRE)\n try:\n validador = validador_archivo(PREGUNTA_NOMBRE)\n grafica_1 = p.read_csv(archivoUsuario,encoding='UTF-8',header=0, delimiter=\";\").to_dict()\n x = list (grafica_1[\"muestra\"].values())\n y = list (grafica_1 [\"valor\"].values())\n plt.plot(x,y)\n except FileNotFoundError :\n print(\"ingresaste un archivo que no existe\")\n\nPREGUNTA_TITULO = \"Ingrese el titulo que le desea colocar a la grafica \\n\"\nPREGUNTA_EJE_X = \"Ingrese el titulo que le desea colocar al eje x \\n\"\nPREGUNTA_EJE_y = \"Ingrese el titulo que le desea colocar al eje y \\n\"\n\ntitulo = input (PREGUNTA_TITULO)\ntitulo_x = input (PREGUNTA_EJE_X)\ntitulo_y = input (PREGUNTA_EJE_y)\nplt.title(titulo)\nplt.xlabel(titulo_x)\nplt.ylabel(titulo_y)\nplt.savefig(archivoUsuario + \".png\")\nplt.show()\n \n#------------------------------------------------------------------------------------------#\n#2.#------------MESAJES-----------------#\nPREGUNTA_NOMBRE = \"Ingrese su nombre \\n \"\nPREGUNTA_EDAD = \"Ingreses su edad \\n\"\nPREGUNTA_PESO = \"Ingrese su peso \\n\"\nPREGUNTA_ESTATURA = \"Ingrese su estatura \\n\"\n\n#-------------VARIABLE------------------#\nIMC = 0.0\n#--------------ENTRADA------------------#\n_nombreUsuario = \" \"\n_edadUsuario = 0\n_pesoUsuario = 0.0\n_estaturaUsuario = 0.0\n#--------------CODIGO-------------------#\n\n_nombreUsuario = input (PREGUNTA_NOMBRE)\n\ntry:\n _edadUsuario = int (input (PREGUNTA_EDAD))\nexcept ValueError:\n print(\"ingresaste mal el peso\")\ntry:\n _pesoUsuario = float (input (PREGUNTA_PESO))\nexcept ValueError:\n print(\"ingresaste mal el peso\")\ntry:\n _estaturaUsuario = float (input (PREGUNTA_ESTATURA))\nexcept ValueError:\n print(\"ingresaste mal la estatura \")\n\nIMC = (_pesoUsuario/_estaturaUsuario**2)\nprint (\"Su imc es de {}\".format (IMC) )\n \n#-----------------------------------------------------------------------------------------#\n#3. #------------MESAJES-----------------#\nPREGUNTA_ARROZ = \"cuantos kilos tiene de arroz \\n \"\nPREGUNTA_LENTEJA = \" cuantos kilos tiene de lentejas\\n\"\nPREGUNTA_FRIJOL = \"cuantos kilos tiene de frijoles \\n\"\nPREGUNTA_PAPA = \"Cuantos kilos tiene de papa \\n\"\n\n#--------------ENTRADA-------------------#\n_kilosArroz= 0\n_kilosLentejas = 0\n_kilosFrijol = 0\n_kilosPapa = 0\n\n#--------------CODIGO---------------------#\nimport matplotlib.pyplot as plt\ntry:\n _kilosArroz= int (input (PREGUNTA_ARROZ))\n _kilosLentejas = int (input (PREGUNTA_LENTEJA))\n _kilosFrijol = int (input (PREGUNTA_FRIJOL))\n _kilosPapa = int (input (PREGUNTA_PAPA))\n pregunta = {\n \"nombres\" : [\"Arroz\", \"Lenteja\" , \"Frijol\" ,\"Papa\"] ,\n \"kilos\" : [_kilosArroz, _kilosLentejas, _kilosFrijol , _kilosPapa]\n }\n plt.bar (pregunta [\"nombres\"],pregunta [\"kilos\"],color = \"r\", alpha = 0.2)\nexcept ValueError:\n print(\"Entreda no valida\")\n \nplt.savefig(\"Mercado.png\")\nplt.show()\n\n#------------------------------------------------------------------------------------------#\n#4.texto finalizado en punto \n\ndef validador_parrafo(parrafo):\n assert(parrafo.endswith(\".\"))\n return False\nvalidador = True\n\nwhile (validador):\n parrafo = input('cuentame como te has sentido .')\n try:\n validador = validador_parrafo(parrafo)\n except AssertionError:\n print(\"Entrada no válida, intruduzca el texto pero acuerdate en finalizar en punto\")\n\n\n#-----------------------------------------------------------------------------------------#\n# 5.Grafico de pie \n\nlabels = 'Leche', 'Huevo', 'Vino' , 'Arroz','Queso', \"Salchichas\"\nsizes = [12,8,4,26,30,20]\nexplode = [0,0,0,0,0.1,0]\nplt.pie (sizes, explode=explode, labels=labels , shadow=True, startangle=45 ,)\nplt.title (\"Compras en la tienda\")\nplt.savefig (\"compras_en_la_tienda.png\")\nplt.close\nplt.show()","sub_path":"talleres/trabajo.py/reto_final.py","file_name":"reto_final.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"651095728","text":"from random import randint\n\nn, m, k, v1, v2, v3 = 100, 300, 64, 1000, 300, 800\n\nprint('%d %d %d 2' % (n, m + (n - 2) * 2, k))\nfor i in range(2, n):\n print('%d %d' % (1, i))\n print('%d %d' % (i, n))\nedges = []\nfor i in range(m):\n while True:\n u, v = randint(2, n - 1), randint(2, n - 1)\n if u < v and not (u, v) in edges:\n break\n edges.append((u, v))\n print('%d %d' % (u, v))\nfor i in range(n):\n print(' '.join([ str(randint(v1, v1 + v2)) for j in range(k) ]))\nfor i in range(k):\n print(' '.join([ '0' if i == j else str(randint(1, v3)) for j in range(k) ]))\n\n","sub_path":"day2/placement/data/data_maker/9/dm.py","file_name":"dm.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"332768825","text":"import pdb\nimport random\nimport numpy as np\nfrom dist import uniform_dist, delta_dist, mixture_dist\nfrom util import argmax_with_val, argmax\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import Adam\n\nclass MDP:\n # Needs the following attributes:\n # states: list or set of states\n # actions: list or set of actions\n # discount_factor: real, greater than 0, less than or equal to 1\n # start: optional instance of DDist, specifying initial state dist\n # if it's unspecified, we'll use a uniform over states\n # These are functions:\n # transition_model: function from (state, action) into DDist over next state\n # reward_fn: function from (state, action) to real-valued reward\n\n def __init__(self, states, actions, transition_model, reward_fn,\n discount_factor = 1.0, start_dist = None):\n self.states = states\n self.actions = actions\n self.transition_model = transition_model\n self.reward_fn = reward_fn\n self.discount_factor = discount_factor\n self.start = start_dist if start_dist else uniform_dist(states)\n\n # Given a state, return True if the state should be considered to\n # be terminal. You can think of a terminal state as generating an\n # infinite sequence of zero reward.\n def terminal(self, s):\n return False\n\n # Randomly choose a state from the initial state distribution\n def init_state(self):\n return self.start.draw()\n\n # Simulate a transition from state s, given action a. Return\n # reward for (s,a) and new state, drawn from transition. If a\n # terminal state is encountered, sample next state from initial\n # state distribution\n def sim_transition(self, s, a):\n return (self.reward_fn(s, a),\n self.init_state() if self.terminal(s) else\n self.transition_model(s, a).draw())\n\n def state2vec(self, s):\n '''\n Return one-hot encoding of state s; used in neural network agent implementations\n '''\n v = np.zeros((1, len(self.states)))\n v[0,self.states.index(s)] = 1.\n return v\n\n# Perform value iteration on an MDP, also given an instance of a q\n# function. Terminate when the max-norm distance between two\n# successive value function estimates is less than eps.\n# interactive_fn is an optional function that takes the q function as\n# argument; if it is not None, it will be called once per iteration,\n# for visuzalization\n\n# The q function is typically an instance of TabularQ, implemented as a\n# dictionary mapping (s, a) pairs into Q values This must be\n# initialized before interactive_fn is called the first time.\n\ndef value_iteration(mdp, q, eps=0.01, max_iters=1000): # Your code here\n for i in range(max_iters):\n new_q = q.copy()\n stop = float('-inf')\n for a in mdp.actions:\n for s in mdp.states:\n val = mdp.reward_fn(s, a) + mdp.discount_factor * sum(\n [mdp.transition_model(s, a).prob(s_0) * value(q, s_0) for s_0 in mdp.states])\n new_q.set(s, a, val)\n temp = abs(new_q.get(s, a) - q.get(s, a))\n if temp > stop:\n stop = temp\n if stop < eps:\n break\n q = new_q\n return new_q\n\n\n# Given a state, return the value of that state, with respect to the\n# current definition of the q function\ndef value(q, s): # Your code here\n \"\"\" Return Q*(s,a) based on current Q\n\n >>> q = TabularQ([0,1,2,3],['b','c'])\n >>> q.set(0, 'b', 5)\n >>> q.set(0, 'c', 10)\n >>> q_star = value(q,0)\n >>> q_star\n 10\n \"\"\"\n result = float('-inf')\n for action in q.actions:\n if q.get(s, action) > result:\n result = q.get(s,action)\n return result\n\n\n# Given a state, return the action that is greedy with reespect to the\n# current definition of the q function\ndef greedy(q, s): # Your code here\n return argmax(q.actions, lambda a: q.get(s, a))\n\ndef epsilon_greedy(q, s, eps = 0.5): # Your code here\n if random.random() < eps: # True with prob eps, random action\n return uniform_dist(q.actions).draw()\n else:\n return greedy(q,s)\n\nclass TabularQ:\n def __init__(self, states, actions):\n self.actions = actions\n self.states = states\n self.q = dict([((s, a), 0.0) for s in states for a in actions])\n def copy(self):\n q_copy = TabularQ(self.states, self.actions)\n q_copy.q.update(self.q)\n return q_copy\n def set(self, s, a, v):\n self.q[(s,a)] = v\n def get(self, s, a):\n return self.q[(s,a)]\n def update(self, data, lr):\n # Your code here\n for d in data:\n self.q[(d[0], d[1])] = self.q[(d[0], d[1])] + lr * (d[2] - self.q[(d[0], d[1])])\n\ndef Q_learn(mdp, q, lr=.1, iters=100, eps = 0.5, interactive_fn=None):\n # Your code here\n s0 = mdp.init_state()\n for i in range(iters):\n a = epsilon_greedy(q, s0, eps)\n r, s_prime = mdp.sim_transition(s0, a)\n target = value(q, s_prime) if not mdp.terminal(s0) else 0\n q.update([(s0, a, (r + mdp.discount_factor * target))], lr)\n s0 = s_prime\n # include this line in the iteration, where i is the iteration number\n if interactive_fn: interactive_fn(q, i)\n return q\n\n# Simulate an episode (sequence of transitions) of at most\n# episode_length, using policy function to select actions. If we find\n# a terminal state, end the episode. Return accumulated reward a list\n# of (s, a, r, s') where s' is None for transition from terminal state.\n# Also return an animation if draw=True.\ndef sim_episode(mdp, episode_length, policy, draw=False):\n episode = []\n reward = 0\n s = mdp.init_state()\n all_states = [s]\n for i in range(int(episode_length)):\n a = policy(s)\n (r, s_prime) = mdp.sim_transition(s, a)\n reward += r\n if mdp.terminal(s):\n episode.append((s, a, r, None))\n break\n episode.append((s, a, r, s_prime))\n if draw: \n mdp.draw_state(s)\n s = s_prime\n all_states.append(s)\n animation = animate(all_states, mdp.n, episode_length) if draw else None\n return reward, episode, animation\n\n# Create a matplotlib animation from all states of the MDP that\n# can be played both in colab and in local versions.\ndef animate(states, n, ep_length):\n try:\n from matplotlib import animation, rc\n import matplotlib.pyplot as plt\n from google.colab import widgets\n\n plt.ion()\n plt.figure(facecolor=\"white\")\n fig, ax = plt.subplots()\n plt.close()\n\n def animate(i):\n if states[i % len(states)] == None or states[i % len(states)] == 'over':\n return\n ((br, bc), (brv, bcv), pp, pv) = states[i % len(states)]\n im = np.zeros((n, n+1))\n im[br, bc] = -1\n im[pp, n] = 1\n ax.cla()\n ims = ax.imshow(im, interpolation = 'none',\n cmap = 'viridis', \n extent = [-0.5, n+0.5,\n -0.5, n-0.5],\n animated = True)\n ims.set_clim(-1, 1)\n rc('animation', html='jshtml')\n anim = animation.FuncAnimation(fig, animate, frames=ep_length, interval=100)\n return anim\n except:\n # we are not in colab, so the typical animation should work\n return None\n\n# Return average reward for n_episodes of length episode_length\n# while following policy (a function of state) to choose actions.\ndef evaluate(mdp, n_episodes, episode_length, policy):\n score = 0\n length = 0\n for i in range(n_episodes):\n # Accumulate the episode rewards\n r, e, _ = sim_episode(mdp, episode_length, policy)\n score += r\n length += len(e)\n # print(' ', r, len(e))\n return score/n_episodes, length/n_episodes\n\ndef Q_learn_batch(mdp, q, lr=.1, iters=100, eps=0.5, episode_length=10, n_episodes=2, interactive_fn=None):\n # Your code here\n all_experiences = []\n for i in range(iters):\n for e in range(n_episodes):\n r, ep, an = sim_episode(mdp, episode_length, lambda s: epsilon_greedy(q, s, eps), draw=False)\n all_experiences.extend(ep)\n all_q_targets = []\n for ex in all_experiences:\n target = 0 if ex[3] is None else value(q, ex[3])\n all_q_targets.append((ex[0], ex[1], ex[2]+mdp.discount_factor*target))\n q.update(all_q_targets, lr)\n # include this line in the iteration, where i is the iteration number\n if interactive_fn: interactive_fn(q, i)\n return q\n\ndef make_nn(state_dim, num_hidden_layers, num_units):\n model = Sequential()\n model.add(Dense(num_units, input_dim = state_dim, activation='relu'))\n for i in range(num_hidden_layers-1):\n model.add(Dense(num_units, activation='relu'))\n model.add(Dense(1, activation='linear'))\n model.compile(loss='mse', optimizer=Adam())\n return model\n\n\nclass NNQ:\n def __init__(self, states, actions, state2vec, num_layers, num_units, epochs=1):\n self.actions = actions\n self.states = states\n self.epochs = epochs\n self.state2vec = state2vec\n self.models = {a: make_nn(state2vec(states[0]).shape[1], num_layers, num_units) for a in actions} # Your code here\n\n def get(self, s, a): # Your code here\n return self.models[a].predict(self.state2vec(s))\n\n def update(self, data, lr, epochs=1): # Your code here\n for a in self.actions:\n rel_data = [d for d in data if d[1] == a]\n if rel_data:\n X = np.concatenate([self.state2vec(d[0]) for d in rel_data])\n Y = np.concatenate([np.array([[d[2]]]) for d in rel_data])\n self.models[a].fit(X, Y, self.epochs)\n\n","sub_path":"code_for_hw10/mdp10.py","file_name":"mdp10.py","file_ext":"py","file_size_in_byte":9894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"100028005","text":"from util.util_error1 import *\nfrom util.util_error2 import *\nfrom util.util_error3 import *\nfrom util.util_error4 import *\n\ndef compress():\n \"\"\"Compresses an image.\"\"\"\n img = tf.placeholder(tf.float32, [1, None, None, 3])\n\n # Transform and compress the image, then remove batch dimension.\n y_base = analysis_transform(img, args.conv_filters, args.num_filters)\n y_hat, likelihoods, entropy_bottleneck, string = entropy_estimation(y_base, False)\n x_hat = synthesis_transform(y_hat,args.conv_filters, args.num_filters)\n num_pixels = tf.to_float(tf.reduce_prod(tf.shape(img)[:-1]))\n\n # e1 layer\n x_e1 = img - x_hat\n y_e1 = analysis_transform_e1(x_e1, args.conv_filters, args.num_filters)\n y_hat_e1, likelihoods_e1, entropy_bottleneck_e1, _ = entropy_estimation_e1(y_e1, False)\n x_hat_e1 = synthesis_transform_e1(y_hat_e1, args.conv_filters, args.num_filters)\n x_rec_e1 = x_hat +x_hat_e1\n\n # e2 layer\n x_e2 = img - x_hat - x_hat_e1\n y_e2 = analysis_transform_e2(x_e2, args.conv_filters, args.num_filters * 2)\n y_hat_e2, likelihoods_e2, entropy_bottleneck_e2, _ = entropy_estimation_e2(y_e2, False)\n x_hat_e2 = synthesis_transform_e2(y_hat_e2, args.conv_filters, args.num_filters * 2)\n\n # e3 layer\n x_e3 = img - x_hat - x_hat_e1 - x_hat_e2\n y_e3 = analysis_transform_e3(x_e3, args.conv_filters, args.num_filters * 3)\n y_hat_e3, likelihoods_e3, entropy_bottleneck_e3, _ = entropy_estimation_e3(y_e3, False)\n x_hat_e3 = synthesis_transform_e3(y_hat_e3, args.conv_filters, args.num_filters * 3)\n\n # e3 layer\n x_e4 = img - x_hat - x_hat_e1 - x_hat_e2 - x_hat_e3\n y_e4 = analysis_transform_e4(x_e4, args.conv_filters, args.num_filters * 4)\n y_hat_e4, likelihoods_e4, entropy_bottleneck_e4, string_e4 = entropy_estimation_e4(y_e4, False)\n x_hat_e4 = synthesis_transform_e4(y_hat_e4, args.conv_filters, args.num_filters * 4)\n\n x_rec = x_hat + x_hat_e1 + x_hat_e2 + x_hat_e3 + x_hat_e4\n\n # Total number of bits divided by number of pixels.\n with tf.name_scope('rate'):\n eval_bpp = tf.reduce_sum(tf.log(likelihoods)) / (-tf.log(2.0) * num_pixels)\n eval_bpp_e1 = tf.reduce_sum(tf.log(likelihoods_e1)) / (-tf.log(2.0) * num_pixels)\n eval_bpp_e2 = tf.reduce_sum(tf.log(likelihoods_e2)) / (-tf.log(2.0) * num_pixels)\n eval_bpp_e3 = tf.reduce_sum(tf.log(likelihoods_e3)) / (-tf.log(2.0) * num_pixels)\n eval_bpp_e4 = tf.reduce_sum(tf.log(likelihoods_e4)) / (-tf.log(2.0) * num_pixels)\n\n # Mean squared error across pixels.\n x_hat = tf.clip_by_value(x_hat, 0, 1)\n\n comp_vars_base = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"pre256\")\n comp_vars_e1 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"e1_pre256\")\n comp_vars_e2 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"e2_pre256\")\n comp_vars_e3 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"e3_pre256\")\n prev_layer_vars = comp_vars_base + comp_vars_e1 + comp_vars_e2 + comp_vars_e3\n comp_vars_e4 = [var for var in tf.global_variables() if var not in prev_layer_vars]\n print(comp_vars_e4)\n\n test_image, test_image_padded, bdry = kodak()\n rec_image = np.zeros(np.shape(test_image))\n rec_image_e1_plus_base = np.zeros(np.shape(test_image))\n rec_image_e2_plus_e1_plus_base = np.zeros(np.shape(test_image))\n rec_image_e3_e2_e1_base = np.zeros(np.shape(test_image))\n rec_image_e4_e3_e2_e1_base = np.zeros(np.shape(test_image))\n avg_psnr = []\n avg_psnr_e1_plus_base = []\n avg_psnr_e2_plus_e1_plus_base = []\n avg_psnr_e3_e2_e1_base = []\n avg_psnr_rec = [] # e2e psnr\n avg_entropy_e4 = []\n avg_ms_ssims = []\n ''' eval base layer '''\n with tf.Session() as sess:\n latest_base = tf.train.latest_checkpoint(checkpoint_dir=args.base_checkpoint_dir)\n latest_e1 = tf.train.latest_checkpoint(checkpoint_dir=args.e1_checkpoint_dir)\n latest_e2 = tf.train.latest_checkpoint(checkpoint_dir=args.e2_checkpoint_dir)\n latest_e3 = tf.train.latest_checkpoint(checkpoint_dir=args.e3_checkpoint_dir)\n latest_e4 = tf.train.latest_checkpoint(checkpoint_dir=args.e4_checkpoint_dir)\n tf.train.Saver(comp_vars_base).restore(sess, save_path=latest_base)\n tf.train.Saver(comp_vars_e1).restore(sess, save_path=latest_e1)\n tf.train.Saver(comp_vars_e2).restore(sess, save_path=latest_e2)\n tf.train.Saver(comp_vars_e3).restore(sess, save_path=latest_e3)\n tf.train.Saver(comp_vars_e4).restore(sess, save_path=latest_e4)\n\n for q in range(len(test_image)):\n cur_data = np.reshape(test_image[q, :, :, :], [1, wid, hgt, channels])\n _, psnr_base, psnr_e1_plus_base, _, _, x_hat_, x_hat_e1_plus_base_, _, _ = eval_test_image_e1(sess,\n cur_data, test_image, img, y_base,x_hat, x_rec_e1, x_hat_e1, y_hat_e1, eval_bpp, string_e4, q)\n\n _, psnr_e2_plus_e1_plus_base, _, x_hat_e2_plus_e1_plus_base_, _ = eval_test_image_e2(sess,\n x_rec - x_hat_e2 - x_hat_e3, cur_data, test_image, img, y_e2, x_hat_e2, x_hat_e1_plus_base_, string_e4, q)\n\n _, psnr_e3_e2_e1_base, _, x_hat_e3_e2_e1_base_, _ = eval_test_image_e3(sess,\n x_rec - x_hat_e3, cur_data, test_image, img, y_e3, x_hat_e3, x_hat_e2_plus_e1_plus_base_, string_e4, q)\n\n psnr_rec, psnr_e4_e3_e2_e1_base, bpp_e4, x_hat_e4_e3_e2_e1_base_, msssim_rec = eval_test_image_e4(sess,\n x_rec, cur_data, test_image, img, y_e4, x_hat_e4, x_hat_e3_e2_e1_base_, string_e4, q)\n\n avg_psnr.append(psnr_base)\n avg_psnr_e1_plus_base.append(psnr_e1_plus_base)\n avg_psnr_e2_plus_e1_plus_base.append(psnr_e2_plus_e1_plus_base)\n avg_psnr_e3_e2_e1_base.append(psnr_e3_e2_e1_base)\n avg_psnr_rec.append(psnr_rec)\n avg_entropy_e4.append(bpp_e4)\n avg_ms_ssims.append(msssim_rec)\n rec_image[q,:,:,:] = x_hat_\n rec_image_e1_plus_base[q,:,:,:] = x_hat_e1_plus_base_\n rec_image_e2_plus_e1_plus_base[q,:,:,:] = x_hat_e2_plus_e1_plus_base_\n rec_image_e3_e2_e1_base[q,:,:,:] = x_hat_e3_e2_e1_base_\n rec_image_e4_e3_e2_e1_base[q,:,:,:] = x_hat_e4_e3_e2_e1_base_\n\n if (q % 8) == 0:\n print(\"Progress %d/%d.\" % (q, len(test_image)))\n\n base_avg_psnr = np.mean(avg_psnr)\n psnr_e1_plus_base = np.mean(avg_psnr_e1_plus_base)\n psnr_e2_plus_e1_plus_base = np.mean(avg_psnr_e2_plus_e1_plus_base)\n psnr_e3_e2_e1_base = np.mean(avg_psnr_e3_e2_e1_base)\n rec_psnr = np.mean(avg_psnr_rec)\n e4_avg_entropy = np.mean(avg_entropy_e4)\n avg_msssim = np.mean(avg_ms_ssims)\n if os.path.exists(\"./color/base.png\"):\n os.remove(\"./color/base.png\")\n if os.path.exists(\"./color/base_e1.png\"):\n os.remove(\"./color/base_e1.png\")\n if os.path.exists(\"./color/base_e1_e2.png\"):\n os.remove(\"./color/base_e1_e2.png\")\n if os.path.exists(\"./color/base_e1_e2_e3.png\"):\n os.remove(\"./color/base_e1_e2_e3.png\")\n mpimg.imsave(r\"./color/base.png\", np.squeeze(rec_image[0,:,:,:]))\n mpimg.imsave(r\"./color/base_e1.png\", np.squeeze(rec_image_e1_plus_base[0,:,:,:]))\n mpimg.imsave(r\"./color/base_e1_e2.png\", np.squeeze(rec_image_e2_plus_e1_plus_base[0,:,:,:]))\n mpimg.imsave(r\"./color/base_e1_e2_e3.png\", np.squeeze(rec_image_e3_e2_e1_base[0,:,:,:]))\n print('End-to-End PSNR: %.4f, Base PSNR: %.4f, E1+base PSNR: %.4f, E2+E1+base: %.4f, E3+E2+E1+base: %.4f, E4 bpp: %.4f. ' %\\\n (rec_psnr, base_avg_psnr, psnr_e1_plus_base, psnr_e2_plus_e1_plus_base, psnr_e3_e2_e1_base, e4_avg_entropy))\n print('End-to-End MS-SSIM: %.4f ' % (avg_msssim))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n \"--conv_filters\", type=int, default=48,\n help=\"Number of filters conv layer.\")\n parser.add_argument(\n \"--num_filters\", type=int, default=48,\n help=\"Number of filters bottleneck layer.\")\n parser.add_argument(\n \"--e4_checkpoint_dir\", default=\"color/model48-48-96-144-192-lambda3000-1000-300-100-30\",\n help=\"Directory where to save/load e4 layer model checkpoints.\")\n parser.add_argument(\n \"--e3_checkpoint_dir\", default=\"color/model48-48-96-144-lambda3000-1000-300-100\",\n help=\"Directory where to save/load e3 layer model checkpoints.\")\n parser.add_argument(\n \"--e2_checkpoint_dir\", default=\"color/model48-48-96-lambda3000-1000-300\",\n help=\"Directory where to save/load e2 layer model checkpoints.\")\n parser.add_argument(\n \"--e1_checkpoint_dir\", default=\"color/model48-48-lambda3000-1000\",\n help=\"Directory where to save/load e1 layer model checkpoints.\")\n parser.add_argument(\n \"--base_checkpoint_dir\", default=\"color/model48-lambda3000\",\n help=\"Directory where to save/load base layer model checkpoints.\")\n\n args = parser.parse_args()\n\n compress()\n","sub_path":"src/test_e4.py","file_name":"test_e4.py","file_ext":"py","file_size_in_byte":8695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"233595813","text":"import uuid\n\nfrom Firefly import aliases, logging\nfrom Firefly.automation.triggers import Triggers\nfrom Firefly.const import COMMAND_NOTIFY, SERVICE_NOTIFICATION, TYPE_AUTOMATION, API_ALEXA_VIEW, API_FIREBASE_VIEW, API_INFO_REQUEST\nfrom Firefly.helpers.action import Action\nfrom Firefly.helpers.conditions import Conditions\nfrom Firefly.helpers.events import Command, Event, Request\nfrom Firefly.helpers.automation.automation_interface import AutomationInterface\n\n# TODO(zpriddy): These should be in const file\nLABEL_ACTIONS = 'actions'\nLABEL_CONDITIONS = 'conditions'\nLABEL_DELAYS = 'delays'\nLABEL_DEVICES = 'devices'\nLABEL_MESSAGES = 'messages'\nLABEL_TRIGGERS = 'triggers'\nLABEL_TRIGGER_ACTION = 'trigger_actions'\n\nINTERFACE_LABELS = [LABEL_ACTIONS, LABEL_CONDITIONS, LABEL_DELAYS, LABEL_DEVICES, LABEL_MESSAGES, LABEL_TRIGGERS, LABEL_TRIGGER_ACTION]\n\nfrom typing import Callable, Any\n\n\nclass Automation(object):\n def __init__(self, firefly, package: str, event_handler: Callable, metadata: dict = {}, interface: dict = {}, **kwargs):\n self.actions = {}\n self.command_map = {}\n self.conditions = {}\n self.delays = {}\n self.devices = {}\n self.event_handler = event_handler\n self.firefly = firefly\n self.interface = interface\n self.messages = {}\n self.metadata = metadata\n self.package = package\n self.triggers = {}\n self.trigger_actions = {}\n\n # TODO(zpriddy): Should should be a shared function in a lib somewhere.\n # Alias and id functions\n ff_id = kwargs.get('ff_id')\n alias = kwargs.get('alias')\n # If alias given but no ID look at config files for ID.\n if not ff_id and alias:\n if aliases.get_device_id(alias):\n ff_id = aliases.get_device_id(alias)\n\n elif ff_id and not alias:\n if aliases.get_alias(ff_id):\n alias = aliases.get_alias(ff_id)\n\n # If no ff_id ID given -> generate random ID.\n if not ff_id:\n ff_id = str(uuid.uuid4())\n\n self.id = ff_id\n self.alias = alias if alias else ff_id\n\n\n self.new_interface = AutomationInterface(firefly, self.id, self.interface)\n self.new_interface.build_interface()\n\n #self.build_interfaces()\n\n def event(self, event: Event, **kwargs):\n logging.info('[AUTOMATION] %s - Receiving event: %s' % (self.id, event))\n # Check each triggerList in triggers.\n for trigger_index, trigger in self.new_interface.triggers.items():\n if trigger.check_triggers(event):\n # Check if there are conditions with the same index, if so check them.\n if self.new_interface.conditions.get(trigger_index):\n if not self.new_interface.conditions.get(trigger_index).check_conditions(self.firefly):\n logging.info('[AUTOMATION] failed condition checks.')\n continue\n # Call the event handler passing in the trigger_index and return.\n logging.info('[AUTOMATION] no conditions. executing event handler.')\n return self.event_handler(event, trigger_index, **kwargs)\n\n def request(self, request: Request) -> Any:\n \"\"\"Function to request data from the ff_id.\n\n The returned data can be in any format. Common formats should be:\n str, int, dict\n\n Args:\n request (Request): Request object\n\n Returns:\n Requested Data\n\n \"\"\"\n logging.debug('[AUTOMATION] %s: Got Request %s' % (self.id, request))\n if request.request == API_INFO_REQUEST:\n return self.get_api_info()\n if request.request == API_FIREBASE_VIEW:\n return self.get_firebase_views()\n if request.request == API_ALEXA_VIEW:\n return self.get_alexa_view()\n return None\n\n def get_api_info(self, **kwargs):\n return {}\n\n def get_firebase_views(self, **kwargs):\n return {}\n\n def get_alexa_view(self, **kwargs):\n logging.info('[AUTOMATION] no alexa view')\n return {}\n\n def export(self, **kwargs):\n \"\"\"\n Export ff_id config with options current values to a dictionary.\n\n Args:\n\n Returns:\n (dict): A dict of the ff_id config.\n \"\"\"\n export_data = {\n 'alias': self.alias, # 'commands': self.command_map.keys(),\n 'ff_id': self.id,\n 'interface': self.new_interface.export(),\n 'metadata': self.metadata,\n 'package': self.package,\n 'type': self.type\n }\n return export_data\n\n def command(self, command, **kwargs):\n \"\"\"\n Function that is called to send a command to a ff_id.\n\n Commands can be used to reset times or other items if the automation needs it.\n Args:\n command (Command): The command to be sent in a Command object\n\n Returns:\n (bool): Command successful.\n \"\"\"\n logging.debug('%s: Got Command: %s' % (self.id, command.command))\n if command.command in self.command_map.keys():\n try:\n self.command_map[command.command](**command.args)\n return True\n except:\n return False\n return False\n\n def build_interfaces(self, **kwargs):\n \"\"\"\n builds the interfaces (actions, conditions, delays, triggers) using the metadata and config information.\n Args:\n **kwargs:\n\n Returns:\n\n \"\"\"\n meta_interfaces = self.metadata.get('interface')\n if not meta_interfaces:\n return\n for label in INTERFACE_LABELS:\n interface_data = meta_interfaces.get(label)\n if not interface_data:\n continue\n if label == LABEL_ACTIONS:\n self.build_actions_interface(interface_data)\n if label == LABEL_TRIGGERS:\n self.build_triggers_interface(interface_data)\n if label == LABEL_CONDITIONS:\n self.build_conditions_interface(interface_data)\n if label == LABEL_DELAYS:\n self.build_delays_interface(interface_data)\n if label == LABEL_DEVICES:\n self.build_devices_interface(interface_data)\n if label == LABEL_MESSAGES:\n self.build_messages_interface(interface_data)\n if label == LABEL_TRIGGER_ACTION:\n self.build_trigger_actions_interface(interface_data)\n\n def build_actions_interface(self, interface_data: dict, **kwargs):\n for action_index in interface_data.keys():\n self.actions[action_index] = []\n # TODO(zpriddy): Do we want to keep the add_action function?\n if not self.interface.get(LABEL_ACTIONS):\n continue\n for action in self.interface.get(LABEL_ACTIONS).get(action_index):\n self.actions[action_index].append(Action(**action))\n\n def build_triggers_interface(self, interface_data: dict, **kwargs):\n for trigger_index in interface_data.keys():\n if not self.interface.get(LABEL_TRIGGERS):\n continue\n self.triggers[trigger_index] = Triggers(self.firefly, self.id)\n self.triggers[trigger_index].import_triggers(self.interface.get(LABEL_TRIGGERS).get(trigger_index))\n\n def build_trigger_actions_interface(self, interface_data: dict, **kwargs):\n for trigger_action_index in interface_data.keys():\n if not self.interface.get(LABEL_TRIGGER_ACTION):\n continue\n self.trigger_actions[trigger_action_index] = self.interface.get(LABEL_TRIGGER_ACTION).get(trigger_action_index)\n\n def build_conditions_interface(self, interface_data: dict, **kwargs):\n for condition_index in interface_data.keys():\n self.conditions[condition_index] = None\n if not self.interface.get(LABEL_CONDITIONS):\n continue\n if not self.interface.get(LABEL_CONDITIONS).get(condition_index):\n continue\n self.conditions[condition_index] = Conditions(**self.interface.get(LABEL_CONDITIONS).get(condition_index))\n\n def build_delays_interface(self, interface_data: dict, **kwargs):\n for delay_index in interface_data.keys():\n if not self.interface.get(LABEL_DELAYS):\n continue\n self.delays[delay_index] = self.interface.get(LABEL_DELAYS).get(delay_index)\n\n def build_devices_interface(self, interface_data: dict, **kwargs):\n for device_index in interface_data.keys():\n if not self.interface.get(LABEL_DEVICES):\n continue\n self.devices[device_index] = self.interface.get(LABEL_DEVICES).get(device_index)\n\n def build_messages_interface(self, interface_data: dict, **kwargs):\n for message_index in interface_data.keys():\n if not self.interface.get(LABEL_MESSAGES):\n continue\n self.messages[message_index] = self.interface.get(LABEL_MESSAGES).get(message_index)\n\n def export_interface(self, **kwargs):\n interface = {}\n\n interface[LABEL_TRIGGERS] = {}\n for trigger_index, trigger in self.triggers.items():\n if trigger is None:\n continue\n interface[LABEL_TRIGGERS][trigger_index] = trigger.export()\n\n interface[LABEL_ACTIONS] = {}\n for action_index, action in self.actions.items():\n interface[LABEL_ACTIONS][action_index] = [a.export() for a in action]\n\n interface[LABEL_CONDITIONS] = {}\n for condition_index, condition in self.conditions.items():\n if condition is None:\n continue\n interface[LABEL_CONDITIONS][condition_index] = condition.export()\n\n interface[LABEL_MESSAGES] = {}\n for message_index, message in self.messages.items():\n if message is None:\n continue\n interface[LABEL_MESSAGES][message_index] = message\n\n interface[LABEL_DELAYS] = {}\n for delay_index, delay in self.delays.items():\n if delay is None:\n continue\n interface[LABEL_DELAYS][delay_index] = delay\n\n interface[LABEL_DEVICES] = {}\n for device_index, device in self.devices.items():\n if device is None:\n continue\n interface[LABEL_DEVICES][device_index] = device\n\n interface[LABEL_TRIGGER_ACTION] = {}\n for trigger_action_index, trigger_action in self.trigger_actions.items():\n if trigger_action is None:\n continue\n interface[LABEL_TRIGGER_ACTION][trigger_action_index] = trigger_action\n\n return interface\n\n def add_command(self, command: str, function: Callable) -> None:\n \"\"\"\n Adds a command to the list of supported ff_id commands.\n\n Args:\n command (str): The string of the command\n function (Callable): The function to be executed.\n \"\"\"\n self.command_map[command] = function\n\n def execute_actions(self, action_index: str, **kwargs) -> bool:\n if not self.new_interface.actions.get(action_index):\n return False\n for action in self.new_interface.actions.get(action_index):\n action.execute_action(self.firefly)\n return True\n\n def send_messages(self, message_index: str, **kwargs) -> bool:\n if not self.new_interface.messages.get(message_index):\n return False\n notify = Command(SERVICE_NOTIFICATION, self.id, COMMAND_NOTIFY, message=self.new_interface.messages.get(message_index))\n self.firefly.send_command(notify)\n return True\n\n def event_handler(self, event: Event = None, trigger_index=\"\", **kwargs):\n logging.error('EVENT HANDLER NOT CREATED')\n\n @property\n def type(self):\n return TYPE_AUTOMATION\n","sub_path":"Firefly/helpers/automation/automation.py","file_name":"automation.py","file_ext":"py","file_size_in_byte":10789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"145575311","text":"\"\"\"Python client for Ziggo Next.\"\"\"\nimport json\nfrom logging import Logger\nimport random\nimport time\nimport sys, traceback\n\nimport requests\nfrom .models import ZiggoNextSession, ZiggoChannel\nfrom .ziggonextbox import ZiggoNextBox\nfrom .exceptions import ZiggoNextConnectionError, ZiggoNextAuthenticationError\n\nfrom .const import (\n BOX_PLAY_STATE_BUFFER,\n BOX_PLAY_STATE_CHANNEL,\n BOX_PLAY_STATE_DVR,\n BOX_PLAY_STATE_REPLAY,\n ONLINE_RUNNING,\n ONLINE_STANDBY,\n UNKNOWN,\n MEDIA_KEY_PLAY_PAUSE,\n MEDIA_KEY_CHANNEL_DOWN,\n MEDIA_KEY_CHANNEL_UP,\n MEDIA_KEY_POWER,\n COUNTRY_URLS_HTTP,\n COUNTRY_URLS_PERSONALIZATION_FORMAT\n)\n\nDEFAULT_PORT = 443\n\ndef _makeId(stringLength=10):\n letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n return \"\".join(random.choice(letters) for i in range(stringLength))\n\n\nclass ZiggoNext:\n \"\"\"Main class for handling connections with Ziggo Next Settop boxes.\"\"\"\n logger: Logger\n session: ZiggoNextSession\n def __init__(self, username: str, password: str, country_code: str = \"nl\") -> None:\n \"\"\"Initialize connection with Ziggo Next\"\"\"\n self.username = username\n self.password = password\n self.token = None\n self.session = None\n self.logger = None\n self.settop_boxes = {}\n self.channels = {}\n self._country_code = country_code\n\n def get_session(self):\n \"\"\"Get Ziggo Next Session information\"\"\"\n payload = {\"username\": self.username, \"password\": self.password}\n try:\n response = requests.post(self._api_url_session, json=payload)\n except (Exception):\n raise ZiggoNextConnectionError(\"Unknown connection failure\")\n\n if not response.ok:\n status = response.json()\n self.logger.debug(status)\n if status[0]['code'] == 'invalidCredentials':\n raise ZiggoNextAuthenticationError(\"Invalid credentials\")\n raise ZiggoNextConnectionError(\"Connection failed: \" + status)\n else:\n session = response.json()\n self.logger.debug(session)\n self.session = ZiggoNextSession(\n session[\"customer\"][\"householdId\"], session[\"oespToken\"]\n )\n\n def get_session_and_token(self):\n \"\"\"Get session and token from Ziggo Next\"\"\"\n self.get_session()\n self._get_token()\n\n def _register_settop_boxes(self):\n \"\"\"Get settopxes\"\"\"\n jsonResult = self._do_api_call(self.session, self._api_url_settop_boxes)\n for box in jsonResult:\n if not box[\"platformType\"] == \"EOS\":\n continue\n box_id = box[\"deviceId\"]\n self.settop_boxes[box_id] = ZiggoNextBox(box_id, box[\"settings\"][\"deviceFriendlyName\"], self.session.householdId, self.token, self._country_code, self.logger)\n\n\n\n def _do_api_call(self, session, url):\n \"\"\"Executes api call and returns json object\"\"\"\n headers = {\n \"X-OESP-Token\": session.oespToken,\n \"X-OESP-Username\": self.username,\n }\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return response.json()\n else:\n raise ZiggoNextConnectionError(\"API call failed: \" + str(response.status_code))\n \n def _get_token(self):\n \"\"\"Get token from Ziggo Next\"\"\"\n jsonResult = self._do_api_call(self.session, self._api_url_token)\n self.token = jsonResult[\"token\"]\n self.logger.debug(\"Fetched a token: %s\", jsonResult)\n \n def initialize(self, logger, enableMqttLogging: bool = True):\n \"\"\"Get token and start mqtt client for receiving data from Ziggo Next\"\"\"\n baseUrl = COUNTRY_URLS_HTTP[self._country_code]\n self._api_url_session = baseUrl + \"/session\"\n self._api_url_token = baseUrl + \"/tokens/jwt\"\n self._api_url_channels = baseUrl + \"/channels\"\n self.logger = logger\n self.get_session_and_token()\n self._api_url_settop_boxes = COUNTRY_URLS_PERSONALIZATION_FORMAT[self._country_code].format(household_id=self.session.householdId)\n self._register_settop_boxes()\n self.load_channels()\n\n def _send_key_to_box(self, box_id: str, key: str):\n self.settop_boxes[box_id].send_key_to_box(key)\n\n def select_source(self, source, box_id):\n \"\"\"Changes te channel from the settopbox\"\"\"\n channel = [src for src in self.channels.values() if src.title == source][0]\n self.settop_boxes[box_id].set_channel(channel.serviceId)\n\n def pause(self, box_id):\n \"\"\"Pauses the given settopbox\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_RUNNING and not box.info.paused:\n self._send_key_to_box(box_id, MEDIA_KEY_PLAY_PAUSE)\n\n def play(self, box_id):\n \"\"\"Resumes the settopbox\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_RUNNING and box.info.paused:\n self._send_key_to_box(box_id, MEDIA_KEY_PLAY_PAUSE)\n\n def next_channel(self, box_id):\n \"\"\"Select the next channel for given settop box.\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_RUNNING:\n self._send_key_to_box(box_id, MEDIA_KEY_CHANNEL_UP)\n\n def previous_channel(self, box_id):\n \"\"\"Select the previous channel for given settop box.\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_RUNNING:\n self._send_key_to_box(box_id, MEDIA_KEY_CHANNEL_DOWN)\n\n def turn_on(self, box_id):\n \"\"\"Turn the settop box on.\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_STANDBY:\n self._send_key_to_box(box_id, MEDIA_KEY_POWER)\n\n def turn_off(self, box_id):\n \"\"\"Turn the settop box off.\"\"\"\n box = self.settop_boxes[box_id]\n if box.state == ONLINE_RUNNING:\n self._send_key_to_box(box_id, MEDIA_KEY_POWER)\n box.turn_off()\n\n def is_available(self, box_id):\n box = self.settop_boxes[box_id]\n state = box.state\n return (state == ONLINE_RUNNING or state == ONLINE_STANDBY)\n\n def load_channels(self):\n \"\"\"Refresh channels list for now-playing data.\"\"\"\n response = requests.get(self._api_url_channels)\n if response.status_code == 200:\n content = response.json()\n\n for channel in content[\"channels\"]:\n station = channel[\"stationSchedules\"][0][\"station\"]\n serviceId = station[\"serviceId\"]\n streamImage = None\n channelImage = None\n for image in station[\"images\"]:\n if image[\"assetType\"] == \"imageStream\":\n streamImage = image[\"url\"]\n if image[\"assetType\"] == \"station-logo-small\":\n channelImage = image[\"url\"]\n\n self.channels[serviceId] = ZiggoChannel(\n serviceId,\n channel[\"title\"],\n streamImage,\n channelImage,\n channel[\"channelNumber\"],\n )\n self.channels[\"NL_000073_019506\"] = ZiggoChannel(\n \"NL_000073_019506\",\n \"Netflix\",\n None,\n None,\n \"150\"\n )\n\n self.channels[\"NL_000074_019507\"] = ZiggoChannel(\n \"NL_000074_019507\",\n \"Videoland\",\n None,\n None,\n \"151\"\n )\n self.logger.debug(\"Updated channels.\")\n for box in self.settop_boxes.values():\n box.channels = self.channels\n else:\n self.logger.error(\"Can't retrieve channels...\")\n","sub_path":"ziggonext/ziggonext.py","file_name":"ziggonext.py","file_ext":"py","file_size_in_byte":7785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"402719272","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\nimport tensorflow as tf\nimport numpy as np\nfrom dataset import load_movielens1m_mapped\n\n\ndef random_weights(R, C):\n return tf.random_normal(shape=(R, C), mean=0,\n stddev=0.001, dtype=tf.float32)\n\n\nif __name__ == '__main__':\n np.random.seed(2634)\n tf.set_random_seed(1237)\n M, N, train_data, valid_data, test_data, nla, nlb, nlc, nld = \\\n load_movielens1m_mapped('data/ml-1m.zip')\n\n # set configurations and hyper parameters\n N_train = np.shape(train_data)[0]\n N_valid = np.shape(valid_data)[0]\n N_test = np.shape(test_data)[0]\n D = 30\n epoches = 100\n batch_size = 100000\n valid_batch_size = 100000\n test_batch_size = 100000\n lambda_U = 10\n lambda_V = 10\n learning_rate = 0.005\n save_freq = 50\n valid_freq = 10\n test_freq = 10\n iters = (N_train + batch_size - 1) // batch_size\n valid_iters = (N_valid + valid_batch_size - 1) // valid_batch_size\n test_iters = (N_test + test_batch_size - 1) // test_batch_size\n result_path = 'tmp/pmf_map/'\n\n # Find non-trained files or peoples\n trained_movie = [False] * M\n trained_user = [False] * N\n for i in range(N_train):\n trained_user[train_data[i, 0]] = True\n trained_movie[train_data[i, 1]] = True\n us = 0\n vs = 0\n for i in range(N):\n us += trained_user[i]\n for j in range(M):\n vs += trained_movie[j]\n print('Untrained users = %d, untrained movied = %d' % (N - us, M - vs))\n trained_movie = tf.constant(trained_movie, dtype=tf.bool)\n trained_user = tf.constant(trained_user, dtype=tf.bool)\n\n # Build the computation graph\n is_training = tf.placeholder(tf.bool, shape=[], name='is_training')\n learning_rate_ph = tf.placeholder(tf.float32, shape=[], name='lr')\n optimizer = tf.train.AdamOptimizer(learning_rate_ph, beta1=0.5)\n\n U = tf.Variable(random_weights(N, D)) # (N, D)\n V = tf.Variable(random_weights(M, D)) # (M, D)\n U_bias = tf.Variable(random_weights(N, 1))\n V_bias = tf.Variable(random_weights(M, 1))\n global_bias = tf.Variable(random_weights(1, 1))\n\n pair_U = tf.placeholder(tf.int32, shape=[None, ], name='s_U')\n pair_V = tf.placeholder(tf.int32, shape=[None, ], name='s_V')\n true_rating = tf.placeholder(tf.float32, shape=[None, ],\n name='true_rating')\n num_films = tf.cast(tf.shape(pair_U)[0], tf.float32)\n\n optimized_U = tf.gather(U, pair_U) # (batch_size, D)\n optimized_V = tf.gather(V, pair_V) # (batch_size, D)\n optimized_bias = global_bias + tf.gather(U_bias, pair_U) + \\\n tf.gather(V_bias, pair_V)\n mf_pred_rating = tf.reduce_sum(optimized_U * optimized_V + optimized_bias, axis=1)\n constant_rating = tf.convert_to_tensor([3.0], dtype=tf.float32)\n constant_rating = tf.tile(constant_rating, tf.shape(mf_pred_rating))\n\n exists_u = tf.gather(trained_user, pair_U)\n exists_v = tf.gather(trained_movie, pair_V)\n exists_uv = tf.logical_and(exists_u, exists_v)\n pred_rating = tf.where(exists_uv, mf_pred_rating, constant_rating)\n\n error = pred_rating - true_rating\n old_error = mf_pred_rating - true_rating\n rmse = tf.sqrt(tf.reduce_mean(error * error))\n old_rmse = tf.sqrt(tf.reduce_mean(old_error * old_error))\n cost = 0.5 * tf.reduce_sum(error * error) * \\\n ((N_train + 0.0) / num_films) + \\\n lambda_U * 0.5 * tf.reduce_sum(U * U, axis=[0, 1]) + \\\n lambda_V * 0.5 * tf.reduce_sum(V * V, axis=[0, 1])\n\n grads = optimizer.compute_gradients(cost)\n infer = optimizer.apply_gradients(grads)\n\n params = tf.trainable_variables()\n for i in params:\n print(i.name, i.get_shape())\n\n saver = tf.train.Saver(max_to_keep=10)\n\n # Run the inference\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n # Restore from the latest checkpoint\n ckpt_file = tf.train.latest_checkpoint(result_path)\n begin_epoch = 1\n if ckpt_file is not None:\n print('Restoring model from {}...'.format(ckpt_file))\n begin_epoch = int(ckpt_file.split('.')[-2]) + 1\n saver.restore(sess, ckpt_file)\n\n for epoch in range(begin_epoch, epoches + 1):\n time_epoch = -time.time()\n res = []\n np.random.shuffle(train_data)\n for t in range(iters):\n ed_pos = min((t + 1) * batch_size, N_train + 1)\n su = train_data[t * batch_size:ed_pos, 0]\n sv = train_data[t * batch_size:ed_pos, 1]\n tr = train_data[t * batch_size:ed_pos, 2]\n _, re = sess.run([infer, rmse, ],\n feed_dict={pair_U: su,\n pair_V: sv,\n true_rating: tr,\n learning_rate_ph: learning_rate})\n res.append(re)\n time_epoch += time.time()\n print('Epoch {} ({:.1f}s): train rmse = {}'.format(\n epoch, time_epoch, np.mean(res)))\n\n if epoch % valid_freq == 0:\n valid_rmse = []\n valid_rrmse = []\n time_valid = -time.time()\n for t in range(valid_iters):\n ed_pos = min((t + 1) * valid_batch_size, N_valid + 1)\n su = valid_data[t * valid_batch_size:ed_pos, 0]\n sv = valid_data[t * valid_batch_size:ed_pos, 1]\n tr = valid_data[t * valid_batch_size:ed_pos, 2]\n re, ore = sess.run([rmse, old_rmse],\n feed_dict={pair_U: su, pair_V: sv,\n true_rating: tr})\n valid_rmse.append(re)\n valid_rrmse.append(ore)\n time_valid += time.time()\n print('>>> VALIDATION ({:.1f}s)'.format(time_valid))\n print('>> Validation rmse = {}, uncorrected rmse = {}'.\n format(np.mean(valid_rmse), np.mean(valid_rrmse)))\n\n if epoch % test_freq == 0:\n test_rmse = []\n test_rrmse = []\n time_test = -time.time()\n for t in range(test_iters):\n ed_pos = min((t + 1) * test_batch_size, N_test + 1)\n su = test_data[t * test_batch_size:ed_pos, 0]\n sv = test_data[t * test_batch_size:ed_pos, 1]\n tr = test_data[t * test_batch_size:ed_pos, 2]\n re, ore = sess.run([rmse, old_rmse],\n feed_dict={pair_U: su, pair_V: sv,\n true_rating: tr})\n test_rmse.append(re)\n test_rrmse.append(ore)\n time_test += time.time()\n print('>>> TEST ({:.1f}s)'.format(time_test))\n print('>> Test rmse = {}, uncorrected rmse = {}'.\n format(np.mean(test_rmse), np.mean(test_rrmse)))\n\n if epoch % save_freq == 0:\n save_path = os.path.join(result_path,\n \"pmf_map.epoch.{}.ckpt\".format(epoch))\n if not os.path.exists(os.path.dirname(save_path)):\n os.makedirs(os.path.dirname(save_path))\n saver.save(sess, save_path)\n","sub_path":"Collaborative Filtering/BiasMF.py","file_name":"BiasMF.py","file_ext":"py","file_size_in_byte":7467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110417058","text":"import gevent.monkey; gevent.monkey.patch_all()\nfrom gevent.pywsgi import WSGIServer\nfrom geventwebsocket.handler import WebSocketHandler\n\nimport logging\nimport json\nimport redis\nimport docker\nimport base64\nimport time\nimport os\nimport requests\n\nfrom urllib.parse import urlsplit, urlunsplit\n\nfrom bottle import debug, default_app, request, jinja2_view, TEMPLATE_PATH, static_file\nfrom bottle import response\nfrom scalarbook import ScalarBook\nfrom autobrowser import AutoBrowser, AutoTab\n\n\n# ============================================================================\nclass Main(object):\n GSESH = 'ssesh:{0}'\n\n BLIST = 'ssesh:{0}:br'\n\n USER_IMAGE = 'dynpreserve/user-scalar:{0}'\n USER_IMAGE_PREFIX = 'dynpreserve/user-scalar'\n\n SCALAR_BASE_IMAGE = 'dynpreserve/scalar'\n PYWB_IMAGE = 'dynpreserve/pywb'\n\n START_URL_LABEL = 'dyn.start_url'\n\n VOL_PREFIX = 'dynpreserve-'\n\n NETWORK_NAME = 'autoscalar_default'\n\n REDIS_URL = 'redis://redis/2'\n\n BROWSER_IMAGE = 'chrome:60'\n\n NUM_BROWSERS = 4\n\n AUTH_CODE = os.environ.get('AUTH_CODE', '')\n\n def __init__(self):\n debug(True)\n TEMPLATE_PATH.insert(0, './templates')\n logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.WARN)\n\n logging.getLogger('autobrowser').setLevel(logging.DEBUG)\n\n self.redis = redis.StrictRedis.from_url(self.REDIS_URL,\n decode_responses=True)\n\n self.app = default_app()\n\n self.init_routes()\n\n self.client = docker.from_env()\n\n def sesh_id(self):\n return base64.b32encode(os.urandom(10)).decode('utf-8').lower()\n\n def c_hostname(self, container):\n return container.id[:12]\n\n def launch_group(self, url=None, image_name=None, imagename_access=False):\n id = self.sesh_id()\n id_key = self.GSESH.format(id)\n print('Group Id: ' + id)\n\n # create an alias for the image name to be accessed directly\n if imagename_access:\n aliases = ['user-' + image_name]\n else:\n aliases = None\n\n if image_name:\n image_name = self.USER_IMAGE.format(image_name)\n try:\n image = self.client.images.get(image_name)\n url = image.labels[self.START_URL_LABEL]\n\n except Exception as e:\n return {'error': str(e)}\n\n else:\n if not url:\n return {'error': 'url_missing'}\n\n image_name = self.SCALAR_BASE_IMAGE\n\n self.redis.hset(id_key, 'start_url', url)\n\n volumes = {self.VOL_PREFIX + id: {'bind': '/data', 'mode': 'rw'}}\n\n scalar = self.client.containers.run(image_name,\n detach=True,\n network=self.NETWORK_NAME,\n auto_remove=True,\n volumes=volumes)\n\n self.redis.hset(id_key, 'scalar_id', scalar.id)\n\n parts = urlsplit(url)\n\n scalar_host = self.c_hostname(scalar)\n local_url = 'http://' + scalar_host + os.path.dirname(parts.path)\n\n filter_url = parts.scheme + '://' + parts.netloc\n\n media_q = 'media_q:' + id\n browser_q = 'browser_q:' + id\n\n pywb_env = {'SCALAR_HOST': 'http://' + scalar_host,\n 'PYWB_FILTER_PREFIX': filter_url,\n 'MEDIA_PREFIX': url + '/media',\n 'MEDIA_Q': media_q,\n 'BROWSER_Q': browser_q,\n 'START_URL': url + '/index',\n }\n\n pywb = self.client.containers.run(self.PYWB_IMAGE,\n detach=True,\n auto_remove=True,\n #network=self.NETWORK_NAME,\n environment=pywb_env,\n volumes=volumes)\n\n network = self.client.networks.get(self.NETWORK_NAME)\n network.connect(pywb, aliases=aliases)\n\n pywb_host = self.c_hostname(pywb)\n\n self.redis.hset(id_key, 'pywb_id', pywb_host)\n\n return {'id': id,\n 'pywb_host': pywb_host,\n 'scalar_host': scalar_host,\n 'local_url': local_url,\n 'url': url,\n 'scalar': scalar,\n 'pywb': pywb,\n 'media_q': media_q,\n 'browser_q': browser_q,\n 'browser_list_key': self.BLIST.format(id)\n }\n\n def wait_for_load(self, ws, hostname, port):\n while True:\n try:\n res = requests.get('http://{0}:{1}/'.format(hostname, port))\n break\n except Exception as e:\n print(e)\n print('Waiting for pywb init')\n time.sleep(5)\n self.send_ws(ws, {'msg': 'Waiting for data copy'})\n\n def list_images(self, single_image=None):\n try:\n images = self.client.images.list(name=self.USER_IMAGE_PREFIX)\n except Exception as e:\n return {'error': str(e)}\n\n images = [{'name': image.tags[0].rsplit(':', 1)[1],\n 'url': image.labels[self.START_URL_LABEL],\n 'size': image.attrs['Size'],\n 'created': image.attrs['Created'],\n } for image in images]\n\n if not single_image:\n image_list = sorted(images, key=lambda x: x.get('name'))\n return {'images': image_list or []}\n else:\n image_list = [image for image in images if image.get('name') == single_image]\n return {'images': image_list or [], 'single_image': True}\n\n def delete_group(self, id):\n id_key = self.GSESH.format(id)\n\n sesh_data = self.redis.hgetall(id_key)\n\n try:\n print('Removing scalar')\n self.client.containers.get(sesh_data['scalar_id']).remove(v=True, force=True)\n except Exception as e:\n print(e)\n\n try:\n print('Removing pywb')\n self.client.containers.get(sesh_data['pywb_id']).remove(v=True, force=True)\n except Exception as e:\n print(e)\n\n try:\n print('Removing volume')\n volume = self.client.volumes.get(self.VOL_PREFIX + id)\n volume.remove(force=True)\n except Exception as e:\n print(e)\n\n try:\n print('Removing browsers')\n browser_ids = self.redis.smembers(self.BLIST.format(id))\n\n for browser in browser_ids:\n res = requests.get('http://shepherd:9020/remove_browser?reqid=' + browser)\n\n except Exception as e:\n print(e)\n\n def commit_image(self, id, image_name):\n id_key = self.GSESH.format(id)\n\n scalar_id = self.redis.hget(id_key, 'scalar_id')\n if not scalar_id:\n return {'error': 'id_not_found'}\n\n url = self.redis.hget(id_key, 'start_url') or 'about:blank'\n\n conf = {'Labels': {self.START_URL_LABEL: url}}\n\n try:\n scalar = self.client.containers.get(scalar_id)\n res = scalar.exec_run(['/tmp/commit.sh'])\n\n scalar.commit(self.USER_IMAGE.format(image_name), conf=conf)\n return {'new_id': image_name}\n\n except Exception as e:\n return {'error': str(e)}\n\n def wait_for_queue(self, ws, queue, msg, total):\n last_remaining = None\n\n while True:\n remaining = self.redis.llen(queue)\n if remaining == last_remaining:\n continue\n\n last_remaining = remaining\n done = total - remaining\n self.send_ws(ws, {'msg': msg.format(done=done, total=total)})\n if remaining == 0:\n break\n\n time.sleep(1.0)\n\n def new_scalar_archive(self, ws, url, image_name='', email='', password='', authcode=''):\n if authcode != self.AUTH_CODE:\n print('invalid authcode')\n self.send_ws(ws, {'msg': 'Sorry, the passcode is not valid. This Demo is not yet publicly available. Please contact us at support@webrecorder.io to request a passcode', 'error': 'auth'})\n return\n\n self.send_ws(ws, {'msg': 'Check Scalar Url...'})\n book = ScalarBook(url, email=email, password=password)\n cmd = book.load_book_init_cmd()\n if not cmd:\n self.send_ws(ws, {'msg': 'Not a valid Scalar Url', 'error': 'not_valid'})\n return\n\n url = book.base_url\n\n cinfo = self.launch_group(url=url)\n if 'error' in cinfo:\n cinfo['msg'] = 'Error Launching'\n self.send_ws(ws, cinfo)\n return\n else:\n self.wait_for_load(ws, cinfo['pywb_host'], 8080)\n\n self.send_ws(ws, {'msg': 'Loading And Queing Media...'})\n self.queue_media(book, cinfo)\n\n self.send_ws(ws, {'msg': 'Starting Import...', 'launch_id': cinfo['id']})\n import_reqid = self.start_import(cinfo, book, cmd, url)\n\n self.send_ws(ws, {'import_reqid': import_reqid})\n\n self.wait_for_queue(ws, cinfo['media_q'], 'Crawling Media: {done} of {total}', len(book.media_urls) + len(book.external_urls))\n\n #while not book.cookies:\n # print('Waiting for cookies')\n # time.sleep(5)\n\n browser_q_len = self.redis.llen(cinfo['browser_q'])\n\n if browser_q_len > 0:\n self.send_ws(ws, {'msg': 'Starting Auto Browsers...'})\n auto_reqids = self.start_browser_auto(cinfo, book, url, self.NUM_BROWSERS)\n\n self.send_ws(ws, {'auto_reqids': auto_reqids})\n\n browser_q_len = self.redis.llen(cinfo['browser_q'])\n self.wait_for_queue(ws, cinfo['browser_q'], 'Capturing External Links: {done} of {total}', browser_q_len)\n else:\n self.send_ws(ws, {'msg': 'No Browser Auto Needed'})\n\n while book.new_url == None:\n self.send_ws(ws, {'msg': 'Waiting for Scalar Import'})\n\n time.sleep(5)\n\n if not image_name:\n image_name = url.rsplit('/', 1)[-1]\n else:\n image_name = image_name.replace(':', '')\n\n self.send_ws(ws, {'msg': 'Committing to Image {0}...'.format(image_name)})\n\n self.commit_image(cinfo['id'], image_name)\n\n self.send_ws(ws, {'msg': 'Deleting Launch Group'})\n\n self.delete_group(cinfo['id'])\n\n self.send_ws(ws, {'msg': 'Done! Image Committed: {0}'.format(image_name)})\n\n def queue_media(self, book, cinfo):\n book.load_media()\n\n for url, html_url in book.external_urls:\n # experimental optimization: queue for captureworker to examine first\n # data = json.dumps({'url': url, 'html_url': html_url, 'hops': 0})\n # self.redis.rpush(cinfo['media_q'], data)\n\n # queue directly to browser\n data = json.dumps({'url': html_url, 'hops': 0})\n print('Q', data)\n self.redis.rpush(cinfo['browser_q'], data)\n\n for url in book.media_urls:\n data = json.dumps({'url': url})\n self.redis.rpush(cinfo['media_q'], data)\n\n def send_ws(self, ws, data):\n try:\n ws.send(json.dumps(data))\n except:\n print('WS Error')\n print(json.dumps(data))\n\n def load_existing_archive(self, ws, image_name):\n self.send_ws(ws, {'msg': 'Launching Image: {0}'.format(image_name)})\n\n cinfo = self.launch_group(image_name=image_name)\n if 'error' in cinfo:\n cinfo['msg'] = 'Error Launching'\n self.send_ws(ws, cinfo)\n return\n else:\n self.wait_for_load(ws, cinfo['pywb_host'], 8080)\n\n self.send_ws(ws, {'msg': 'Starting Browser'})\n browser = self.start_browser(cinfo, prefix='/combined/bn_/',\n url=cinfo['url'])\n\n launch_url = request.urlparts.scheme + '://' + request.urlparts.netloc\n launch_url += '/replay/{0}/combined/{1}'.format(cinfo['pywb_host'], cinfo['url'])\n\n data = {'launch_id': cinfo['id'],\n 'reqid': browser.reqid,\n 'url': cinfo['url'],\n 'launch_url': launch_url,\n\n 'msg': 'Scalar Image Ready: '\n }\n\n self.send_ws(ws, data)\n while True:\n time.sleep(5)\n\n def start_import(self, cinfo, book, cmd, url):\n self.init_scalar(cinfo['scalar'], book, cmd)\n\n tab_opts = {'base_url': url,\n 'book': book,\n 'scalar_host': cinfo['scalar_host'],\n 'local_base_url': cinfo['local_url'],\n }\n\n browser = self.start_browser(cinfo, browser_q='import_q:',\n tab_class=ImportTabDriver,\n tab_opts=tab_opts)\n\n if book.email and book.password:\n browser.queue_urls([url])\n else:\n browser.queue_urls([cinfo['local_url']])\n\n return browser.reqid\n\n def start_browser_auto(self, cinfo, book, url, count):\n ids = []\n first = True\n\n tab_opts = {'use_debugger': True}\n\n if book.cookies:\n tab_opts['cookies'] = book.cookies\n\n # add base url also\n self.redis.rpush(cinfo['browser_q'], json.dumps({'url': url}))\n\n for i in range(count):\n autob = self.start_browser(cinfo, browser_q='browser_q:',\n prefix='/store/record/bn_/',\n tab_opts=tab_opts)\n\n autob.queue_urls(['about:blank'])\n #if first:\n #autob.queue_urls(book.external_urls)\n #first = False\n\n ids.append(autob.reqid)\n\n return ids\n\n def init_scalar(self, scalar, book, init_cmd):\n try:\n #time.sleep(10)\n exit_code, output = scalar.exec_run(init_cmd)\n #print('OUTPUT', output.decode('utf-8'))\n return exit_code == 0\n except Exception as e:\n print(e)\n return False\n\n def start_browser(self, cinfo, browser_q='replay_q:',\n url=None, prefix=None, tab_class=AutoTab, tab_opts=None):\n browser_q += cinfo['id']\n\n cdata = {}\n\n if prefix:\n cdata['pywb_prefix'] = prefix\n cdata['proxy_host'] = cinfo['pywb_host']\n cdata['audio_type'] = 'opus'\n\n if url:\n cdata['url'] = url\n\n browser = AutoBrowser(redis=self.redis,\n browser_image=self.BROWSER_IMAGE,\n browser_q=browser_q,\n cdata=cdata,\n tab_class=tab_class,\n tab_opts=tab_opts)\n\n self.redis.sadd(cinfo['browser_list_key'], browser.reqid)\n\n return browser\n\n def download_container(self, image_name, filename):\n image_name = self.USER_IMAGE.format(image_name)\n container = self.client.containers.create(image_name,\n command='bash',\n entrypoint='/bin/bash -c',\n auto_remove=True,\n detach=True)\n\n if filename:\n out_gen, stat = container.get_archive(filename)\n else:\n out_gen = container.export()\n\n def gen_cleanup():\n try:\n for chunk in out_gen:\n yield chunk\n\n finally:\n print('removing container')\n container.remove(force=True, v=True)\n\n return gen_cleanup()\n\n def init_routes(self):\n @self.app.get('/')\n @jinja2_view('index.html')\n def index():\n return self.list_images()\n\n @self.app.get('/view/')\n @jinja2_view('index.html')\n def single_image(image):\n return self.list_images(single_image=image)\n\n @self.app.get('/launch')\n @jinja2_view('launch.html')\n def launch():\n return self.list_images()\n\n @self.app.get('/archive/list/images')\n def list_images():\n return self.list_images()\n\n @self.app.get('/archive/delete/')\n def delete_group(id):\n self.delete_group(id)\n return {}\n\n @self.app.get('/archive/ws/new')\n def start_new_scalar():\n url = request.query.get('url')\n email = request.query.get('email', '')\n password = request.query.get('password', '')\n image_name = request.query.get('image-name', '')\n\n auth_code = request.query.get('auth-code', '')\n\n ws = request.environ['wsgi.websocket']\n self.new_scalar_archive(ws, url, image_name, email, password, auth_code)\n time.sleep(1.0)\n ws.close()\n\n @self.app.get('/archive/commit/')\n def commit_image(id):\n return self.commit_image(id, request.query.get('name'))\n\n @self.app.get('/archive/ws/launch/')\n def launch_existing(image_name):\n ws = request.environ['wsgi.websocket']\n self.load_existing_archive(ws, image_name)\n ws.close()\n\n # make instance acccessible by name directly\n @self.app.get('/archive/launch-named/')\n def launch_named_image(image_name):\n #ws = request.environ['wsgi.websocket']\n #self.send_ws(ws, {'msg': 'Launching Image: {0}'.format(image_name)})\n\n cinfo = self.launch_group(image_name=image_name, imagename_access=True)\n if 'error' in cinfo:\n print(cinfo)\n return {'error': cinfo['error']}\n\n return {'success': image_name}\n\n @self.app.get('/static/')\n def server_static(filename):\n return static_file(filename, root='./static/')\n\n @self.app.get('/archive/download_image/')\n def download_image(image_name):\n name = image_name\n image_name = self.USER_IMAGE.format(image_name)\n try:\n image = self.client.images.get(image_name)\n gen = image.save()\n\n except Exception as e:\n return {'error': str(e)}\n\n response.content_type = 'application/tar'\n response.headers['Content-Disposition'] = 'attachment; filename=\"{0}-image.tar\"'.format(name)\n return gen\n\n @self.app.get('/archive/download_container/')\n def download_cont(image_name):\n try:\n gen = self.download_container(image_name, None)\n except Exception as e:\n return {'error': str(e)}\n\n response.content_type = 'application/tar'\n response.headers['Content-Disposition'] = 'attachment; filename=\"{0}-container.tar\"'.format(image_name)\n return gen\n\n @self.app.get('/archive/download_warcs/')\n def download_warcs(image_name):\n try:\n gen = self.download_container(image_name, '/collections.warc.gz')\n except Exception as e:\n return {'error': str(e)}\n\n response.content_type = 'application/tar'\n response.headers['Content-Disposition'] = 'attachment; filename=\"{0}-webarchive-only.tar\"'.format(image_name)\n return gen\n\n\n# ============================================================================\nclass ImportTabDriver(AutoTab):\n LOGIN_REMOTE = '10'\n LOGIN_REMOTE_DONE = '20'\n\n INIT = '30'\n LOGIN = '40'\n LOGGED_IN_REDIR = '50'\n LOGGED_IN = '60'\n IMPORTING = '70'\n DONE = '80'\n\n LOGIN_REMOTE_SCRIPT = \"\"\"\ndocument.querySelector(\"form input[name='email']\").setAttribute(\"value\", \"{email}\");\ndocument.querySelector(\"form input[name='password']\").setAttribute(\"value\", \"{password}\");\ndocument.querySelector(\"form\").submit();\n\"\"\"\n\n LOGIN_SCRIPT = \"\"\"\ndocument.querySelector(\"form input[name='email']\").setAttribute(\"value\", \"scalar@example.com\");\ndocument.querySelector(\"form\").submit();\n\"\"\"\n\n IMPORT_SCRIPT = \"\"\"\nvar url = \"%s\";\nvar doc = window.frames[0].document;\ndoc.querySelector(\"#urlform input.source_url\").setAttribute(\"value\", url);\ndoc.querySelector(\"#urlform button[type=submit]\").click();\n\nvar waitLoad = setInterval(do_load, 500);\n\nwindow.scrollBy(0, 1000);\n\nfunction do_load() {\n var rdf = doc.querySelector(\"#source_rdf\");\n var submit = doc.querySelector(\"#commit button[type=submit]\");\n\n if (rdf && rdf.value && rdf.value.indexOf(\"Loading\") == 0 || submit && submit.getAttribute(\"disabled\")) {\n //console.log(\"Still Loading\");\n return;\n }\n clearInterval(waitLoad);\n\n doc.querySelector(\"#commit button[type=submit]\").click();\n\n waitLoad = setInterval(do_import, 500);\n}\n\nfunction do_import() {\n var submit = doc.querySelector(\"#commit button[type=submit]\");\n\n if (submit && submit.getAttribute(\"disabled\")) {\n return;\n }\n\n window.all_done = true;\n console.log(\"Done!\");\n clearInterval(waitLoad);\n\n var start_url = new URL(url);\n start_url.hostname = window.location.hostname;\n window.location.href = start_url.href;\n}\n\n\n\n\"\"\"\n\n IMPORT_TAB_URL = '/system/dashboard?book_id=1&zone=transfer#tabs-transfer'\n\n def __init__(self, *args, **kwargs):\n self.base_url = kwargs.get('base_url')\n self.book = kwargs.get('book')\n self.scalar_host = kwargs.get('scalar_host')\n self.local_url = kwargs.get('local_base_url')\n\n if self.book.email and self.book.password:\n self.stage = self.LOGIN_REMOTE\n else:\n self.stage = self.INIT\n\n super(ImportTabDriver, self).__init__(*args, **kwargs)\n\n def navigate_to(self, url, stage):\n self.rdp.Page.navigate(url=url)\n self.stage = stage\n\n def handle_done_loading(self):\n if self.stage == self.LOGIN_REMOTE:\n print('LOGIN_REMOTE', self.curr_url)\n self.stage = self.LOGIN_REMOTE_DONE\n self.eval(self.LOGIN_REMOTE_SCRIPT.format(email=self.book.email, password=self.book.password))\n\n elif self.stage == self.LOGIN_REMOTE_DONE:\n print('LOGIN_REMOTE_DONE', self.curr_url)\n self.navigate_to(self.local_url, self.INIT)\n\n def save_cookies(resp):\n cookies = resp['result']['cookies']\n print('GOT COOKIES', cookies)\n\n self.book.cookies = cookies\n\n self.rdp.Network.getCookies(urls=[self.curr_url], callback=save_cookies)\n\n elif self.stage == self.INIT:\n print('INIT', self.curr_url)\n self.import_tab_url = self.local_url + self.IMPORT_TAB_URL\n\n self.navigate_to(self.import_tab_url, self.LOGIN)\n\n elif self.stage == self.LOGIN:\n print('LOGIN', self.curr_url)\n self.stage = self.LOGGED_IN_REDIR\n self.eval(self.LOGIN_SCRIPT)\n\n elif self.stage == self.LOGGED_IN_REDIR:\n print('LOGGED_IN_REDIR', self.curr_url, self.import_tab_url)\n\n self.navigate_to(self.import_tab_url, self.LOGGED_IN)\n\n elif self.stage == self.LOGGED_IN:\n print('LOGGED_IN')\n\n self.stage = self.IMPORTING\n self.eval(self.IMPORT_SCRIPT % self.base_url)\n\n elif self.stage == self.IMPORTING:\n print('IMPORTING TOC')\n try:\n self.book.import_toc(target_host=self.scalar_host,\n username='scalar@example.com',\n password='')\n except:\n import traceback\n traceback.print_exc()\n\n self.stage = self.DONE\n\n #self.browser.queue_urls([book.new_url])\n self.eval('window.location.reload()')\n print('DONE IMPORTING')\n\n\n# ============================================================================\nif __name__ == \"__main__\":\n main = Main()\n WSGIServer('0.0.0.0:8376', main.app, handler_class=WebSocketHandler).serve_forever()\n\n\n","sub_path":"driver/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":24304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82748320","text":"from nepc import nepc\nfrom nepc.util import util\nimport pandas as pd\nimport os\nimport pytest\nimport platform\n# TODO: remove dependence on csv; put function in scraper that uses built-in\n# readlines function\nimport csv\n\n# TODO: test that all values in [nepc]/tests/data are in the nepc database\n\n@pytest.mark.usefixtures(\"data_config\", \"nepc_connect\")\ndef test_states_table_has_species_metadata(data_config, nepc_connect):\n \"\"\"\n check that the states table has a species_id column\n \"\"\"\n NEPC_DATA = data_config[0]\n number_of_states = util.wc_fxn(NEPC_DATA + 'states.tsv') - 1\n df_states = nepc.table_as_df(nepc_connect[1], 'states')\n assert len(df_states) == number_of_states\n assert 'species_id' in list(df_states.columns)\n\n\n@pytest.mark.usefixtures(\"data_config\", \"nepc_connect\")\ndef test_csdata_lines(data_config, nepc_connect):\n DIR_NAMES = data_config[1]\n cs_lines = 0\n for directoryname in DIR_NAMES:\n directory = os.fsencode(directoryname)\n\n for file in os.listdir(directory):\n filename = os.fsdecode(file)\n if filename.endswith(\".met\") or filename.endswith(\".mod\"):\n continue\n else:\n # subtract 1 to account for header\n cs_lines += util.wc_fxn(directoryname + filename) - 1\n\n assert cs_lines == nepc.count_table_rows(nepc_connect[1], \"csdata\")\n\n\n@pytest.mark.usefixtures(\"data_config\", \"nepc_connect\")\ndef test_data_entered(data_config, nepc_connect, local):\n NEPC_DATA = data_config[0]\n if local is False or platform.node() == 'ppdadamsonlinux':\n cs_dat_files = pd.read_csv(NEPC_DATA + 'cs_datfile_prod.tsv',\n delimiter='\\t')\n else:\n cs_dat_files = pd.read_csv(NEPC_DATA + 'cs_datfile_local.tsv',\n delimiter='\\t')\n\n for index, row in cs_dat_files.iterrows():\n cs_id = row['cs_id']\n dat_file = row['filename']\n df = pd.read_csv(NEPC_DATA + dat_file + '.dat', delimiter='\\t',\n usecols=['e_energy', 'sigma'])\n e_energy, sigma = nepc.cs_e_sigma(nepc_connect[1], cs_id)\n # assert e_energy == pytest.approx(df['e_energy'].tolist())\n assert sigma == pytest.approx(df['sigma'].tolist())\n\n\n@pytest.mark.usefixtures(\"data_config\", \"nepc_connect\")\ndef test_meta_entered(data_config, nepc_connect, local, dbug):\n NEPC_DATA = data_config[0]\n if local is False or platform.node() == 'ppdadamsonlinux':\n cs_dat_files = pd.read_csv(NEPC_DATA + 'cs_datfile_prod.tsv',\n delimiter='\\t')\n else:\n cs_dat_files = pd.read_csv(NEPC_DATA + 'cs_datfile_local.tsv',\n delimiter='\\t')\n\n for index, row in cs_dat_files.iterrows():\n cs_id = row['cs_id']\n met_file = row['filename']\n if dbug:\n print(cs_id, met_file)\n e, sigma = nepc.cs_e_sigma(nepc_connect[1], cs_id)\n\n meta_cols = ['cs_id', 'process', 'units_e',\n 'units_sigma', 'ref', 'lhsA',\n 'lhsB', 'rhsA', 'rhsB', 'threshold', 'wavelength',\n 'lhs_v', 'rhs_v', 'lhs_j', 'rhs_j',\n 'background', 'lpu', 'upu']\n\n with open(NEPC_DATA + met_file + \".met\", 'r', newline='') as f:\n reader = csv.reader(f, delimiter='\\t')\n next(reader)\n meta_disk = list(reader)[0]\n\n meta_disk = [meta_disk[i] for i in list(range(len(meta_cols)))]\n\n for i in [0, 11, 12, 13, 14]:\n meta_disk[i] = (int(meta_disk[i]) if meta_disk[i] != '\\\\N'\n else meta_disk[i])\n for i in [2, 3, 9, 10, 16, 17]:\n meta_disk[i] = (float(meta_disk[i]) if meta_disk[i] != '\\\\N'\n else meta_disk[i])\n\n meta_db = [nepc.cs_metadata(nepc_connect[1], cs_id)[i]\n for i in list(range(0, len(meta_cols)))]\n if dbug:\n print('meta_db: {}\\t from {}'.format(meta_db, met_file))\n for i in range(len(meta_cols)):\n if dbug:\n print('meta_db[{}]: {}\\t from {}'.format(str(i), str(meta_db[i]), met_file))\n if (type(meta_db[i]) is float):\n assert (pytest.approx(meta_disk[i]) ==\n pytest.approx(meta_db[i]))\n elif meta_db[i] is None:\n assert meta_disk[i] == '\\\\N'\n else:\n assert meta_disk[i] == meta_db[i]\n","sub_path":"tests/test_mysql_build.py","file_name":"test_mysql_build.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"289633090","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# thumbor imaging service\n# https://github.com/globocom/thumbor/wiki\n\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license\n# Copyright (c) 2011 globo.com timehome@corp.globo.com\n\nimport math\n\nfrom thumbor.point import FocalPoint\n\nclass Transformer(object):\n def __init__(self, context):\n self.context = context\n self.engine = self.context.modules.engine\n\n def calculate_target_dimensions(self):\n source_width, source_height = self.engine.size\n source_width = float(source_width)\n source_height = float(source_height)\n\n if not self.context.request.width and not self.context.request.height:\n self.target_width = source_width\n self.target_height = source_height\n else:\n if self.context.request.width:\n self.target_width = float(self.context.request.width)\n else:\n self.target_width = self.engine.get_proportional_width(self.context.request.height)\n\n if self.context.request.height:\n self.target_height = float(self.context.request.height)\n else:\n self.target_height = self.engine.get_proportional_height(self.context.request.width)\n\n def calculate_focal_points(self):\n source_width, source_height = self.engine.size\n\n if self.context.request.focal_points:\n self.focal_points = self.context.request.focal_points\n else:\n self.focal_points = [\n FocalPoint.from_alignment(self.context.request.halign,\n self.context.request.valign,\n source_width,\n source_height)\n ]\n\n self.engine.focus(self.focal_points)\n\n def transform(self, callback):\n self.done_callback = callback\n self.manual_crop()\n self.calculate_target_dimensions()\n self.smart_detect()\n\n @property\n def smart_storage_key(self):\n key = self.context.request.image_url\n if self.context.request.should_crop:\n key += '_%d_%d_%d_%d' % (self.context.request.crop['left'],\n self.context.request.crop['top'],\n self.context.request.crop['right'],\n self.context.request.crop['bottom'])\n return key\n\n def smart_detect(self):\n if self.context.modules.detectors and self.context.request.smart:\n storage = self.context.modules.storage\n focal_points = storage.get_detector_data(self.smart_storage_key)\n if focal_points:\n self.after_smart_detect(focal_points)\n else:\n detectors = self.context.modules.detectors\n detectors[0](self.context, index=0, detectors=detectors).detect(self.after_smart_detect)\n else:\n self.after_smart_detect([])\n\n def after_smart_detect(self, focal_points=[]):\n for point in focal_points:\n self.context.request.focal_points.append(FocalPoint.from_dict(point))\n\n if self.context.request.focal_points and self.context.modules.storage:\n storage = self.context.modules.storage\n points = []\n for point in self.context.request.focal_points:\n points.append(point.to_dict())\n\n storage.put_detector_data(self.smart_storage_key, points)\n\n self.calculate_focal_points()\n\n if self.context.request.debug:\n self.debug()\n else:\n if self.context.request.fit_in:\n self.fit_in_resize()\n else:\n self.auto_crop()\n self.resize()\n self.flip()\n\n self.done_callback()\n\n def manual_crop(self):\n if self.context.request.should_crop:\n limit = lambda dimension, maximum: min(max(dimension, 0), maximum)\n\n source_width, source_height = self.engine.size\n\n crop_left = limit(self.context.request.crop['left'], source_width)\n crop_top = limit(self.context.request.crop['top'], source_height)\n crop_right = limit(self.context.request.crop['right'], source_width)\n crop_bottom = limit(self.context.request.crop['bottom'], source_height)\n\n if crop_left >= crop_right or crop_top >= crop_bottom:\n return\n\n self.engine.crop(crop_left, crop_top, crop_right, crop_bottom)\n\n self.calculate_target_dimensions()\n\n def auto_crop(self):\n source_width, source_height = self.engine.size\n\n source_ratio = round(float(source_width) / source_height, 2)\n target_ratio = round(float(self.target_width) / self.target_height, 2)\n\n if source_ratio == target_ratio:\n return\n\n focal_x, focal_y = self.get_center_of_mass()\n focal_x_percentage = 1.0\n focal_y_percentage = 1.0\n\n if self.target_width / source_width > self.target_height / source_height:\n crop_width = source_width\n crop_height = round(source_width * self.target_height / self.target_width, 0)\n focal_y_percentage = max(focal_y - (crop_height / 2), 0.0) / source_height\n else:\n crop_width = round(math.ceil(self.target_width * source_height / self.target_height), 0)\n crop_height = source_height\n focal_x_percentage = max(focal_x - (crop_width / 2), 0.0) / source_width\n\n crop_width_amount = source_width - crop_width\n crop_left = int(crop_width_amount * focal_x_percentage)\n crop_right = int(source_width - crop_width_amount + crop_left)\n\n crop_height_amount = source_height - crop_height\n crop_top = int(crop_height_amount * focal_y_percentage)\n crop_bottom = int(source_height - crop_height_amount + crop_top)\n\n self.engine.crop(crop_left, crop_top, crop_right, crop_bottom)\n\n def flip(self):\n if self.context.request.horizontal_flip:\n self.engine.flip_horizontally()\n if self.context.request.vertical_flip:\n self.engine.flip_vertically()\n\n def get_center_of_mass(self):\n total_weight = 0.0\n total_x = 0.0\n total_y = 0.0\n\n for focal_point in self.focal_points:\n total_weight += focal_point.weight\n total_x += focal_point.x * focal_point.weight\n total_y += focal_point.y * focal_point.weight\n\n return total_x / total_weight, total_y / total_weight\n\n def resize(self):\n source_width, source_height = self.engine.size\n if self.target_width == source_width and self.target_height == source_height:\n return\n self.engine.resize(self.target_width, self.target_height)\n\n def fit_in_resize(self):\n source_width, source_height = self.engine.size\n\n if self.target_width >= source_width and self.target_height >= source_height:\n return\n\n if source_width / self.target_width >= source_height / self.target_height:\n resize_height = source_height * self.target_width / source_width\n resize_width = self.target_width\n else:\n resize_height = self.target_height\n resize_width = source_width * self.target_height / source_height\n\n self.engine.resize(resize_width, resize_height)\n\n def debug(self):\n if not self.context.request.focal_points:\n return\n\n for point in self.context.request.focal_points:\n if point.width <= 1:\n point.width = 10\n if point.height <= 1:\n point.height = 10\n self.engine.draw_rectangle(int(point.x - (point.width / 2)),\n int(point.y - (point.height / 2)),\n point.width,\n point.height)\n\n","sub_path":"thumbor/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":7973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"449893742","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time :2020/6/19 12:14\n# @Author :春衫\n# @File :get_two_float.py\n\nfrom decimal import *\n\n\ndef get_two_float(f_str, n):\n '''\n\n Parameters\n ----------\n f_str:'{}'.format(f_str) 也可以转换为字符串\n n:无论传入的函数有几位小数,在字符串后面都添加n位小数0\n\n Returns\n -------\n\n '''\n f_str = str(f_str)\n a, b, c = f_str.partition('.')\n c = (c + \"0\" * n)[:n]\n return \".\".join([a, c])\n\n\nif __name__ == '__main__':\n b = Decimal('0.1350')\n a = get_two_float(b, 2)\n print(a)\n print(type(a))\n d = Decimal(a)\n print(d)\n print(type(d))\n","sub_path":"fenyongV2.0/new_muban/get_two_float.py","file_name":"get_two_float.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"422892253","text":"import torch\nimport torchvision\nfrom torch import nn\nfrom torchvision.models import ResNet\n# noinspection PyProtectedMember\nfrom torchvision.models.resnet import Bottleneck\n\n\nclass ResNet50(ResNet):\n \"\"\"Custom ResNet50 used as the network backbone\n\n Modified version of the base ResNet50 from torchvision,\n found at: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n\n This ResNet replace stride with a dilation on layer 4 for a larger feature map, and\n removes the average pooling and fully-connected part of the network.\n During training, BatchNorm is frozen.\n \"\"\"\n\n def __init__(self) -> None:\n # Replace stride with dilation on layer 4\n super().__init__(Bottleneck, [3, 4, 6, 3], replace_stride_with_dilation=[False, False, True])\n self.training = True\n\n # Pretrain the network\n self.load_state_dict(torchvision.models.resnet50(pretrained=True).state_dict())\n\n # Replace last 2 (unused) layers with identity\n self.avgpool = nn.Identity()\n self.fc = nn.Identity()\n\n def _forward_impl(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\" Forward implementation of ResNet50 where avg_pool, flatten and fc are removed\n\n Shape:\n - X: :math:`(N, 3, H_in, W_in)` where :math:`(H_in, W_in)` are the image height and width\n - Output: :math:`(N, C_out, H_out, W_out)` where :math:`C_out` is the number of output channels\n |\n For ROCK implementation on the NYUv2 dataset:\n - :math:`(H_in, W_in) = (480, 640)`\n - :math:`(C_out, H_out, W_out) = (2048, 30, 40)`\n \"\"\"\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n return x\n\n def freeze_bn(self) -> None:\n \"\"\"Freezes batch norm layers\n \"\"\"\n\n for module in self.modules():\n if type(module) == nn.modules.batchnorm.BatchNorm2d:\n module.eval()\n\n def train(self, mode=True):\n r\"\"\"Override of nn.module method to freeze batchnorm in all cases\n\n Sets the module in training mode.\n\n This has any effect only on certain modules. See documentations of\n particular modules for details of their behaviors in training/evaluation\n mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,\n etc.\n\n Args:\n mode (bool): whether to set training mode (``True``) or evaluation\n mode (``False``). Default: ``True``.\n\n Returns:\n Module: self\n \"\"\"\n self.training = mode\n for module in self.children():\n module.train(mode)\n\n self.freeze_bn()\n\n return self\n\n","sub_path":"rock/model/backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"359857802","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport itertools, os, datetime\nuse_gpu = torch.cuda.is_available()\n\ndef validate_model(val_iter, model, criterion, TEXT, logger=None):\n model.eval()\n \n # Initial states for LSTM\n batch_size = val_iter.batch_size\n num_layers, hidden_size = model.num_layers, model.hidden_size\n init = Variable(torch.zeros(num_layers, batch_size, hidden_size), requires_grad=False)\n init = init.cuda() if use_gpu else init\n states = (init, init.clone())\n\n # Compute mean average precision table for k=20\n map_list = [sum(1/(j+1) for j in range(i,20)) for i in range(20)]\n map_matrix = torch.FloatTensor(map_list)\n map_matrix = map_matrix.cuda() if use_gpu else map_matrix\n \n # Iterate over words in validation batch. Note that a Variable from val_iter is volatile.\n loss_total = 0\n map_total = 0\n words_total = 0\n for i, batch in enumerate(val_iter):\n text = batch.text.cuda() if use_gpu else batch.text \n targets = batch.target.cuda() if use_gpu else batch.target\n\n # Forward, calculate loss\n outputs, states = model(text, states)\n outputs = outputs.contiguous().view(outputs.size(0) * outputs.size(1), outputs.size(2))\n targets = targets.view(outputs.size(0)) # reshape for loss function\n\n # Remove '' from predictions\n outputs[TEXT.vocab.stoi['']] = -1000\n # outputs[TEXT.vocab.stoi['']] = -1000\n\n # Get top 20 predictions\n scores, preds = outputs.topk(20)\n rank_onehot = (preds == targets.view(-1,1)).data.float()\n map_scores = rank_onehot @ map_matrix\n map_total += map_scores.sum()\n words_total += len(map_scores)\n \n # Calculate losses\n loss = criterion(outputs, targets)\n loss_total += loss.data[0]\n \n # Log information after validation\n loss_avg = loss_total / len(val_iter) \n map_avg = map_total / words_total\n ppl = torch.exp(torch.FloatTensor([loss_avg]))[0]\n info = 'Validation complete. MAP: {map:.3f}, \\t Loss: {loss:.3f}, \\t Sorta-Perplexity: {perplexity:.3f}'.format(\n map=map_avg, loss=loss_avg, perplexity=ppl)\n logger.log(info) if logger is not None else print(info)\n return ppl\n","sub_path":"valid.py","file_name":"valid.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"355005700","text":"import numpy as np\nimport torch\n\nfrom torch.nn import Module, Embedding, LSTM, Linear, Dropout\nfrom torch.nn.functional import one_hot, binary_cross_entropy\nfrom sklearn import metrics\n\nif torch.cuda.is_available():\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n\n\nclass DKT(Module):\n def __init__(self, num_q, emb_size, hidden_size):\n super(DKT, self).__init__()\n self.num_q = num_q\n self.emb_size = emb_size\n self.hidden_size = hidden_size\n\n self.interaction_emb = Embedding(self.num_q * 2, self.emb_size)\n self.lstm_layer = LSTM(\n self.emb_size, self.hidden_size, batch_first=False\n )\n self.out_layer = Linear(self.hidden_size, self.num_q)\n self.dropout_layer = Dropout()\n\n def forward(self, q, r):\n qr = q + self.num_q * r\n\n h, _ = self.lstm_layer(self.interaction_emb(qr))\n y = self.out_layer(h)\n y = self.dropout_layer(y)\n y = torch.sigmoid(y)\n\n return y\n\n def train_model(self, train_loader, test_loader, num_epochs, opt):\n aucs = []\n loss_means = []\n\n for i in range(1, num_epochs + 1):\n loss_mean = []\n\n for data in train_loader:\n q, r, t, d, m = data\n\n self.train()\n\n y = self(q, r)\n y = (y * one_hot(d, self.num_q)).sum(-1)\n\n y = torch.masked_select(y, m)\n t = torch.masked_select(t, m)\n\n opt.zero_grad()\n loss = binary_cross_entropy(y, t)\n loss.backward()\n opt.step()\n\n loss_mean.append(loss.detach().cpu().numpy())\n\n with torch.no_grad():\n for data in test_loader:\n q, r, t, d, m = data\n\n self.eval()\n\n y = self(q, r)\n y = (y * one_hot(d, self.num_q)).sum(-1)\n\n y = torch.masked_select(y, m).detach().cpu()\n t = torch.masked_select(t, m).detach().cpu()\n\n auc = metrics.roc_auc_score(\n y_true=t.numpy(), y_score=y.numpy()\n )\n\n loss_mean = np.mean(loss_mean)\n\n print(\n \"Epoch: {}, AUC: {}, Loss Mean: {}\"\n .format(i, auc, loss_mean)\n )\n\n aucs.append(auc)\n loss_means.append(loss_mean)\n\n return aucs, loss_means\n","sub_path":"models/dkt.py","file_name":"dkt.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"545293912","text":"import numpy as np\nimport pprint\nfrom pprint import pprint\nimport statistics\nimport cv2\nimport os\nimport random\n\n\n\n\n\n\nclassifiers = None\n\n\n# cas_temp = {}\n# cas_temp[\"haarcascade_mcs_lefteye.xml\"] = cascades[\"haarcascade_mcs_lefteye.xml\"]\n# cas_temp['haarcascade_mcs_mouth.xml'] = cascades['haarcascade_mcs_mouth.xml']\n\n# cascades = cas_temp\n# to test - lefteye\n# to test - mouth\n\ndef load_all_cascades_in_dir():\n cascades = {}\n files = os.listdir(\".\")\n for cas in filter(lambda x: \".xml\" in x, files):\n try:\n cas_model = cv2.CascadeClassifier(cas)\n cascades[cas] = cas_model\n except Exception as e:\n \"Cannot create model from {0}\".format(cas)\n return cascades\n\n\n# def has_upper_body(img):\n# cas_res = upper_body.detectMultiScale(img, 1.3, 5)\n# front_res = frontal2.detectMultiScale(img, 1.3, 5)\n# front_default_res = frontaldefault.detectMultiScale(img, 1.3, 5)\n# mouth_res = mouth.detectMultiScale(img, 1.3, 5)\n# l_eye_res = left_eye.detectMultiScale(img, 1.3, 5)\n# if (len(l_eye_res)+ len(mouth_res) +len(cas_res) + len(front_res) + len(front_default_res)) > 0 :\n# return True\n#\n# def test_specific_haar_classifiers():\n# total_images = 0\n# recognized_in = 0\n# for img_path in os.listdir(\"../train_eye/images\"):\n# total_images += 1\n# if total_images % 50 == 0:\n# print(recognized_in)\n# print(total_images)\n# print(\"Total recognized : {0}\".format(float(recognized_in) / total_images))\n# img_path = os.path.join(\"../train_eye/images\",img_path)\n# img = cv2.imread(img_path)\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# if has_upper_body(img):\n# recognized_in +=1\n# print(\"Total recognized : {0}\".format(float(recognized_in)/total_images))\n# print(\"Finished\")\n\n\ndef find_center(coor_list):\n # x_sum = 0\n # y_sum = 0\n # total = 0\n x_s = []\n y_s = []\n for coor in coor_list:\n # total += 1\n x_s.append(coor[0])\n y_s.append(coor[1])\n # x_sum += coor[0]\n # y_sum += coor[1]\n return (statistics.median(x_s), statistics.median(y_s))\n\ndef load_crop_classifiers():\n global classifiers\n if classifiers != None:\n return\n upper_body = cv2.CascadeClassifier(os.path.join('haar', 'haarcascade_mcs_upperbody.xml'))\n frontal2 = cv2.CascadeClassifier(os.path.join('haar', 'haarcascade_frontalface_alt2.xml'))\n frontaldefault = cv2.CascadeClassifier(os.path.join('haar', 'haarcascade_frontalface_default.xml'))\n mouth = cv2.CascadeClassifier(os.path.join('haar', 'haarcascade_mcs_mouth.xml'))\n left_eye = cv2.CascadeClassifier(os.path.join('haar', 'haarcascade_mcs_lefteye.xml'))\n classifiers = [upper_body, frontal2, frontaldefault, mouth, left_eye]\n\n\ndef crop_face(img, crop_size):\n global classifiers\n load_crop_classifiers()\n centers = []\n for clas in classifiers:\n detect = clas.detectMultiScale(img, 1.3, 5)\n for x,y,w,h in detect:\n # cv2.rectangle(img, (x + (w / 2), y + (h / 2)), (x + (w / 2) + 10, y + (h / 2) + 10), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 2)\n centers.append((x+(w/2), y+(h/2)))\n center = find_center(centers)\n topleft_X = max(int(center[0] - crop_size/2),0)\n topleft_Y = max(int(center[1] - crop_size/2),0)\n if (topleft_X + crop_size) > img.shape[1]:\n topleft_X = img.shape[1] - crop_size\n if (topleft_Y + crop_size) > img.shape[0]:\n topleft_Y = img.shape[0] - crop_size\n\n # cv2.rectangle(img, (topleft_X, topleft_Y), (topleft_X+crop_size, topleft_Y+crop_size), (33,33,33),2)\n\n cropped_image = img[topleft_Y:topleft_Y+crop_size,topleft_X:topleft_X+crop_size]\n return cropped_image\n\nif __name__ == \"__main__\":\n pass\n\n\n\n\n\n '''\n test_specific_haar_classifiers()\n\n\n total_images = 0\n reses = {}\n for i,img_path in enumerate(os.listdir(\"../train_eye/images\")):\n if i%50 == 0:\n print reses\n total_images += 1\n img_path = os.path.join(\"../train_eye/images\",img_path)\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # print \"=======================\"\n for cas_name, cas_m in cascades.items():\n cas_recognized = cas_m.detectMultiScale(img, 1.3, 5)\n if len(cas_recognized):\n # print cas_name\n reses[cas_name] = reses.get(cas_name,0) + 1\n for (x, y, w, h) in cas_recognized:\n cv2.rectangle(img, (x, y), (x + w, y + h), (random.randint(0,255), random.randint(0,255), random.randint(0,255)), 2)\n cv2.imshow('img', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n # raw_input(\"foobar\")\n # for (x, y, w, h) in faces:\n # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n # roi_gray = img[y:y + h, x:x + w]\n # roi_color = img[y:y + h, x:x + w]\n # eyes = eye_cascade.detectMultiScale(roi_gray)\n # for (ex, ey, ew, eh) in eyes:\n # cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)\n \n '''\n","sub_path":"trainer/cv_classifiers.py","file_name":"cv_classifiers.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"227764499","text":"# -*- coding:utf-8 -*-\n\nfrom urllib import parse\nfrom urllib import request\nfrom urllib import error\nimport json\nimport ssl\n\n#\n# access image tagging\n#\ndef image_tagging(token, url, image):\n _url = 'https://ais.cn-north-1.myhuaweicloud.com/v1.0/image/tagging'\n\n _data = {\n \"image\":str(image),\n \"url\":url,\n \"language\": \"zh\",\n \"limit\": 10,\n \"threshold\": 30.0\n }\n\n json_data = json.dumps(_data).encode('utf8')\n headers = {'Content-Type':'application/json', 'X-Auth-Token':token}\n kreq = request.Request( url = _url, data = json_data, headers = headers)\n \n resp = None\n status_code = None\n _context = ssl._create_unverified_context()\n try:\n r = request.urlopen(kreq, context=_context)\n except error.HTTPError as err: \n resp = err.read()\n print(resp)\n else:\n status_code = r.code\n resp = r.read().decode('utf-8') \n \n return resp \n","sub_path":"imageRec/image_tagging.py","file_name":"image_tagging.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"252320313","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 migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('core', '0003_auto_20141020_0347'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='file',\n name='titulo',\n field=models.CharField(default=None, max_length=30),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='file',\n name='user',\n field=models.ForeignKey(default=None, to=settings.AUTH_USER_MODEL),\n preserve_default=False,\n ),\n ]\n","sub_path":"core/migrations/0004_auto_20141020_0401.py","file_name":"0004_auto_20141020_0401.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174345420","text":"import datetime\nimport random\nimport re\nimport subprocess\nimport traceback\nimport urllib.parse\n\nimport dateutil.parser\nimport dateutil.tz\nimport requests\n\nimport config\n\nrs = requests.Session()\nrs.headers['User-Agent'] = 'sbot (github.com/raylu/sbot)'\n\ndef help(cmd):\n\tif cmd.args: # only reply on \"!help\"\n\t\treturn\n\tcommands = set(cmd.bot.commands.keys())\n\tguild_id = cmd.bot.channels[cmd.channel_id]\n\tif config.bot.roles is None or guild_id != config.bot.roles['server']:\n\t\tfor name, func in cmd.bot.commands.items():\n\t\t\tif func.__module__ == 'management':\n\t\t\t\tcommands.remove(name)\n\treply = 'commands: `!%s`' % '`, `!'.join(commands)\n\tcmd.reply(reply)\n\ndef calc(cmd):\n\tif not cmd.args:\n\t\treturn\n\tresponse = rs.get('https://www.calcatraz.com/calculator/api', params={'c': cmd.args})\n\tif response.status_code == 200:\n\t\tcmd.reply(response.text.rstrip()[:1000])\n\telse:\n\t\tcmd.reply('<@!%s>: error calculating' % cmd.sender['id'])\n\ndef unicode(cmd):\n\tif not cmd.args:\n\t\treturn\n\tcommand = ['unicode', '--max', '5', '--color', '0',\n\t\t\t'--format', '{pchar} U+{ordc:04X} {name} (UTF-8: {utf8})\\\\n', cmd.args]\n\tproc = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE)\n\toutput, _ = proc.communicate()\n\tcmd.reply(output)\n\ntemp_re = re.compile(r'\\A(-?[0-9 ]*)(C|F)\\Z')\ndef units(cmd):\n\tsplit = cmd.args.split(' in ', 1)\n\tfor i, part in enumerate(split):\n\t\tmatch = temp_re.match(part)\n\t\tif match:\n\t\t\t# turn \"20 C\" into \"tempC(20)\"\n\t\t\tif match.group(1):\n\t\t\t\tsplit[i] = 'temp%s(%s)' % (match.group(2), match.group(1))\n\t\t\telse:\n\t\t\t\tsplit[i] = 'temp%s' % (match.group(2))\n\tcommand = ['units', '--compact', '--one-line', '--quiet', '--'] + split\n\t# in case we get in interactive mode, PIPE stdin so communicate will close it\n\tproc = subprocess.Popen(command, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\toutput, _ = proc.communicate()\n\tif proc.wait() == 0:\n\t\tcmd.reply(output)\n\telse:\n\t\tcmd.reply('<@!%s>: error running `units`' % cmd.sender['id'])\n\ndef roll(cmd):\n\targs = cmd.args or '1d6'\n\tresponse = rs.get('https://rolz.org/api/?' + args) # don't urlencode\n\tsplit = response.text.split('\\n')\n\tdetails = split[2].split('=', 1)[1].strip()\n\tdetails = details.replace(' +', ' + ').replace(' + ', ' + ')\n\tresult = split[1].split('=', 1)[1]\n\tcmd.reply('%s %s' % (result, details))\n\npacific = dateutil.tz.gettz('America/Los_Angeles')\neastern = dateutil.tz.gettz('America/New_York')\nutc = dateutil.tz.tzutc()\nkorean = dateutil.tz.gettz('Asia/Seoul')\naustralian = dateutil.tz.gettz('Australia/Sydney')\ndef timezones(cmd):\n\tif cmd.args:\n\t\ttry:\n\t\t\tdt = dateutil.parser.parse(cmd.args)\n\t\texcept (ValueError, AttributeError) as e:\n\t\t\tcmd.reply(str(e))\n\t\t\treturn\n\telse:\n\t\tdt = datetime.datetime.utcnow()\n\tif not dt.tzinfo:\n\t\tdt = dt.replace(tzinfo=utc)\n\tresponse = '{:%a %-d %-I:%M %p %Z}\\n{:%a %-d %-I:%M %p %Z}\\n{:%a %-d %H:%M %Z}\\n'\n\tresponse += '{:%a %-d %H:%M %Z}\\n{:%a %-d %-I:%M %p %Z}'\n\tresponse = response.format(dt.astimezone(pacific), dt.astimezone(eastern), dt.astimezone(utc),\n\t\t\tdt.astimezone(korean), dt.astimezone(australian))\n\tcmd.reply(response)\n\ndef weather(cmd):\n\tif not cmd.args:\n\t\treturn\n\tsplit = cmd.args.split()\n\tif split[0].startswith('-'):\n\t\tflags = split[0][1:]\n\t\tlocation = ' '.join(split[1:])\n\telif split[-1].startswith('-'):\n\t\tflags = split[-1][1:]\n\t\tlocation = ' '.join(split[:-1])\n\telse:\n\t\tflags = '1Fp'\n\t\tlocation = cmd.args\n\tfilename = '%s_%s.png' % (urllib.parse.quote_plus(location), flags)\n\turl = 'https://wttr.in/' + filename\n\ttry:\n\t\tresponse = rs.get(url)\n\t\tresponse.raise_for_status()\n\texcept Exception:\n\t\tcmd.reply('%s: error getting weather at %s' % (cmd.sender['username'], url),\n\t\t\t\t{'description': '```%s```' % traceback.format_exc()[-500:]})\n\t\treturn\n\tcmd.reply(None, files={filename: response.content})\n\ndef ohno(cmd):\n\turl = 'https://www.raylu.net/f/ohno/ohno%03d.png' % random.randint(1, 294)\n\tcmd.reply('', {'image': {'url': url}})\n\ndef ohyes(cmd):\n\turl = 'https://www.raylu.net/f/ohyes/ohyes%02d.gif' % random.randint(1, 19)\n\tcmd.reply('', {'image': {'url': url}})\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"587382798","text":"# -*- coding:utf-8 -*-\n\n\ndef del_blank_lines(old_filename, new_filename=None):\n \"\"\"\n :param old_filename: 待去空格的文件\n :param new_filename: 去掉空格后保存到的文件,若未设定则保存到原文件中\n :return:\n \"\"\"\n new_str = []\n with open(old_filename, 'r') as f:\n old_str = f.readlines()\n for s in old_str:\n if s != \"\\n\":\n new_str.append(s)\n new_doc = \"\".join(new_str)\n if new_filename is None:\n new_filename = old_filename\n with open(new_filename, 'w') as f:\n f.write(new_doc)\n\nif __name__ == \"__main__\":\n filename = \"for_test.txt\"\n del_blank_lines(filename)\n","sub_path":"text_.py","file_name":"text_.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"49678945","text":"from pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pytest\n\nimport pdfstream.cli as cli\nimport pdfstream.io as io\n\n\n@pytest.mark.parametrize(\n 'bg_img_file, mask_file, kwargs', [\n (None, None, {}),\n ('Ni_img_file', 'mask_file', {}),\n (None, None, {'parallel': True, 'plot_setting': 'OFF', 'img_setting': 'OFF'})\n ]\n)\ndef test_integrate(test_data, bg_img_file, mask_file, kwargs):\n with TemporaryDirectory() as tempdir:\n img_file = Path(test_data['Ni_img_file'])\n chi_file = Path(tempdir).joinpath(img_file.with_suffix('.chi').name)\n cli.integrate(\n test_data['Ni_poni_file'],\n str(img_file),\n bg_img_file=test_data.get(bg_img_file, None),\n mask_file=test_data.get(mask_file, None),\n output_dir=tempdir,\n **kwargs,\n test=True\n )\n assert chi_file.exists()\n plt.close()\n\n\n@pytest.mark.parametrize(\n 'kwargs', [\n {},\n {'weights': [1, 1]}\n ]\n)\ndef test_average(test_data, kwargs):\n with TemporaryDirectory() as tempdir:\n img_file = Path(tempdir).joinpath('new_dir/average.tiff')\n cli.average(img_file, test_data['white_img_file'], test_data['white_img_file'], **kwargs)\n avg_img = io.load_img(img_file)\n white_img = io.load_img(test_data['white_img_file'])\n assert np.array_equal(avg_img, white_img)\n\n\n@pytest.mark.parametrize(\n 'keys,kwargs', [\n (['Ni_gr_file', 'Ni_gr_file'], {'mode': 'line', 'legends': ['Ni0', 'Ni1']}),\n (['Ni_gr_file', 'Ni_gr_file'], {'mode': 'line', 'stack': False}),\n (['Ni_gr_file', 'Ni_gr_file'], {'mode': 'line', 'xy_kwargs': {'color': 'black'}, 'texts': ['Ni0', 'Ni1']}),\n (['Ni_gr_file', 'Ni_gr_file'], {'mode': 'line', 'colors': ['r', 'b'], 'texts': ['Ni0', 'Ni1']}),\n (['Ni_fgr_file', 'Ni_fgr_file'], {'mode': 'fit', 'texts': ['Ni0', 'Ni1']}),\n (['Ni_fgr_file', 'Ni_fgr_file'], {'mode': 'fit', 'stack': False}),\n (['Ni_fgr_file', 'Ni_fgr_file'], {'mode': 'fit', 'xy_kwargs': {'color': 'black'}})\n ]\n)\ndef test_waterfall(test_data, keys, kwargs):\n data_files = (test_data[key] for key in keys)\n cli.waterfall(*data_files, **kwargs, show_fig=False)\n plt.close()\n\n\ndef test_waterfall_exception():\n with pytest.raises(ValueError):\n cli.waterfall(*tuple())\n plt.close()\n\n\n@pytest.mark.parametrize(\n 'key,kwargs', [\n ('Ni_gr_file', {'mode': 'line', 'text': 'Ni', 'xy_kwargs': {'color': 'black'}}),\n ('Ni_gr_file', {'mode': 'line', 'legends': 'Ni', 'xy_kwargs': {'color': 'black'}}),\n ('Ni_fgr_file', {'mode': 'fit', 'text': 'Ni', 'xy_kwargs': {'color': 'black'}})\n ]\n)\ndef test_visualize(test_data, key, kwargs):\n cli.visualize(test_data[key], **kwargs, show_fig=False)\n plt.close()\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"224681867","text":"from vascomputer import login_with_new_user\nfrom vastestcase import *\nfrom vas import vasUtilities\nfrom user import User\nimport random\n\nclass gssapi(VasTestCase):\n \"\"\"\n Smoke suite that can be used to test multiple tests. Can have both a global and individual setup and cleanup\n \"\"\" \n\n @classmethod\n def setUpClass(cls):\n #cls.computer.vastool.configureVas.debug_level('4')\n #cls.computer.daemonRestart(\"vasd\")\n #cls.computer.vasd.isReady()\n \n # Test computer\n cls.halYea = User(password=\"auto123\")\n cls.library32 = \"\"\n cls.library64 = \"\"\n cls.testFile32 = \"\"\n cls.testFile64 = \"\"\n cls.testFile = \"\"\n \n if cls.computer.os.find('mac') == -1:\n # TODO: I think this might go better in the vas computer class or something\n if cls.computer.os == \"AIX\":\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.so\"\n cls.library64 = \"/opt/quest/lib/libvas-gssapi64.so\"\n cls.testFile32 = \"gsstest-aix32\"\n cls.testFile64 = \"gsstest-aix64\"\n cls.testFile = \"gsstest-aix*\"\n \n elif cls.computer.os == \"HP-UX\" and cls.computer.version == '11.31':\n cls.library32 = \"/opt/quest/lib/hpux32/libvas-gssapi.so\"\n cls.library64 = \"/opt/quest/lib/hpux64/libvas-gssapi.so\"\n cls.testFile32 = \"gsstest-hpia32\"\n cls.testFile64 = \"gsstest-hpia64\"\n cls.testFile = \"gsstest-hpia*\" \n \n elif cls.computer.os == \"HP-UX\":\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.sl\"\n cls.library64 = \"/opt/quest/lib/pa20_64/libvas-gssapi.sl\"\n cls.testFile32 = \"gsstest-pa32\"\n cls.testFile64 = \"gsstest-pa64\"\n cls.testFile = \"gsstest-pa*\"\n \n elif cls.computer.os == 'linux' and cls.computer.distro in [\"redhat\", \"fedora\"]:\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.so\"\n cls.library64 = \"/opt/quest/lib64/libvas-gssapi.so\"\n cls.testFile32 = \"gsstest-linux32\"\n cls.testFile64 = \"gsstest-linux64\"\n cls.testFile = \"gsstest-linux*\"\n \n elif cls.computer.os == \"solaris\":\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.so\"\n cls.library64 = \"/opt/quest/lib/sparcv9/libvas-gssapi.so\"\n cls.testFile32 = \"gsstest-sparc32\"\n cls.testFile64 = \"gsstest-sparc64\"\n cls.testFile = \"gsstest-sparc*\"\n \n elif cls.computer.os == 'linux' and cls.computer.distro.lower() in [\"ubuntu\", \"suse\", \"debian\"]:\n cls.library64 = \"/opt/quest/lib64/libvas-gssapi.so\"\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.so\"\n cls.testFile32 = \"gsstest-linux32\"\n cls.testFile64 = \"gsstest-linux64\"\n cls.testFile = \"gsstest-linux*\" \n \n else:\n cls.library32 = \"/opt/quest/lib/libvas-gssapi.so\"\n cls.library64 = \"/opt/quest/lib64/libvas-gssapi.so\"\n cls.testFile32 = \"gsstest-linux32\"\n cls.testFile64 = \"gsstest-linux64\"\n cls.testFile = \"gsstest-linux*\"\n \n cls.computer.scp(\"hal9000.vintela.com:/automation/cvs/DEV/smoke/gssFiles/{}\".format(cls.testFile), \n \"/tmp/\", cls.halYea)\n \n # Give host.keytab read rights\n cls.computer.run(\"chmod a+r /etc/opt/quest/vas/host.keytab\")\n\n def test_00_gssapiHostPrep(self):\n '''GSSAPI: Host Prep'''\n if self.computer.os.find('mac') > -1:\n self.skipTest(\"No support for mac\")\n self.logger.info('No support for mac')\n \n testUser = User(name=vasUtilities.get_user_name(\"gss-{}\".format(self.computer.suffix), self.upnMode), password=\"Test123\") \n gssapi.userLogin = login_with_new_user(self.computer, testUser.name, testUser.password)\n self.assertTrue(gssapi.userLogin.is_connected, 'Failed to login with gss user')\n\n gssapi.host, rc = gssapi.userLogin.run(\"/opt/quest/bin/vastool ktutil list|awk '/host\\// {print $3}'|head -1\", True)\n gssapi.host = gssapi.host.splitlines()\n gssapi.host = gssapi.host.pop()\n self.computer.run(\"/opt/quest/bin/vastool -u 'host/' kinit\")\n\n def test_01_gssapiTest32(self):\n '''GSSAPI: GSS-API 32 Library''' \n if self.computer.os.find('mac') > -1:\n self.skipTest(\"No support for mac\")\n self.logger.info('No support for mac')\n \n self.assertTrue(gssapi.userLogin.is_connected, 'Failed to login with nested user')\n \n if self.computer.os == \"linux\" and self.computer.distro == 'Ubuntu':\n self.skipTest(\"For some reason we don't do a 32 bit gssapi test on ubuntu\") \n else:\n output, rc = gssapi.userLogin.run(\"/tmp/{} -l {} -a {}\".format(self.testFile32, self.library32, gssapi.host), True)\n self.assertEqual(rc, 0, \"Got a non-zero exit code\")\n self.assertTrue(self._check_results(output), \"Something is NOT ok\")\n\n def test_02_gssapiTest64(self):\n '''GSSAPI: GSS-API 64 Library'''\n if 'mac' in self.computer.os:\n self.skipTest(\"No support for mac\")\n self.logger.info('No support for mac')\n \n self.assertTrue(gssapi.userLogin.is_connected, 'Failed to login with nested user')\n \n if self.computer.os == \"linux\" and self.computer.cpuArchitecture.find(\"x86_64\") == -1:\n self.skipTest(\"No support for x86_64\")\n self.logger.info('No support for x86_64')\n \n output, rc = gssapi.userLogin.run(\"/tmp/{} -l {} -a {}\".format(self.testFile64, self.library64, gssapi.host), True)\n self.assertEqual(rc, 0, \"Got a non-zero exit code\")\n self.assertTrue(self._check_results(output), \"Something is NOT ok\")\n \n @classmethod\n def tearDownClass(cls):\n if 'mac' not in cls.computer.os:\n if gssapi.userLogin:\n gssapi.userLogin.closeConnection()\n cls.computer.removeFile(\"/tmp/gsstest*\")\n \n def _check_results(self, output):\n lines = output.splitlines()\n for line in lines:\n if \"RESULT\" in line:\n if \"NOT\" in line:\n return False\n return True\n\n \nif __name__ == '__main__':\n unittest.main(argv=gssapi.args, verbosity=2)\n\n ","sub_path":"smokeTests/test_gssapi.py","file_name":"test_gssapi.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"592784678","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport os\nfrom collections import Counter\n\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport tflearn\nfrom tflearn.data_utils import to_categorical\n\n\n# preparing the data\nDATA_PATH = '/Users/liuxiangyu/Workspace/Dororis/dist/dlnd/intro-to-tflearn'\nreviews = pd.read_csv(os.path.sep.join([DATA_PATH, 'reviews.txt']), header=None)\nlabels = pd.read_csv(os.path.sep.join([DATA_PATH, 'labels.txt']), header=None)\n\n# 计算单词频率\ntotal_counts = Counter()\n\nfor _, row in reviews.iterrows():\n # data_frame 方法 iterrows()\n total_counts.update(row[0].split(' '))\n# print('Total words in data set: ', len(total_counts))\n\n# 截取 10000 most frequent words\nvocab = sorted(total_counts, key=total_counts.get, reverse=True)[:10000]\n# print(vocab[:50])\nprint(vocab[-1], ': ', total_counts[vocab[-1]])\n\n# word2index\nword2index = {word: i for i, word in enumerate(vocab)}\n\ndef text_to_vector(text):\n # np.int_ -> numpy.int64\n # 初始化为 零值矩阵 长度为 vocab 长度\n word_vector = np.zeros(len(vocab), dtype=np.int_)\n for word in text.split(' '):\n index = word2index.get(word, None)\n if index is None:\n continue\n else:\n word_vector[index] += 1\n return np.array(word_vector)\n\n# print(text_to_vector('The tea is for a party to celebrate the movie so she has no time for a cake'))\n\n\n# build network\n\n\ndef build_model():\n tf.reset_default_graph()\n\n # Inputs\n net = tflearn.input_data([None, 10000])\n\n # Hidden layers\n net = tflearn.fully_connected(net, 200, activation='ReLU')\n net = tflearn.fully_connected(net, 25, activation='ReLU')\n\n # Output\n net = tflearn.fully_connected(net, 2, activation='softmax')\n net = tflearn.regression(net, optimizer='sgd',\n learning_rate=0.1,\n loss='categorical_crossentropy')\n\n model = tflearn.DNN(net)\n return model\n\n\nmodel = build_model()\n\nword_vectors = np.zeros((len(reviews), len(vocab)), dtype=np.int_)\nfor i, (_, text) in enumerate(reviews.iterrows()):\n word_vectors[i] = text_to_vector(text[0])\nprint(word_vectors[:5, :23])\n# Y = (labels=='positive').astype(np.int_)\n# records = len(labels)\n# shuffle = np.arange(records)\n# np.random.shuffle(shuffle)\n# test_fraction = 0.9\n# train_split, test_split = shuffle[:int(records*test_fraction)], shuffle[int(records * test_fraction):]\n# trainX, trainY = word_vectors[train_split,:], to_categorical(Y.values[train_split], 2)\n# model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=128, n_epoch=50)\n","sub_path":"machinelearning/udacity-dlnd/lesson3/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"227869707","text":"class Male:\r\n def __init__(self, name, age, job, money, weight, height):\r\n self.name = name\r\n self.age = age\r\n self.job = job\r\n self.money = money\r\n self.weight = weight\r\n self.height = height\r\n\r\n\r\nclass Female:\r\n def __init__(self, name, age, job, money, weight, height):\r\n self.name = name\r\n self.age = age\r\n self.job = job\r\n self.money = money\r\n self.weight = weight\r\n self.height = height\r\n\r\n def get_money(self, Male):\r\n self.money += Male.money\r\n Male.money = 0\r\n\r\n\r\nAdward = Male('Adward', 38, 'professor', 1000000, 95, 180)\r\n\r\nAmy = Female('Amy', 29, 'florist', 70000, 55, 169)\r\nAmy.get_money(Adward)\r\n\r\nprint(Amy.money)\r\nprint(Adward.money)\r\n\r\n","sub_path":"zadanie2.2_Nikolaeva.py","file_name":"zadanie2.2_Nikolaeva.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"130653224","text":"\nfrom tkinter import *\nfields = ['amp', 'freq_hz', 'phase_rad', 'len_str', 'len_data', 'fs_hz']\n\ndef fetch(entries):\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n print('%s: \"%s\"' % (field, text)) \n\ndef makeform(root, fields):\n entries = []\n for field in fields:\n row = Frame(root)\n lab = Label(row, width=15, text=field, anchor='w')\n ent = Entry(row)\n row.pack(side=TOP, fill=X, padx=5, pady=5)\n lab.pack(side=LEFT)\n ent.pack(side=RIGHT, expand=YES, fill=X)\n entries.append((field, ent))\n return entries\n\nif __name__ == '__main__':\n root = Tk()\n ents = makeform(root, fields)\n root.bind('', (lambda event, e=ents: fetch(e))) \n b1 = Button(root, text='Show',\n command=(lambda e=ents: fetch(e)))\n b1.pack(side=LEFT, padx=5, pady=5)\n b2 = Button(root, text='Quit', command=root.quit)\n b2.pack(side=LEFT, padx=5, pady=5)\n root.mainloop()\n \n \n'''\n def time_domain_wave_creation(self):\n\n\n self.amp_l = Label(master, text=\"amp\")\n self.freq_hz_l = Label(master, text=\"freq_hz\")\n self.phase_rad_l = Label(master, text=\"phase_rad\")\n self.len_str_l = Label(master, text=\"len_str\")\n self.len_data_l = Label(master, text=\"len_data\")\n self.fs_hz_l = Label(master, text=\"fs_hz\")\n \n vcmd = master.register(self.store) # we have to wrap the command\n self.amp_e = Entry(master, validate=\"key\", validatecommand=(vcmd, '%P'))\n self.freq_hz_e = Entry(master, validate=\"key\", validatecommand=(vcmd, '%P'))\n self.phase_rad_e = Entry(master, validate=\"key\", validatecommand=(vcmd, '%P'))\n'''\n\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"556790604","text":"#!/usr/bin/python\n# coding=utf-8\n\nimport cgi\n\nimport dbconnector\nimport session\nimport viewer\n\nviewer = viewer.Viewer()\nform = cgi.FieldStorage()\nimg_id = form.getfirst('img_id')\nresponse = {'code': -1, 'msg': '修改失败,请重试'}\ntry:\n db = dbconnector.DbConnector()\n session = session.get_session(db)\n if session is None:\n response['code'] = 1\n response['msg'] = '请先登录'\n else:\n db.execute('update users set AvatarId = %s where id = %s',\n [img_id, session['user_id'].value])\n response['code'] = 0\n response['msg'] = '修改成功'\nfinally:\n db.close()\n\nviewer.output(response)\n","sub_path":"src/modifyimg.py","file_name":"modifyimg.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"80092757","text":"# -*- encoding: utf-8 -*-\n\nimport tkinter as tk\nimport tkinter.messagebox as messagebox\n\nwindow = tk.Tk()\nwindow.title('my window')\nwindow.geometry('600x400')\n\n# 窗口的内容\nframe1 = tk.Frame(window)\nframe1.pack()\nframe2 = tk.Frame(window)\nframe2.pack()\nframe3 = tk.Frame(window)\nframe3.pack()\n\n# pack 可以按照上下左右的方式排列.\ntk.Label(frame1, text='1').pack(side='top') #上\ntk.Label(frame1, text='1').pack(side='bottom') #上\ntk.Label(frame1, text='1').pack(side='left') #上\ntk.Label(frame1, text='1').pack(side='right') #上\n\n# grid\nfor i in range(4):\n for j in range(3):\n tk.Label(frame2, text='2').grid(row=i, column=j, padx=10, pady=10)\n\n# place\ntk.Label(window, text=3).place(x=20, y=10, anchor='nw')\n\n\n# 显示窗口\nwindow.mainloop()\n\n","sub_path":"15.图形界面/tkinter/tk_position.py","file_name":"tk_position.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"444042340","text":"#!/usr/bin/env python\n\nimport re\nimport os\nimport sys\nimport json\nimport pandas as pd\n\ntry:\n from io import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom argparse import ArgumentParser\nfrom datetime import datetime\nfrom genologics.lims import Lims\nfrom genologics.entities import Process\nfrom genologics.config import BASEURI, USERNAME, PASSWORD\n\nfrom data.Chromium_10X_indexes import Chromium_10X_indexes\n\nSMARTSEQ3_indexes_json = '/opt/gls/clarity/users/glsai/repos/scilifelab_epps/data/SMARTSEQ3_indexes.json'\n\nwith open(SMARTSEQ3_indexes_json, 'r') as file:\n SMARTSEQ3_indexes = json.loads(file.read())\n\nDESC = \"\"\"EPP used to check index distance in library pool\nAuthor: Chuan Wang, Science for Life Laboratory, Stockholm, Sweden\n\"\"\"\n\n# Pre-compile regexes in global scope:\nIDX_PAT = re.compile(\"([ATCG]{4,}N*)-?([ATCG]*)\")\nTENX_SINGLE_PAT = re.compile(\"SI-(?:GA|NA)-[A-H][1-9][0-2]?\")\nTENX_DUAL_PAT = re.compile(\"SI-(?:TT|NT|NN|TN|TS)-[A-H][1-9][0-2]?\")\nSMARTSEQ_PAT = re.compile('SMARTSEQ[1-9]?-[1-9][0-9]?[A-P]')\nNGISAMPLE_PAT =re.compile(\"P[0-9]+_[0-9]+\")\n\n\ndef verify_indexes(data):\n message = []\n pools = set([x['pool'] for x in data])\n for p in sorted(pools):\n subset = [i for i in data if i['pool'] == p]\n subset = sorted(subset, key=lambda d: d['sn'])\n if len(subset) == 1:\n continue\n idx_length = set()\n for i, sample_a in enumerate(subset[:-1]):\n idx_a = sample_a.get('idx1', '') + '-' + sample_a.get('idx2', '')\n idx_length.add(len(idx_a))\n if sample_a.get('idx1', '') == '' and sample_a.get('idx2', '') == '':\n message.append(\"INDEX WARNING: Sample {} in pool {} has no index\".format(sample_a.get('sn', ''), p))\n j = i+1\n for sample_b in subset[j:]:\n idx_b = sample_b.get('idx1', '') + '-' + sample_b.get('idx2', '')\n if idx_a == idx_b:\n message.append(\"INDEX WARNING: Same index {} for samples {} and {} in pool {}\".format(idx_a, sample_a.get('sn', ''), sample_b.get('sn', ''), p))\n sample_last = subset[-1]\n idx_last = sample_last.get('idx1', '') + '-' + sample_last.get('idx2', '')\n idx_length.add(len(idx_last))\n if sample_last.get('idx1', '') == '' and sample_last.get('idx2', '') == '':\n message.append(\"INDEX WARNING: Sample {} in pool {} has no index\".format(sample_last.get('sn', ''), p))\n if len(idx_length) >1:\n message.append(\"INDEX WARNING: Multiple index lengths noticed in pool {}\".format(p))\n return message\n\n\ndef verify_placement(data):\n message = []\n pools = set([x['pool'] for x in data])\n for p in sorted(pools):\n subset = [i for i in data if i['pool'] == p]\n subset = sorted(subset, key=lambda d: d['sn'])\n for sample in subset:\n if sample.get('step_container_name', '') != sample.get('submitted_container_name', ''):\n message.append(\"PLACEMENT WARNING: Sample {} in pool {} is placed in container {} which is different than the submitted container {}\".format(sample.get('sn', ''), p, sample.get('step_container_name', ''), sample.get('submitted_container_name', '')))\n if sample.get('step_pool_well', '') != sample.get('submitted_pool_well', ''):\n message.append(\"PLACEMENT WARNING: Sample {} in pool {} is placed in well {} which is different than the submitted well {}\".format(sample.get('sn', ''), p, sample.get('step_pool_well', ''), sample.get('submitted_pool_well', '')))\n return message\n\ndef verify_samplename(data):\n message = []\n pools = set([x['pool'] for x in data])\n for p in sorted(pools):\n subset = [i for i in data if i['pool'] == p]\n subset = sorted(subset, key=lambda d: d['sn'])\n for sample in subset:\n if not NGISAMPLE_PAT.findall(sample.get('sn', '')):\n message.append(\"SAMPLE NAME WARNING: Bad sample name format {}\".format(sample.get('sn', '')))\n else:\n if sample.get('sn', '').split('_')[0] != sample.get('proj_id', ''):\n message.append(\"SAMPLE NAME WARNING: Sample name {} does not match project ID {}\".format(sample.get('sn', ''), sample.get('proj_id', '')))\n return message\n\ndef check_index_distance(data):\n message = []\n pools = set([x['pool'] for x in data])\n for p in sorted(pools):\n subset = [i for i in data if i['pool'] == p]\n if len(subset) == 1:\n continue\n for i, sample_a in enumerate(subset[:-1]):\n if sample_a.get('idx1', '') == '' and sample_a.get('idx2', '') == '':\n message.append(\"NO INDEX ERROR: Sample {} in pool {} has no index\".format(sample_a.get('sn', ''), p))\n j = i+1\n for sample_b in subset[j:]:\n d = 0\n if sample_a.get('idx1', '') and sample_b.get('idx1', ''):\n d += my_distance(sample_a['idx1'], sample_b['idx1'])\n if sample_a.get('idx2', '') and sample_b.get('idx2', ''):\n d += my_distance(sample_a['idx2'], sample_b['idx2'])\n if d == 0:\n idx_a = sample_a.get('idx1', '') + '-' + sample_a.get('idx2', '')\n idx_b = sample_b.get('idx1', '') + '-' + sample_b.get('idx2', '')\n message.append(\"INDEX COLLISION ERROR: {} for sample {} and {} for sample {} in pool {}\".format(idx_a, sample_a.get('sn', ''), idx_b, sample_b.get('sn', ''), p))\n if d == 1:\n idx_a = sample_a.get('idx1', '') + '-' + sample_a.get('idx2', '')\n idx_b = sample_b.get('idx1', '') + '-' + sample_b.get('idx2', '')\n message.append(\"SIMILAR INDEX WARNING: {} for sample {} and {} for sample {} in pool {}\".format(idx_a, sample_a.get('sn', ''), idx_b, sample_b.get('sn', ''), p))\n sample_last = subset[-1]\n if sample_last.get('idx1', '') == '' and sample_last.get('idx2', '') == '':\n message.append(\"NO INDEX ERROR: Sample {} in pool {} has no index\".format(sample_last.get('sn', ''), p))\n return message\n\n\ndef my_distance(idx_a, idx_b):\n diffs = 0\n short = min((idx_a, idx_b), key=len)\n lon = idx_a if short == idx_b else idx_b\n for i, c in enumerate(short):\n if c != lon[i]:\n diffs += 1\n return diffs\n\n\ndef prepare_index_table(process):\n data=[]\n message = []\n for out in process.all_outputs():\n if out.type == \"Analyte\":\n pool_name = out.name\n step_container_name = out.container.name\n step_pool_well = out.location[1]\n for sample in out.samples:\n proj_id = sample.project.id\n submitted_container_name = ''\n submitted_pool_well = ''\n if process.type.name == 'Library Pooling (Finished Libraries) 4.0':\n submitted_container_name = sample.artifact.container.name.split('-')[0]\n try:\n submitted_pool_well_row = re.findall(\"[a-zA-Z]+\", sample.artifact.container.name.split('-')[2])[0]\n submitted_pool_well_col = re.findall(\"[0-9]+\", sample.artifact.container.name.split('-')[2])[0]\n submitted_pool_well = submitted_pool_well_row + ':' + submitted_pool_well_col\n except IndexError:\n submitted_pool_well = sample.artifact.container.name.split('-')[2]\n sample_idxs = set()\n find_barcode(sample_idxs, sample, process)\n if sample_idxs:\n for idxs in sample_idxs:\n sp_obj = {}\n sp_obj['step_container_name'] = step_container_name\n sp_obj['step_pool_well'] = step_pool_well\n sp_obj['submitted_container_name'] = submitted_container_name\n sp_obj['submitted_pool_well'] = submitted_pool_well\n if idxs[0] == 'NoIndex':\n sp_obj['pool'] = pool_name\n sp_obj['proj_id'] = proj_id\n sp_obj['sn'] = sample.name.replace(',','')\n sp_obj['idx1'] = ''\n sp_obj['idx2'] = ''\n data.append(sp_obj)\n elif TENX_DUAL_PAT.findall(idxs[0]):\n sp_obj['pool'] = pool_name\n sp_obj['proj_id'] = proj_id\n sp_obj['sn'] = sample.name.replace(',','')\n sp_obj['idx1'] = Chromium_10X_indexes[TENX_DUAL_PAT.findall(idxs[0])[0]][0].replace(',','')\n sp_obj['idx2'] = Chromium_10X_indexes[TENX_DUAL_PAT.findall(idxs[0])[0]][1].replace(',','')\n data.append(sp_obj)\n elif TENX_SINGLE_PAT.findall(idxs[0]):\n for tenXidx in Chromium_10X_indexes[TENX_SINGLE_PAT.findall(idxs[0])[0]]:\n sp_obj_sub = {}\n sp_obj_sub['pool'] = pool_name\n sp_obj_sub['proj_id'] = proj_id\n sp_obj_sub['sn'] = sample.name.replace(',','')\n sp_obj_sub['idx1'] = tenXidx.replace(',','')\n sp_obj_sub['idx2'] = ''\n data.append(sp_obj_sub)\n elif SMARTSEQ_PAT.findall(idxs[0]):\n for i7_idx in SMARTSEQ3_indexes[idxs[0]][0]:\n for i5_idx in SMARTSEQ3_indexes[idxs[0]][1]:\n sp_obj_sub = {}\n sp_obj_sub['pool'] = pool_name\n sp_obj_sub['proj_id'] = proj_id\n sp_obj_sub['sn'] = sample.name.replace(',','')\n sp_obj_sub['idx1'] = i7_idx\n sp_obj_sub['idx2'] = i5_idx\n data.append(sp_obj_sub)\n else:\n sp_obj['pool'] = pool_name\n sp_obj['proj_id'] = proj_id\n sp_obj['sn'] = sample.name.replace(',','')\n sp_obj['idx1'] = idxs[0].replace(',','') if idxs[0] else ''\n sp_obj['idx2'] = idxs[1].replace(',','') if idxs[1] else ''\n data.append(sp_obj)\n else:\n sp_obj = {}\n sp_obj['step_container_name'] = step_container_name\n sp_obj['step_pool_well'] = step_pool_well\n sp_obj['submitted_container_name'] = submitted_container_name\n sp_obj['submitted_pool_well'] = submitted_pool_well\n sp_obj['pool'] = pool_name\n sp_obj['proj_id'] = proj_id\n sp_obj['sn'] = sample.name.replace(',','')\n sp_obj['idx1'] = ''\n sp_obj['idx2'] = ''\n data.append(sp_obj)\n return data, message\n\n\ndef find_barcode(sample_idxs, sample, process):\n # print \"trying to find {} barcode in {}\".format(sample.name, process.name)\n for art in process.all_inputs():\n if sample in art.samples:\n if len(art.samples) == 1 and art.reagent_labels:\n if process.type.name == 'Library Pooling (Finished Libraries) 4.0':\n reagent_label_name = art.reagent_labels[0].upper()\n if reagent_label_name and reagent_label_name != 'NOINDEX':\n if (IDX_PAT.findall(reagent_label_name) and len(IDX_PAT.findall(reagent_label_name))>1) or (not (IDX_PAT.findall(reagent_label_name) or TENX_SINGLE_PAT.findall(reagent_label_name) or TENX_DUAL_PAT.findall(reagent_label_name) or SMARTSEQ_PAT.findall(reagent_label_name))):\n sys.stderr.write('INDEX FORMAT ERROR: Sample {} has a bad format or unknown index category\\n'.format(sample.name))\n sys.exit(2)\n reagent_label_name = art.reagent_labels[0].upper().replace(' ', '')\n idxs = TENX_SINGLE_PAT.findall(reagent_label_name) or TENX_DUAL_PAT.findall(reagent_label_name) or SMARTSEQ_PAT.findall(reagent_label_name)\n if idxs:\n # Put in tuple with empty string as second index to\n # match expected type:\n sample_idxs.add((idxs[0], \"\"))\n else:\n try:\n idxs = IDX_PAT.findall(reagent_label_name)[0]\n sample_idxs.add(idxs)\n except IndexError:\n try:\n # we only have the reagent label name.\n rt = lims.get_reagent_types(name=reagent_label_name)[0]\n idxs = IDX_PAT.findall(rt.sequence)[0]\n sample_idxs.add(idxs)\n except:\n sample_idxs.add((\"NoIndex\",\"\"))\n else:\n if art == sample.artifact or not art.parent_process:\n pass\n else:\n find_barcode(sample_idxs, sample, art.parent_process)\n\n\ndef main(lims, pid):\n process = Process(lims, id = pid)\n data, message = prepare_index_table(process)\n if process.type.name == 'Library Pooling (Finished Libraries) 4.0':\n message += verify_placement(data)\n message += verify_indexes(data)\n message += verify_samplename(data)\n else:\n message = check_index_distance(data)\n if message:\n print('; '.join(message), file=sys.stderr)\n if process.type.name == 'Library Pooling (Finished Libraries) 4.0':\n if not process.udf.get('Comments'):\n process.udf['Comments'] = '**Warnings from Verify Indexes and Placement EPP: **\\n' + '\\n'.join(message)\n elif \"Warnings from Verify Indexes and Placement EPP\" not in process.udf['Comments']:\n process.udf['Comments'] += '\\n\\n'\n process.udf['Comments'] += '**Warnings from Verify Indexes and Placement EPP: **\\n'\n process.udf['Comments'] += '\\n'.join(message)\n process.put()\n else:\n print('No issue detected with indexes or placement', file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=DESC)\n parser.add_argument('--pid',\n help='Lims id for current Process')\n parser.add_argument('--log', dest = 'log',\n help=('File name for standard log file, '\n 'for runtime information and problems.'))\n args = parser.parse_args()\n\n lims = Lims(BASEURI, USERNAME, PASSWORD)\n lims.check_version()\n main(lims, args.pid)\n","sub_path":"scripts/index_distance_checker.py","file_name":"index_distance_checker.py","file_ext":"py","file_size_in_byte":15059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"403678002","text":"parent = dict()\r\nrank = dict()\r\n\r\ndef make_singleton_set(v):\t\t# 정점의 parent와 rank를 초기화\r\n parent[v] = v\t\t\t\t# parent = {v : v}\r\n rank[v] = 1\t\t\t\t\t# rank = {v : 1}\r\n\r\ndef find(v):\t\t\t\t\t# 집합의 root node를 반환한다.\r\n if parent[v] != v:\r\n parent[v] = find(parent[v])\r\n return parent[v]\r\n\r\ndef union(r1, r2):\t\t\t\t# 집합의 원소수가 많은 쪽으로 합쳐진다.\r\n if r1 != r2:\r\n if rank[r1] > rank[r2]:\r\n parent[r2] = r1\r\n rank[r1] += rank[r2]\r\n else:\r\n parent[r1] = r2\r\n if rank[r1] == rank[r2]: rank[r2] += rank[r1]\r\n\r\ndef kruskal(graph):\r\n\tF = set()\t\t\t\t\t\t\t# MST를 이루는 이음선의 집합\r\n\r\n\tfor v in graph['vertices']:\t\t\t# 초기 집합 생성\r\n\t\tmake_singleton_set(v)\r\n\r\n\tedges = list(graph['edges'])\t\t# set을 list로 변경 후 오름차순으로 정렬\r\n\tedges.sort()\r\n\tn = len(graph['vertices']) # 정점의 개수 n = 5\r\n\r\n\tk = 0\r\n\twhile (len(F) < n - 1):\t\t\t\t# F에 속하는 edge의 개수가 n-1보다 작다.\r\n\t\ti, j = edges[k][1], edges[k][2]\r\n\t\tp = find(i)\r\n\t\tq = find(j)\r\n\t\tif p != q:\t\t\t\t\t\t# 두 부분집합이 서로소인 경우\r\n\t\t\tunion(p, q)\t\t\t\t\t# 두 부분집합을 하나로 합친다.\r\n\t\t\tF.add(edges[k])\t\t\t\t# F에 해당 edge를 추가한다.\r\n\t\tk += 1\r\n\r\n\treturn F\r\n\r\ngraph = {\r\n 'vertices': ['A', 'B', 'C', 'D', 'E'],\r\n 'edges': set([\r\n (1, 'A', 'B'),\r\n (3, 'A', 'C'),\r\n (3, 'B', 'C'),\r\n (6, 'B', 'D'),\r\n (4, 'C', 'D'),\r\n (2, 'C', 'E'),\r\n (5, 'D', 'E'),\r\n ])\r\n }\r\n\r\nmst = kruskal(graph)\r\nprint(\"F : \", mst)\r\n","sub_path":"Python/2020-2_알고리즘분석/4_Greedy/4_2_MST_KruskalAlgorithm.py","file_name":"4_2_MST_KruskalAlgorithm.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"195504167","text":"import time\n\nimport numpy as np\n\nimport imgaug as ia\nimport torch\n\n\nfrom . import functional as F\n\n\n\ndef do_assert(condition, message=\"Assertion failed.\"):\n\t\"\"\"\n\tFunction that behaves equally to an `assert` statement, but raises an\n\tException.\n\n\tThis is added because `assert` statements are removed in optimized code.\n\tIt replaces `assert` statements throughout the library that should be\n\tkept even in optimized code.\n\n\tParameters\n\t----------\n\tcondition : bool\n\t\tIf False, an exception is raised.\n\n\tmessage : string, optional(default=\"Assertion failed.\")\n\t\tError message.\n\n\t\"\"\"\n\tif not condition:\n\t\traise AssertionError(str(message))\n\n\nclass Sometimes(object):\n\n\tdef __init__(self, transform, p ):\n\n\t\tself.transform = transform\n\n\t\tself.p = ia.parameters.Binomial(p)\n\n\n\n\tdef __call__(self, images):\n\n\t\tnb_images = len(images) # 120 x 3 x H x W\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\n\t\tsamples= self.p.draw_samples((nb_images,), random_state=rs_image)\n\t\tsamples_true_index = np.where(samples == 1)[0]\n\t\tsamples_false_index = np.where(samples == 0)[0]\n\n\n\t\t# Check for the zero case , related to pytorch isuee of not accepting zero size array\n\n\t\tif samples_true_index.size > 0:\n\t\t\tsamples_true_index = torch.cuda.LongTensor(samples_true_index)\n\t\t\timages_to_transform = torch.index_select(images, 0, samples_true_index)\n\t\t\tif samples_false_index.size > 0:\n\n\t\t\t\t# images_not_to_transform = torch.index_select(images, 0, torch.cuda.LongTensor(\n\t\t\t\t# samples_false_index))\n\n\t\t\t\ttransformed_imgs = self.transform(images_to_transform)\n\t\t\t\timages = images.index_copy_(0, samples_true_index, transformed_imgs)\n\t\t\t\treturn images\n\t\t\t\t# return torch.cat((self.transform(images_to_transform), images_not_to_transform), 0)\n\n\t\t\telse:\n\t\t\t\treturn self.transform(images)\n\n\t\telse:\n\t\t\treturn images\n\n\n\n\n\nclass Add(ia.augmenters.Add):\n\n\t\"\"\"\n\t\tWrapper for adding class from imgaug\n\n\t\"\"\"\n\tdef __call__(self, images):\n\t\t# input_dtypes = copy_dtypes_for_restore(images, force_list=True)\n\t\tresult = images\n\t\tnb_images = len(images)\n\t\t# Generate new seeds con\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\t\tper_channel = self.per_channel.draw_sample(random_state=rs_image)\n\n\t\tif per_channel == 1:\n\t\t\tnb_channels = images.shape[1]\n\n\t\t\tfor c in range(nb_channels):\n\t\t\t\tsamples = self.value.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(\n\t\t\t\t\tnp.float32)\n\t\t\t\tdo_assert(samples.all() >= 0)\n\n\t\t\t\tresult[:, c:(c+1), ...] = F.add(images[:, c:(c+1), ...], torch.cuda.FloatTensor(samples))\n\n\t\telse:\n\t\t\tsamples = self.value.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(np.float32)\n\t\t\tdo_assert(samples.all() >= 0)\n\n\t\t\tresult = F.add(images, torch.cuda.FloatTensor(samples))\n\n\t\t# image = meta.clip_augmented_image_(image, 0, 255) # TODO make value range more flexible\n\t\t# image = meta.restore_augmented_image_dtype_(image, input_dtypes[i])\n\n\t\treturn result\n\n\n\n\nclass Multiply(ia.augmenters.Multiply):\n\n\t\"\"\"\n\t\tWrapper for multiply class from imgaug\n\n\t\"\"\"\n\tdef __call__(self, images):\n\n\t\tresult = images\n\t\tnb_images = len(images)\n\t\t# Generate new seeds con\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\t\tper_channel = self.per_channel.draw_sample(random_state=rs_image)\n\n\t\tif per_channel == 1:\n\t\t\tnb_channels = images.shape[1] #Considering (N C H W)\n\n\t\t\tfor c in range(nb_channels):\n\t\t\t\tsamples = self.mul.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(\n\t\t\t\t\tnp.float32)\n\t\t\t\tdo_assert(samples.all() >= 0)\n\n\t\t\t\tresult[:, c:(c+1), ...] = F.multiply(images[:, c:(c+1), ...], torch.cuda.FloatTensor(samples))\n\n\t\telse:\n\t\t\tsamples = self.mul.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(np.float32)\n\t\t\tdo_assert(samples.all() >= 0)\n\t\t\tresult = F.multiply(images, torch.cuda.FloatTensor(samples))\n\n\t\treturn result\n\n\n\n\n\n\nclass MultiplyElementwise(ia.augmenters.MultiplyElementwise):\n\t\"\"\"\n\tWrapper\n\t\"\"\"\n\n\tdef __init__(self, mul=1.0, per_channel=False, name=None, deterministic=False, random_state=None):\n\t\tsuper(MultiplyElementwise, self).__init__(name=name, deterministic=deterministic, random_state=random_state)\n\t\tself.prob = mul\n\n\t\t\"\"\"\n\t\tif ia.is_single_number(mul):\n\t\t\tassert mul >= 0.0, \"Expected multiplier to have range [0, inf), got value %.4f.\" % (mul,)\n\t\t\tself.mul = ia.parameters.Deterministic(mul)\n\t\telif ia.is_iterable(mul):\n\t\t\tassert len(mul) == 2, \"Expected tuple/list with 2 entries, got %d entries.\" % (len(mul),)\n\t\t\tself.mul = ia.parameters.Uniform(mul[0], mul[1])\n\t\telif isinstance(mul, ia.parameters.StochasticParameter):\n\t\t\tself.mul = mul\n\t\telse:\n\t\t\traise Exception(\"Expected float or int, tuple/list with 2 entries or StochasticParameter. Got %s.\" % (type(mul),))\n\n\t\tif per_channel in [True, False, 0, 1, 0.0, 1.0]:\n\t\t\tself.per_channel = ia.parameters.Deterministic(int(per_channel))\n\t\telif ia.is_single_number(per_channel):\n\t\t\tassert 0 <= per_channel <= 1.0\n\t\t\tself.per_channel = ia.parameters.Binomial(per_channel)\n\t\telse:\n\t\t\traise Exception(\"Expected per_channel to be boolean or number or StochasticParameter\")\n\t\t\"\"\"\n\n\n\tdef __call__(self, images):\n\n\t\t\"\"\"\n\t\tnb_images = len(images)\n\n\n\t\tnb_channels, height, width = images[0].shape\n\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\n\n\t\tper_channel = self.per_channel.draw_sample(random_state=rs_image)\n\t\tif per_channel == 1:\n\n\t\t\tsamples = self.mul.draw_samples((nb_images, height, width, nb_channels), random_state=rs_image)\n\n\n\t\telse:\n\t\t\tcapture_time = time.time()\n\t\t\tsamples = self.mul.draw_samples((nb_images, height, width, 1), random_state=rs_image)\n\t\t\tprint (\"Sampling time \", time.time() - capture_time)\n\t\t\tprint(samples.shape)\n\n\t\t\tcapture_time = time.time()\n\t\t\tsamples = np.tile(samples, (1, 1, 1, nb_channels))\n\t\t\tprint (\"Tiling time \", time.time() - capture_time)\n\t\t\tprint (samples.shape)\n\n\t\tsamples = np.swapaxes(samples, 1, 3)\n\t\tsamples = np.swapaxes(samples, 2, 3)\n\t\t\"\"\"\n\n\n\t\treturn F.multiply_element_wise(images, self.prob)\n\n\n\ndef Dropout(p=0, per_channel=False, name=None, deterministic=False,\n\t\t\trandom_state=None):\n\t\"\"\"\n\t\tCopy of IMGAUG dropout,\n\t\tTODO: how to I basically make imgaug dropout to call my multiply elemenwise ?\n\t\"\"\"\n\tif ia.is_single_number(p):\n\t\tp2 = ia.parameters.Binomial(1 - p)\n\telif isinstance(p, (tuple, list)):\n\t\tdo_assert(len(p) == 2)\n\t\tdo_assert(p[0] < p[1])\n\t\tdo_assert(0 <= p[0] <= 1.0)\n\t\tdo_assert(0 <= p[1] <= 1.0)\n\t\tp2 = ia.parameters.Binomial(ia.parameters.Uniform(1 - p[1], 1 - p[0]))\n\telse:\n\t\traise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\treturn MultiplyElementwise(p2, per_channel=per_channel, name=name, deterministic=deterministic, random_state=random_state)\n\n\n\n\ndef CoarseDropout(p=0, size_px=None, size_percent=None,\n\t\t\t\t per_channel=False, min_size=4, name=None, deterministic=False,\n\t\t\t\t random_state=None):\n\t\"\"\"\n\tThe version exactly the same, it would be nice to just route the calling from IMGaug\n\t\"\"\"\n\tif ia.is_single_number(p):\n\t\tp2 = ia.parameters.Binomial(1 - p)\n\telif ia.is_iterable(p):\n\t\tdo_assert(len(p) == 2)\n\t\tdo_assert(p[0] < p[1])\n\t\tdo_assert(0 <= p[0] <= 1.0)\n\t\tdo_assert(0 <= p[1] <= 1.0)\n\t\tp2 = ia.parameters.Binomial(ia.parameters.Uniform(1 - p[1], 1 - p[0]))\n\telif isinstance(p, ia.parameters.StochasticParameter):\n\t\tp2 = p\n\telse:\n\t\traise Exception(\"Expected p to be float or int or StochasticParameter, got %s.\" % (type(p),))\n\n\tif size_px is not None:\n\t\tp3 = ia.parameters.FromLowerResolution(other_param=p2, size_px=size_px, min_size=min_size)\n\telif size_percent is not None:\n\t\tp3 = ia.parameters.FromLowerResolution(other_param=p2, size_percent=size_percent, min_size=min_size)\n\telse:\n\t\traise Exception(\"Either size_px or size_percent must be set.\")\n\n\n\treturn MultiplyElementwise(p3, per_channel=per_channel, name=name, deterministic=deterministic, random_state=random_state)\n\n\n\n\nclass ContrastNormalization(ia.augmenters.ContrastNormalization):\n\n\n\n\tdef __call__(self, images):\n\n\t\tresult = images\n\t\tnb_images = len(images)\n\t\t# Generate new seeds con\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\t\tper_channel = self.per_channel.draw_sample(random_state=rs_image)\n\n\t\tif per_channel == 1:\n\t\t\tnb_channels = images.shape[1] #Considering (N C H W)\n\n\t\t\tfor c in range(nb_channels):\n\t\t\t\talphas = self.alpha.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(\n\t\t\t\t\tnp.float32)\n\t\t\t\tdo_assert(alphas.all() >= 0)\n\n\t\t\t\tresult[:, c:(c+1), ...] = F.contrast(images[:, c:(c+1), ...], torch.cuda.FloatTensor(alphas))\n\n\t\telse:\n\t\t\talphas = self.alpha.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(np.float32)\n\t\t\tdo_assert(alphas.all() >= 0)\n\n\t\t\t#print(alphas)\n\n\t\t\tresult = F.contrast(images, torch.cuda.FloatTensor(alphas))\n\t\treturn result\n\n\n\n\n\n\nclass GaussianBlur(ia.augmenters.GaussianBlur): # pylint: disable=locally-disabled, unused-variable, line-too-long\n\n\n\n\tdef __call__ (self, images):\n\n\t\tresult = images\n\t\tnb_images = len(images)\n\n\t\tnb_channels, height, width = images[0].shape\n\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\n\t\tsamples = self.sigma.draw_samples((nb_images,), random_state=rs_image)\n\n\n\n\t\t# note that while gaussian_filter can be applied to all channels\n\t\t# at the same time, that should not be done here, because then\n\t\t# the blurring would also happen across channels (e.g. red\n\t\t# values might be mixed with blue values in RGB)\n\t\tfor c in range(nb_channels):\n\n\t\t\tresult[:, c:(c+1), ...] = F.blur(result[:, c:(c+1), ...], samples)\n\n\t\treturn result\n\n\n\n\nclass AddElementwise(ia.augmenters.AddElementwise):\n\n\n\n\tdef __init__(self, value=0, per_channel=False, name=None, deterministic=False, random_state=None):\n\t\t\"\"\"Create a new AddElementwise instance.\n\n\n\t\t\"\"\"\n\t\tself.value = value\n\n\tdef __call__(self, images):\n\n\t\t\"\"\"\n\t\tnb_images = len(images)\n\n\n\t\tnb_channels, height, width = images[0].shape\n\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\n\t\tper_channel = self.per_channel.draw_sample(random_state=rs_image)\n\t\tif per_channel == 1:\n\t\t\tsamples = self.value.draw_samples((nb_images, height, width, nb_channels), random_state=rs_image)\n\n\n\t\telse:\n\t\t\tsamples = self.value.draw_samples((nb_images, height, width, 1), random_state=rs_image)\n\n\t\t\tsamples = np.tile(samples, (1, 1, 1, nb_channels))\n\n\n\t\tsamples = np.swapaxes(samples, 1, 3)\n\t\tsamples = np.swapaxes(samples, 2, 3)\n\t\t\"\"\"\n\n\t\treturn F.add_element_wise(images, self.value)\n\n\n\n\n\ndef AdditiveGaussianNoise(loc=0, scale=0, per_channel=False, name='None', deterministic=False, random_state=None):\n\n\tif ia.is_single_number(loc):\n\t\tloc2 = ia.parameters.Deterministic(loc)\n\telif ia.is_iterable(loc):\n\t\tassert len(loc) == 2, \"Expected tuple/list with 2 entries for argument 'loc', got %d entries.\" % (len(scale),)\n\t\tloc2 = ia.parameters.Uniform(loc[0], loc[1])\n\telif isinstance(loc, ia.parameters.StochasticParameter):\n\t\tloc2 = loc\n\telse:\n\t\traise Exception(\"Expected float, int, tuple/list with 2 entries or StochasticParameter for argument 'loc'. Got %s.\" % (type(loc),))\n\n\tif ia.is_single_number(scale):\n\t\tscale2 = ia.parameters.Deterministic(scale)\n\telif ia.is_iterable(scale):\n\t\tassert len(scale) == 2, \"Expected tuple/list with 2 entries for argument 'scale', got %d entries.\" % (len(scale),)\n\t\tscale2 = ia.parameters.Uniform(scale[0], scale[1])\n\telif isinstance(scale, ia.parameters.StochasticParameter):\n\t\tscale2 = scale\n\telse:\n\t\traise Exception(\"Expected float, int, tuple/list with 2 entries or StochasticParameter for argument 'scale'. Got %s.\" % (type(scale),))\n\n\treturn AddElementwise(scale,\n\t\t\t\t\t\t per_channel=per_channel, name=name,\n\t\t\t\t\t\t deterministic=deterministic, random_state=random_state)\n\n\n\n\nclass ChangeColorspace(ia.augmenters.ChangeColorspace):\n\t\"\"\"\n\tAugmenter to change the colorspace of images.\n\n\t\"\"\"\n\n\n\tdef __call__(self, images):\n\n\n\n\t\t# Convert to Grayscale direction\n\n\t\tnb_images = len(images)\n\t\t# Generate new seeds con\n\t\tseeds = ia.current_random_state().randint(0, 10**6, (nb_images,))\n\t\trs_image = ia.new_random_state(seeds[0])\n\n\t\tsamples = self.alpha.draw_samples((nb_images, 1, 1, 1), random_state=rs_image).astype(np.float32)\n\t\tdo_assert(samples.all() >= 0)\n\t\tresult = F.grayscale(images, torch.cuda.FloatTensor(samples))\n\n\t\treturn result\n\n\n\n\n# TODO tests\n# TODO rename to Grayscale3D and add Grayscale that keeps the image at 1D\ndef Grayscale(alpha=0, from_colorspace=\"RGB\", name=None,\n\t\t\t deterministic=False, random_state=None):\n\n\n\treturn ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha,\n\t\t\t\t\t\t\tfrom_colorspace=from_colorspace, name=name,\n\t\t\t\t\t\t\tdeterministic=deterministic, random_state=random_state)\n","sub_path":"imgaug_gpu/build/lib/imgauggpu/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":12842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"424904240","text":"col, row = map(int, input().split())\n\nmatrix = []\nfor i in range(row): # 줄 수 만큼 반복\n matrix.append(list(input())) # 입력한 값 리스트 생성\n # 생성한 리스트 matrix 리스트 요소로 추가 \n \nfor i in range(len(matrix)): \n for j in range(len(matrix[i])):\n \n print(matrix[i][j])\n print()","sub_path":"study/3/23_1.py","file_name":"23_1.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"340606710","text":"#!/usr/bin/env python\n#\n# Build dynamic library with JNI using user-provided arguments and place it to resources directory\n# of Maven package\n#\n# NOTE: this script must be python2/3 compatible\n\nfrom __future__ import absolute_import, print_function\n\nimport contextlib\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\n\n@contextlib.contextmanager\ndef _tempdir(prefix=None):\n tmp_dir = tempfile.mkdtemp(prefix=prefix)\n yield tmp_dir\n # TODO(yazevnul): log error\n shutil.rmtree(tmp_dir, ignore_errors=True)\n\n\ndef _get_platform():\n if sys.platform.startswith('linux'):\n return 'linux'\n return sys.platform\n\n\ndef _get_arcadia_root():\n arcadia_root = None\n path = os.path.dirname(os.path.abspath(sys.argv[0]))\n while True:\n if os.path.isfile(os.path.join(path, '.arcadia.root')):\n arcadia_root = path\n break\n\n if path == os.path.dirname(path):\n break\n\n path = os.path.dirname(path)\n\n assert arcadia_root is not None, 'you are probably trying to use this script with repository being checkout not from the root'\n return arcadia_root\n\n\ndef _get_ya_path():\n ya_path = os.path.join(_get_arcadia_root(), 'ya')\n assert os.path.isfile(ya_path), 'no `ya` in arcadia root'\n assert os.access(ya_path, os.X_OK), '`ya` must be executable'\n return ya_path\n\n\ndef _get_package_resources_dir():\n return os.path.join(\n _get_arcadia_root(),\n os.path.join(*'catboost/jvm-packages/catboost4j-prediction/src/main/resources'.split('/')))\n\n\ndef _get_native_lib_dir(relative=None):\n if relative is None:\n relative = _get_arcadia_root()\n return os.path.join(\n relative,\n os.path.join(*'catboost/jvm-packages/catboost4j-prediction/src/native'.split('/')))\n\n\ndef _ensure_dir_exists(path):\n try:\n os.makedirs(path)\n except OSError as e:\n import errno\n if e.errno != errno.EEXIST:\n raise\n\n\ndef _get_current_machine_resources_dir():\n return ''.join((_get_platform(), '-', platform.machine()))\n\n\ndef _main():\n ya_path = _get_ya_path()\n shared_lib_dir = os.path.join(\n _get_package_resources_dir(),\n _get_current_machine_resources_dir(),\n 'lib')\n native_lib_dir = _get_native_lib_dir()\n env = os.environ.copy()\n\n print('building dynamic library with `ya`', file=sys.stderr)\n sys.stderr.flush()\n\n with _tempdir(prefix='catboost_build-') as build_output_dir:\n ya_make = ([sys.executable, ya_path, 'make', native_lib_dir]\n + ['--output', build_output_dir]\n + ['-D', 'CATBOOST_OPENSOURCE=yes']\n + ['-D', 'CFLAGS=-DCATBOOST_OPENSOURCE=yes']\n + sys.argv[1:])\n subprocess.check_call(\n ya_make,\n env=env,\n stdout=sys.stdout,\n stderr=sys.stderr)\n\n _ensure_dir_exists(shared_lib_dir)\n native_lib_name = {\n 'darwin': 'libcatboost4j-prediction.dylib',\n 'win32': 'catboost4j-prediction.dll',\n 'linux': 'libcatboost4j-prediction.so',\n }[_get_platform()]\n\n print('copying dynamic library to resources/lib', file=sys.stderr)\n shutil.copy(\n os.path.join(_get_native_lib_dir(build_output_dir), native_lib_name),\n shared_lib_dir)\n\n\nif '__main__' == __name__:\n _main()\n","sub_path":"catboost/jvm-packages/catboost4j-prediction/src/native/build_for_maven.py","file_name":"build_for_maven.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"291440075","text":"from flask import Flask, render_template\n\n\nimport lotto_package as lp\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/pick_lotto')\ndef pick_lotto():\n lucky_numbers = lp.get_random_numbers()\n # return f'이번주 로또 예상 번호는 {lucky_numbers}입니다.'\n return render_template('pick_lotto.html', numbers=lucky_numbers)\n\n\n@app.route('/find_lotto/')\ndef find_lotto(num):\n data = lp.get_lotto_numbers(num)\n\n return render_template('find_lotto.html', numbers=data, num=num)\n\n\n@app.route('/lotto/')\ndef lotto(num):\n lucky_numbers = lp.get_random_numbers()\n\n real_data = lp.get_lotto_numbers(num)\n real_numbers = real_data['real']\n bonus_number = real_data['bonus']\n winning_ammount = real_data['winning']\n rank = lp.get_result(lucky_numbers, real_numbers, bonus_number)\n\n\n return render_template('lotto.html',\n my_numbers=lucky_numbers,\n times=num,\n lotto_numbers=real_numbers,\n bonus_number=bonus_number,\n rank=rank,\n winning=winning_ammount)\n\n\n@app.route('/square/')\ndef square(num):\n result = num**2\n return f'{result}'\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"3_Flask/first_flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"615811835","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 16 15:37:15 2019\n\n@author: davidblair\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils import data\nfrom scipy import sparse\nfrom typing import Iterable\nfrom collections import OrderedDict\nfrom sklearn.utils import shuffle\nimport copy\nimport pickle\nimport itertools\nfrom vlpi.utils.UtilityFunctions import one_hot_scipy,one_hot\nfrom vlpi.data.ICDUtilities import ICDUtilities\n\nclass ClinicalDataset:\n\n def none_to_int(self,val):\n if val!=None:\n return 1\n else:\n return 0\n\n def initialize_empty_df(self,columns, dtypes, index=None):\n assert len(columns)==len(dtypes)\n df = pd.DataFrame(index=index)\n for c,d in zip(columns, dtypes):\n df[c] = pd.Series(dtype=d)\n return df\n\n def _parseICDCodeList(self,codeList):\n codeList = list(set(codeList.strip().split(',')))\n codeList=[x.strip() for x in codeList if x.strip()!='']\n\n newCodeList=[]\n for code in codeList:\n try:\n newCodeList+=[self.dxCodeToDataIndexMap[code]]\n except KeyError:\n pass\n\n return newCodeList\n\n def _parseCatCov(self,covList,catCovNames):\n covVals = []\n for i,covName in enumerate(catCovNames):\n try:\n covVals+=[(covName,self.catCovConversionDicts[covName][covList[i]])]\n except KeyError:\n newIndex = len(self.catCovConversionDicts[covName])\n self.catCovConversionDicts[covName][covList[i]]=newIndex\n covVals+=[(covName,newIndex)]\n return covVals\n\n\n def __init__(self,ICDFilePaths:Iterable[str]=[]):\n \"\"\"\n\n\n Parameters\n ----------\n ICDFilePaths : Iterable[str], optional\n This passes a list of strings ([ICD_hierarchy, ICD_chapters], see ICDUtilities) in order to initialize Dx Code data structure and mappings. This is only relevant when constructing new datasets from a flat text file. Otherwise, the Dx Code information is read from the stored ClinicalDataset Object, so the file paths are irrelevant. By default, the class instantiates the 2018 ICD10-CM coding structure, which is included with the software (as is the UKBB ICD10 encoding structure, downloaded in Jan 2020).\n\n The default is value [], which defaults to ICD10-CM 2018.\n\n Returns\n -------\n None.\n\n \"\"\"\n if len(ICDFilePaths)==0:\n self.ICDInfo=ICDUtilities()\n else:\n assert len(ICDFilePaths)==2, \"Expects a list containing 2 elecments: file paths for ICD10 hierarchy and chapters\"\n self.ICDInfo=ICDUtilities(hierarchyFile=ICDFilePaths[0],chapterFile=ICDFilePaths[1])\n\n #initialize the clinical data structure to line up with the ICD codebook,\n #although the clinical dataset need not correspond strictly to ICD codes (and this is frequently true)\n self.dxCodeToDataIndexMap = copy.deepcopy(self.ICDInfo.usableCodeToIndexMap)\n self.dataIndexToDxCodeMap = dict(zip(self.dxCodeToDataIndexMap.values(),self.dxCodeToDataIndexMap.keys()))\n\n self.numDxCodes = len(self.dxCodeToDataIndexMap)\n self.data=None\n self.catCovConversionDicts={}\n\n def ReadDatasetFromFile(self,clinicalDataset,dxCodeColumn,indexColumn = None, skipColumns=[], hasHeader=True,chunkSize = 500):\n \"\"\"\n\n Initializes the Pandas clinical dataset by reading it from a text file.\n\n Expects that clinical dataset is in ICD format. Can transition to other formats (HPO)\n by using using ConvertCodes function.\n\n Parameters\n ----------\n clinicalDataset : str\n File Name for clinical dataset.\n dxCodeColumn : int\n Column that contains a comma-separated list of associated ICD codes, first column denoted by 0\n indexColumn : int\n Column to use as index for the dataset\n skipColumns : list of ints\n List that indicates which columns should be skipped [uses 0-based indexing]\n hasHeader : type\n Indicates whether file has header, which is used to generate column names\n chunkSize : type\n Indicates how often database should be written into. Defaults to every 500 lines.\n\n Returns\n -------\n None\n\n \"\"\"\n\n assert chunkSize >1, \"chunkSize must be > 1\"\n clinicalFile = open(clinicalDataset)\n if hasHeader:\n headLine = clinicalFile.readline().strip('\\n').split('\\t')\n catCovNames = [h for h in headLine if headLine.index(h) not in [dxCodeColumn,indexColumn]+skipColumns]\n else:\n pos=clinicalFile.tell()\n currentLine = clinicalFile.readline().strip('\\n').split('\\t')\n catCovNames=['Covariate_'+str(i+1) for i in range(len(currentLine)-(1+self.none_to_int(indexColumn)+len(skipColumns)))]\n clinicalFile.seek(pos)\n\n colNames = ['patient_id','dx_codes']+catCovNames\n\n self.catCovConversionDicts = {covName:{} for covName in catCovNames}\n self.data = self.initialize_empty_df(colNames,[np.int64,object]+[np.int32 for i in range(len(catCovNames))])\n patientCounter = int(0)\n currentDataList ={colName:[] for colName in self.data.columns}\n for line in clinicalFile:\n line = line.strip('\\n').split('\\t')\n currentDataList['dx_codes']+=[self._parseICDCodeList(line[dxCodeColumn])]\n for nm, val in self._parseCatCov([line[i] for i in range(len(line)) if i not in [dxCodeColumn,indexColumn]+skipColumns],catCovNames):\n currentDataList[nm]+=[val]\n\n if indexColumn!=None:\n currentDataList['patient_id']+=[int(line[indexColumn])]\n else:\n currentDataList['patient_id']+=[patientCounter]\n patientCounter+=1\n if patientCounter % chunkSize==0:\n self.data=self.data.append(pd.DataFrame(currentDataList),ignore_index=True)\n currentDataList ={colName:[] for colName in self.data.columns}\n\n\n if len(currentDataList['patient_id'])>0:\n self.data=self.data.append(pd.DataFrame(currentDataList),ignore_index=True)\n\n #shuffle data and create new index\n self.data = self.data.sample(frac=1).reset_index(drop=True)\n self.data.set_index('patient_id',drop=False, inplace=True)\n\n\n def FindAllPatients_wDx(self,dx_code):\n \"\"\"\n\n Finds all patients with a particular dx code, returns their index vals.\n\n Parameters\n ----------\n dx_code : str\n ICD code string.\n\n Returns\n -------\n pd.Series\n Series containing index of patients with particular diagnosis.\n\n \"\"\"\n if '.' in dx_code:\n dx_code.replace('.','')\n intVal = self.dxCodeToDataIndexMap[dx_code]\n return self.data['patient_id'][self.data['dx_codes'].apply(lambda x: intVal in x)]\n\n\n def IncludeOnly(self,dx_code_list):\n \"\"\"\n Removes all dx_codes from the dataset except those from the dx_code_list.\n\n Parameters\n ----------\n dx_code_list : list of str\n List of ICD10 strings to include.\n\n Returns\n -------\n None\n\n \"\"\"\n\n\n dx_code_list=[x.replace('.','') for x in dx_code_list]\n allKept = set([self.dxCodeToDataIndexMap[x] for x in dx_code_list])\n\n #now we need to remove all non-kept codes from the ICD conversion dictionaries\n removedCodes = set(self.dxCodeToDataIndexMap.keys()).difference(dx_code_list)\n\n for old_code in removedCodes:\n del self.dxCodeToDataIndexMap[old_code]\n\n self.dataIndexToDxCodeMap = {}\n newCodeToIntMap = {}\n oldToNewIntMap={}\n for i,key in enumerate(self.dxCodeToDataIndexMap):\n oldToNewIntMap[self.dxCodeToDataIndexMap[key]]=i\n self.dataIndexToDxCodeMap[i]=key\n newCodeToIntMap[key] = i\n\n self.dxCodeToDataIndexMap=newCodeToIntMap\n if isinstance(self.data,pd.DataFrame):\n self.data['dx_codes']=self.data['dx_codes'].apply(lambda x: [oldToNewIntMap[y] for y in x if y in allKept])\n\n self.numDxCodes=len(self.dxCodeToDataIndexMap)\n\n def ConvertCodes(self,dx_code_list:Iterable[str],new_code:str):\n \"\"\"\n\n Converts set of ICD codes into a single dx code through logical-OR function. If given a single code, simply renames code as new_code.\n\n Parameters\n ----------\n dx_code_list : Iterable[str]\n List of codes to convert into a single, new code.\n new_code : str\n Name of new code\n\n Returns\n -------\n None\n \"\"\"\n\n assert len(dx_code_list)>0, \"dx_code_list must have one elemenent to collapse.\"\n dx_code_list=[x.replace('.','') for x in dx_code_list]\n\n #set the all codes in the list to the integer value of the first code in the list\n removedCodes = set(dx_code_list[1:])\n oldInts =[]\n for old_code in removedCodes:\n oldInts+=[self.dxCodeToDataIndexMap[old_code]]\n del self.dxCodeToDataIndexMap[old_code]\n\n\n if len(removedCodes)>0:\n self.dataIndexToDxCodeMap = {}\n newCodeToIntMap = {}\n oldToNewIntMap={}\n for i,key in enumerate(self.dxCodeToDataIndexMap):\n oldToNewIntMap[self.dxCodeToDataIndexMap[key]]=i\n self.dataIndexToDxCodeMap[i]=key\n newCodeToIntMap[key] = i\n\n self.dxCodeToDataIndexMap=newCodeToIntMap\n newInt = self.dxCodeToDataIndexMap[dx_code_list[0]]\n collapsedInt_to_Int = dict(zip(oldInts,[newInt for i in range(len(oldInts))]))\n oldToNewIntMap.update(collapsedInt_to_Int)\n if isinstance(self.data,pd.DataFrame):\n self.data['dx_codes']=self.data['dx_codes'].apply(lambda x: list(set([oldToNewIntMap[y] for y in x])))\n else:\n newInt = self.dxCodeToDataIndexMap[dx_code_list[0]]\n\n\n #update the code information\n\n self.dataIndexToDxCodeMap[newInt] = new_code\n self.dxCodeToDataIndexMap[new_code] = newInt\n del self.dxCodeToDataIndexMap[dx_code_list[0]]\n self.numDxCodes=len(self.dxCodeToDataIndexMap)\n\n\n def ConstructNewDataArray(self,oldCodeToNewMap):\n \"\"\"This function translates diagnostic codes and symptom data to a new encoding using the dictionary oldCodeToNewMap. The previous codes are provided as keys (strings), and the new codes as values (also strings). The names for the new codes will be changed automatically. Values can also be iterables such that the old code maps to multiple new ones. Any code not provided as a key in the input dictionary will be dropped from the dataset.\n\n Parameters\n ----------\n oldCodeToNewMap : dict\n Key,value pairs indicating translation of old codes to new.\n\n Returns\n -------\n None\n\n \"\"\"\n allNewCodes = sorted(list(set().union(*oldCodeToNewMap.values())))\n newCodeToIntMap = dict(zip(allNewCodes,range(len(allNewCodes))))\n newIntToCodeMap = dict(zip(newCodeToIntMap.values(),newCodeToIntMap.keys()))\n if self.data is not None:\n def _convFunc(x):\n newDxSet=set([])\n for dx in x:\n try:\n newDxSet.update(oldCodeToNewMap[self.dataIndexToDxCodeMap[dx]])\n except KeyError:\n pass\n return list({newCodeToIntMap[x] for x in newDxSet})\n\n self.data['dx_codes'] = self.data['dx_codes'].apply(_convFunc)\n self.dataIndexToDxCodeMap = newIntToCodeMap\n self.dxCodeToDataIndexMap = newCodeToIntMap\n self.numDxCodes=len(self.dxCodeToDataIndexMap)\n\n def ExcludeAll(self,dx_code_list):\n \"\"\"\n Removes all codes in dx_code_list from the dataset\n\n Parameters\n ----------\n dx_code_list : list\n List of diagnostic codes to drop from the dataset.\n\n Returns\n -------\n None\n\n \"\"\"\n\n keptCodes = set(self.dxCodeToDataIndexMap.keys()).difference(dx_code_list)\n self.IncludeOnly(list(keptCodes))\n\n def ConditionOnDx(self,dx_code_list):\n \"\"\"\n\n This function conditions the data table on whether a patient has each diagnosis in the list 'dx_code_list'. This is accomplished by finding all patients with each diagnosis in 'dx_code_list', then adding a column (boolean) to the data table indicating diagnostic status. Each column will be named 'has_DX_CODE', where DX_CODE is the diagnostic code being conditioned on. These codes are then removed from the symptom data table. This function is expecially useful for supervised learning, as it creates labels from diagnostic codes.\n\n Parameters\n ----------\n dx_code_list : list of st\n List of codes to on which to condition the dataset\n\n Returns\n -------\n None.\n\n \"\"\"\n\n for dx_code in dx_code_list:\n dx_code.replace('.','')\n allPatients_wDx=self.FindAllPatients_wDx(dx_code)\n hasDx=np.zeros(self.data.shape[0],dtype=np.bool)\n self.data.insert(len(self.data.columns),'has_'+dx_code,hasDx)\n self.data.loc[allPatients_wDx,'has_'+dx_code]=True\n self.ExcludeAll(dx_code_list)\n\n\n\n def WriteToDisk(self,fileName):\n \"\"\"\n\n Writes ClinicalDataset to disk. Recommended way to store data after parsing text file.\n\n Parameters\n ----------\n fileName : str\n Path to storage file.\n\n Returns\n -------\n None\n\n \"\"\"\n\n if fileName[-4:]!='.pth':\n fileName+='.pth'\n with open(fileName,'wb') as f:\n pickle.dump(self.data,f,protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(self.catCovConversionDicts,f,protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(self.dxCodeToDataIndexMap,f,protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(self.dataIndexToDxCodeMap,f,protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(self.numDxCodes,f,protocol=pickle.HIGHEST_PROTOCOL)\n\n def ReadFromDisk(self,fileName):\n \"\"\"\n\n Reads ClinicalDataset written with WriteToDisk. To load a previously processed dataset, you must instantiate a ClinicalDataset class, which can then be used to read the file.\n\n Parameters\n ----------\n fileName : str\n Path to storage file.\n\n Returns\n -------\n None\n\n \"\"\"\n\n if fileName[-4:]!='.pth':\n fileName+='.pth'\n with open(fileName,'rb') as f:\n self.data = pickle.load(f)\n self.catCovConversionDicts = pickle.load(f)\n self.dxCodeToDataIndexMap = pickle.load(f)\n self.dataIndexToDxCodeMap = pickle.load(f)\n self.numDxCodes = pickle.load(f)\n\n\n\n\n def LoadFromArrays(self,incidenceArray,covariateArrays,covariateNames,catCovDicts=None, arrayType = 'Numpy'):\n \"\"\"\n\n Loads clinical dataset from array data, generally used for simulation purposes. However, could also be used to bypass the ICD10 structure and load custom binary datasets. Dataset would need to be manipulated ahead of time using ConvertCodes and IncludeOnly to obtain a dataset with the dimensions/labels. Input arrays must be Numpy or PyTorch tensors.\n\n Parameters\n ----------\n incidenceArray : np.array or torch.tensor\n Binary symptom array\n covariateArrays : list of numpy.array or torch.tensor\n List of categorical covariates, which contains one numpy.array/torch.tensor per covariate\n covariateNames : List of str\n List of names for covariates\n catCovDicts : list of dicts\n List of dictionaries (one for each covariate) that maps covariates to integer values. If not provided, this is done automatically\n arrayType : str\n Indictes the array type. Numpy arrays ['Numpy'] or pyTorch tensors ['Torch']. Default is Numpy.\n\n Returns\n -------\n None\n\n \"\"\"\n\n assert arrayType in ['Numpy','Torch'], \"Only Numpy arrarys or Torch tensors supported\"\n if covariateArrays==None:\n covariateArrays=[]\n if covariateNames==None:\n covariateNames=[]\n assert len(covariateArrays)==len(covariateNames), \"Number of covariate names does not match number of covariate arrays.\"\n assert incidenceArray.shape[1]==self.numDxCodes, \"Dimension of incidence data does not match number of codes.\"\n\n if arrayType=='Torch':\n incidenceArray=incidenceArray.to('cpu').detach().numpy()\n covariateArrays=[x.to('cpu').detach().numpy().ravel() for x in covariateArrays]\n else:\n covariateArrays=[x.ravel() for x in covariateArrays]\n\n dataDict={}\n for i,name in enumerate(covariateNames):\n if catCovDicts == None:\n uniqueCats = list(set(covariateArrays[i]))\n self.catCovConversionDicts[name] = dict(zip(uniqueCats,list(range(len(uniqueCats)))))\n covariateArrays[i] = np.array([self.catCovConversionDicts[name][x] for x in covariateArrays[i]],dtype=np.int64)\n else:\n self.catCovConversionDicts[name]=catCovDicts[i]\n covariateArrays[i] = np.array([self.catCovConversionDicts[name][x] for x in covariateArrays[i]],dtype=np.int64)\n dataDict[name] = covariateArrays[i]\n\n dataDict['patient_id']=np.arange(incidenceArray.shape[0],dtype=np.int64)\n dataDict['dx_codes'] = [np.where(x==1)[0].tolist() for x in incidenceArray]\n\n self.data = pd.DataFrame(dataDict)\n self.data = self.data.sample(frac=1).reset_index(drop=True)\n self.data.set_index('patient_id',drop=False, inplace=True)\n\n def ReturnSparseDataMatrix(self,index:Iterable[int]=[]):\n \"\"\"\n\n Returns disease incidence array as sparse coo matrix. Takes optional index, which returns only data points contained within the index.\n\n Parameters\n ----------\n index : Iterable[int]\n Index of patients to include.\n\n Returns\n -------\n sparse.coo_matrix\n Sparse, binary array of diagnoses.\n\n \"\"\"\n\n if len(index)==0:\n index = self.data.index\n y_inds = list(itertools.chain.from_iterable(self.data.loc[index]['dx_codes']))\n x_inds = list(itertools.chain.from_iterable([[i]*len(x) for i,x in enumerate(self.data.loc[index]['dx_codes'])]))\n return sparse.coo_matrix((np.ones((len(x_inds))),(x_inds,y_inds)),shape=(len(index),self.numDxCodes),dtype=np.float32)\n\n\n\n\nclass ClinicalDatasetSampler():\n\n\n def _numpyWrapper(self,x):\n if x.dtype == np.float32:\n if sparse.issparse(x):\n return x.toarray()\n else:\n return np.array(x,dtype=np.float32)\n\n elif x.dtype == np.float64:\n if sparse.issparse(x):\n return x.toarray()\n else:\n return np.array(x,dtype=np.float64)\n else:\n if sparse.issparse(x):\n return x.toarray()\n else:\n return np.array(x,dtype=np.int64)\n\n def _scipySparseWrapper(self,x):\n if x.dtype == np.float32:\n if sparse.issparse(x):\n return x.tocsr()\n else:\n return sparse.csr_matrix(x,dtype=np.float32)\n\n elif x.dtype==np.float64:\n if sparse.issparse(x):\n return x.tocsr()\n else:\n return sparse.csr_matrix(x,dtype=np.float64)\n else:\n if sparse.issparse(x):\n return x.tocsr()\n else:\n return sparse.csr_matrix(x,dtype=np.int64)\n\n def _torchWrapper(self,x):\n\n \"\"\"\n Note, all torch floating point tensors are converted to 32-bits to\n ensure GPU compatibility.\n \"\"\"\n\n if x.dtype==np.float32:\n if sparse.issparse(x):\n return torch.tensor(x.toarray(),dtype = torch.float32)\n else:\n return torch.tensor(x,dtype = torch.float32)\n\n elif x.dtype==np.float64:\n if sparse.issparse(x):\n return torch.tensor(x.toarray(),dtype = torch.float32)\n else:\n return torch.tensor(x,dtype = torch.float32)\n else:\n if sparse.issparse(x):\n return torch.tensor(x.toarray(),dtype = torch.long)\n else:\n return torch.tensor(x,dtype = torch.long)\n\n\n def __init__(self, currentClinicalDataset,trainingFraction,conditionSamplingOnDx:Iterable[str]=[],returnArrays='Numpy',shuffle=True):\n \"\"\"\n\n Generates random samples from a clinical dataset. Samples can be generated unconditionially, or conditional on a patient having a particular dx. Note, that in the latter case, the dx will be removed from the dataset and included as a separate column in the data if not already done.\n\n Parameters\n ----------\n currentClinicalDataset : ClinicalDataset\n Instance of the class ClinicalDataset\n trainingFraction : type\n Fraction of dataset used for training. Must be between 0.0 and 1.0.\n conditionSamplingOnDx : Iterable[str]\n Allows sampling to be conditioned on a set of diagnoses such that at least one patient in every sample had at least one of the diagnoses in the set. Note: original dataset is modified.\n returnArrays : str\n Array type returned by the sampling. Can be 'Numpy', 'Sparse' or 'Torch'. In the case of Sparse arrays, incidence arrays are returned as csr matrices, 1-d covariate vectors default to COO format.\n shuffle : bool\n Indcates whether to shuffle the data prior to splitting into training and test sets. Defaults to True, only make False for very large datasets that have already been shuffled.\n\n Returns\n -------\n None\n\n \"\"\"\n self.conditionSamplingOnDx=conditionSamplingOnDx\n if len(conditionSamplingOnDx)>0:\n self.isConditioned = True\n else:\n self.isConditioned = False\n self.currentClinicalDataset=currentClinicalDataset\n self._returnAuxData=False\n self._auxDataset=None\n self.trainingFraction = trainingFraction\n assert self.trainingFraction >0.0 and self.trainingFraction<1.0, \"Fraction of dataset used for training must be between 0.0 and 1.0.\"\n self.fracWDx=0.0\n self.numTotalSamples = len(self.currentClinicalDataset.data)\n self.includedCovariates = self.currentClinicalDataset.catCovConversionDicts.keys()\n\n\n assert returnArrays in ['Numpy','Torch','Sparse'], \"Only Numpy arrarys, Torch tensors, or Scipy.Sparse (csr) supported\"\n\n self.returnArrays=returnArrays\n if returnArrays =='Numpy':\n self.arrayFunc = self._numpyWrapper\n elif returnArrays =='Torch':\n self.arrayFunc=self._torchWrapper\n else:\n self.arrayFunc=self._scipySparseWrapper\n\n\n\n\n if shuffle==True:\n self.currentClinicalDataset.data=self.currentClinicalDataset.data.sample(frac=1)\n\n if len(self.conditionSamplingOnDx)==0:\n self.currentClinicalDataset = currentClinicalDataset\n cutOffVal = int(np.floor(len(currentClinicalDataset.data)*self.trainingFraction))\n self.trainingDataIndex = currentClinicalDataset.data.index[0:cutOffVal]\n self.testDataIndex = currentClinicalDataset.data.index[cutOffVal:]\n else:\n conditionedColumns = set(['has_'+dx_code for dx_code in self.conditionSamplingOnDx])\n missingColumns = conditionedColumns.difference(self.currentClinicalDataset.data.columns)\n\n if len(missingColumns)>0:\n self.currentClinicalDataset.ConditionOnDx([x.replace('has_','') for x in missingColumns])\n\n has_at_least_one_dx = np.array(np.sum(np.vstack([self.currentClinicalDataset.data['has_'+dx] for dx in self.conditionSamplingOnDx]),axis=0),dtype=np.bool)\n dataWithDx = self.currentClinicalDataset.data.index[has_at_least_one_dx>0]\n dataWithoutDx = self.currentClinicalDataset.data.index[has_at_least_one_dx==0]\n self.fracWDx = len(dataWithDx)/len(self.currentClinicalDataset.data)\n cutOffValWDx = int(np.floor(len(dataWithDx)*self.trainingFraction))\n cutOffValWoDx = int(np.floor(len(dataWithoutDx)*self.trainingFraction))\n\n self.trainingDataIndex=[dataWithDx[0:cutOffValWDx],dataWithoutDx[0:cutOffValWoDx]]\n self.testDataIndex=[dataWithDx[cutOffValWDx:],dataWithoutDx[cutOffValWoDx:]]\n\n def DropSamples(self,index_vals,dropFromFullDataset=True):\n\n \"\"\"\n\n Parameters\n ----------\n index_vals : array\n Index values to drop from the dataset.\n\n dropFromFullDataset : boolean; default True\n Indicates whether to drop the samples from the full dataset rather than only the sampler. By default, drops from the full dataset to avoid cases where samples are returned because data is accessed outside of sampler.\n\n Returns\n -------\n None\n \"\"\"\n\n #first remove samples from indices\n if isinstance(self.trainingDataIndex,list)==False:\n self.trainingDataIndex=np.setdiff1d(self.trainingDataIndex,index_vals)\n self.testDataIndex=np.setdiff1d(self.testDataIndex,index_vals)\n else:\n self.trainingDataIndex=[np.setdiff1d(ind,index_vals) for ind in self.trainingDataIndex]\n self.testDataIndex=[np.setdiff1d(ind,index_vals) for ind in self.testDataIndex]\n if dropFromFullDataset==False:\n print(\"WARNING: Samples dropped from ClinicalDatasetSampler are still in the ClinicalDataset. Therefore, they can be returned by methods that bypass the Sampler!\")\n\n else:\n index_vals=self.currentClinicalDataset.data.index.intersection(index_vals)\n self.currentClinicalDataset.data.drop(index=index_vals,inplace=True)\n\n\n\n\n def ChangeArrayType(self,newArrayType):\n \"\"\"\n\n Changes the return array type.\n\n Parameters\n ----------\n newArrayType : str\n Must be one of 'Numpy','Torch','Sparse'\n\n Returns\n -------\n None\n\n \"\"\"\n\n assert newArrayType in ['Numpy','Torch','Sparse'], \"Only Numpy arrarys, Torch tensors, or Scipy.Sparse (csr) supported\"\n self.returnArrays=newArrayType\n if newArrayType =='Numpy':\n self.arrayFunc = self._numpyWrapper\n elif newArrayType =='Torch':\n self.arrayFunc=self._torchWrapper\n else:\n self.arrayFunc=self._scipySparseWrapper\n\n\n\n def WriteToDisk(self,fName):\n \"\"\"\n Writes sampler to disk so that it can be re-instantiated for further use. This is important for using the same test/training set across multiple models.\n\n Parameters\n ----------\n fName : str\n Path to storage file.\n\n Returns\n -------\n None\n\n \"\"\"\n\n if fName[-4:]!='.pth':\n fName+='.pth'\n currentSampler = OrderedDict()\n currentSampler['conditionSamplingOnDx']=self.conditionSamplingOnDx\n currentSampler['numTotalSamples'] = self.numTotalSamples\n currentSampler['trainingDataIndex']=self.trainingDataIndex\n currentSampler['testDataIndex']=self.testDataIndex\n currentSampler['trainingFraction']=self.trainingFraction\n currentSampler['fracWDx']=self.fracWDx\n\n\n with open(fName, 'wb') as f:\n pickle.dump(currentSampler,f)\n\n\n\n def ReadFromDisk(self,fName):\n \"\"\"\n Reads sampler from disk. This is important for using the same test/training set across multiple models.\n\n Parameters\n ----------\n fName : str\n Path to storage file.\n\n Returns\n -------\n None\n\n \"\"\"\n if fName[-4:]!='.pth':\n fName+='.pth'\n\n with open(fName, 'rb') as f:\n currentSampler = pickle.load(f)\n #assertions to make sure that sampler parameters match up\n\n assert currentSampler['numTotalSamples'] == self.numTotalSamples, \"Datasets used by saved and current sampler are different lengths! Suspect they are not referring to same dataset\"\n assert currentSampler['conditionSamplingOnDx']==self.conditionSamplingOnDx, \"Saved and current sampler are not conditioned on same dx\"\n assert currentSampler['trainingFraction']==self.trainingFraction,\"Saved and current sampler do not have the same training fraction\"\n self.testDataIndex=currentSampler['testDataIndex']\n self.trainingDataIndex=currentSampler['trainingDataIndex']\n self.fracWDx=currentSampler['fracWDx']\n\n def ConvertToUnconditional(self):\n \"\"\"\n\n Converts a previously conditional sampler to unconditional while keeping the same testing and training sets. This way, the conditional diagnosis is NOT returned with the symptom/covariate data. Note, if unconditional, disease that is conditioned on won't be part of the symptom data array.\n\n Returns\n -------\n None\n\n \"\"\"\n\n assert len(self.conditionSamplingOnDx)!=0, \"Sampler is already uncoditional and was never conditional to start.\"\n assert isinstance(self.trainingDataIndex,list) is True, \"Sampler has already been converted to unconditional.\"\n self.trainingDataIndex=np.concatenate(self.trainingDataIndex)\n self.testDataIndex=np.concatenate(self.testDataIndex)\n self.isConditioned=False\n\n def RevertToConditional(self):\n \"\"\"\n\n Reverts a previously unconditional sampler to conditional while keeping the same testing and training sets. This way, the conditional diagnosis is returned with the symptom/covariate data.\n\n Returns\n -------\n None\n\n \"\"\"\n assert len(self.conditionSamplingOnDx)!=0, \"Sampler was not constructed as a conditional sampler. If you want a conditional sampler for this dataset, create a new ClincalDatasetSampler instance.\"\n assert isinstance(self.trainingDataIndex,list) is False, \"Sampler is already conditional.\"\n has_at_least_one_dx_train= np.array(np.sum(np.vstack([self.currentClinicalDataset.data.loc[self.trainingDataIndex]['has_'+dx] for dx in self.conditionSamplingOnDx]),axis=0),dtype=np.bool)\n has_at_least_one_dx_test= np.array(np.sum(np.vstack([np.array(self.currentClinicalDataset.data.loc[self.testDataIndex]['has_'+dx],dtype=np.bool) for dx in self.conditionSamplingOnDx]),axis=0),dtype=np.bool)\n self.trainingDataIndex=[self.trainingDataIndex[has_at_least_one_dx_train],self.trainingDataIndex[np.invert(has_at_least_one_dx_train)]]\n self.testDataIndex=[self.testDataIndex[has_at_least_one_dx_test],self.testDataIndex[np.invert(has_at_least_one_dx_test)]]\n self.isConditioned=True\n\n def SubsetCovariates(self,newCovList):\n \"\"\"\n Indicates the covariates contained within ClinicalDataset that should be returned by the sampler. Can be empty list, which indicates that no covariates should be returned.\n\n Parameters\n ----------\n newCovList : list\n List of covariate names\n\n Returns\n -------\n None.\n\n \"\"\"\n assert set(newCovList).issubset(self.includedCovariates), \"Subset of covariates provided is not subset of current covariates.\"\n self.includedCovariates=newCovList\n\n\n def _returnData(self,newIndex,collapseAnchorDx=True):\n if isinstance(newIndex,Iterable)==False:\n newIndex=[newIndex]\n\n incidenceData = self.arrayFunc(self.currentClinicalDataset.ReturnSparseDataMatrix(newIndex))\n covData = [self.currentClinicalDataset.data.loc[newIndex][s].values for s in self.includedCovariates]\n covData = [self.arrayFunc(x.reshape(incidenceData.shape[0],1)) for x in covData]\n\n if not self.isConditioned:\n target_data = None\n else:\n target_data = np.array(pd.concat([self.currentClinicalDataset.data.loc[newIndex]['has_'+dx] for dx in self.conditionSamplingOnDx],axis=1),dtype=np.float32)\n target_data=self.arrayFunc(target_data.reshape(incidenceData.shape[0],len(self.conditionSamplingOnDx)))\n\n\n if not self._returnAuxData:\n encoded_data = None\n else:\n encoded_data = self.arrayFunc(self._auxDataset.ReturnSparseDataMatrix(newIndex))\n\n return incidenceData,covData,target_data,encoded_data\n\n def _generateRandomSample(self,numSamples,datasetIndex,fixedFracWDx):\n if fixedFracWDx!=None:\n assert isinstance(fixedFracWDx, float) and fixedFracWDx < 1.0 and fixedFracWDx > 0.0, \"fixedFrac with dx must be float between 0.0 and 1.0\"\n assert len(self.conditionSamplingOnDx)>0, \"Cannot include fixed fraction of positive cases if conditionSamplingOnDx not enabled\"\n if fixedFracWDx*numSamples >= len(datasetIndex[0]):\n numSamplesWDx = len(datasetIndex[0])\n print(\"Warning: fixedFracWDx exceeds or is equal to the total number of positive training samples.\\nEvery positive case will be included in random sample\")\n else:\n numSamplesWDx = int(np.ceil(numSamples*fixedFracWDx))\n elif self.isConditioned:\n numSamplesWDx=int(np.ceil(numSamples*self.fracWDx))\n\n\n if not self.isConditioned:\n newIndex = np.random.choice(datasetIndex,size=numSamples,replace=False)\n else:\n newIndex = shuffle(np.concatenate((np.random.choice(datasetIndex[0],size=numSamplesWDx,replace=False),np.random.choice(datasetIndex[1],size=(numSamples-numSamplesWDx),replace=False))))\n return self._returnData(newIndex)\n\n\n def GenerateRandomTrainingSample(self,numSamples, fixedFracWDx=None):\n \"\"\"\n\n Returns a random subset of numSamples from training dataset.\n\n Parameters\n ----------\n numSamples : int\n Number of samples to return\n fixedFracWDx : float in [0.0,1.0]\n If the sampler is conditioned, will return a sample with fixedFracWDx*100% of subjects having the conditioned dx.\n\n Returns\n -------\n Tuple of arrays: (symptom data,list of covariate data, conditioned disease value, encoded data)\n\n \"\"\"\n\n return self._generateRandomSample(numSamples,self.trainingDataIndex,fixedFracWDx)\n\n\n def GenerateRandomTestSample(self,numSamples,fixedFracWDx=None):\n \"\"\"\n\n Returns a random subset of numSamples from testing dataset.\n\n Parameters\n ----------\n numSamples : int\n Number of samples to return\n fixedFracWDx : float in [0.0,1.0]\n If the sampler is conditioned, will return a sample with fixedFracWDx*100% of subjects having the conditioned dx.\n\n Returns\n -------\n Tuple of arrays: (symptom data,list of covariate data, conditioned disease value [if indicated], auxillary data [if included])\n\n \"\"\"\n\n return self._generateRandomSample(numSamples,self.testDataIndex,fixedFracWDx)\n\n def _returnFullDataset(self,datasetIndex,randomize):\n if self.isConditioned:\n datasetIndex = np.concatenate(datasetIndex,axis=0)\n if randomize==True:\n datasetIndex=shuffle(datasetIndex)\n\n return self._returnData(datasetIndex)\n\n\n def ReturnFullTrainingDataset(self,randomize=True):\n \"\"\"\n\n Returns the full training dataset.\n\n Returns\n -------\n Tuple of arrays: (symptom data,list of covariate data, conditioned disease value [if indicated], auxillary data [if included])\n\n \"\"\"\n return self._returnFullDataset(self.trainingDataIndex,randomize)\n\n def ReturnFullTestingDataset(self,randomize=True):\n \"\"\"\n\n Returns the full testing dataset.\n\n Returns\n -------\n Tuple of arrays: (symptom data,list of covariate data, conditioned disease value [if indicated], auxillary data [if included])\n \"\"\"\n return self._returnFullDataset(self.testDataIndex,randomize)\n\n\n def _indexSplit(self,dataSetSize,totalNumBatches):\n if totalNumBatches>0:\n nEachBatch, extras = divmod(dataSetSize, totalNumBatches)\n section_sizes = ([0] +extras * [nEachBatch+1] +(totalNumBatches-extras) * [nEachBatch])\n return np.array(section_sizes, dtype=np.int32).cumsum()\n else:\n return np.array([0]+[dataSetSize], dtype=np.int32)\n\n\n def _epoch(self,datasetIndex,batch_size):\n\n if self.isConditioned:\n #shuffle the order of the dataset at the start of every epoch\n datasetIndex[0]=np.random.permutation(datasetIndex[0])\n datasetIndex[1]=np.random.permutation(datasetIndex[1])\n totalNumBatches,leftover = divmod((len(datasetIndex[0])+len(datasetIndex[1])),batch_size)\n assert totalNumBatches <= len(datasetIndex[0]), \"Batch size too small. Cannot ensure at least one positive example per batch.\"\n #first shuffle the data\n\n hasDxSplits=self._indexSplit(len(datasetIndex[0]),totalNumBatches)\n noDxSplits=self._indexSplit(len(datasetIndex[1]),totalNumBatches)\n if totalNumBatches == 0:\n totalNumBatches+=1\n\n for i in range(totalNumBatches):\n hasDxSubset = datasetIndex[0][hasDxSplits[i]:hasDxSplits[i+1]]\n noDxSubset = datasetIndex[1][noDxSplits[i]:noDxSplits[i+1]]\n\n batchIndex = np.concatenate((hasDxSubset,noDxSubset))\n #need to shuffle positive cases within all others\n yield shuffle(batchIndex)\n else:\n datasetIndex=shuffle(datasetIndex)\n totalNumBatches,leftover = divmod(len(datasetIndex),batch_size)\n splits = self._indexSplit(len(datasetIndex),totalNumBatches)\n if totalNumBatches == 0:\n totalNumBatches+=1\n for i in range(totalNumBatches):\n\n yield datasetIndex[splits[i]:splits[i+1]]\n\n\n def TrainingEpochGenerator(self, batch_size):\n \"\"\"\n Provides an iterator over the training dataset. Equivalent to performing one pass (epoch) through the dataset.\n\n Parameters\n ----------\n batch_size : int\n Batch size for the samples in the epoch.\n\n Returns\n -------\n iterator\n Iterates through training data samples.\n \"\"\"\n for batch in self._epoch(self.trainingDataIndex,batch_size):\n yield self._returnData(batch)\n\n\n def TestingEpochGenerator(self,batch_size):\n \"\"\"\n Provides an iterator over the testing dataset. Equivalent to performing one pass (epoch) through the dataset.\n\n Parameters\n ----------\n batch_size : int\n Batch size for the samples in the epoch.\n\n Returns\n -------\n iterator\n Iterates through testing data samples.\n \"\"\"\n for batch in self._epoch(self.testDataIndex,batch_size):\n yield self._returnData(batch)\n\n def GenerateValidationSampler(self,validation_fraction):\n \"\"\"\n\n Returns a new ClinicalDatasetSampler that splits the training set into training and validation sets. This new sampler can be used just like the original except that the testing dataset is now a validation subset of the training data. It accomplishes this task by making a general shallow copy of the class (to avoid copying, for example, the whole dataset)while making deep copies of the information that changes between the validation and test datasets.\n\n Parameters\n ----------\n validation_fraction : float\n Fraction of the training data to use for validation.\n\n Returns\n -------\n ClinicalDatasetSampler\n A new ClinicalDatasetSampler with the testing dataset set to a validation subset of the training data.\n\n \"\"\"\n\n new_instance = copy.copy(self)\n new_instance.trainingDataIndex=copy.deepcopy(self.trainingDataIndex)\n new_instance.testDataIndex=copy.deepcopy(self.testDataIndex)\n new_instance.trainingFraction=copy.deepcopy(self.trainingFraction)\n new_instance.trainingFraction = 1.0-validation_fraction\n\n if self.isConditioned==False:\n new_instance.numTotalSamples=len(self.trainingDataIndex)\n trainingDataIndexShuffled = shuffle(self.trainingDataIndex)\n cutOffVal = int(np.floor(len(trainingDataIndexShuffled)*new_instance.trainingFraction))\n new_instance.trainingDataIndex = trainingDataIndexShuffled[0:cutOffVal]\n new_instance.testDataIndex = trainingDataIndexShuffled[cutOffVal:]\n else:\n new_instance.numTotalSamples=len(self.trainingDataIndex[0])+len(self.trainingDataIndex[1])\n trainingDataIndexShuffled = np.append(*[shuffle(np.array(x)) for x in self.trainingDataIndex])\n\n has_at_least_one_dx = np.array(np.sum(np.vstack([self.currentClinicalDataset.data.loc[trainingDataIndexShuffled]['has_'+dx] for dx in self.conditionSamplingOnDx]),axis=0),dtype=np.bool)\n dataWithDx = self.currentClinicalDataset.data.loc[trainingDataIndexShuffled].index[has_at_least_one_dx>0]\n dataWithoutDx = self.currentClinicalDataset.data.loc[trainingDataIndexShuffled].index[has_at_least_one_dx==0]\n self.fracWDx = len(dataWithDx)/len(trainingDataIndexShuffled)\n cutOffValWDx = int(np.floor(len(dataWithDx)*new_instance.trainingFraction))\n cutOffValWoDx = int(np.floor(len(dataWithoutDx)*new_instance.trainingFraction))\n\n new_instance.trainingDataIndex=[dataWithDx[0:cutOffValWDx],dataWithoutDx[0:cutOffValWoDx]]\n new_instance.testDataIndex=[dataWithDx[cutOffValWDx:],dataWithoutDx[cutOffValWoDx:]]\n return new_instance\n\n def CollapseDataArrays(self,disInds=None,cov_vecs=None,drop_column=False):\n \"\"\"\n Converts\n\n\n Parameters\n ----------\n disInds : type\n Description of parameter `disInds`.\n cov_vecs : type\n Description of parameter `cov_vecs`.\n drop_column : type\n Description of parameter `drop_column`.\n\n Returns\n -------\n type\n Description of returned object.\n\n \"\"\"\n list_of_arrays=[]\n if disInds is not None:\n list_of_arrays+=[disInds]\n\n\n if cov_vecs is not None:\n n_cat_vec = [len(self.currentClinicalDataset.catCovConversionDicts[x]) for x in self.includedCovariates]\n\n for i,n_cat in enumerate(n_cat_vec):\n if torch.is_tensor(cov_vecs[0]):\n list_of_arrays+=[one_hot(cov_vecs[i],n_cat,dropColumn=drop_column)]\n else:\n list_of_arrays+=[one_hot_scipy(cov_vecs[i],n_cat,dropColumn=drop_column)]\n\n\n list_of_arrays=[self.arrayFunc(x) for x in list_of_arrays]\n\n if self.returnArrays=='Numpy':\n return np.hstack(list_of_arrays,dtype=np.float64)\n elif self.returnArrays=='Sparse':\n return sparse.hstack(list_of_arrays,format='csr',dtype=np.float64)\n else:\n return torch.cat(list_of_arrays,dim=1,dtype=torch.float32)\n\n def AddAuxillaryDataset(self,newClinicalDataset):\n \"\"\"\n Adds another, auxillary ClinicalDataset to the sampler. This way, different clinical datasets for the same sets of patients can be generated in parallel. If activated, this data is returned as the 4th element in the return tuple.\n\n Parameters\n ----------\n newClinicalDataset : ClinicalDataset\n A ClinicalDataset Class with the same subjects as the current class.\n\n Returns\n -------\n None\n\n \"\"\"\n assert len(self.currentClinicalDataset.data.index.difference(newClinicalDataset.data.index))==0,\"Auxillary ClinicalDataset must contain the same samples as the original ClinicalDataset\"\n self._returnAuxData=True\n self._auxDataset=newClinicalDataset\n\n\n\n def RemoveAuxillaryDataset(self):\n \"\"\"\n Removes an auxillary dataset from the sampler\n\n Returns\n -------\n None\n\n \"\"\"\n self._returnAuxData=False\n self._auxDataset=None\n\nclass _TorchDatasetWrapper(data.Dataset):\n\n def __init__(self,clinicalDatasetSampler,sampling_index,batch_size):\n \"\"\"\n\n Wrapper for ClinicalData and ClinicalDatasetSampler to allow for rapid subset sampling using PyTorch DataLoader, which allows for multi-threaded loading/queueing of data.\n\n Parameters\n ----------\n clinicalDatasetSampler : ClinicalDatasetSampler\n ClinicalDatasetSampler to be wrapped\n sampling_index : Iterable or list of Iterables\n Index of subjects from ClincalDataset to sample from. Use ClinicalDatasetSampler.trainingDataIndex or ClinicalDatasetSampler.testingDataIndex\n batch_size : int\n Batch size for the sampler.\n\n Returns\n -------\n None\n\n \"\"\"\n\n\n self.clinicalDatasetSampler = clinicalDatasetSampler\n self.sampling_index=sampling_index\n\n\n if self.clinicalDatasetSampler.isConditioned:\n #shuffle the order of the dataset at the start of every epoch\n self.sampling_index[0]=shuffle(self.sampling_index[0])\n self.sampling_index[1]=shuffle(self.sampling_index[1])\n self.totalNumBatches,leftover = divmod((len(self.sampling_index[0])+len(self.sampling_index[1])),batch_size)\n assert self.totalNumBatches <= len(sampling_index[0]), \"Batch size too small. Cannot ensure at least one positive example per batch.\"\n #first shuffle the data\n\n self.hasDxSplits=self.clinicalDatasetSampler._indexSplit(len(self.sampling_index[0]),self.totalNumBatches)\n self.noDxSplits=self.clinicalDatasetSampler._indexSplit(len(self.sampling_index[1]),self.totalNumBatches)\n if self.totalNumBatches == 0:\n self.totalNumBatches+=1\n\n else:\n self.sampling_index=shuffle(self.sampling_index)\n self.totalNumBatches,leftover = divmod(len(self.sampling_index),batch_size)\n self.splits = self.clinicalDatasetSampler._indexSplit(len(self.sampling_index),self.totalNumBatches)\n if self.totalNumBatches == 0:\n self.totalNumBatches+=1\n\n def __len__(self):\n return self.totalNumBatches\n\n def shuffle_index(self):\n if self.clinicalDatasetSampler.isConditioned:\n self.sampling_index[0]=shuffle(self.sampling_index[0])\n self.sampling_index[1]=shuffle(self.sampling_index[1])\n else:\n self.sampling_index=shuffle(self.sampling_index)\n\n\n\n def __getitem__(self,index):\n if self.clinicalDatasetSampler.isConditioned:\n hasDxSubset = self.sampling_index[0][self.hasDxSplits[index]:self.hasDxSplits[index+1]]\n noDxSubset = self.sampling_index[1][self.noDxSplits[index]:self.noDxSplits[index+1]]\n batchIndex = np.concatenate((hasDxSubset,noDxSubset))\n\n else:\n batchIndex=self.sampling_index[self.splits[index]:self.splits[index+1]]\n\n return self.clinicalDatasetSampler._returnData(batchIndex)\n","sub_path":"build/lib/vlpi/data/ClinicalDataset.py","file_name":"ClinicalDataset.py","file_ext":"py","file_size_in_byte":47755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"595610857","text":"from src import WEB_CRAWLER_PATH, RESULT_FILE_PATH\nfrom subprocess import run as run_command\n\n\nclass Controller(object):\n\n def __init__(self, view, model):\n self.view = view\n self.model = model\n\n def run(self):\n events = {}\n\n events['main'] = {}\n events['header'] = {}\n\n events['main']['copy_link'] = self.event_copy_link\n events['header']['search_link'] = self.event_search_link\n\n self.view.run(events=events)\n self.model.run()\n\n self.view.container.main.load_items(links=self.model.links)\n\n def find_links(self, url):\n command = ['scrapy', 'runspider',\n f'-s URL={url}', f'-s OUTPUT={RESULT_FILE_PATH}', '--nolog',\n WEB_CRAWLER_PATH]\n\n return run_command(command).returncode\n\n def event_copy_link(self, event, link):\n self.view.clipboard_clear()\n self.view.clipboard_append(link)\n\n def event_search_link(self, event):\n user_input = self.view.container.header.search_input.get()\n\n if not self.model.validate_user_input(user_input):\n return None\n\n url = self.model.handle_url(url=user_input)\n\n self.find_links(url=url)\n self.model.load_result_file()\n self.view.container.main.load_items(links=self.model.links)\n","sub_path":"src/app/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"13523472","text":"import random\r\nimport math\r\n\r\naverage = 0\r\nfor i in range(1000000):\r\n\tx1 = random.uniform(-1, 1)\r\n\tx2 = random.uniform(-1, 1)\r\n\t\r\n\ty1 = math.sin(math.pi * x1)\r\n\ty2 = math.sin(math.pi * x2)\r\n\r\n\ta = (x1 * y1 + x2 * y2) / (x1 ** 2 + x2 ** 2)\r\n\taverage += a\r\n\r\nahat = round(average/1000000, 2)\r\n\r\nprint(\"g(x) = {}x\".format(ahat))\r\n\r\nbias = 0\r\n\r\nfor j in range(-1000, 1000):\r\n\t\tbias += (ahat * j/1000 - math.sin(math.pi * j/1000)) ** 2\r\n\r\nbias /= 2000\r\n\r\nprint(\"bias: \" + str(bias))\t\t\r\n\r\nvariance = 0\r\n\r\nfor z in range(100000):\r\n\tx1 = random.uniform(-1, 1)\r\n\tx2 = random.uniform(-1, 1)\r\n\r\n\ty1 = math.sin(math.pi * x1)\r\n\ty2 = math.sin(math.pi * x2)\r\n\r\n\ta = (x1 * y1 + x2 * y2) / (x1 ** 2 + x2 ** 2)\r\n\t\r\n\tfor w in range(-1000, 1000):\r\n\t\tvariance += (a * w/1000 - ahat * w/1000) ** 2\r\n\r\nvariance /= 2000 * 100000\r\n\r\nprint(\"var: \" + str(variance))","sub_path":"PS4Question4.py","file_name":"PS4Question4.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"456049346","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom core.skills.db.melee import MeleeSpells\r\nfrom core.units.enemy_unit import EnemyUnit\r\nfrom core.units.player.resources.stash import Stash\r\nfrom core.game.text.damage_text import DamageText\r\nimport constants.globals\r\nfrom core.items.consumable.db.consumable_db import HEALTH_POTION\r\n\r\n# Init: Damage Text, CombatTextResolver\r\ndamage_text = DamageText()\r\n\r\n\r\nclass Bandit(EnemyUnit, MeleeSpells):\r\n def __init__(self, level, attack_power, attack_rating, magic_power, max_hp, max_mp, sound_master):\r\n EnemyUnit.__init__(self, 'Bandit', level, attack_power, attack_rating, magic_power, max_hp, max_mp)\r\n MeleeSpells.__init__(self, sound_master)\r\n\r\n self.sound_master = sound_master\r\n self.animation_set = None\r\n self.animation_callbacks = None\r\n self.stash = Stash(healing_potions=1, mana_potions=0, gold=0)\r\n\r\n def set_animations(self, animation_set, animation_callbacks):\r\n self.animation_set = animation_set\r\n self.animation_callbacks = animation_callbacks\r\n\r\n def use_animation(self, animation):\r\n self.animation_callbacks[animation](self.animation_set)\r\n\r\n def use_attack(self, target, text_sprite):\r\n self.use_animation('Attack')\r\n self.cast_attack(self, target, text_sprite)\r\n return True\r\n\r\n def use_strong_attack(self, target, text_sprite):\r\n self.use_animation('Attack')\r\n self.cast_strong_attack(self, target, text_sprite)\r\n return True\r\n\r\n def use_healing_potion(self, text_sprite):\r\n constants.globals.action_cooldown = 0\r\n if self.stash.consume_healing_potion():\r\n self.sound_master.play_item_fx_sound('health_potion')\r\n HEALTH_POTION.consume(self, text_sprite)\r\n return True\r\n\r\n damage_text.warning(self, 'No Healing Potions', text_sprite)\r\n return False\r\n\r\n def action(self, target, text_sprite):\r\n health_trigger = self.current_hp <= round(self.max_hp * 0.15)\r\n if self.stash.has_healing_potion() and health_trigger:\r\n self.use_healing_potion(text_sprite)\r\n elif not self.stash.has_healing_potion() and self.has_tried_to_consume_health_potion() and health_trigger:\r\n self.use_healing_potion(text_sprite)\r\n self.update_try_to_consume_health_potion()\r\n else:\r\n self.use_attack(target, text_sprite)\r\n","sub_path":"core/units/enemy/bandit/bandit.py","file_name":"bandit.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"364331389","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 ('rango', '0009_hyderabadtango_title'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Page_location',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=128)),\n ('url', models.URLField()),\n ('fbpage', models.URLField(blank=True)),\n ('location', models.CharField(max_length=100, blank=True)),\n ('email', models.EmailField(max_length=75)),\n ('contact', models.IntegerField(default=0)),\n ('views', models.IntegerField(default=0)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Tango',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=128)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.DeleteModel(\n name='HyderabadTango',\n ),\n migrations.AddField(\n model_name='page_location',\n name='category',\n field=models.ForeignKey(to='rango.Tango'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='page',\n name='views',\n field=models.IntegerField(default=0),\n ),\n ]\n","sub_path":"tango_with_django_project/rango/migrations/0010_auto_20160711_1346.py","file_name":"0010_auto_20160711_1346.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"317208053","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\ndf=pd.read_excel('JD2019.xlsx')\n#数据处理,提取2019年2月和2020年2月的数据\ndf= df.set_index('日期') # 将日期设置为索引\ndf1=pd.concat([df['2019-02'],df['2020-02']])\ndf1=df1[df1['商品名称']=='零基础学Python(全彩版)']\ndf1=df1[['北京','上海','广州','成都','武汉','沈阳','西安']]\ndf2=df1.T #行列转置\nx=np.array([0,1,2,3,4,5,6])\ny1=df2['2019-02-01']\ny2=df2['2020-02-01']\n#同比增长率\ndf2['rate']=((df2['2020-02-01']-df2['2019-02-01'])/df2['2019-02-01'])*100\ny=df2['rate']\nprint(y)\nwidth =0.25 #柱子宽度\nplt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码\nplt.title('全国各地区销量及同比增长情况') #图表标题\nplt.ylabel('销售数量(册)') #y轴标签\n#x轴标签\nplt.xticks(x,['北京','上海','广州','成都','武汉','沈阳','西安'])\n#双柱形图\nplt.bar(x,y1,width=width,color = 'orange',label='2019年2月')\nplt.bar(x+width,y2,width=width,color = 'deepskyblue',label='2020年2月')\n# 增长率标签\nfor a, b in zip(x,y):\n plt.text(a,b,('%.1f%%' % b), ha='center', va='bottom', fontsize=11)\nplt.legend()\nplt.show()","sub_path":"Python数据分析从入门到精通/MR/Code/09/example/02/01/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"567026064","text":"from pymongo import MongoClient\nfrom bson import Binary, Code\nfrom bson import json_util\nfrom bson import ObjectId\nfrom bson.json_util import dumps\nfrom flask import jsonify\n\nimport json\nimport pprint\nimport datetime\n\n\ndef ultimaSesion():\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n existe = coll.find({'sesion':{'$exists': True}}).count()\n if existe > 0:\n sesion = int(coll.find().sort([('sesion', -1)]).limit(1)[0][\"sesion\"])\n else:\n sesion = 1\n \n client.close()\n return sesion\n\ndef grabafechaSesion(numsesion,fecha,fechaIni,activo):\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n if (activo == True):\n tipo=\"fechaIni\"\n else:\n tipo=\"fechaFin\"\n tiempoSesion= (fecha - fechaIni).total_seconds()\n post = {'sesion':numsesion, 'tipo':tipo, 'date':fecha, 'fechaIni':fechaIni, 'tiempoSesion':tiempoSesion}\n post_id = coll.insert_one(post)\n client.close()\n\ndef obtenerID():\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n IDalumno = 0\n existe = coll.find({'IDalumno':{'$exists': True}}).count()\n #cursor= coll.find({'IDalumno':{'$exists': True}}).sort([('IDalumno', -1)])\n #for post in cursor:\n # print(post)\n if existe > 0:\n IDalumno = int(coll.find({'IDalumno':{'$exists': True}, 'tipo':'cookie'}).sort([('IDalumno', -1)]).limit(1)[0][\"IDalumno\"]) \n IDalumno += 1\n post = {'tipo':'cookie',\"IDalumno\": IDalumno}\n #print(existe)\n post_id = coll.insert_one(post)\n #print(post_id)\n client.close()\n return IDalumno\n\ndef grabaConexion(numsesion,IDalum,grabando,fecha,fechaIni):\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n tiempoSesion= (fecha - fechaIni).total_seconds()\n tipo = \"conexion\"\n \n existe = coll.find({'sesion':numsesion, 'IDalumno':IDalum,'conexion':{'$exists': True}}).count()\n if existe > 0:\n conexion = int(coll.find({'sesion':numsesion, 'IDalumno':IDalum}).sort([('conexion', -1)]).limit(1)[0][\"conexion\"])\n else:\n conexion = 0\n \n if (grabando == True):\n razon=\"conecta\"\n conexion += 1\n else:\n razon=\"desconecta\"\n \n identificador=str(numsesion)+str(IDalum)+str(conexion)\n post = {'sesion':numsesion, 'tipo':tipo, 'IDalumno':IDalum, 'conexion':conexion, 'identificador':identificador, 'razon': razon, 'date':fecha, 'tiempoSesion':tiempoSesion}\n post_id = coll.insert_one(post)\n client.close()\n\n\n \ndef calculaMedias(numsesion,filename,fechaIni,fechahora):\n nombre= filename.split(\".\")\n nameList=nombre[0].split(\"_\")\n tipo=\"audio\"\n anio=int(nameList[1])\n mes=int(nameList[2])\n dia=int(nameList[3])\n hora=int(nameList[4])\n minuto=int(nameList[5])\n segundo=int(nameList[6])\n fecha = datetime.datetime(anio, mes, dia, hora, minuto, segundo)\n fecha = fechahora\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n\n existe = coll.find({'sesion':numsesion, 'tipo':tipo,'date':{'$lt': fecha}}).count()\n if existe > 0:\n fechaAnt = coll.find({'sesion':numsesion, 'tipo':tipo,'date':{'$lt': fecha}}).sort([('date', -1)]).limit(1)[0][\"date\"]\n else:\n fechaAnt = fechaIni\n \n existe = coll.find({'sesion':numsesion,'tipo':'medias'}).count()\n print(existe)\n if existe > 0:\n ultimaMedia = coll.find({'sesion':numsesion,'tipo':'medias'}).sort([('tiempoSesion', -1)]).limit(1)[0]\n numAlumnosAnt=ultimaMedia['numAlumnos']\n conexionAnt=ultimaMedia['conexion']\n else:\n numAlumnosAnt=0\n conexionAnt=0\n\n tiempoSesion =int((fecha - fechaIni).total_seconds())\n numAlumnos = len(coll.distinct( \"IDalumno\", { 'sesion':numsesion, 'tipo':'pic', 'date':{ \"$gte\" :fechaAnt} } ))\n\n if numAlumnos > 0:\n '''\n if numAlumnosAnt > 0:\n conexion = conexionAnt\n else:\n conexion = conexionAnt +1\n '''\n conexion = conexionAnt\n identificador=str(numsesion)+\"medias\"+str(conexion) \n pipeline = [\n {\"$match\":{'sesion':numsesion, 'tipo':'pic', 'date':{ \"$gte\" :fechaAnt}}}, \n {\"$group\":{\"_id\":'$sesion', \"alegria\":{\"$avg\":'$alegria'}, \"pena\":{\"$avg\":'$pena'}, \"enfado\":{\"$avg\":'$enfado'},\"sorpresa\":{\"$avg\":'$sorpresa'}}},\n {\"$project\" : { \"_id\":0, \"alegria\" :1 , \"pena\" : 1, \"enfado\" : 1, \"sorpresa\" : 1}},\n {\"$addFields\": { 'sesion': numsesion , 'tipo': 'medias' ,'tiempoSesion': tiempoSesion,'numAlumnos': numAlumnos,'conexion':conexion,'identificador':identificador}}\n ]\n lista=list(coll.aggregate(pipeline));\n post=lista[0]\n #print(lista)\n #print(cursor.count())\n \n else:\n '''\n if numAlumnosAnt > 0:\n conexion = conexionAnt +1\n else:\n conexion = conexionAnt\n '''\n conexion = conexionAnt\n \n identificador=str(numsesion)+\"medias\"+str(conexion)\n post={'sesion': numsesion , 'tipo': 'medias' , 'conexion':conexion, 'identificador':identificador,'tiempoSesion': tiempoSesion, 'numAlumnos': 0,\"alegria\":0, \"pena\":0, \"enfado\":0,\"sorpresa\":0}\n \n post_id = coll.insert_one(post)\n client.close()\n\n\ndef enviaGrafProfe(numsesion,fechaIni):\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n tiempoSesion=coll.find({\"sesion\" : numsesion, \"tipo\" : \"audio\"}).sort([('tiempoSesion', -1)]).limit(1)[0][\"tiempoSesion\"]\n #tiempoSesion = (fechaFin - fechaIni).total_seconds()\n \n Ident = coll.distinct( \"identificador\", { 'sesion': numsesion, \"tipo\" : { \"$in\": [\"pic\",\"medias\"]}, \"alegria\":{\"$ne\":0} } )\n Idalum = coll.distinct( \"IDalumno\", { 'sesion': numsesion, \"tipo\":\"pic\" } )\n cursor = coll.find({\"sesion\" : numsesion, \"tipo\" : { \"$in\": [\"pic\",\"medias\"]}, \"alegria\":{\"$ne\":0}})\n datos = json.dumps(json.loads(dumps(cursor), object_hook=json_util.object_hook), cls=APIEncoder)\n datos= datos.replace(\"_\", \"\")\n respuesta=[{\"fechaIni\":fechaIni,\"tiempoSesion\":tiempoSesion,\"Identificadores\":Ident,\"IDalumno\":Idalum, \"datos\":datos}]\n print(respuesta)\n client.close()\n return jsonify(respuesta)\n\ndef consultaGrafica(numsesion):\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n registroFin=coll.find({\"sesion\" : numsesion, \"tipo\" : \"fechaFin\", 'date':{'$exists': True}})[0]\n tiempoSesion= registroFin[\"tiempoSesion\"]\n fechaFin= registroFin[\"date\"].strftime(\"%Y-%m-%d %H:%M:%S\")\n fechaIni= registroFin[\"fechaIni\"].strftime(\"%Y-%m-%d %H:%M:%S\")\n \n Ident = coll.distinct( \"identificador\", { 'sesion': numsesion, \"tipo\" : { \"$in\": [\"pic\",\"medias\"]}, \"alegria\":{\"$ne\":0} } )\n Idalum = coll.distinct( \"IDalumno\", { 'sesion': numsesion, \"tipo\":\"pic\" } )\n cursor = coll.find({\"sesion\" : numsesion, \"$or\":[{\"tipo\" : { \"$in\": [\"pic\",\"medias\"]}, \"alegria\":{\"$ne\":0}},{\"tipo\" :\"tfidf\"}]})\n datos = json.dumps(json.loads(dumps(cursor), object_hook=json_util.object_hook), cls=APIEncoder)\n respuesta=[{\"fechaIni\":fechaIni,\"fechaFin\":fechaFin,\"tiempoSesion\":tiempoSesion,\"Identificadores\":Ident,\"IDalumno\":Idalum, \"datos\":datos}]\n print(respuesta)\n client.close()\n return jsonify(respuesta)\n\ndef findSesiones():\n client = MongoClient()\n\n db = client.test\n coll = db.tfm\n \n cursor = coll.find({\"tipo\" :'fechaFin'},{\"_id\":0,\"sesion\":1,\"fechaIni\":1,\"tiempoSesion\":1}).sort(\"sesion\",-1)\n #print(json.dumps(json.loads(dumps(cursor), object_hook=json_util.object_hook), cls=APIEncoder))\n\n respuesta=[]\n\n for post in cursor:\n respuesta.append({\"sesion\":post[\"sesion\"], \"fechaIni\":post[\"fechaIni\"].strftime(\"%Y-%m-%d %H:%M:%S\"),\"tiempoSesion\":post[\"tiempoSesion\"]})\n client.close()\n print(respuesta)\n return respuesta\n\n \n\n\n \n \n'''\npasar a segundos desde 1970 y leer en segundos desde 1970 trabajandoi en UTC\n(t-datetime.datetime(1970,1,1)).total_seconds()\ndatetime.datetime.utcfromtimestamp(1284286794)\n\nLo soluciono poniendo la hora de my sistema a UTC\n'''\n\nclass APIEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif isinstance(obj, ObjectId):\n return str(obj)\n return jsonJSONEncoder.default(obj)\n\n","sub_path":"RecEmEn_Remoto_Centos/accesosDB.py","file_name":"accesosDB.py","file_ext":"py","file_size_in_byte":8315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"526443785","text":"import pgzrun\nimport random\n\nWIDTH = 800\nHEIGHT = 600\n\nx = WIDTH / 2\ny = HEIGHT / 2\n\nspeed_x = 3\nspeed_y = 5\n\nr = 1\n\n# 定义了一个绘图函数,说明具体的绘制工作\ndef draw():\n # 填充背景颜色\n # screen.fill('white')\n # 绘制一个填充圆\n\n random_r = int(random.random() * 255)\n random_g = int(random.random() * 255)\n random_b = int(random.random() * 255)\n\n screen.draw.filled_circle((x, y), r, (random_r, random_g, random_b))\n\n\n\ndef update():\n global x, y, speed_x, speed_y\n x = x + speed_x\n y = y + speed_y\n if x >= WIDTH - r or x <= r:\n speed_x = -speed_x\n if y >= HEIGHT - r or y <= r:\n speed_y = - speed_y\n\n # screen.draw.filled_circle((x, y), 5, 'green')\n\n\n# 让游戏开始运行\npgzrun.go()\n\n\n","sub_path":"PygameZero/003-斜着弹跳的小球.py","file_name":"003-斜着弹跳的小球.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"513066716","text":"# Crie um programa que leia o ano de nascimento de sete pessoas. \n# No final, mostre quantas pessoas ainda não atingiram a maioridade \n# e quantas já são maiores.\n\n# from datetime import date\n# qme = qma = 0\n# ano_atual = date.today().year\n# for i in range(0, 7):\n# nascimento = int(input(\"Qual o seu ano de nascimento? \"))\n# idade = ano_atual - nascimento\n# if idade >= 21:\n# qma = qma + 1\n# if idade < 21:\n# qme = qme + 1\n# print(f\"A quantidade de pessoas maior de idade são {qma}.\")\n# print(f\"A quantidade de pessoas menor de idade são {qme}.\")\n\nfrom datetime import date\ntotmaior = totmenor = 0\nano_atual = date.today().year\nfor pess in range(1, 8):\n nascimento = int(input(f\"Em que ano a {pess} pessoa nasceu? \"))\n idade = ano_atual - nascimento\n if idade >= 21:\n totmaior = totmaior + 1\n else:\n totmenor = totmenor + 1\nprint(f\"A quantidade de pessoas maior de idade são {totmaior}.\")\nprint(f\"A quantidade de pessoas menor de idade são {totmenor}.\")\n","sub_path":"exercicios/desafio054.py","file_name":"desafio054.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"447119248","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import KFold, StratifiedKFold, RepeatedStratifiedKFold, GridSearchCV\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, \\\n classification_report\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.utils._testing import ignore_warnings\nfrom tempfile import mkdtemp\nfrom shutil import rmtree\nfrom collections import defaultdict\n\nfrom preprocessing import features_from_df, preprocess\nfrom inspection import feature_importance\n\npd.set_option('use_inf_as_na', True)\n\n\ndef performance(y_test, y_pred, y_scores, average='binary'):\n \"\"\"Obtain performance estimates (for a single CV fold)\"\"\"\n accuracy = accuracy_score(y_test, y_pred)\n precision = precision_score(y_test, y_pred, zero_division=1, average=average)\n recall = recall_score(y_test, y_pred, zero_division=1, average=average)\n specificity = recall_score(y_test, y_pred, zero_division=1, average=average, pos_label=0)\n f1 = f1_score(y_test, y_pred, zero_division=1, average=average)\n try:\n roc_auc = roc_auc_score(y_test, y_scores)\n except ValueError:\n roc_auc = np.nan\n\n print(classification_report(y_test, y_pred, labels=[0, 1], target_names=['negative', 'positive'],\n zero_division=1))\n return accuracy, precision, recall, specificity, f1, roc_auc\n\n\ndef prediction_per_subject(y_test_subjects, y_pred, y_scores, sample_names, subjects):\n \"\"\"A subject is predicted positive if at least half of the samples from the subject are predicted positive\"\"\"\n y_pred_subjects = []\n y_scores_subjects = []\n for s in subjects:\n sum = 0\n scores = []\n for i in range(len(sample_names)):\n if sample_names[i].split('_')[0] == s:\n sum += y_pred[i]\n scores.append(y_scores[i])\n if sum > (len(y_pred) / len(y_test_subjects)) / 2:\n y_pred_subjects.append(1)\n else:\n y_pred_subjects.append(0)\n y_scores_subjects.append(np.mean(scores))\n\n for i in range(len(subjects)):\n print(y_test_subjects[i], y_pred_subjects[i], '%.3f' % y_scores_subjects[i], subjects[i])\n\n return y_pred_subjects, y_scores_subjects\n\n\ndef custom_cv(cv, X_df, subjects, subs_y):\n \"\"\"\n Return cross-validation splits so that all samples from a single subject are either in the train set\n or the test set but never both (this function is currently only needed in the grid search)\n \"\"\"\n inds = []\n subject_wise_inds = []\n for ii, (train, test) in enumerate(cv.split(subjects, y=subs_y)):\n train_idx = X_df.index.str.split(pat='_').str[0].isin(subjects[train])\n test_idx = X_df.index.str.split(pat='_').str[0].isin(subjects[test])\n inds.append((train_idx, test_idx))\n subject_wise_inds.append((train, test))\n return inds, subject_wise_inds\n\n\ndef run_grid(clf, selector, X, y, cv_inds, param_space):\n \"\"\"Run grid search for the hyperparameters\"\"\"\n cachedir = mkdtemp()\n pipe = make_pipeline(selector, clf, memory=cachedir)\n grid = GridSearchCV(pipe, param_space, scoring='accuracy', cv=cv_inds, n_jobs=4, verbose=1)\n grid.fit(X, y)\n means = grid.cv_results_['mean_test_score']\n stds = grid.cv_results_['std_test_score']\n for mean, std, params in zip(means, stds, grid.cv_results_['params']):\n if mean > 0.68:\n print(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params))\n print('Best params:', grid.best_params_)\n print('Estimated score: %.3f\\n' % grid.best_score_)\n best_clf = grid.best_estimator_[-1]\n best_selector = grid.best_estimator_[0]\n rmtree(cachedir)\n\n return best_clf, best_selector\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef run_cv(clf, X_df, y, subs_y, selector='passthrough', average='binary', n_splits=7, n_perm_repeats=3, param_grid=None,\n nested=False, rep_cv=False, random_state=1):\n \"\"\"Run the cross-validation\"\"\"\n sample_names = [s.split('_')[0] for s in X_df.index]\n subjects = np.asarray(list(dict.fromkeys(sample_names)))\n\n # data frame for storing the average accuracy and the decision function value per subject\n subject_results = pd.DataFrame(0, columns=['classif_score', 'df_score'], index=subjects, dtype=float)\n\n if rep_cv:\n # repeat the cross-validation with different splits each time\n cv_outer = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=5, random_state=random_state)\n else:\n cv_outer = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_state)\n\n print(f'Starting {cv_outer.get_n_splits()}-fold cross validation')\n print(clf)\n # dict for storing the performance measures\n results_dict = defaultdict(list)\n # initialize an empty array for storing feature importances\n importances = np.zeros((cv_outer.get_n_splits(), X_df.shape[1], n_perm_repeats))\n\n if param_grid is not None and not nested:\n # do the hyperparameter grid search (if not using nested CV)\n cv_inds, sub_inds = custom_cv(cv_outer, X_df, subjects, subs_y)\n if selector == 'passthrough':\n param_grid = [{k: v for k, v in params.items() if 'selector' not in k} for params in param_grid]\n X, feature_names_orig = features_from_df(X_df)\n best_clf, best_selector = run_grid(clf, selector, X, y, cv_inds, param_grid)\n else:\n best_selector = selector\n best_clf = clf\n\n # make a pipeline to be cross-validated, consisting of an optional feature selector and the classifier\n cachedir = mkdtemp()\n pipe = make_pipeline(best_selector, best_clf, memory=cachedir)\n\n # start the actual cross-validation\n # note that we are splitting the list of subjects, not samples, to avoid leaking information\n for ii, (train, test) in enumerate(cv_outer.split(subjects, y=subs_y)):\n print('Fold', ii + 1)\n # convert the 'subject indices' to 'sample indices'\n train_idx = X_df.index.str.split(pat='_').str[0].isin(subjects[train])\n test_idx = X_df.index.str.split(pat='_').str[0].isin(subjects[test])\n X_df_train = X_df.iloc[train_idx]\n y_train = y[train_idx]\n X_df_test = X_df.iloc[test_idx]\n y_test = y[test_idx]\n\n # prepare the training and testing set\n X_train, feature_names_orig = features_from_df(X_df_train)\n X_test, _ = features_from_df(X_df_test)\n X_train, y_train, X_test, y_test = preprocess(X_train, y_train, X_test, y_test)\n\n X_train_orig, X_test_orig = X_train.copy(), X_test.copy()\n\n if nested:\n # do the grid search in an inner loop\n cv_inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=random_state)\n cv_inds, sub_inds = custom_cv(cv_inner, X_df_train, subjects[train], subs_y[train])\n if selector == 'passthrough':\n param_grid = [{k: v for k, v in params.items() if 'selector' not in k} for params in param_grid]\n best_clf, best_selector = run_grid(clf, selector, X_train, y_train, cv_inds, param_grid)\n pipe = make_pipeline(best_selector, best_clf)\n\n pipe.fit(X_train_orig, y_train)\n\n if selector != 'passthrough':\n feature_inds = pipe[0].get_support()\n\n X_train = pipe[0].transform(X_train_orig)\n X_test = pipe[0].transform(X_test_orig)\n\n # calculate feature importances\n importances[ii, feature_inds] = feature_importance(pipe[1], X_test, y_test, n_repeats=n_perm_repeats,\n random_state=random_state)\n\n # make the predictions and evaluate the model\n y_pred = pipe.predict(X_test_orig)\n try:\n y_scores = pipe.decision_function(X_test_orig)\n except:\n y_scores = np.max(pipe.predict_proba(X_test_orig), axis=1)\n\n y_pred_subjects, y_scores_subjects = prediction_per_subject(subs_y[test], y_pred, y_scores,\n list(X_df_test.index), subjects[test])\n cv_accuracy, cv_precision, cv_recall, cv_specif, cv_f1, cv_roc_auc = performance(subs_y[test], y_pred_subjects,\n y_scores_subjects,\n average=average)\n\n for i in range(len(subjects[test])):\n if rep_cv:\n div = 5\n else:\n div = 1\n if y_pred_subjects[i] == subs_y[test][i]:\n subject_results.at[subjects[test][i], 'classif_score'] += (1 / div)\n subject_results.at[subjects[test][i], 'df_score'] += (y_scores_subjects[i] / div)\n\n results_dict['accuracy'].append(cv_accuracy)\n results_dict['precision'].append(cv_precision)\n results_dict['recall'].append(cv_recall)\n results_dict['specif'].append(cv_specif)\n results_dict['f1'].append(cv_f1)\n results_dict['roc_auc'].append(cv_roc_auc)\n\n print(pipe)\n rmtree(cachedir)\n\n return pipe, results_dict, np.mean(importances, axis=0), subject_results\n","sub_path":"model/cross_validate.py","file_name":"cross_validate.py","file_ext":"py","file_size_in_byte":9286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"216269516","text":"#Boa:Frame:frmDataFilter\n\nfrom datetime import datetime\nimport wx\nfrom wx.lib.pubsub import pub as Publisher\n\n\ndef create(parent):\n return frmDataFilter(parent)\n\n[wxID_FRMDATAFILTER, wxID_FRMDATAFILTERBTNAPPLY, wxID_FRMDATAFILTERBTNCANCEL,\n wxID_FRMDATAFILTERBTNCLEAR, wxID_FRMDATAFILTERBTNOK,\n wxID_FRMDATAFILTERCBGAPTIME, wxID_FRMDATAFILTERDBAFTER,\n wxID_FRMDATAFILTERDPBEFORE, wxID_FRMDATAFILTERLBLDATEAFTER,\n wxID_FRMDATAFILTERLBLDATEBEFORE, wxID_FRMDATAFILTERLBLGAPSTIME,\n wxID_FRMDATAFILTERLBLGAPVALUE, wxID_FRMDATAFILTERLBLTHRESHVALGT,\n wxID_FRMDATAFILTERLBLTHRESHVALLT, wxID_FRMDATAFILTERPANEL1,\n wxID_FRMDATAFILTERRBDATAGAPS, wxID_FRMDATAFILTERRBDATE,\n wxID_FRMDATAFILTERRBTHRESHOLD, wxID_FRMDATAFILTERRBVCHANGETHRESH,\n wxID_FRMDATAFILTERSBDATE, wxID_FRMDATAFILTERSBGAPS,\n wxID_FRMDATAFILTERSBTHRESHOLD, wxID_FRMDATAFILTERTXTGAPSVAL,\n wxID_FRMDATAFILTERTXTTHRESHVALGT, wxID_FRMDATAFILTERTXTTHRESVALLT,\n wxID_FRMDATAFILTERTXTVCHANGETHRESH, wxID_FRMDATAFILTERCHKFILTER,\n] = [wx.NewId() for _init_ctrls in range(27)]\n\nclass frmDataFilter(wx.Dialog):\n def _init_ctrls(self, prnt):\n self.is_applied = False\n # generated method, don't edit\n wx.Dialog.__init__(self, id=wxID_FRMDATAFILTER, name=u'frmDataFilter',\n parent=prnt, pos=wx.Point(599, 384), size=wx.Size(313, 400),\n style=wx.DEFAULT_DIALOG_STYLE, title=u'Data Filter')\n self.SetClientSize(wx.Size(297, 370))\n self.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False,\n u'MS Shell Dlg 2'))\n\n self.panel1 = wx.Panel(id=wxID_FRMDATAFILTERPANEL1, name='panel1',\n parent=self, pos=wx.Point(0, 0), size=wx.Size(297, 370),\n style=wx.TAB_TRAVERSAL)\n\n self.sbThreshold = wx.StaticBox(id=wxID_FRMDATAFILTERSBTHRESHOLD,\n label=u'Value Threshold', name=u'sbThreshold', parent=self.panel1,\n pos=wx.Point(16, 8), size=wx.Size(272, 72), style=0)\n self.sbThreshold.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False,\n u'MS Shell Dlg 2'))\n\n self.sbGaps = wx.StaticBox(id=wxID_FRMDATAFILTERSBGAPS,\n label=u'Data Gaps', name=u'sbGaps', parent=self.panel1,\n pos=wx.Point(16, 88), size=wx.Size(272, 72), style=0)\n self.sbGaps.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False,\n u'MS Shell Dlg 2'))\n\n self.sbDate = wx.StaticBox(id=wxID_FRMDATAFILTERSBDATE, label=u'Date',\n name=u'sbDate', parent=self.panel1, pos=wx.Point(16, 168),\n size=wx.Size(264, 112), style=0)\n self.sbDate.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD, False,\n u'MS Shell Dlg 2'))\n\n self.rbThreshold = wx.RadioButton(id=wxID_FRMDATAFILTERRBTHRESHOLD,\n label=u'', name=u'rbThreshold', parent=self.panel1,\n pos=wx.Point(8, 8), size=wx.Size(16, 13), style=0)\n self.rbThreshold.SetValue(True)\n\n self.rbDataGaps = wx.RadioButton(id=wxID_FRMDATAFILTERRBDATAGAPS,\n label=u'', name=u'rbDataGaps', parent=self.panel1, pos=wx.Point(8,\n 88), size=wx.Size(16, 13), style=0)\n\n self.rbDate = wx.RadioButton(id=wxID_FRMDATAFILTERRBDATE, label=u'',\n name=u'rbDate', parent=self.panel1, pos=wx.Point(8, 168),\n size=wx.Size(16, 13), style=0)\n\n self.rbVChangeThresh = wx.RadioButton(id=wxID_FRMDATAFILTERRBVCHANGETHRESH,\n label=u'Value Change Threshold >=', name=u'rbVChangeThresh',\n parent=self.panel1, pos=wx.Point(8, 288), size=wx.Size(152, 13),\n style=0)\n self.rbVChangeThresh.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD,\n False, u'MS Shell Dlg 2'))\n\n self.lblThreshValGT = wx.StaticText(id=wxID_FRMDATAFILTERLBLTHRESHVALGT,\n label=u'Value >', name=u'lblThreshValGT', parent=self.panel1,\n pos=wx.Point(24, 32), size=wx.Size(38, 13), style=0)\n\n self.lblThreshValLT = wx.StaticText(id=wxID_FRMDATAFILTERLBLTHRESHVALLT,\n label=u'Value<', name=u'lblThreshValLT', parent=self.panel1,\n pos=wx.Point(24, 56), size=wx.Size(35, 13), style=0)\n\n self.txtThreshValGT = wx.TextCtrl(id=wxID_FRMDATAFILTERTXTTHRESHVALGT,\n name=u'txtThreshValGT', parent=self.panel1, pos=wx.Point(72, 24),\n size=wx.Size(200, 21), style=0, value='')\n\n self.txtThreshValLT = wx.TextCtrl(id=wxID_FRMDATAFILTERTXTTHRESVALLT,\n name=u'txtThresValLT', parent=self.panel1, pos=wx.Point(72, 48),\n size=wx.Size(200, 21), style=0, value='')\n\n self.lblGapValue = wx.StaticText(id=wxID_FRMDATAFILTERLBLGAPVALUE,\n label=u'Value:', name=u'lblGapValue', parent=self.panel1,\n pos=wx.Point(32, 112), size=wx.Size(31, 13), style=0)\n\n self.lblGapsTime = wx.StaticText(id=wxID_FRMDATAFILTERLBLGAPSTIME,\n label=u'Time Period:', name=u'lblGapsTime', parent=self.panel1,\n pos=wx.Point(32, 136), size=wx.Size(60, 13), style=0)\n\n self.txtGapsVal = wx.TextCtrl(id=wxID_FRMDATAFILTERTXTGAPSVAL,\n name=u'txtGapsVal', parent=self.panel1, pos=wx.Point(80, 104),\n size=wx.Size(192, 21), style=0, value='')\n\n self.cbGapTime = wx.ComboBox(choices=['second', 'minute', 'hour',\n 'day'], id=wxID_FRMDATAFILTERCBGAPTIME, name=u'cbGapTime',\n parent=self.panel1, pos=wx.Point(96, 128), size=wx.Size(176, 21),\n style=0, value='second')\n\n self.lblDateAfter = wx.StaticText(id=wxID_FRMDATAFILTERLBLDATEAFTER,\n label=u'After:', name=u'lblDateAfter', parent=self.panel1,\n pos=wx.Point(24, 232), size=wx.Size(30, 13), style=0)\n\n self.lblDateBefore = wx.StaticText(id=wxID_FRMDATAFILTERLBLDATEBEFORE,\n label=u'Before:', name=u'lblDateBefore', parent=self.panel1,\n pos=wx.Point(24, 184), size=wx.Size(37, 13), style=0)\n\n self.dpAfter = wx.DatePickerCtrl(id=wxID_FRMDATAFILTERDBAFTER,\n name=u'dbAfter', parent=self.panel1, pos=wx.Point(24, 248),\n size=wx.Size(248, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)\n\n self.dpBefore = wx.DatePickerCtrl(id=wxID_FRMDATAFILTERDPBEFORE,\n name=u'dpBefore', parent=self.panel1, pos=wx.Point(24, 200),\n size=wx.Size(248, 21), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)\n\n self.txtVChangeThresh = wx.TextCtrl(id=wxID_FRMDATAFILTERTXTVCHANGETHRESH,\n name=u'changeThresh', parent=self.panel1, pos=wx.Point(168, 280),\n size=wx.Size(100, 21), style=0, value='')\n\n self.chkToggleFilterSelection = wx.CheckBox(id=wxID_FRMDATAFILTERCHKFILTER,\n name=u'checkbox', label=u'Filter from previous filter',\n parent=self.panel1, pos=wx.Point(8, 306),\n size=wx.Size(232,25), style=0)\n self.chkToggleFilterSelection.Bind(wx.EVT_CHECKBOX, self.OnCheckbox,\n id=wxID_FRMDATAFILTERCHKFILTER)\n\n self.btnClear = wx.Button(id=wxID_FRMDATAFILTERBTNCLEAR,\n label=u'Clear Filter', name=u'btnClear', parent=self.panel1,\n pos=wx.Point(8, 335), size=wx.Size(64, 23), style=0)\n self.btnClear.Bind(wx.EVT_BUTTON, self.OnBtnClearButton,\n id=wxID_FRMDATAFILTERBTNCLEAR)\n\n self.btnOK = wx.Button(id=wxID_FRMDATAFILTERBTNOK, label=u'OK',\n name=u'btnOK', parent=self.panel1, pos=wx.Point(128, 335),\n size=wx.Size(48, 23), style=0)\n self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton,\n id=wxID_FRMDATAFILTERBTNOK)\n\n self.btnCancel = wx.Button(id=wxID_FRMDATAFILTERBTNCANCEL,\n label=u'Cancel', name=u'btnCancel', parent=self.panel1,\n pos=wx.Point(184, 335), size=wx.Size(48, 23), style=0)\n self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,\n id=wxID_FRMDATAFILTERBTNCANCEL)\n\n self.btnApply = wx.Button(id=wxID_FRMDATAFILTERBTNAPPLY, label=u'Apply',\n name=u'btnApply', parent=self.panel1, pos=wx.Point(240, 335),\n size=wx.Size(48, 23), style=0)\n self.btnApply.Bind(wx.EVT_BUTTON, self.OnBtnApplyButton,\n id=wxID_FRMDATAFILTERBTNAPPLY)\n\n\n self.setDates()\n\n def __init__(self, parent, series):\n self.recordService = series\n self._init_ctrls(parent)\n\n def OnCheckbox(self, event):\n self.recordService.toggle_filter_previous()\n\n def OnBtnClearButton(self, event):\n self.setDates()\n self.txtThreshValGT.Clear()\n self.txtThreshValLT.Clear()\n self.txtGapsVal.Clear()\n self.cbGapTime.SetStringSelection(\"second\")\n self.txtVChangeThresh.Clear()\n self.recordService.reset_filter()\n\n Publisher.sendMessage((\"changePlotSelection\"), sellist=self.recordService.get_filter_list())\n\n def OnBtnOKButton(self, event):\n if not self.is_applied:\n self.OnBtnApplyButton(event)\n self.Close()\n\n def OnBtnCancelButton(self, event):\n self.Close()\n\n def OnBtnApplyButton(self, event):\n self.is_applied = True\n if self.rbThreshold.GetValue():\n if self.txtThreshValGT.GetValue():\n self.recordService.filter_value(float(self.txtThreshValGT.GetValue()), '>')\n if self.txtThreshValLT.GetValue():\n self.recordService.filter_value(float(self.txtThreshValLT.GetValue()), '<')\n\n if self.rbDataGaps.GetValue():\n if self.txtGapsVal.GetValue():\n self.recordService.data_gaps(float(self.txtGapsVal.GetValue()), self.cbGapTime.GetValue())\n\n if self.rbDate.GetValue():\n dateAfter = self.dpAfter.GetValue()\n dateBefore = self.dpBefore.GetValue()\n\n dtDateAfter = datetime(int(dateAfter.Year), int(dateAfter.Month) + 1, int(dateAfter.Day))\n dtDateBefore = datetime(int(dateBefore.Year), int(dateBefore.Month) + 1, int(dateBefore.Day))\n self.recordService.filter_date(dtDateBefore, dtDateAfter)\n\n if self.rbVChangeThresh.GetValue():\n if self.txtVChangeThresh.GetValue():\n self.recordService.value_change_threshold(float(self.txtVChangeThresh.GetValue()))\n\n Publisher.sendMessage((\"changePlotSelection\"), sellist=self.recordService.get_filter_list())\n\n\n def setDates(self):\n dateAfter = self.recordService.get_series_points()[0][2]\n dateBefore = self.recordService.get_series_points()[-1][2]\n formattedDateAfter = wx.DateTimeFromDMY(int(dateAfter.day) - 1, int(dateAfter.month), int(dateAfter.year), 0, 0, 0)\n formattedDateBefore = wx.DateTimeFromDMY(int(dateBefore.day) + 1, int(dateBefore.month), int(dateBefore.year), 0, 0, 0)\n self.dpAfter.SetRange(formattedDateAfter, formattedDateBefore)\n self.dpBefore.SetRange(formattedDateAfter, formattedDateBefore)\n self.dpAfter.SetValue(formattedDateAfter)\n self.dpBefore.SetValue(formattedDateBefore)","sub_path":"src/Gui/frmDataFilters.py","file_name":"frmDataFilters.py","file_ext":"py","file_size_in_byte":10943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"455841338","text":"#!/usr/bin/python\r\n# @name: My_mgmt_cfg\r\n# @author: xiamengbing@ruijie.com.cn\r\n# @date: 2016-02-01\r\n# @brief: user defined class intends only in eth_driver case, altered from BasicCmd\r\n# @topology: default\r\n\r\nimport time\r\nimport re\r\n\r\nfrom libcom.device_adapt.device_adapt import SwitchAdapter\r\nfrom libcom.console_drv.console_drv import Console\r\n\r\n\r\n__metaclass__ = type\r\n\r\n__all__ = ['MyMgmtCfg']\r\n\r\nclass MyMgmtCfg():\r\n def __init__(self, dev_key):\r\n self.__con = Console(dev_key)\r\n self.__sw_adap = SwitchAdapter(dev_key)\r\n\r\n def exit(self):\r\n self.__con.run_cmd('exit')\r\n \r\n def default_intf(self, intf_key):\r\n \"set the configure of the interface to default\"\r\n cmd_str = 'default interface ' + self.__sw_adap.get_intf_name(intf_key)\r\n self.__con.run_cmd(cmd_str)\r\n time.sleep(1)\r\n \r\n def get_mgmt_name(self):\r\n mgmt = self.__sw_adap.get_switch_mgmt()\r\n mgmt_name = self.__sw_adap.get_intf_name(mgmt.mgmt_key)\r\n return mgmt_name\r\n \r\n def intf_mode(self, intf_key):\r\n cmd_str = 'interface ' + self.__sw_adap.get_intf_name(intf_key)\r\n self.__con.run_cmd(cmd_str)\r\n \r\n def cfg_mgmt(self, set2def=False):\r\n \"\"\"\r\n set2def: if set the mgmt to default\r\n \"\"\"\r\n mgmt = self.__sw_adap.get_switch_mgmt()\r\n mgmt_key = mgmt.mgmt_key\r\n mgmt_ip = mgmt.mgmt_ip\r\n mask = mgmt.ip_mask\r\n\r\n if set2def == True:\r\n self.default_intf(mgmt_key)\r\n else:\r\n self.intf_mode(mgmt_key)\r\n self.__con.run_cmd('ip ad %s %s' % (mgmt_ip, mask))\r\n time.sleep(1)","sub_path":"cases_set/eth_driver/my_mgmt_cfg.py","file_name":"my_mgmt_cfg.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"8781679","text":"from django.db import models\n\n\nclass List(models.Model):\n title = models.CharField(max_length=200)\n description = models.TextField()\n priority = models.IntegerField(default=2)\n due_date = models.TextField(null=True, blank=True)\n completed = models.BooleanField(default=False)\n expired = models.TextField(blank=True, default=\"\")\n\n def __str__(self):\n return self.title + ' l ' + str(self.completed)\n\n class Meta:\n ordering=['priority', 'due_date', 'title']","sub_path":"mysite/todolist/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"457075750","text":"from functools import partial\nimport os\nimport pickle\nfrom typing import Callable, List, Union\n\nimport numpy as np\nfrom rdkit import Chem\n\nfrom .morgan_fingerprint import morgan_fingerprint\n\n\ndef load_features(path: str) -> List[np.ndarray]:\n \"\"\"\n Loads features saved as a .pckl file or as a directory of .pckl files.\n\n If path is a directory, assumes features are saved in files named 0.pckl, 1.pckl, ...\n\n :param path: Path to a .pckl file or a directory of .pckl files named as above.\n :return: A list of numpy arrays containing the features.\n \"\"\"\n if os.path.isfile(path):\n with open(path, 'rb') as f:\n features = pickle.load(f)\n features = [np.squeeze(np.array(feat.todense())) for feat in features]\n else:\n features = []\n features_num = 0\n features_path = os.path.join(path, f'{features_num}.pckl')\n\n while os.path.exists(features_path):\n with open(features_path, 'rb') as f:\n feats = pickle.load(f)\n features.extend([np.squeeze(np.array(feat.todense())) for feat in feats])\n\n features_num += 1\n features_path = os.path.join(path, f'{features_num}.pckl')\n\n return features\n\n\ndef get_features_func(features_generator: str) -> Union[Callable[[Union[str, Chem.Mol]], np.ndarray], partial]:\n \"\"\"\n Gets a features generator function by name.\n\n :param features_generator: The name of a features generator function.\n :return: A features generator function which process RDKit molecules and returns numpy arrays of features.\n \"\"\"\n if features_generator == 'morgan':\n return partial(morgan_fingerprint, use_counts=False)\n\n if features_generator == 'morgan_count':\n return partial(morgan_fingerprint, use_counts=True)\n\n if features_generator == 'rdkit_2d':\n from .rdkit_features import rdkit_2d_features\n\n return rdkit_2d_features\n\n if features_generator == \"rdkit_2d_normalized\":\n from .rdkit_features import rdkit_2d_normalized_features\n\n return rdkit_2d_normalized_features\n\n raise ValueError(f'features_generator type \"{features_generator}\" not supported.')\n","sub_path":"chemprop/features/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"25311844","text":"import unittest\n\nfrom conans.client.conf import default_settings_yml\nfrom conans.client.generators.compiler_args import CompilerArgsGenerator\nfrom conans.client.generators.gcc import GCCGenerator\nfrom conans.model.build_info import CppInfo, DepsCppInfo\nfrom conans.model.env_info import DepsEnvInfo, EnvInfo\nfrom conans.model.settings import Settings\nfrom conans.model.user_info import DepsUserInfo\nfrom conans.test.utils.conanfile import ConanFileMock\n\n\nclass CompilerArgsTest(unittest.TestCase):\n\n def visual_studio_extensions_test(self):\n settings = Settings.loads(default_settings_yml)\n settings.os = \"Windows\"\n settings.compiler = \"Visual Studio\"\n settings.compiler.version = \"15\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n\n conan_file = ConanFileMock()\n conan_file.settings = settings\n conan_file.deps_env_info = DepsEnvInfo()\n conan_file.deps_user_info = DepsUserInfo()\n conan_file.deps_cpp_info = DepsCppInfo()\n cpp_info = CppInfo(\"/root\")\n cpp_info.libs.append(\"mylib\")\n cpp_info.libs.append(\"other.lib\")\n conan_file.deps_cpp_info.update(cpp_info, \"zlib\")\n conan_file.env_info = EnvInfo()\n\n gen = CompilerArgsGenerator(conan_file)\n self.assertEqual('-O2 -Ob2 -DNDEBUG -link mylib.lib other.lib', gen.content)\n\n def _get_conanfile(self, settings):\n conan_file = ConanFileMock()\n conan_file.settings = settings\n conan_file.source_folder = \"my_cache_source_folder\"\n conan_file.build_folder = \"my_cache_build_folder\"\n conan_file.deps_env_info = DepsEnvInfo()\n conan_file.deps_user_info = DepsUserInfo()\n conan_file.deps_cpp_info = DepsCppInfo()\n cpp_info = CppInfo(\"/root\")\n cpp_info.include_paths.append(\"path/to/include1\")\n cpp_info.lib_paths.append(\"path/to/lib1\")\n cpp_info.libs.append(\"mylib\")\n cpp_info.bindirs = \"path/to/bin1\"\n cpp_info.cflags.append(\"c_flag1\")\n cpp_info.cxxflags.append(\"cxx_flag1\")\n cpp_info.defines.append(\"mydefine1\")\n\n conan_file.deps_cpp_info.update(cpp_info, \"zlib\")\n conan_file.env_info = EnvInfo()\n return conan_file\n\n def gcc_test(self):\n settings = Settings.loads(default_settings_yml)\n settings.os = \"Linux\"\n settings.compiler = \"gcc\"\n settings.compiler.version = \"6.3\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n settings.cppstd = \"gnu17\"\n\n conan_file = self._get_conanfile(settings)\n gcc = GCCGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m32 -O3 -s -DNDEBUG '\n '-Wl,-rpath=\"path/to/lib1\" '\n '-Lpath/to/lib1 -lmylib -std=gnu++17', gcc.content)\n\n settings.arch = \"x86_64\"\n settings.build_type = \"Debug\"\n settings.compiler.libcxx = \"libstdc++11\"\n\n gcc = GCCGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m64 -g '\n '-Wl,-rpath=\"path/to/lib1\" -Lpath/to/lib1 -lmylib '\n '-D_GLIBCXX_USE_CXX11_ABI=1 -std=gnu++17',\n gcc.content)\n\n settings.compiler.libcxx = \"libstdc++\"\n gcc = GCCGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m64 -g '\n '-Wl,-rpath=\"path/to/lib1\" -Lpath/to/lib1 -lmylib '\n '-D_GLIBCXX_USE_CXX11_ABI=0 -std=gnu++17',\n gcc.content)\n\n settings.os = \"Windows\"\n settings.compiler = \"Visual Studio\"\n settings.compiler.version = \"15\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n gcc = GCCGenerator(conan_file)\n # GCC generator ignores the compiler setting, it is always gcc\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m32 -O3 -s '\n '-DNDEBUG -Wl,-rpath=\"path/to/lib1\" -Lpath/to/lib1 -lmylib',\n gcc.content)\n\n def compiler_args_test(self):\n settings = Settings.loads(default_settings_yml)\n settings.os = \"Windows\"\n settings.compiler = \"Visual Studio\"\n settings.compiler.version = \"15\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n\n conan_file = self._get_conanfile(settings)\n gen = CompilerArgsGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath\\\\to\\\\include1 cxx_flag1 c_flag1 -O2 -Ob2 -DNDEBUG '\n '-link -LIBPATH:path\\\\to\\\\lib1 mylib.lib', gen.content)\n\n settings = Settings.loads(default_settings_yml)\n settings.os = \"Macos\"\n settings.compiler = \"apple-clang\"\n settings.compiler.version = \"9.0\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n conan_file = self._get_conanfile(settings)\n gen = CompilerArgsGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m32 -O3 -DNDEBUG '\n '-Wl,-rpath,\"path/to/lib1\" -Lpath/to/lib1 -lmylib', gen.content)\n\n settings = Settings.loads(default_settings_yml)\n settings.os = \"Linux\"\n settings.os_build = \"Macos\"\n settings.compiler = \"apple-clang\"\n settings.compiler.version = \"9.0\"\n settings.arch = \"x86\"\n settings.build_type = \"Release\"\n\n conan_file = self._get_conanfile(settings)\n args = CompilerArgsGenerator(conan_file)\n self.assertEqual('-Dmydefine1 -Ipath/to/include1 cxx_flag1 c_flag1 -m32 -O3 -DNDEBUG '\n '-Wl,-rpath,\"path/to/lib1\" '\n '-Lpath/to/lib1 -lmylib', args.content)\n","sub_path":"conans/test/unittests/client/generators/compiler_args_test.py","file_name":"compiler_args_test.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"20605841","text":"import django_filters\nfrom django.contrib.auth import get_user_model\n\nDjangoUser = get_user_model()\n\n\nclass User(django_filters.FilterSet):\n username = django_filters.CharFilter(field_name='username', lookup_expr='icontains')\n last_name = django_filters.CharFilter(field_name='last_name', lookup_expr='icontains')\n is_active = django_filters.BooleanFilter(method='filter_is_active')\n\n class Meta:\n model = DjangoUser\n fields = ['username', 'last_name', 'is_active']\n\n def filter_is_active(self, qs, name, value):\n return qs.filter(is_active=value)\n","sub_path":"core/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"234181695","text":"'''\nThis package collects and aggregates various news\nfeeds and stock market predictions to serve as \nendpoint.\n'''\n\nfrom flask import Flask , jsonify\nfrom scrape import scrape\n\napp = Flask(__name__)\n\nstock_key = \"5DY4VU38W7Q94GSL\"\n\n@app.route('/topnews')\n# def grab_news(\t`\t\t\t\t\t\t\t\t\t\t\t`\t``\t\t)\n@app.route('/search/')\ndef ini_search(company):\n\t'''\n\tThis function aggregates the news and stock\n\tfor given company. \n\t'''\n\n\tletitscrape = scrape(company)\n\tsearchTerm = company\n\tnewsBloomberg = letitscrape.getBloomberg()\n\treturn jsonify(newsBloomberg)\n\nif __name__ == \"__main__\":\n\tapp.run(host=\"0.0.0.0\" , port=5454 ,debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"283626015","text":"# Copyright 2018 luozhouyang\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport abc\n\nimport tensorflow as tf\nfrom tensorflow.python.layers import core\n\n\nclass DecoderInterface(abc.ABC):\n \"\"\"Decoder interface.\"\"\"\n\n @abc.abstractmethod\n def decode(self, mode, encoder_outputs, encoder_state, labels, src_seq_len):\n \"\"\"Decode target.\n\n Args:\n mode: mode\n encoder_outputs: encoder's output\n encoder_state: encoder's state\n labels: target inputs, an instance of ``naivenmt.inputters.Labels``\n src_seq_len: source sequence length\n\n Returns:\n logits: logits\n sample_id: sample id\n final context state: decoder's state\n \"\"\"\n raise NotImplementedError()\n\n\nclass AbstractDecoder(DecoderInterface):\n\n def __init__(self,\n params,\n embedding,\n sos,\n eos,\n scope=None,\n dtype=None):\n \"\"\"Init decoder.\n\n Args:\n params: hparams\n embedding: embedding, an instance of ``naivenmt.embeddings.Embedding``\n sos: sos token\n eos: eos token\n scope: variables scope\n dtype: variables dtype\n \"\"\"\n self.embedding = embedding\n self.sos = sos\n self.eos = eos\n self.scope = scope or \"decoder\"\n self.dtype = dtype or tf.float32\n\n self.time_major = params.time_major\n self.beam_width = params.beam_width\n self.length_penalty_weight = params.length_penalty_weight\n self.infer_batch_size = params.infer_batch_size\n self.target_vocab_size = params.target_vocab_size\n self.tgt_max_len_infer = params.tgt_max_len_infer\n self.sampling_temperature = params.sampling_temperature\n self.random_seed = params.random_seed\n\n def decode(self, mode, encoder_outputs, encoder_state, labels, src_seq_len):\n tgt_seq_len = labels.target_sequence_length\n with tf.variable_scope(self.scope, dtype=self.dtype) as scope:\n cell, decoder_initial_state = self._build_decoder_cell(\n mode, encoder_outputs, encoder_state, src_seq_len)\n output_layer = core.Dense(\n self.target_vocab_size, use_bias=False, name=\"output_projection\")\n\n if mode != tf.estimator.ModeKeys.PREDICT:\n helper = tf.contrib.seq2seq.TrainingHelper(\n self.embedding.decoder_embedding_input(labels.target_input_ids),\n tgt_seq_len,\n time_major=self.time_major)\n decoder = tf.contrib.seq2seq.BasicDecoder(\n cell, helper, decoder_initial_state)\n outputs, final_context_state, _ = tf.contrib.seq2seq.dynamic_decode(\n decoder,\n output_time_major=self.time_major,\n swap_memory=True,\n scope=scope)\n sample_id = outputs.sample_id\n logits = output_layer(outputs.rnn_output)\n else:\n beam_width = self.beam_width\n length_penalty_weight = self.length_penalty_weight\n tgt_sos_id = self.embedding.decoder_embedding_input(\n tf.constant(self.sos))\n tgt_sos_id = tf.cast(tgt_sos_id, tf.int32)\n tgt_eos_id = self.embedding.decoder_embedding_input(\n tf.constant(self.eos))\n tgt_eos_id = tf.cast(tgt_eos_id, tf.int32)\n\n max_iteration = self._get_max_infer_iterations(src_seq_len)\n start_tokens = tf.fill([self.infer_batch_size], tgt_sos_id)\n end_token = tgt_eos_id\n\n if beam_width > 0:\n decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n cell=cell,\n embedding=self.embedding,\n start_tokens=start_tokens,\n end_token=end_token,\n initial_state=decoder_initial_state,\n beam_width=beam_width,\n output_layer=output_layer,\n length_penalty_weight=length_penalty_weight)\n else:\n sampling_temperature = self.sampling_temperature\n if sampling_temperature > 0.0:\n helper = tf.contrib.seq2seq.SampleEmbeddingHelper(\n self.embedding, start_tokens, end_token,\n softmax_temperature=sampling_temperature,\n seed=self.random_seed)\n else:\n helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n self.embedding, start_tokens, end_token)\n\n decoder = tf.contrib.seq2seq.BasicDecoder(\n cell,\n helper,\n decoder_initial_state,\n output_layer=output_layer)\n\n outputs, final_context_state, _ = tf.contrib.seq2seq.dynamic_decode(\n decoder,\n max_iterations=max_iteration,\n output_time_major=self.time_major,\n swap_memory=True,\n scope=scope)\n\n if beam_width > 0:\n logits = tf.no_op()\n sample_id = outputs.predicted_ids\n else:\n logits = outputs.rnn_output\n sample_id = outputs.sample_id\n\n return logits, sample_id, final_context_state\n\n @abc.abstractmethod\n def _build_decoder_cell(self,\n mode,\n encoder_outputs,\n encoder_state,\n sequence_length):\n \"\"\"Build decoder cells.\n\n Args:\n mode: mode\n encoder_outputs: encoder's output\n encoder_state: encoder's state\n sequence_length: source sequence length\n \"\"\"\n raise NotImplementedError()\n\n def _get_max_infer_iterations(self, sequence_length):\n if self.tgt_max_len_infer:\n max_iterations = self.tgt_max_len_infer\n else:\n decoding_length_factor = 2.0\n max_encoder_length = tf.reduce_max(sequence_length)\n max_iterations = tf.to_int32(tf.round(\n tf.to_float(max_encoder_length) * decoding_length_factor))\n return max_iterations\n\n @staticmethod\n def _get_device_str(device_id, num_gpus):\n if num_gpus == 0:\n return \"/cpu:0\"\n device_str = \"/gpu:%d\" % (device_id % num_gpus)\n return device_str\n","sub_path":"naivenmt/decoders/abstract_decoder.py","file_name":"abstract_decoder.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"88084515","text":"#v1.0 2012_01_19\nimport sys\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport pymel.core as pm\n\ndef anamorphicConvert():\n sel = pm.selected()\n if len(sel) == 0:\n pm.error( \"Nothing is selected. Please select a camera and try again\" )\n camera = sel[0]\n cameraShape = camera.getShape()\n imagePlane = pm.listConnections(cameraShape, type = 'imagePlane')[0]\n hfa = cameraShape.getAttr('horizontalFilmAperture')\n lensSqueeze = cameraShape.getAttr('lensSqueezeRatio')\n if lensSqueeze ==1:\n cameraShape.setAttr('horizontalFilmAperture', hfa/2)\n cameraShape.setAttr('lensSqueezeRatio', 2.0)\n cameraShape.setAttr('overscan', 2.0)\n imagePlane.setAttr('sizeX', hfa/2)\n else:\n cameraShape.setAttr('horizontalFilmAperture', hfa*2)\n cameraShape.setAttr('lensSqueezeRatio', 1.0)\n cameraShape.setAttr('overscan', 1.0)\n imagePlane.setAttr('sizeX', hfa*2)","sub_path":"BDmaya/main_customToolsByCompany/tools_ALFuel/BD_anamorphicConvert.py","file_name":"BD_anamorphicConvert.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"166779264","text":"from django.shortcuts import redirect, render\nfrom lists.models import Item, List\nfrom lists.forms import ItemForm, ExistingListItemForm, NewListForm\nfrom django.contrib.auth import get_user_model\nfrom django.contrib import messages\n\nUser = get_user_model()\n\n\ndef home_page(request):\n return render(request, 'lists/home.html', {'form': ItemForm()})\n\n\ndef view_list(request, list_id):\n list_ = List.objects.get(id=list_id)\n form = ExistingListItemForm(for_list=list_)\n\n if request.method == 'POST':\n form = ExistingListItemForm(for_list=list_, data=request.POST)\n if form.is_valid():\n form.save()\n return redirect(list_)\n return render(request, 'lists/list.html', {'list': list_, 'form': form})\n\n\ndef new_list(request):\n form = NewListForm(data=request.POST)\n if form.is_valid():\n list_ = form.save(owner=request.user)\n return redirect(list_)\n return render(request, 'lists/home.html', {'form': form})\n\n\ndef my_lists(request, email):\n owner = User.objects.get(email=email)\n list_ = List.objects.filter(shared_with=owner)\n return render(request, 'lists/my_lists.html', {'owner': owner, 'list': list_})\n\n\ndef share(request, list_id):\n list_ = List.objects.get(id=list_id)\n try:\n user_to_share = User.objects.get(email=request.POST['sharee'])\n list_.shared_with.add(user_to_share)\n messages.success(request,\n f\"Your list has been shared with {user_to_share.email}\")\n except User.DoesNotExist:\n messages.warning(request,\n \"There is no such email in our Database, please try again\")\n return redirect(list_)\n","sub_path":"lists/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"644326554","text":"'''\nCreated on 11 Oct 2017\n\n@author: clementderrez\n'''\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nimport h5py\nfrom time import sleep\nimport glob\n\nDELAY = 600\n#files = next(os.walk('.'))[2]\n\nwhile True:\n plt.close(\"all\")\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.set_title('spectrum timeline')\n ax.view_init(elev=20., azim=-35)\n files = glob.glob('spectra*.*')\n arr = []\n n = 1\n z = np.array([1.0 for point in files])\n for f in files:\n h5file = h5py.File(f, 'r')\n dataset = h5file.get('entry/data/data')\n arr = np.array(dataset)*n\n ax.plot(arr[0,:], arr[1,:], zs=n, zdir = 'z')\n ax.set_zlabel('file index')\n n+=1\n h5file.close()\n \n plt.show()\n sleep(DELAY)","sub_path":"legacy/post_proc_DTU.py","file_name":"post_proc_DTU.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"143985286","text":"from PIL import Image\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, BatchNormalization\nimport os\nimport random\n\nDATA_DIR = \"./hw4_train\"\nTEST_DIR = \"./hw4_test\"\nCLASSES = [\"0\", \"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\nIMG_SIZE = 28\n\ndef getData():\n\t# convert .png images to numpy arrays\n\ttraining_data = []\n\tfor num in CLASSES:\n\t\tpath = os.path.join(DATA_DIR, num)\n\t\tclass_num = CLASSES.index(num)\n\t\tfor img in os.listdir(path):\n\t\t\ttemp = Image.open(os.path.join(path,img))\n\t\t\timg_numpy = np.array(temp.getdata())\n\t\t\ttraining_data.append([img_numpy, class_num])\n\n\t#randomize data to improve training\n\trandom.shuffle(training_data)\n\n\t# X: training input y: training labels\n\tX = []\n\ty = []\n\n\tfor features, label in training_data:\n\t X.append(features)\n\t y.append(label)\n\n\t# model takes numpy array as input\n\t# training input dimmensionality: (50400,28,28,1)\n\tX = np.array(X).reshape(-1,IMG_SIZE, IMG_SIZE,1)\n\n\t# all values should be between 0 and 1\n\tX = tf.keras.utils.normalize(X, axis=1)\n\n\ty = np.array(y)\n\n\treturn X,y\n\n\ndef createModel():\n\tX,y = getData()\n\n\tmodel = Sequential()\n\n\t# 4 layer convolutional neural network\n\t# BatchNormalization layers are used to normalize input\n\t# MaxPooling is used to reduce dimmensionality\n\t# Dropout is used to prevent overfitting\n\t# Flatten is used because Dense fully connected layers require 1D input\n\t# ReLU is used as the activation function because it is linear,\n\t# faster to compute, and converges faster\n\t# Softmax is used as the last activation function because it calculates\n\t# the probabilites of each target class\n\t# Sparse categorical crossentropy was chosen because our labels have values 0-9\n\t# Adam was chosen as the optimizer\n\t# Validation split is used for cross validation\n\tmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=X.shape[1:]))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Dropout(0.25))\n\n\tmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu'))\n\tmodel.add(BatchNormalization())\n\tmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\tmodel.add(Dropout(0.25))\n\n\tmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Dropout(0.25))\n\n\tmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\n\tmodel.add(BatchNormalization())\n\tmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\tmodel.add(Dropout(0.25))\n\n\tmodel.add(Flatten())\n\n\tmodel.add(Dense(512, activation='relu'))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Dropout(0.25))\n\n\tmodel.add(Dense(128, activation='relu'))\n\tmodel.add(Dropout(0.25))\n\tmodel.add(Dense(10, activation='softmax'))\n\n\tmodel.compile(loss='sparse_categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])\n\tmodel.fit(X, y, batch_size=32, validation_split=0.1, epochs=50)\n\n\tmodel.save(\"./testing_cnn.h5\")\n\n\ndef testModel():\n\ttest_data = []\n\n\tfor num in range(10000):\n\t path = os.path.join(\"./hw4_test\", str(num) + \".png\")\n\t temp = Image.open(path)\n\t img_numpy = np.array(temp.getdata())\n\t test_data.append([img_numpy])\n\n\ttest_data = np.array(test_data).reshape(-1,IMG_SIZE, IMG_SIZE,1)\n\ttest_data = test_data/255.0\n\n\tnew_model = tf.keras.models.load_model(\"./testing_cnn.h5\")\n\tpredictions = new_model.predict(test_data)\n\n\tprediction_file = open(\"./prediction.txt\", \"w\")\n\tfor prediction in predictions:\n\t actual_prediction = np.argmax(prediction)\n\t prediction_file.write(str(actual_prediction))\n\t prediction_file.write(\"\\n\")\n\tprediction_file.close()\n\n\nif __name__ == \"__main__\":\n#\tcreateModel()\n\ttestModel()","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"111940093","text":"from ast import literal_eval\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import View\nfrom onegeo_api.models import Resource\nfrom onegeo_api.models import Task\nfrom onegeo_api import utils\n\n\nPDF_BASE_DIR = settings.PDF_DATA_BASE_DIR\nMSG_406 = \"Le format demandé n'est pas pris en charge. \"\n\n\n@method_decorator(csrf_exempt, name=\"dispatch\")\nclass ResourceView(View):\n\n def get(self, request, id):\n user = utils.get_user_or_401(request)\n if isinstance(user, HttpResponse):\n return user\n src_id = literal_eval(id)\n\n try:\n tsk = Task.objects.get(model_type_id=src_id, model_type=\"source\")\n except Task.DoesNotExist:\n data = utils.get_objects(user(), Resource, src_id)\n opts = {\"safe\": False}\n else:\n if tsk.stop_date is not None and tsk.success is True:\n data = utils.get_objects(user(), Resource, src_id)\n opts = {\"safe\": False}\n\n if tsk.stop_date is not None and tsk.success is False:\n data = {\"error\": tsk.description,\n \"task\": \"tasks/{}\".format(tsk.id)}\n opts = {\"status\": 424}\n\n if tsk.stop_date is None and tsk.success is None:\n data = {\"error\": tsk.description,\n \"task\": \"tasks/{}\".format(tsk.id)}\n opts = {\"status\": 423}\n\n return JsonResponse(data, **opts)\n\n\n@method_decorator(csrf_exempt, name=\"dispatch\")\nclass ResourceIDView(View):\n\n def get(self, request, src_id, rsrc_id):\n user = utils.get_user_or_401(request)\n if isinstance(user, HttpResponse):\n return user\n return JsonResponse(utils.get_object_id(user(), rsrc_id, Resource, src_id), safe=False)\n","sub_path":"onegeo_api/views/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174410705","text":"# Copyright (c) 2019.\n# MIT License\n#\n# Copyright (c) 2019 YumeNetwork\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n#\nfrom datetime import datetime, timedelta\n\nimport discord\nfrom discord.ext import commands\n\nimport modules.utils.checks as check\nfrom modules.sanction import Sanction\nfrom modules.utils.db import Settings\nfrom modules.utils.format import Embeds\nfrom modules.utils.format import Mod\nfrom modules.utils.guildy import GuildY\n\n\nclass Checks:\n\n @staticmethod\n async def member_check(member: discord.Member):\n guild = member.guild\n now = datetime.now()\n create = member.created_at\n\n strike = await Settings().get_sanction_settings_member(str(member.id), str(guild.id))\n\n sanctions = len(strike)\n time = (now - create).days\n\n return sanctions, time\n\n\nclass Automod(commands.Cog):\n conf = {}\n\n def __init__(self, bot):\n self.bot = bot\n self.config = bot.config\n self.mention_limit = 6\n\n async def check_mention_spam(self, message):\n author = message.author\n mentions = set(message.mentions)\n\n guildy = GuildY(message.guild)\n await guildy.get()\n\n if await self.immune(message):\n return\n\n if len(mentions) >= self.mention_limit:\n try:\n await message.delete()\n except discord.HTTPException:\n return False\n\n id = await Sanction().create_strike(message.author, \"Strike\", message.guild, \"Mentions Spam\")\n\n em = await Embeds().format_automod_embed(author, \"Mention spam\", id, message)\n if guildy.logging:\n channel = self.bot.get_channel(int(guildy.log_channel))\n try:\n await channel.send(embed=em)\n except discord.Forbidden:\n await message.channel.send(embed=em)\n else:\n await message.channel.send(embed=em)\n\n return True\n else:\n return False\n\n @staticmethod\n async def immune(message):\n return await check.is_immune(message)\n\n async def check_invite(self, message):\n author = message.author\n\n guildy = GuildY(message.guild)\n await guildy.get()\n\n if await self.immune(message):\n return\n\n if \"discord.gg/\" in message.content:\n try:\n await message.delete()\n except discord.HTTPException:\n return False\n\n id = await Sanction().create_strike(message.author, \"Strike\", message.guild, \"Discord Invite Link\")\n\n em = await Embeds().format_automod_embed(author, \"Discord Invite Link\", id, message)\n if guildy.logging:\n\n channel = self.bot.get_channel(int(guildy.log_channel))\n try:\n await channel.send(embed=em)\n except discord.Forbidden:\n await message.channel.send(embed=em)\n else:\n await message.channel.send(embed=em)\n return True\n else:\n return False\n\n @staticmethod\n async def spam_check(message):\n\n m_max = 3\n author = message.author\n m_count = 0\n\n async for m in message.channel.history(after=(datetime.utcnow() + timedelta(seconds=-10))):\n if m.author == author:\n m_count += 1\n if m_count > m_max:\n await message.delete()\n await message.channel.send(f\"No spamming, {message.author.mention}\", delete_after=5)\n await Sanction().create_strike(message.author, \"Strike\", message.guild, \"Spamming\")\n\n # TODO: Si mode strict, mute l'user...\n\n return True\n else:\n return False\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if (\n not message.guild\n or message.author.bot\n ):\n return\n\n guildy = GuildY(message.guild)\n await guildy.get()\n\n if guildy.automod:\n deleted = await self.check_mention_spam(message)\n if not deleted:\n await self.check_invite(message)\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n \"\"\"\n\n :param member: The member who joined the guild\n \"\"\"\n guildy = GuildY(member.guild)\n await guildy.get()\n\n glob = await Settings().get_glob_settings()\n\n # Check if the user has already been muted to avoid any sanctions bypass\n if member.id in guildy.mute:\n # Mute him again\n role = discord.utils.get(member.guild.roles, name=\"Muted\")\n if not role:\n role = await member.guild.create_role(name=\"Muted\", permissions=discord.Permissions.none(),\n reason=\"Mute Role\")\n for chan in member.guild.text_channels:\n await chan.set_permissions(role, send_messages=False)\n await member.add_roles(role)\n\n # Check if the user is in the blacklist\n if 'Blacklist' in glob:\n if member.id in glob['Blacklist'] and guildy.bl:\n # Ban the member\n await member.guild.ban(member, reason=\"Blacklist\")\n try:\n await member.send(\"you're in the blacklist ! If you think it's an error, ask here --> \"\n \"yume.network@protonmail.com\")\n except discord.Forbidden:\n return\n\n if guildy.logging:\n sanctions, time = await Checks().member_check(member)\n em = await Mod().check_embed(member, member.guild, sanctions, time)\n if guildy.log_channel:\n channel = self.bot.get_channel(int(guildy.log_channel))\n if isinstance(channel, discord.TextChannel):\n try:\n await channel.send(embed=em)\n except discord.Forbidden:\n return\n\n\n @commands.group()\n @check.is_admin()\n async def automod(self, ctx):\n return\n\n @automod.command()\n @check.is_admin()\n async def setup(self, ctx):\n await ctx.send(\"Not ready yet ! Be patient dear ;)\")\n\n @automod.command()\n @check.is_admin()\n async def gate(self, ctx):\n await ctx.send(\"Not ready yet ! Be patient dear ;)\")\n\n # TODO: Gateway\n\ndef setup(bot):\n bot.add_cog(Automod(bot))\n","sub_path":"modules/automod.py","file_name":"automod.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"168575872","text":"from random import randint\r\n\r\ndef porovnaj(vyzrebovane,tip):\r\n user_uhadnute = 0\r\n user_uhadnute_ls = []\r\n for i in tip:\r\n if i in vyzrebovane:\r\n user_uhadnute_ls.append(i)\r\n user_uhadnute += 1\r\n return user_uhadnute, user_uhadnute_ls\r\n\r\ninp = input(\"Zadajte vas tip:\")\r\ntip = inp.split(\" \")\r\ntip = [int(i) for i in tip]\r\n\r\nvyzrebovane = []\r\nfor i in range(6):\r\n temp = randint(1,49)\r\n while temp in vyzrebovane:\r\n temp = randint(1,49)\r\n vyzrebovane.append(temp)\r\n\r\nprint(\"Zrebovane cisla:\",*vyzrebovane)\r\n\r\nuser_uhadnute, user_uhadnute_ls = porovnaj(vyzrebovane,tip)\r\n\r\nprint(\"Pocet uhadnutych cisel:\",user_uhadnute)\r\nprint(\"Uhadnute cisla:\",*user_uhadnute_ls)\r\n\r\nwith open(\"loteria_2.txt\",\"r\") as file:\r\n temp = file.read().split(\"\\n\")\r\n\r\ndata = [i.split(\" \") for i in temp]\r\nucastnici = {}\r\nfor i in data:\r\n uhadnute, ls = porovnaj(vyzrebovane,[int(a) for a in i])\r\n if uhadnute not in ucastnici:\r\n ucastnici[uhadnute] = 1\r\n else:\r\n ucastnici[uhadnute] += 1\r\n\r\nfor pocet in range(1,7):\r\n if pocet in ucastnici:\r\n print(f\"Pocet ucastnikov, ktori spravne tipovali prave {pocet} cisel: {ucastnici[pocet]}\")\r\n else:\r\n print(f\"Pocet ucastnikov, ktori spravne tipovali prave {pocet} cisel: 0\")","sub_path":"inf_2022/Maturitne zadania/Zadanie 12/zadanie12.py","file_name":"zadanie12.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"59526747","text":"import os\n\nfrom django.conf import settings\nfrom django.db import IntegrityError, transaction\nfrom django.db.models import ObjectDoesNotExist\nfrom django.core.files.base import ContentFile\nfrom django.core.files.storage import default_storage\nfrom django_dicom.models import Image, Series, Study, Patient\nfrom django_dicom.models.dicom_entity import DicomEntity\nfrom io import BufferedReader\n\n\nclass ImportImage:\n \"\"\"\n A class to handle importing new DICOM files to the database. Takes care of\n maintaining the Series, Study, and Patient relations with the created Image.\n \"\"\"\n\n def __init__(self, dcm: BufferedReader):\n \"\"\"\n Assigns the file data to the *dcm* attribute and declares the image attribute\n that will later be assigned the created :class:`django_dicom.Image` instance\n \n Parameters\n ----------\n dcm : BufferedReader\n Raw buffered DICOM file (*.dcm*).\n \n \"\"\"\n\n self.dcm = dcm\n self.image = None\n\n def store_file(self) -> str:\n \"\"\"\n Stores the DICOM file in a temporary location under `MEDIA_ROOT `_ \n using Django's `default_storage `_.\n \n Returns\n -------\n str\n The name of the temporary file created.\n \"\"\"\n\n content = ContentFile(self.dcm.read())\n return default_storage.save(\"tmp.dcm\", content)\n\n def create_image(self) -> Image:\n \"\"\"\n Stores the DICOM file locally and creates an Image instance from it without\n saving it (allowing for the fields to be updated from the header beforehand).\n \n Returns\n -------\n Image\n The created Image for the given file.\n \"\"\"\n\n temp_file_name = self.store_file()\n return Image(dcm=temp_file_name)\n\n def get_entity_uid_from_header(self, Entity: DicomEntity) -> str:\n \"\"\"\n Returns the UID of the given entity from the DICOM header information.\n \n Parameters\n ----------\n Entity : DicomEntity\n One of the DICOM entities (Image, Series, Study, and Patient).\n \n Returns\n -------\n str\n The UID value for the given entity.\n \"\"\"\n\n keyword = Entity.get_header_keyword(\"uid\")\n return self.image.header.get_value(keyword)\n\n def get_or_create_entity(self, Entity: DicomEntity, save: bool = True) -> tuple:\n \"\"\"\n Gets or creates an instance of the given :class:`django_dicom.DicomEntity`\n using its UID. \n The *save* parameter is mostly meant to help with testing.\n \n Parameters\n ----------\n Entity : DicomEntity\n One of the DICOM entities (Image, Series, Study, and Patient).\n save : bool\n Whether to save the instance to the database if it is created (default to True, which will call the save() method).\n \n Returns\n -------\n tuple\n (dicom_entity, created)\n \"\"\"\n\n uid = self.get_entity_uid_from_header(Entity)\n try:\n return Entity.objects.get(uid=uid), False\n except ObjectDoesNotExist:\n entity = Entity(uid=uid)\n entity.update_fields_from_header(self.image.header)\n if save:\n entity.save()\n return entity, True\n\n def get_image_destination(self) -> str:\n \"\"\"\n Returns the default relative path for this image under `MEDIA_ROOT `_.\n TODO: Add a way for the user to configure this.\n \n Returns\n -------\n str\n Default relative path for this image.\n \"\"\"\n\n patient_uid = self.get_entity_uid_from_header(Patient)\n series_uid = self.get_entity_uid_from_header(Series)\n name = f\"{self.image.number}.dcm\"\n return os.path.join(\"MRI\", patient_uid, series_uid, \"DICOM\", name)\n\n def move_image_to_destination(self) -> str:\n \"\"\"\n Moves the created image to its default location under `MEDIA_ROOT `_.\n \n Returns\n -------\n str\n Full path of the new location.\n \"\"\"\n\n relative_destination = self.get_image_destination()\n destination = os.path.join(settings.MEDIA_ROOT, relative_destination)\n # Save a reference to the current path for renaming\n current_path = self.image.dcm.path\n # Make sure the destination directory exists\n os.makedirs(os.path.dirname(destination), exist_ok=True)\n # Move file\n os.rename(current_path, destination)\n return relative_destination\n\n def generate_entities_and_relationships(self) -> None:\n \"\"\"\n Execute the generation and association of the new image's DICOM entities.\n \"\"\"\n\n self.image = self.create_image()\n self.image.update_fields_from_header(self.image.header)\n\n # We create the Series instance but avoid saving if it was created in\n # order to have a chance to first set its patient and study fields.\n series, created_series = self.get_or_create_entity(Series, save=False)\n if created_series or not all([series.study, series.patient]):\n # If the instance was created, we get or create the appropriate\n # Patient and Study instances and set the created instance's fields.\n patient, _ = self.get_or_create_entity(Patient)\n study, _ = self.get_or_create_entity(Study)\n series.patient = patient\n series.study = study\n series.save()\n\n # Finally we can relate the Series instance to the created Image instance and save.\n self.image.series = series\n self.image.save()\n\n def handle_integrity_error(self) -> tuple:\n \"\"\"\n If an IntegrityError is raised during generation of the DICOM entities,\n delete the temporary file.\n An InegrityError should indicate the image already exists in the database,\n so the method also tries to return the existing Image instance.\n \n Returns\n -------\n tuple\n ( existing_image , created )\n \"\"\"\n\n os.remove(self.image.dcm.path)\n return Image.objects.get(uid=self.image.uid), False\n\n def run(self) -> tuple:\n \"\"\"\n Adds the image to the database and generates its associated entities as\n an atomic transaction. If the transaction fails, calls :meth:`~django_dicom.data_import.import_image.ImportImage.handle_integrity_error`\n This assumes an existing image and tries to return it.\n \n Returns\n -------\n tuple\n ( image_instance, created )\n \"\"\"\n try:\n with transaction.atomic():\n self.generate_entities_and_relationships()\n\n # An IntegrityError should indicate the image exists in the database.\n except IntegrityError:\n\n # Assume image exists in database and returns it.\n try:\n return self.handle_integrity_error()\n\n # If this assumption was wrong, handle_integity_error() will raise an\n # ObjectDoesNotExist, and in that case we re-raise the original IntegrityError.\n except ObjectDoesNotExist:\n pass\n raise\n\n # If we got here, the transaction must have been successful, so we move the\n # dcm file to its desired location in the file-system and return it.\n self.image.dcm.name = self.move_image_to_destination()\n self.image.save()\n return self.image, True\n","sub_path":"django_dicom/data_import/import_image.py","file_name":"import_image.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"640637425","text":"\"\"\"Includes private helpers for the API class.\n\nCopyright 2013 by Rackspace Hosting, Inc.\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 http://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\"\"\"\n\nimport re\nfrom falcon import responders\n\nHTTP_METHODS = (\n 'CONNECT',\n 'DELETE',\n 'GET',\n 'HEAD',\n 'OPTIONS',\n 'POST',\n 'PUT',\n 'TRACE',\n 'PATCH'\n)\n\n\ndef should_ignore_body(status, method):\n \"\"\"Return True if the status or method indicates no body, per RFC 2616\n\n Args:\n status: An HTTP status line, e.g., \"204 No Content\"\n\n Returns:\n True if method is HEAD, or the status is 1xx, 204, or 304; returns\n False otherwise.\n\n \"\"\"\n return (method == 'HEAD' or\n status.startswith('204') or\n status.startswith('1') or\n status.startswith('304'))\n\n\ndef set_content_length(resp):\n \"\"\"Set Content-Length when given a fully-buffered body or stream length\n\n Pre:\n Either resp.body or resp.stream is set\n Post:\n resp contains a \"Content-Length\" header unless a stream is given, but\n resp.stream_len is not set (in which case, the length cannot be\n derived reliably).\n Args:\n resp: The response object on which to set the content length.\n\n \"\"\"\n\n if resp.body is not None:\n # Since body is assumed to be a byte string (str in Python 2, bytes in\n # Python 3), figure out the length using standard functions.\n resp.set_header('Content-Length', str(len(resp.body)))\n elif resp.stream is not None:\n if resp.stream_len is not None:\n # Total stream length is known in advance (e.g., streaming a file)\n resp.set_header('Content-Length', str(resp.stream_len))\n else:\n # Stream given, but length is unknown (dynamically-generated body)\n pass\n else:\n # No body given\n resp.set_header('Content-Length', '0')\n\n\ndef compile_uri_template(template):\n \"\"\"Compile the given URI template string into a pattern matcher.\n\n Currently only recognizes Level 1 URI templates, and only for the path\n portion of the URI.\n\n See also: http://tools.ietf.org/html/rfc6570\n\n Args:\n template: A Level 1 URI template. Method responders can retrieve values\n for the fields specified as part of the template path by calling\n req.get_param(field_name)\n\n \"\"\"\n if not isinstance(template, str):\n raise TypeError('uri_template is not a string')\n\n # Convert Level 1 var patterns to equivalent named regex groups\n escaped = re.sub(r'([\\.\\(\\)\\[\\]\\?\\*\\+\\^\\|])', r'\\.', template)\n pattern = re.sub(r'{([a-zA-Z][a-zA-Z_]*)}', r'(?P<\\1>[^/]+)', escaped)\n pattern = r'\\A' + pattern + r'\\Z'\n\n return re.compile(pattern, re.IGNORECASE)\n\n\ndef create_http_method_map(resource):\n \"\"\"Maps HTTP methods (such as GET and POST) to methods of resource object\n\n Args:\n resource: An object with \"responder\" methods, starting with on_*, that\n correspond to each method the resource supports. For example, if a\n resource supports GET and POST, it should define\n on_get(self, req, resp) and on_post(self,req,resp).\n\n \"\"\"\n method_map = {}\n\n for method in HTTP_METHODS:\n try:\n func = getattr(resource, 'on_' + method.lower())\n except AttributeError:\n # resource does not implement this method\n pass\n else:\n # Usually expect a method, but any callable will do\n if hasattr(func, '__call__'):\n method_map[method] = func\n\n # Attach a resource for unsupported HTTP methods\n allowed_methods = list(method_map.keys())\n func = responders.create_method_not_allowed(allowed_methods)\n\n for method in HTTP_METHODS:\n if method not in allowed_methods:\n method_map[method] = func\n\n return method_map\n","sub_path":"falcon/api_helpers.py","file_name":"api_helpers.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"105353719","text":"import tensorflow as tf\n\n\ndef get_mask(val, max_val):\n val0 = tf.greater_equal(val, 0)\n val1 = tf.less(val, max_val)\n mask = tf.logical_and(val0, val1)\n return mask\n\n\ndef get_valid_mask(x, y, height, width):\n x_mask = get_mask(x, width)\n y_mask = get_mask(y, height)\n mask = tf.logical_and(x_mask, y_mask)\n return mask\n\n\ndef miss_values(new_coords, height, width):\n new_y = tf.slice(new_coords, [0, 0], [-1, 1])\n new_x = tf.slice(new_coords, [0, 1], [-1, 1])\n mask0 = get_valid_mask(new_x, new_y, height, width)\n mask1 = tf.identity(mask0)\n mask2d = tf.concat((mask0, mask1), axis=1)\n new_coords = tf.boolean_mask(new_coords, mask2d)\n new_coords = tf.reshape(new_coords, shape=(-1, 2))\n values = tf.ones(shape=(new_coords.shape[0]))\n mask = tf.scatter_nd(new_coords, values, shape=(height, width))\n coords = tf.where(mask == 0)\n coords = tf.cast(coords, dtype=tf.int32)\n return coords\n\n\ndef padding_mask(coordinates, height, width):\n c = tf.transpose(coordinates)\n y = tf.slice(c, [0, 0], [1, -1])\n x = tf.slice(c, [1, 0], [1, -1])\n xm0 = tf.equal(x, 0)\n xm1 = tf.equal(x, width + 1)\n xm = tf.logical_or(xm0, xm1)\n ym0 = tf.equal(y, 0)\n ym1 = tf.equal(y, height + 1)\n ym = tf.logical_or(ym0, ym1)\n mask = tf.logical_or(xm, ym)\n m0 = tf.reshape(mask, shape=(-1, 1))\n m1 = tf.identity(m0)\n mask = tf.concat((m0, m1), axis=1)\n coords = tf.boolean_mask(coordinates, mask)\n coords = tf.reshape(coords, shape=(-1, 2))\n values = tf.ones(shape=coords.shape[0], dtype=tf.uint8)\n pad_mask = tf.scatter_nd(coords, values, tf.constant([height + 2, width + 2]))\n pad_mask = tf.clip_by_value(pad_mask, 0, 1)\n return pad_mask\n\n\ndef fill_channel(channel,\n empty_coordinates,\n den,\n height,\n width,\n p0, p1,\n p2, p3,\n p4, p5,\n p6, p7):\n \"\"\"\n Заполнить канал channel в значениях empty_coordinates\n \"\"\"\n p0v = tf.gather_nd(channel, p0)\n p1v = tf.gather_nd(channel, p1)\n p2v = tf.gather_nd(channel, p2)\n p3v = tf.gather_nd(channel, p3)\n p4v = tf.gather_nd(channel, p4)\n p5v = tf.gather_nd(channel, p5)\n p6v = tf.gather_nd(channel, p6)\n p7v = tf.gather_nd(channel, p7)\n\n values = tf.math.add_n((p0v, p1v, p2v, p3v, p4v, p5v, p6v, p7v))\n den = tf.cast(den, tf.float32)\n values = tf.divide(values, den)\n\n empty_coordinates = tf.subtract(empty_coordinates, 1)\n shape = (height, width)\n filled_channel = tf.scatter_nd(empty_coordinates, values, shape)\n return filled_channel\n\n\ndef interpolation(image: tf.Variable, new_coords: tf.Variable) -> tf.Variable:\n height, width = image.shape[1], image.shape[2]\n empty_coordinates = miss_values(new_coords, height, width)\n # Строим маску пропусков с паддингом 1\n empty_coordinates = tf.add(empty_coordinates, 1)\n values = tf.ones(shape=empty_coordinates.shape[0], dtype=tf.uint8)\n miss_values_mask = tf.scatter_nd(empty_coordinates, values, tf.constant([height + 2, width + 2]))\n y = tf.slice(empty_coordinates, [0, 0], [-1, 1])\n x = tf.slice(empty_coordinates, [0, 1], [-1, 1])\n # Координаты x,y вокруг пропусков\n px0 = tf.squeeze(tf.subtract(x, 1), axis=1)\n py0 = tf.squeeze(tf.subtract(y, 1), axis=1)\n px1 = tf.squeeze(tf.add(x, 1), axis=1)\n py1 = tf.squeeze(tf.add(y, 1), axis=1)\n\n x = tf.squeeze(x, axis=1)\n y = tf.squeeze(y, axis=1)\n # Координаты точек вокруг пропусков\n p0 = tf.stack((py0, px0), axis=1)\n p1 = tf.stack((py0, x), axis=1)\n p2 = tf.stack((py0, px1), axis=1)\n p3 = tf.stack((y, px0), axis=1)\n p4 = tf.stack((y, px1), axis=1)\n p5 = tf.stack((py1, px0), axis=1)\n p6 = tf.stack((py1, x), axis=1)\n p7 = tf.stack((py1, px1), axis=1)\n\n coords_around = tf.stack((p0, p1, p2, p3, p4, p5, p6, p7), axis=0)\n coords_around = tf.reshape(coords_around, shape=(-1, 2))\n coords_around = tf.cast(coords_around, tf.int32)\n values = tf.ones(shape=coords_around.shape[0], dtype=tf.uint8)\n # Маска крайних точек, которые мы попытаемся взять\n pad_mask = padding_mask(coords_around, height, width)\n # Маска точек вокруг пропусков\n t = tf.scatter_nd(coords_around, values, tf.constant([height + 2, width + 2]))\n t = tf.clip_by_value(t, 0, 1)\n # Убрать точки в паддинге\n t = tf.subtract(t, pad_mask)\n # t - маска существующих пикселей вокруг пропущенных точек\n t = tf.bitwise.bitwise_xor(miss_values_mask, t)\n\n # den - количество известных точек вокруг каждой неизвестной\n pd0v = tf.gather_nd(t, p0)\n pd1v = tf.gather_nd(t, p1)\n pd2v = tf.gather_nd(t, p2)\n pd3v = tf.gather_nd(t, p3)\n pd4v = tf.gather_nd(t, p4)\n pd5v = tf.gather_nd(t, p5)\n pd6v = tf.gather_nd(t, p6)\n pd7v = tf.gather_nd(t, p7)\n h = tf.stack((pd0v, pd1v, pd2v, pd3v, pd4v, pd5v, pd6v, pd7v), axis=0)\n h = tf.cast(h, tf.float32)\n den = tf.reduce_sum(h, axis=0)\n den = tf.add(den, 1)\n\n # Вернем координаты на место (без паддинга)\n p0 = tf.subtract(p0, 1)\n p1 = tf.subtract(p1, 1)\n p2 = tf.subtract(p2, 1)\n p3 = tf.subtract(p3, 1)\n p4 = tf.subtract(p4, 1)\n p5 = tf.subtract(p5, 1)\n p6 = tf.subtract(p6, 1)\n p7 = tf.subtract(p7, 1)\n p = (p0, p1, p2, p3, p4, p5, p6, p7)\n # Заполним пропуски для каждого канала\n channels = tf.map_fn(fn=lambda ch: fill_channel(ch, empty_coordinates, den, height, width, *p), elems=image)\n return channels\n","sub_path":"affine_tf/resample/resamples.py","file_name":"resamples.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"166706924","text":"import numpy as np\nimport networkx as nx\nimport itertools\nfrom scipy.spatial import distance\nfrom scipy.sparse import csr_matrix\nfrom scipy.optimize import linear_sum_assignment\nfrom numba import jit\nimport time\nimport json\nimport sys\nimport threading\nimport _thread as thread\n\nimport community as cm #http://perso.crans.org/aynaud/communities/\n\ndef create_points(file):\n ''' Reads .json file and returns numpy array of features.\n\n Reads .json file containing feature information as formatted as of July 2017.\n Currently only reads endpoints of Lines, Line Sequences, and Points, and converts their location\n into real world length by the given pixel ratio.\n\n Parameters\n ----------\n file : string\n Name of .json file as string (in current directory).\n\n Returns\n -------\n P : numpy array\n An (n x 3) Numpy array of locations of features on the impressions with the form [x, y, c]\n where c is some characterization of the feature. As of now, it is automatically set to 1.\n\n '''\n with open(file,'r') as f:\n file = json.load(f)\n\n file_endpoints = []\n\n ppcm = file['Image Data']['Pixel Ratio'] # points per centimeter\n\n dictionary = file['Features']\n for key in dictionary.keys():\n\n if key == 'LineSequences':\n for d in dictionary[key]:\n endpts = d['Boundary Points']\n for endpt in endpts:\n file_endpoints.append(endpt)\n\n if key == 'Lines':\n for d in dictionary[key]:\n endpts = d['Endpoints']\n for endpt in endpts:\n file_endpoints.append(endpt)\n\n if key == 'Points':\n for d in dictionary[key]:\n pts = d['Center']\n file_endpoints.append(pts)\n\n file_endpoints = np.asarray(file_endpoints)\n file_endpoints = file_endpoints / ppcm\n P = np.ones((len(file_endpoints), 3))\n P[:, :-1] = file_endpoints\n\n return P\n\n\ndef exit_after(s):\n ''' Decorator that calls quit_function after s seconds.\n\n '''\n def outer(fn):\n def inner(*args, **kwargs):\n timer = threading.Timer(s, quit_function, args=[fn.__name__])\n timer.start()\n try:\n result = fn(*args, **kwargs)\n finally:\n timer.cancel()\n return result\n return inner\n return outer\n\n\ndef quit_function(fn_name):\n '''Raises KeyboardInterrupt if called.\n\n '''\n sys.stderr.flush()\n thread.interrupt_main()\n\n\n@jit(nopython=True)\ndef create_sparse_matrix(vertices,distance_matrix_P,distance_matrix_Q,epsilon,R,C,D):\n '''Creates sparse adjacency matrix.\n\n Creates sparse adjacency matrix of the product graph.\n\n Parameters\n ----------\n vertices : list\n A list of ordered pairs (i,j) which corresponds to the vertex in the product graph\n pairing the i-th point in P and the j-th point in Q\n\n distance_matrix_P, distance_matrix_Q\n Matrix where the i,j-th entry is distance between the i-th point and j-th point of P (same with Q)\n\n Returns\n -------\n\n R,C,D : numpy arrays\n Arrays used with csr_matrix to create a sparse matrix.\n csr_matrix puts the i-th entry of D in the (i-th entry of R) row and (i-th entry of C) column\n\n Notes\n -----\n Given two sets of points P={p1,p2,...,pn} and Q={q1,q2,...,qm},\n the vertices of the graph are all m x n pairs possible by taking\n one point in P and one point in Q. There is an edge between vertices\n if the distances between the points in P and this distance between\n the points in Q are within epsilon percent of each other.\n\n\n '''\n\n n = len(vertices)\n\n edge_index = 0\n for r in range(0, n):\n i0 = vertices[r][0]\n j0 = vertices[r][1]\n for c in range(r + 1, n):\n i1 = vertices[c][0]\n j1 = vertices[c][1]\n if (i0 != i1) and (j0 != j1):\n d1 = distance_matrix_P[i0, i1]\n d2 = distance_matrix_Q[j0, j1]\n if d1/d2 < 1 + epsilon and d2/d1 < 1 + epsilon:\n R[edge_index] = r\n C[edge_index] = c\n D[edge_index] = 1\n edge_index += 1\n return R[:edge_index], C[:edge_index], D[:edge_index]\n\n\ndef create_graph(P,Q,epsilon):\n '''Creates NetworkX graph from the sparse matrix.\n\n '''\n\n distance_matrix_P = distance.squareform(distance.pdist(P))\n distance_matrix_Q = distance.squareform(distance.pdist(Q))\n\n l = len(P)\n k = len(Q)\n\n vertices = []\n verticesCopy = list(itertools.product(list(range(0, l)), list(range(0, k))))\n\n for v in verticesCopy: # remove vertices by 'color'\n i, j = v\n if P[i][2] == Q[j][2]:\n vertices.append(v)\n\n n = len(vertices)\n m = int(n*(n-1)/2)\n\n R = np.empty(m, dtype=int)\n C = np.empty(m, dtype=int)\n D = np.empty(m, dtype=float)\n\n R,C,D = create_sparse_matrix(vertices,distance_matrix_P,distance_matrix_Q,epsilon,R,C,D)\n\n A = csr_matrix((D,(R,C)),(n,n))\n\n G = nx.from_scipy_sparse_matrix(A)\n\n # adding position label to vertices\n positions = dict()\n\n for v in G.nodes():\n i, j = vertices[v]\n positions[v] = (P[i], Q[j])\n\n nx.set_node_attributes(G,'pos',positions)\n\n return G\n\n# timeout after 5 minutes\n@exit_after(300)\ndef find_large_cliques(G):\n\n ''' Finds a list of large cliques.\n\n First G is partitioned into communities by maximizing modularity.\n Then searches communities with size at least 75% of the maximum\n for cliques with size at least 80% of the clique number.\n\n Notes\n -----\n\n The .75 and .8 were chosen arbitrarily. Sometimes the largest cliques don't\n provide the best alignment, so I added these to broaden the search a little.\n\n This can take a while for large or dense graphs. So the @exit_after decorator\n quits this function after the specified number of seconds.\n '''\n\n partition = cm.best_partition(G)\n com_nodes = []\n\n max_community = max(set(partition.values()), key=list(partition.values()).count)\n large_communities = [com for com in set(partition.values()) if\n list(partition.values()).count(com) > .75*list(partition.values()).count(max_community)]\n\n #lists vertices of large_communities\n for com in large_communities:\n nodes = [node for node in partition.keys() if partition[node] == com]\n com_nodes.append(nodes)\n\n large_cliques = []\n\n for com in com_nodes:\n H = nx.subgraph(G,com)\n com_clique_list = list(nx.find_cliques(H))\n clique_num = max([len(cliq) for cliq in com_clique_list])\n\n for clique in com_clique_list:\n if len(clique) >= .80*clique_num:\n large_cliques.append(clique)\n\n #remove cliques that require reflection\n for clique in large_cliques:\n if check_for_reflection(G, clique):\n large_cliques.remove(clique)\n\n return large_cliques\n\n\ndef check_for_reflection(G, clique):\n '''Checks if the clique mapping requires relfection\n\n Does so by comparing the distance after rotation, translation and\n the distance after reflection, rotation, translation.\n '''\n\n H = G.subgraph(clique)\n points = nx.get_node_attributes(H, 'pos')\n\n P = []\n Q = []\n\n for point in points.values():\n P.append(point[0])\n Q.append(point[1])\n\n P = np.asarray(P)\n Q = np.asarray(Q)\n\n P, Q, P_transformed, cos_theta, sin_theta, t = transform(P, Q)\n\n Q2d = Q[:, [0, 1]]\n\n err = P_transformed - Q2d\n err = err**2\n err = np.sum(err,axis=1)\n err = err**.5\n err = np.sum(err)\n\n P[:,1] = -1*P[:,1] # make all y values negative\n\n P, Q, P_transformed, cos_theta, sin_theta, t = transform(P, Q)\n\n err_reflected = P_transformed - Q2d\n err_reflected = err_reflected**2\n err_reflected = np.sum(err_reflected, axis=1)\n err_reflected = err_reflected**.5\n err_reflected = np.sum(err_reflected)\n\n if err_reflected < err:\n return True\n else:\n return False\n\n\ndef number_of_colors(P, Q):\n '''Checks for the number of ways the features are characterized (colors).\n This assumes discrete characterization.\n '''\n\n A = np.concatenate((P[:, 2], Q[:, 2]))\n color_num = len(set(list(A))) # trick to count number of unique elements\n\n return color_num\n\n\ndef transform(P, Q):\n ''' An explicit solution to the optimal transformation (rotation, translation) problem.\n\n Parameters\n ----------\n P, Q : numpy arrays\n The sets of points to be optimally aligned.\n\n Returns\n -------\n P_transformed : numpy array\n P after the rotation and translation\n\n (a,b) :\n The translation.\n '''\n P2d = P[:, [0, 1]]\n Q2d = Q[:, [0, 1]]\n\n P_bar = np.array([np.mean(P[:, 0]), np.mean(P[:, 1])]) #average\n Q_bar = np.array([np.mean(Q[:, 0]), np.mean(Q[:, 1])])\n\n P_centered = P2d - P_bar\n Q_centered = Q2d - Q_bar\n\n A = np.sum(np.square(P_centered)) + np.sum(np.square(Q_centered))\n B = np.sum(np.multiply(P_centered, Q_centered))\n C = np.sum(np.multiply(P_centered[:, 0], Q_centered[:, 1])) - np.sum(np.multiply(P_centered[:, 1], Q_centered[:, 0]))\n\n SS = (B ** 2 + C ** 2) ** .5\n\n cos_theta = B / SS\n sin_theta = C / SS\n\n a = Q_bar[0] - cos_theta * P_bar[0] + sin_theta * P_bar[1]\n b = Q_bar[1] - sin_theta * P_bar[0] - cos_theta * P_bar[1]\n\n U = a + cos_theta * P[:, 0] - sin_theta * P[:, 1]\n V = b + sin_theta * P[:, 0] + cos_theta * P[:, 1]\n\n P_transformed = np.column_stack((U.T, V.T))\n\n return P, Q, P_transformed, cos_theta, sin_theta, (a, b)\n\n\ndef find_non_clique_points(P, Q, G, cliques, color_num):\n '''Given a list of cliques, returns a list of points in P and Q that aren't \"in the clique.\"\n\n For each clique in \"cliques\", it finds the points in P and Q that aren't in that clique.\n Then it seperates the points by their 'color' for later use with the hungarian algorithm.\n\n Returns\n -------\n non_clique : dict\n A dictionary where the keys are the indices of the list \"cliques\", and the values are\n a dictionary that seperates the non-clique points by color. The non-clique points are\n organized as a pair (P',Q'), where P' is the set of points in P that aren't in that clique.\n\n '''\n\n j = 0\n\n non_clique = dict()\n non_clique_colored = dict()\n\n\n for clique in cliques:\n\n clique_P = []\n clique_Q = []\n non_clique_P = []\n non_clique_Q = []\n H = G.subgraph(clique)\n\n for pt in list(nx.get_node_attributes(H, 'pos').values()):\n clique_P.append(pt[0])\n clique_Q.append(pt[1])\n\n for point in P:\n dummy = True\n for clique_point in clique_P:\n if np.array_equal(point,clique_point):\n dummy = False\n if dummy:\n non_clique_P.append(point)\n\n for point in Q:\n dummy = True\n for clique_point in clique_Q:\n if np.array_equal(point,clique_point):\n dummy = False\n if dummy:\n non_clique_Q.append(point)\n\n\n for c in range(1, color_num + 1):\n\n A = []\n B = []\n\n # pick out non clique points & by color\n for point in non_clique_P:\n if point[2] == c:\n A.append(point)\n for point in non_clique_Q:\n if point[2] == c:\n B.append(point)\n\n A = np.asarray(A)\n B = np.asarray(B)\n\n non_clique_colored[c] = (A, B)\n\n non_clique[j] = non_clique_colored\n j += 1\n return non_clique\n\n\ndef hungarian(P, Q):\n '''Applies the hungarian algorithm to the assignment problem.\n\n First creates distance matrix A, then adds \"ghost\" columns or rows to get rid\n of the largest distances.\n\n Notes\n -----\n Again, the .25 was chosen somewhat arbitrarily. The motivation is to remove *some* mappings that are\n clearly not the same feature. This will lower the score for mated pairs significantly,\n but the score for non-mated pairs should remain high.\n '''\n A = distance.cdist(P,Q)\n n, m = A.shape\n\n # get rid of the worst distances...\n if n <= m:\n A=np.concatenate((A, np.zeros((n,round(0.25*n)))),axis=1)\n elif n > m:\n A=np.concatenate((A, np.zeros((round(0.25*m),m))),axis=0)\n\n row_ind, col_ind = linear_sum_assignment(A) # apply hungarian algorithm\n\n\n # because of ghost columns, linear_sum_assignment outputs indices greater than\n # the dimension of P or Q.\n delete=[]\n for i in range(0,len(row_ind)):\n if row_ind[i] >= n or col_ind[i] >= m:\n delete.append(i)\n row_ind = np.delete(row_ind,delete)\n col_ind = np.delete(col_ind,delete)\n\n # calculate distance\n d = 0\n for i in range(0,len(row_ind)):\n d += A[row_ind[i],col_ind[i]]\n\n #rearrange P and Q\n P = P[row_ind]\n Q = Q[col_ind]\n\n return P, Q, d\n\n\ndef best_transformation(G, cliques, non_clique, color_num):\n ''' For each clique, it aligns the points. Then it chooses the clique that minimizes the total distance.\n\n For each clique, it gets the clique points, and finds the optimal transformation. Then it calculate the\n distance between the clique points. Then it applies the same transformation to the non-clique points, applies\n the hungarian algorithm to find the best pairings, and calculates the distance between those points.\n Lastly, it chooses the clique (transformation) that minimizes the total distance.\n '''\n transformation_index = dict()\n transformed_non_clique = dict()\n distances = dict()\n\n for j in range(0, len(cliques)):\n\n H = G.subgraph(cliques[j])\n points = nx.get_node_attributes(H, 'pos')\n\n P_clique = []\n Q_clique = []\n transformed_non_clique_colored = dict()\n\n for point in points.values():\n P_clique.append(point[0])\n Q_clique.append(point[1])\n\n P_clique = np.asarray(P_clique)\n Q_clique = np.asarray(Q_clique)\n\n T = transform(P_clique, Q_clique)\n transformation_index[j] = T\n P_clique, Q_clique, transformed_P_clique, cos_theta, sin_theta, t = T\n a, b = t\n\n transformed_P_clique_2d = transformed_P_clique[:,[0,1]]\n Q_clique_2d = Q_clique[:,[0,1]]\n err = transformed_P_clique_2d - Q_clique_2d\n err = err**2\n err = np.sum(err, axis=1)\n err = err**.5\n err_clique = np.sum(err)\n\n n = len(Q_clique_2d)\n\n err_non_clique = dict()\n\n for c in range(1, color_num + 1):\n P, Q = non_clique[j][c]\n\n if P.size != 0 and Q.size != 0:\n #applies transformation to P\n U = a + cos_theta * P[:, 0] - sin_theta * P[:, 1]\n V = b + sin_theta * P[:, 0] + cos_theta * P[:, 1]\n\n P_transformed = np.column_stack((U.T, V.T))\n\n Q2d = Q[:, [0, 1]]\n\n P_transformed, Q2d, err = hungarian(P_transformed, Q2d)\n\n transformed_non_clique_colored[c] = (P_transformed, Q2d)\n\n err_non_clique[c] = err\n n += min(len(P_transformed),len(Q2d))\n\n total_distance = (sum(err_non_clique.values()) + err_clique)\n\n distances[j] = total_distance / n\n transformed_non_clique[j] = transformed_non_clique_colored\n\n min_distance = min(distances.values()) #TODO: fix error when empty\n\n for j in distances.keys():\n if distances[j] == min_distance:\n best_transform = transformation_index[j]\n best_non_clique = transformed_non_clique[j]\n\n return best_transform, best_non_clique, min_distance\n\n\ndef distance_score(P, Q, G, cliques):\n ''' Unnecessary as the distance is returned from best_transformation\n '''\n\n color_num = number_of_colors(P,Q)\n non_clique_points = find_non_clique_points(P, Q, G, cliques, color_num)\n best_transform, best_non_clique, average_distance = best_transformation(G, cliques, non_clique_points, color_num)\n\n return average_distance\n\n\ndef test():\n file1 = 'HKI_01R_P_CB2S1_HEEL.json'\n file2 = 'hri_01R_01_HEEL.json'\n\n P = create_points(file1)\n Q = create_points(file2)\n\n # start with this epsilon, if it takes too long (see @exit_after), it cuts epsilon in half and goes again\n epsilon = .02\n dummy = True\n while dummy:\n G = create_graph(P,Q,epsilon)\n try:\n cliques = find_large_cliques(G)\n dummy = False\n except KeyboardInterrupt:\n epsilon = .5*epsilon\n\n dist = distance_score(P,Q,G,cliques)\n\n return G, dist\n","sub_path":"Large_clique_alignment.py","file_name":"Large_clique_alignment.py","file_ext":"py","file_size_in_byte":16750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"619980347","text":"from flask import Flask, render_template, request, make_response, redirect\nfrom werkzeug import secure_filename\nimport sqlite3\nimport time\nimport json\nimport helpers\n\nconn = sqlite3.connect('meme.db')\nc = conn.cursor()\n\nc.execute('''\n CREATE TABLE IF NOT EXISTS user\n (id integer primary key autoincrement, username text unique, password text, profile_image_url text)\n''')\n\nc.execute('''\n CREATE TABLE IF NOT EXISTS meme\n (id integer primary key autoincrement, photo_url text, body text, title text, user_id integer, foreign key(user_id) references user(id))\n''')\n\nc.execute('''\n CREATE TABLE IF NOT EXISTS friends\n (id integer primary key autoincrement, user_one_id integer, user_two_id integer,\n foreign key(user_one_id) references user(id), foreign key(user_two_id) references user(id))\n''')\n\nc.execute('''\n CREATE TABLE IF NOT EXISTS message\n (id integer primary key autoincrement, photo_url text, body text, user_id integer, foreign key(user_id) references user(id))\n''')\n\napp = Flask(__name__, static_url_path='')\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n@app.route('/register_page')\ndef register_page():\n return render_template('register.html')\n\n@app.route('/register', methods=['POST'])\ndef register():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n print(request.form)\n username=request.form[\"username\"]\n password=request.form[\"password\"]\n c.execute(\"INSERT INTO user(username, password) VALUES (?, ?)\", (username, password))\n last_row_id = c.lastrowid\n conn.commit()\n resp = make_response(redirect('/memecentral', 302))\n resp.set_cookie('user_id', str(last_row_id))\n resp.set_cookie('username', username)\n return resp\n\n@app.route('/login_page')\ndef login_page():\n return render_template('login.html')\n\n@app.route('/login', methods=['POST'])\ndef login():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n print(request.form)\n username=request.form[\"username\"]\n password=request.form[\"password\"]\n c.execute(\"select * from user where username = ? and password = ?\", (username, password))\n user = c.fetchone()\n if user is not None:\n resp = make_response(redirect('/memecentral', 302))\n resp.set_cookie('user_id', str(user[0]))\n resp.set_cookie('username', username)\n return resp\n else:\n return ('please actually login and stop hacking other people kthx')\n\n@app.route('/memecentral')\ndef memecentral():\n return render_template('memecentral.html')\n\n@app.route('/memes')\ndef memes():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n c.execute('select meme.id AS meme_id, photo_url, title, body, user_id, username from meme, user where user_id = user.id')\n memes = c.fetchall()\n return json.dumps(memes)\n\n@app.route('/upload_meme')\ndef memeupload():\n return render_template('memeupload.html')\n\n@app.route('/memeuploader', methods=['POST'])\ndef memeuploader():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n print(request.form)\n title=request.form[\"title\"]\n body=request.form[\"body\"]\n user_id = int(request.cookies.get(\"user_id\"))\n filename = None\n if 'file' in request.files:\n imageFile = request.files['file']\n filename = imageFile.filename\n if len(filename) > 0 and filename.endswith(('.jpg', '.png', '.jpeg', '.gif', '.mp4', '.mov')):\n savePath = \"./static/{}\".format(filename)\n imageFile.save(savePath)\n c.execute(\"INSERT INTO meme(title, body, photo_url, user_id) VALUES (?, ?, ?, ?)\", (title, body, filename, user_id))\n else:\n c.execute(\"INSERT INTO meme(title, body, photo_url, user_id) VALUES (?, ?, ?, ?)\", (title, body, 'https://thumbs.gfycat.com/TemptingInconsequentialFrogmouth-size_restricted.gif', user_id))\n conn.commit()\n return redirect('/memecentral', 302)\n\n@app.route('/chat_room')\ndef chat_room():\n return render_template('chat.html') \n\n@app.route('/messages')\ndef messages():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n c.execute('select message.id AS message_id, photo_url, body, user_id, username from message, user where user_id = user.id ORDER BY message.id DESC LIMIT 50')\n messages = c.fetchall()\n messages.reverse()\n return json.dumps(messages)\n\n@app.route('/post_message', methods=['POST'])\ndef post_message():\n conn = sqlite3.connect('meme.db')\n c = conn.cursor()\n swear_word_dict = helpers.get_swear_words_dict()\n body=request.form[\"body\"]\n body = body.split()\n new_body = []\n for x in body:\n if x.lower() in swear_word_dict:\n x = swear_word_dict[x.lower()]\n new_body.append(x)\n body = \" \".join(new_body)\n user_id = int(request.cookies.get(\"user_id\"))\n username = request.cookies.get(\"username\")\n filename = None\n if 'file' in request.files:\n imageFile = request.files['file']\n filename = imageFile.filename\n if len(filename) > 0:\n savePath = \"./static/{}\".format(filename)\n imageFile.save(savePath)\n if filename.endswith(('.jpg', '.png', '.jpeg', '.gif', '.mp4', '.mov')):\n c.execute(\"INSERT INTO message(body, photo_url, user_id) VALUES (?, ?, ?)\", (body, filename, user_id))\n else:\n c.execute(\"INSERT INTO message(body, photo_url, user_id) VALUES (?, ?, ?)\", (body, 'https://thumbs.gfycat.com/TemptingInconsequentialFrogmouth-size_restricted.gif', user_id))\n else:\n c.execute(\"INSERT INTO message(body, user_id) VALUES (?, ?)\", (body, user_id))\n conn.commit()\n return json.dumps((username, body))\n\n\n\nif __name__ == '__main__':\n app.run(port=3000)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"415586449","text":"from flask import Blueprint, request\nfrom server import mysql\nimport json\nfrom helpers import check_token\nfrom helpers_jobs import *\n\njobs = Blueprint('jobs', __name__)\n\n@jobs.route('', methods = ['GET', 'POST'])\ndef getAndPostJob():\n token_str = request.headers.get('Authorization', default=None)\n if token_str == None:\n return json.dumps({'message': 'Unauthorized Access', 'error': True})\n else:\n cursor = mysql.connection.cursor()\n try:\n if not check_token(cursor, token_str.split(' ')[1]):\n return json.dumps({'message': 'Unauthorized Access', 'error': True})\n else:\n if request.method == 'POST':\n title = request.json['title']\n salary = int(request.json['salary'])\n openings = int(request.json['openings'])\n companyId = int(request.json['companyId'])\n addJob(cursor, title, salary, openings, companyId)\n return json.dumps({'message': 'Job Added Successfully', 'error': False})\n elif request.method == 'GET':\n company = request.args.get('company', default=None)\n location = request.args.get('location', default=None)\n sortBy = request.args.get('sortBy', default=None)\n sortType = request.args.get('sortType', default='asc')\n page = int(request.args.get('page', default=1))\n data, count, cnt = getJobs(cursor, company, location, sortBy, sortType, page)\n return json.dumps({'data': data, 'count': count, 'totalCnt': cnt, 'error': False})\n except Exception as e:\n print(e)\n return json.dumps({'message': 'Some Error Occurred', 'error': True})\n finally:\n mysql.connection.commit()\n cursor.close()\n\n@jobs.route('/', methods = ['PATCH', 'DELETE', 'GET'])\ndef editAndDeleteJob(jobId):\n token_str = request.headers.get('Authorization', default=None)\n if token_str == None:\n return json.dumps({'message': 'Unauthorized Access', 'error': True})\n else:\n cursor = mysql.connection.cursor()\n try:\n if not check_token(cursor, token_str.split(' ')[1]):\n return json.dumps({'message': 'Unauthorized Access', 'error': True})\n else:\n if request.method == 'PATCH':\n title = request.json['title']\n salary = int(request.json['salary'])\n openings = int(request.json['openings'])\n updateJob(cursor, title, salary, openings, jobId)\n return json.dumps({'message': 'Job Updated Successfully', 'error': False})\n elif request.method == 'DELETE':\n deleteJob(cursor, jobId)\n return json.dumps({'message': 'Job Deleted Successfully', 'error': False})\n elif request.method == 'GET':\n cursor.execute('''select * from jobs where id=%s''', (jobId, ))\n result = cursor.fetchone()\n return json.dumps({'data': result, 'error': False})\n except:\n return json.dumps({'message': 'Some Error Occurred', 'error': True})\n finally:\n mysql.connection.commit()\n cursor.close()","sub_path":"submissions/sm_012_gaurav/week_23/day_5/evaluation/backend/blueprint_jobs.py","file_name":"blueprint_jobs.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"378666258","text":"from flask import Flask\nfrom flask import jsonify\nfrom flask import request\n\napp = Flask(__name__)\nservice_id = 1\n\n@app.route(\"/\")\ndef check_service():\n response = {\"response\": \"Service \" + str(service_id) + \" is working.\"}\n return jsonify(response)\n\n@app.route(\"/is_prime\", methods=[\"GET\"])\ndef is_prime():\n number = request.args.get(\"number\")\n f = open(\"/etc/hostname\")\n origin = f.readline().replace(\"\\n\", \"\")\n f.close()\n if number is None:\n response = {\"response\": \"Parameter is not sufficient.\", \"origin\": origin}\n else:\n number = int(number)\n response = {\"response\": \"Number is prime.\", \"origin\": origin}\n for i in range(2, number):\n if number % i == 0:\n response = {\"response\": \"Number is not prime.\", \"origin\": origin}\n return jsonify(response)\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"648376604","text":"# import sys\r\n# import os\r\n# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'evaluateLecture.settings.local')\r\n# import django\r\n# django.setup()\r\n\r\n# from lecture.models import Lecture\r\n\r\nfrom selenium import webdriver as wd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.common.exceptions import TimeoutException\r\nimport time\r\nimport openpyxl\r\n\r\n# def crawling(request):\r\n# 크롬 드라이버 연결\r\ndriver = wd.Chrome(executable_path =r'./chromedriver/chromedriver.exe')\r\n# 접속 주소\r\ndriver.get('https://eis.cbnu.ac.kr/cbnuLogin')\r\n\r\n# 로그인 아이디\r\nuid = driver.find_element_by_name(\"uid\")\r\n# 로그인 비밀번호\r\npswd = driver.find_element_by_name(\"pswd\")\r\ncommonLoginBtn = driver.find_element_by_xpath(\"//*[@id='commonLoginBtn']\")\r\n\r\n# 로그인 정보 입력\r\nuid.send_keys(\"\")\r\npswd.send_keys(\"\")\r\nprint(\"로그인 정보 입력 완료\")\r\n\r\ncommonLoginBtn.click()\r\nprint(\"로그인 버튼 클릭\")\r\n\r\n# 해당 태그를 찾기 전까지 실행 기다림\r\ntry:\r\n element = WebDriverWait(driver, 50).until(\r\n EC.presence_of_element_located((By.ID, \"mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_8_cell_8_0_controltree\"))\r\n )\r\nfinally:\r\n {}\r\n \r\nprint(\"로그인 로딩 완료\")\r\n\r\n## driver.implicitly_wait(10) # 드라이버를 멈추고 10초 기다림 \r\ntime.sleep(10) # 전체 프로세스를 멈추고 5초 기다림\r\n\r\n\r\n# 네비게이션 수업 / 성적 클릭\r\nlecture = driver.find_element_by_id(\"mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_8_cell_8_0_controltree\")\r\nlecture.click()\r\n\r\nprint(\"수업 성적 클릭\")\r\n\r\n# 네비게이션 수업정보 클릭\r\nlecture2 = driver.find_element_by_id(\"mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_9_cell_9_0_controltree\")\r\nlecture2.click()\r\n\r\nprint(\"수업 정보 클릭\")\r\n\r\n# 네비게이션 개설강좌(계획서)조회 클릭\r\nlecture3 = driver.find_element_by_id(\"mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_16_cell_16_0_controltree\")\r\nlecture3.click()\r\n\r\nprint(\"개설강좌 클릭\")\r\n\r\n\r\ntry:\r\n element = WebDriverWait(driver, 30).until(\r\n EC.presence_of_element_located((By.ID, \"mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_btn_search\"))\r\n )\r\nfinally:\r\n {}\r\n\r\nprint(\"조회 버튼 찾음\")\r\n\r\nsearch = driver.find_element_by_id(\"mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_btn_search\")\r\nsearch.click()\r\n\r\nprint(\"조회 버튼 클릭\")\r\n\r\n# 오류 정정시\r\n# time.sleep(20)\r\n\r\n# 일반\r\ntime.sleep(20)\r\n\r\n# 출력 버튼 0~17까지 총 3841개\r\nfor j in range(0, 208):\r\n for i in range(0,20):\r\n download_id = 'mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_body_gridrow_'+str(i)+'_cell_'+str(i)+'_12GridCellContainerElement'\r\n\r\n try:\r\n element = WebDriverWait(driver, 4).until(\r\n EC.presence_of_element_located((By.ID, download_id))\r\n )\r\n except TimeoutException :\r\n print(\"없는 번호\" +str(i))\r\n continue\r\n\r\n\r\n print(\"출력 버튼 찾음\")\r\n print(download_id)\r\n\r\n download = driver.find_element_by_id(download_id)\r\n download.click()\r\n\r\n\r\n print(\"출력 버튼 클릭\")\r\n\r\n # popup창으로 frame 전환\r\n try:\r\n element = WebDriverWait(driver, 60).until(\r\n EC.presence_of_element_located((By.XPATH, \"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_popup_form_div_popWork_web_report_WebBrowser']\"))\r\n )\r\n finally:\r\n {}\r\n\r\n popup = driver.find_element_by_xpath(\"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_popup_form_div_popWork_web_report_WebBrowser']\")\r\n driver.switch_to.frame(popup)\r\n\r\n print(\"popup 전환 완료\")\r\n\r\n time.sleep(1)\r\n\r\n\r\n try:\r\n element = WebDriverWait(driver, 60).until(\r\n EC.presence_of_element_located((By.XPATH, \"//*[@id='iWeb']\"))\r\n )\r\n finally:\r\n {}\r\n \r\n time.sleep(2)\r\n\r\n popup2 = driver.find_element_by_xpath(\"//*[@id='iWeb']\")\r\n driver.switch_to.frame(popup2)\r\n\r\n print(\"popup2 전환 완료\")\r\n\r\n\r\n try:\r\n element = WebDriverWait(driver, 60).until(\r\n EC.presence_of_element_located((By.XPATH, \"//button[@title='엑셀 저장']\"))\r\n )\r\n finally:\r\n {}\r\n\r\n print(\"저장 버튼 찾음\")\r\n\r\n # driver.implicitly_wait(10) # seconds\r\n time.sleep(1)\r\n\r\n download2 = driver.find_element_by_xpath(\"//*[@title='엑셀 저장']\") \r\n download2.click()\r\n download2.click()\r\n\r\n print(\"저장 버튼 클릭\")\r\n\r\n time.sleep(4)\r\n\r\n # rename = driver.find_element_by_xpath(\"//*[@id='targetDiv1']/div[2]/div[1]/div[2]/input\")\r\n # rename.clear()\r\n # rename.send_keys(\"report\"+\" (\"+str(count)+\")\")\r\n # count+=1\r\n # print(\"파일 이름 바꿈\")\r\n \r\n # try:\r\n # element = WebDriverWait(driver, 60).until(\r\n # EC.presence_of_element_located((By.XPATH, \"//button[@title='저장']\"))\r\n # )\r\n # finally:\r\n # {}\r\n\r\n # print(\"저장 버튼 찾음\")\r\n\r\n # # driver.implicitly_wait(10) # seconds\r\n # time.sleep(3)\r\n\r\n # download2 = driver.find_element_by_xpath(\"//*[@title='저장']\") \r\n # download2.click()\r\n # download2.click()\r\n\r\n # print(\"저장 버튼 클릭\")\r\n\r\n # time.sleep(3)\r\n\r\n # # rename = driver.find_element_by_xpath(\"//*[@id='targetDiv1']/div[2]/div[1]/div[2]/input\")\r\n # # rename.clear()\r\n # # rename.send_keys(\"report\"+\" (\"+str(count)+\")\")\r\n # # count+=1\r\n # # print(\"파일 이름 바꿈\")\r\n \r\n # download3 = driver.find_element_by_xpath(\"//*[@id='targetDiv1']/div[2]/div[1]/button[1]\")\r\n # download3.click()\r\n \r\n\r\n # print(\"파일 최종 저장\")\r\n # time.sleep(4)\r\n\r\n # popup 전환\r\n driver.switch_to.default_content() # popup2 -> popup\r\n driver.switch_to.default_content() # popup -> default\r\n\r\n print(\"popup 전환 완료\")\r\n\r\n\r\n # driver.implicitly_wait(10) # seconds\r\n\r\n close = driver.find_element_by_id(\"mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_popup_titlebar_closebutton\")\r\n close.click()\r\n \r\n print(\"popup 닫기\")\r\n\r\n time.sleep(3)\r\n\r\n scroll = driver.find_element_by_id(\"mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_vscrollbar_incbutton\") \r\n \r\n scroll.click()\r\n print(\"스크롤 버튼 클릭\")\r\n \r\n\r\n #driver.quit()\r\n\r\n","sub_path":"crawling.py","file_name":"crawling.py","file_ext":"py","file_size_in_byte":7000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"284865871","text":"# -*- encoding: utf-8 -*-\nimport sys\nr_input = sys.stdin.readline\n\nN = int(r_input()) # 화단 한 변의 크기\nflower = {} # 각 지점당 가격\nflower_cost = {} # 각 지점에 꽃을 심는 비용\n\nfor i in range(N):\n flower[i] = list(map(int, r_input().split()))\n flower_cost[i] = [14620] * N\n\nfor i in range(1, N-1):\n for j in range(1, N-1):\n flower_cost[i][j] = flower[i-1][j] + flower[i+1][j] + flower[i][j-1] + flower[i][j+1] + flower[i][j]\n\n\ndef min_cost(cnt, i, j, total): # 세 씨앗을 심는 최소 비용 찾기(DFS)\n global cost, check\n temp1 = [[i, j], [i-1, j], [i+1, j], [i, j-1], [i, j+1]] # (i, j)에 씨앗을 심으면 해당 범위 내는 방문 처리 해줘야 함\n\n for t in temp1:\n check[t[0]][t[1]] = 1\n\n total += flower_cost[i][j]\n\n if cnt == 3: # 세 씨앗을 모두 심었으면\n cost = min(cost, total)\n\n else:\n for a in range(j + 2, N - 1):\n # 다음 심을 씨앗 근처에 심으면 안되는 구역이 있는지 체크\n temp2 = [check[i - 1][a], check[i + 1][a], check[i][a - 1], check[i][a + 1], check[i][a]]\n\n if not 1 in temp2:\n min_cost(cnt + 1, i, a, total)\n\n for a in range(i + 1, N - 1):\n for b in range(1, N - 1):\n temp2 = [check[a - 1][b], check[a + 1][b], check[a][b - 1], check[a][b + 1], check[a][b]]\n\n if not 1 in temp2:\n min_cost(cnt + 1, a, b, total)\n\n for t in temp1:\n check[t[0]][t[1]] = 0\n\n\ncheck = [] # 꽃 범위 체크\n\nfor i in range(N):\n check.append([0] * N)\n \ncost = 14620 # 최소 비용\n\nfor i in range(1, N-1):\n for j in range(1, N-1):\n min_cost(1, i, j, 0)\n\nprint(cost)\n","sub_path":"Algorithm/Baekjoon/14620 꽃길/14620.py","file_name":"14620.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"251325538","text":"import tensorflow as tf\nimport numpy as np\nimport tf_ops.approxmatch.tf_approxmatch as tfappr\nfrom tqdm import tqdm\n\ntf.enable_eager_execution()\n\nname = 'train_chamfer_unified'\ndata_path = f'./Results/{name}/images/'\nbatch_size = 64\n\ndef eval(xyz1, xyz2):\n loss_arr = []\n \n for i in tqdm(range(xyz1.shape[0] // batch_size)):\n s_idx, e_idx = i * batch_size, (i+1) * batch_size\n \n match = tfappr.approx_match(xyz1[s_idx:e_idx], xyz2[s_idx:e_idx])\n \n mk = np.argmax(match[0].numpy(), 1)\n \n loss = tfappr.match_cost(xyz1[s_idx:e_idx], xyz2[s_idx:e_idx], match).numpy()\n \n loss_arr.append(loss)\n \n loss_arr = np.array(loss_arr)\n loss_arr = loss_arr / 2048\n \n return np.mean(loss_arr), np.std(loss_arr)\n\ngt_points = np.load(data_path + 'shape16_test_data.npy')\npred_points = np.load(data_path + 'shape16_test_encoder3d.npy')\ngt_points = gt_points[:pred_points.shape[0]]\n\nprint('gt shape', gt_points.shape)\nprint('pred shape', pred_points.shape)\n\neval_loss = eval(gt_points, pred_points)\nprint(eval_loss)\n","sub_path":"code/code2/eval_emd.py","file_name":"eval_emd.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"534941044","text":"import csv\n\nfrom nlprep.middleformat import MiddleFormat\nimport nlp2\n\nDATASET_FILE_MAP = {\n \"dataset\": [\n \"https://raw.githubusercontent.com/voidful/Gossiping-Chinese-Positive-Corpus/master/Gossiping-QA-pos-Dataset-2_0.csv\"]\n}\n\n\ndef toMiddleFormat(paths):\n dataset = MiddleFormat()\n for path in paths:\n with open(path, encoding='utf8') as csvfile:\n rows = csv.reader(csvfile)\n for row in rows:\n input = row[0]\n target = row[1]\n if float(row[2]) > 0.75:\n dataset.add_data(input, target)\n return dataset\n","sub_path":"nlprep/datasets/pttposgen/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"386994309","text":"# -*- coding:utf-8 -*-\n#\n# Copyright 2019, Couchbase, Inc.\n# 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#\nfrom couchbase_tests.base import CollectionTestCase\nfrom couchbase.cluster import ClusterOptions, ClassicAuthenticator, PasswordAuthenticator\nfrom couchbase.collection import GetOptions, UpsertOptions, ReplaceOptions, InsertOptions, \\\n RemoveOptions\nfrom couchbase.durability import ServerDurability, ClientDurability, Durability, PersistTo, ReplicateTo\nfrom couchbase.exceptions import InvalidArgumentException, DocumentExistsException, DocumentNotFoundException, \\\n TemporaryFailException, PathNotFoundException, DocumentLockedException, CASMismatchException\nimport unittest\nfrom datetime import timedelta\nfrom unittest import SkipTest\nfrom couchbase.diagnostics import ServiceType\nimport logging\nfrom couchbase.management.collections import CollectionSpec\nimport uuid\nfrom datetime import datetime\nfrom flaky import flaky\nimport warnings\nimport time\n\n\nclass CollectionTests(CollectionTestCase):\n \"\"\"\n These tests should just test the collection interface, as simply\n as possible. We have the Scenario tests for more complicated\n stuff.\n \"\"\"\n CONTENT = {\"some\": \"content\"}\n KEY = \"imakey\"\n NOKEY = \"somerandomkey\"\n\n def setUp(self):\n super(CollectionTests, self).setUp()\n # retry just in case doc is locked from previous test\n self.try_n_times(10, 3, self.cb.upsert, self.KEY, self.CONTENT)\n # be sure NOKEY isn't in there\n try:\n self.cb.remove(self.NOKEY)\n except DocumentNotFoundException as e:\n pass\n # make sure NOKEY is gone\n self.try_n_times_till_exception(10, 1, self.cb.get, self.NOKEY)\n\n def test_exists(self):\n if self.is_mock:\n raise SkipTest(\"mock does not support exists\")\n self.assertTrue(self.cb.exists(self.KEY).exists)\n\n def test_exists_when_it_does_not_exist(self):\n if self.is_mock:\n raise SkipTest(\"mock does not support exists\")\n key = str(uuid.uuid4())\n self.assertRaises(DocumentNotFoundException, self.cb.get, key)\n self.assertFalse(self.cb.exists(key).exists)\n\n def test_exists_with_recently_removed_key(self):\n if self.is_mock:\n raise SkipTest(\"mock does not support exists\")\n self.cb.remove(self.KEY)\n self.assertRaises(DocumentNotFoundException, self.cb.get, self.KEY)\n self.assertFalse(self.cb.exists(self.KEY).exists)\n\n def test_upsert(self):\n self.cb.upsert(self.NOKEY, {\"some\": \"thing\"},\n UpsertOptions(timeout=timedelta(seconds=3)))\n result = self.try_n_times(10, 1, self.cb.get, self.NOKEY)\n self.assertEqual(self.NOKEY, result.id)\n self.assertDictEqual({\"some\": \"thing\"}, result.content_as[dict])\n\n def test_upsert_preserve_expiry_not_used(self):\n if self.is_mock:\n raise SkipTest(\"Mock does not support preserve expiry\")\n if int(self.get_cluster_version().split('.')[0]) < 7:\n raise SkipTest(\"Preserve expiry only in CBS 7.0+\")\n result = self.cb.upsert(self.KEY, {\"some\": \"other content\"}, UpsertOptions(\n expiry=timedelta(seconds=5)))\n expiry1 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n result = self.cb.upsert(self.KEY, {\"some\": \"replaced content\"})\n self.assertTrue(result.success)\n expiry2 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry1)\n self.assertIsInstance(expiry1, datetime)\n self.assertIsNone(expiry2)\n self.assertNotEqual(expiry1, expiry2)\n # if expiry was set, should be expired by now\n time.sleep(6)\n result = self.cb.get(self.KEY)\n self.assertIsNotNone(result)\n\n def test_upsert_preserve_expiry(self):\n if self.is_mock:\n raise SkipTest(\"Mock does not support preserve expiry\")\n if int(self.get_cluster_version().split('.')[0]) < 7:\n raise SkipTest(\"Preserve expiry only in CBS 7.0+\")\n result = self.cb.upsert(self.KEY, {\"some\": \"other content\"}, UpsertOptions(\n expiry=timedelta(seconds=5)))\n expiry1 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n result = self.cb.upsert(\n self.KEY, {\"some\": \"replaced content\"}, UpsertOptions(preserve_expiry=True))\n self.assertTrue(result.success)\n expiry2 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry1)\n self.assertIsInstance(expiry1, datetime)\n self.assertIsNotNone(expiry2)\n self.assertIsInstance(expiry2, datetime)\n self.assertEqual(expiry1, expiry2)\n # if expiry was preserved, should be expired by now\n time.sleep(6)\n with self.assertRaises(DocumentNotFoundException):\n self.cb.get(self.KEY)\n\n def test_insert(self):\n self.cb.insert(self.NOKEY, {\"some\": \"thing\"})\n result = self.try_n_times(10, 1, self.cb.get, self.NOKEY)\n self.assertEqual(self.NOKEY, result.id)\n self.assertDictEqual({\"some\": \"thing\"}, result.content_as[dict])\n\n def test_insert_fail(self):\n self.assertRaises(DocumentExistsException,\n self.cb.insert, self.KEY, self.CONTENT)\n\n def test_replace(self):\n result = self.cb.replace(self.KEY, {\"some\": \"other content\"})\n self.assertTrue(result.success)\n\n def test_replace_preserve_expiry_not_used(self):\n if self.is_mock:\n raise SkipTest(\"Mock does not support preserve expiry\")\n if int(self.get_cluster_version().split('.')[0]) < 7:\n raise SkipTest(\"Preserve expiry only in CBS 7.0+\")\n result = self.cb.upsert(self.KEY, {\"some\": \"other content\"}, UpsertOptions(\n expiry=timedelta(seconds=5)))\n expiry1 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n result = self.cb.replace(self.KEY, {\"some\": \"replaced content\"})\n self.assertTrue(result.success)\n expiry2 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry1)\n self.assertIsInstance(expiry1, datetime)\n self.assertIsNone(expiry2)\n self.assertNotEqual(expiry1, expiry2)\n # if expiry was set, should be expired by now\n time.sleep(6)\n result = self.cb.get(self.KEY)\n self.assertIsNotNone(result)\n\n def test_replace_preserve_expiry(self):\n if self.is_mock:\n raise SkipTest(\"Mock does not support preserve expiry\")\n if int(self.get_cluster_version().split('.')[0]) < 7:\n raise SkipTest(\"Preserve expiry only in CBS 7.0+\")\n result = self.cb.upsert(self.KEY, {\"some\": \"other content\"}, UpsertOptions(\n expiry=timedelta(seconds=5)))\n expiry1 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n result = self.cb.replace(\n self.KEY, {\"some\": \"replaced content\"}, ReplaceOptions(preserve_expiry=True))\n self.assertTrue(result.success)\n expiry2 = self.cb.get(self.KEY, GetOptions(\n with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry1)\n self.assertIsInstance(expiry1, datetime)\n self.assertIsNotNone(expiry2)\n self.assertIsInstance(expiry2, datetime)\n self.assertEqual(expiry1, expiry2)\n # if expiry was preserved, should be expired by now\n time.sleep(6)\n with self.assertRaises(DocumentNotFoundException):\n self.cb.get(self.KEY)\n\n def test_replace_preserve_expiry_fail(self):\n if self.is_mock:\n raise SkipTest(\"Mock does not support preserve expiry\")\n if int(self.get_cluster_version().split('.')[0]) < 7:\n raise SkipTest(\"Preserve expiry only in CBS 7.0+\")\n opts = ReplaceOptions(expiry=timedelta(seconds=5), preserve_expiry=True)\n with self.assertRaises(InvalidArgumentException):\n self.cb.replace(self.KEY, {\"some\": \"other content\"}, opts)\n\n def test_replace_with_cas(self):\n old_cas = self.cb.get(self.KEY).cas\n result = self.cb.replace(\n self.KEY, self.CONTENT, ReplaceOptions(cas=old_cas))\n self.assertTrue(result.success)\n # try same cas again, must fail.\n self.assertRaises(CASMismatchException, self.cb.replace,\n self.KEY, self.CONTENT, ReplaceOptions(cas=old_cas))\n\n def test_replace_fail(self):\n self.assertRaises(DocumentNotFoundException, self.cb.get, self.NOKEY)\n self.assertRaises(DocumentNotFoundException,\n self.cb.replace, self.NOKEY, self.CONTENT)\n\n def test_remove(self):\n result = self.cb.remove(self.KEY)\n self.assertTrue(result.success)\n self.try_n_times_till_exception(10, 1, self.cb.get, self.KEY)\n\n def test_remove_fail(self):\n self.assertRaises(DocumentNotFoundException,\n self.cb.remove, self.NOKEY)\n\n def test_get(self):\n result = self.cb.get(self.KEY)\n self.assertIsNotNone(result.cas)\n self.assertEqual(result.id, self.KEY)\n self.assertIsNone(result.expiryTime)\n self.assertDictEqual(self.CONTENT, result.content_as[dict])\n\n def test_get_options(self):\n result = self.cb.get(self.KEY, GetOptions(\n timeout=timedelta(seconds=2), with_expiry=False))\n self.assertIsNotNone(result.cas)\n self.assertEqual(result.id, self.KEY)\n self.assertIsNone(result.expiryTime)\n self.assertDictEqual(self.CONTENT, result.content_as[dict])\n\n def test_get_fails(self):\n self.assertRaises(DocumentNotFoundException, self.cb.get, self.NOKEY)\n\n def test_expiry_really_expires(self):\n result = self.coll.upsert(\n self.KEY, self.CONTENT, UpsertOptions(expiry=timedelta(seconds=3)))\n self.assertTrue(result.success)\n time.sleep(4)\n with self.assertRaises(DocumentNotFoundException):\n self.coll.get(self.KEY)\n\n def test_get_with_expiry(self):\n if self.is_mock:\n raise SkipTest(\"mock will not return the expiry in the xaddrs\")\n self.coll.upsert(self.KEY, self.CONTENT, UpsertOptions(\n expiry=timedelta(seconds=1000)))\n\n result = self.coll.get(self.KEY, GetOptions(with_expiry=True))\n self.assertIsNotNone(result.expiryTime)\n self.assertDictEqual(self.CONTENT, result.content_as[dict])\n expires_in = (result.expiryTime - datetime.now()).total_seconds()\n self.assertTrue(1001 >= expires_in > 0,\n msg=\"Expected expires_in {} to be between 1000 and 0\".format(expires_in))\n\n def test_deprecated_expiry(self):\n # PYCBC-999 Deprecate GetResult.expiry()\n # expiry returned datetime, was replaced by expiryTime which returns\n # an instant (aka unix timestamp)\n if self.is_mock:\n raise SkipTest(\"mock will not return the expiry in the xaddrs\")\n self.coll.upsert(self.KEY, self.CONTENT, UpsertOptions(\n expiry=timedelta(seconds=1000)))\n result = self.coll.get(self.KEY, GetOptions(with_expiry=True))\n warnings.resetwarnings()\n with warnings.catch_warnings(record=True) as w:\n self.assertIsNotNone(result.expiry)\n self.assertEqual(len(w), 1)\n\n expires_in = (result.expiry - datetime.now()).total_seconds()\n self.assertTrue(1001 >= expires_in > 0,\n msg=\"Expected expires_in {} to be between 1000 and 0\".format(expires_in))\n\n def test_project(self):\n content = {\"a\": \"aaa\", \"b\": \"bbb\", \"c\": \"ccc\"}\n cas = self.coll.upsert(self.KEY, content).cas\n\n def cas_matches(c, new_cas):\n if new_cas != c.get(self.KEY).cas:\n raise Exception(\"nope\")\n\n self.try_n_times(10, 3, cas_matches, self.coll, cas)\n result = self.coll.get(self.KEY, GetOptions(project=[\"a\"]))\n self.assertEqual({\"a\": \"aaa\"}, result.content_as[dict])\n self.assertIsNotNone(result.cas)\n self.assertEqual(result.id, self.KEY)\n self.assertIsNone(result.expiryTime)\n\n def test_project_bad_path(self):\n result = self.coll.get(self.KEY, GetOptions(project=[\"some\", \"qzx\"]))\n self.assertTrue(result.success)\n with self.assertRaisesRegex(PathNotFoundException, 'qzx'):\n result.content_as[dict]\n\n def test_project_bad_project_string(self):\n with self.assertRaises(InvalidArgumentException):\n self.coll.get(self.KEY, GetOptions(project=\"something\"))\n\n def test_project_bad_project_too_long(self):\n project = []\n for _ in range(17):\n project.append(\"something\")\n\n with self.assertRaisesRegex(InvalidArgumentException, \"16 operations or less\"):\n self.coll.get(self.KEY, GetOptions(project=project))\n\n def _check_replicas(self, all_up=True):\n num_replicas = self.bucket.configured_replica_count\n if num_replicas < 1:\n raise SkipTest('need replicas to test get_all/get_any_replicas')\n # TODO: this is far to difficult - having to use the test framework to get the bucket\n kv_results = self.bucket.ping().endpoints.get(ServiceType.KeyValue, None)\n # 2 means at least one replica is up\n num_expected = num_replicas+1 if all_up else 2\n if not kv_results or len(kv_results) < num_expected:\n raise SkipTest('not all replicas are online')\n\n def test_get_any_replica(self):\n self._check_replicas(False)\n self.coll.upsert('imakey100', self.CONTENT)\n result = self.try_n_times(\n 10, 3, self.coll.get_any_replica, 'imakey100')\n self.assertDictEqual(self.CONTENT, result.content_as[dict])\n\n def test_get_all_replicas(self):\n self._check_replicas()\n self.coll.upsert(self.KEY, self.CONTENT)\n # wait till it it there...\n result = self.try_n_times(10, 3, self.coll.get_all_replicas, self.KEY)\n if not hasattr(result, '__iter__'):\n result = [result]\n for r in result:\n self.assertDictEqual(self.CONTENT, r.content_as[dict])\n\n def test_get_all_replicas_returns_master(self):\n self._check_replicas()\n self.coll.upsert('imakey100', self.CONTENT)\n result = self.try_n_times(\n 10, 3, self.coll.get_all_replicas, 'imakey100')\n if not hasattr(result, '__iter__'):\n result = [result]\n # TODO: this isn't implemented yet - waiting on CCBC-1169\n # when it does work, we just need to make sure one of the\n # results returns True for is_replica()\n for r in result:\n with self.assertRaises(NotImplementedError):\n r.is_replica()\n\n def test_touch(self):\n self.cb.touch(self.KEY, timedelta(seconds=3))\n time.sleep(4)\n with self.assertRaises(DocumentNotFoundException):\n self.cb.get(self.KEY)\n\n def test_touch_no_expire(self):\n if self.is_mock:\n self.cb.touch(self.KEY, timedelta(seconds=0))\n time.sleep(1)\n res = self.cb.get(self.KEY)\n self.assertIsNotNone(res.content_as[dict])\n else:\n self.cb.touch(self.KEY, timedelta(seconds=15))\n expiry = self.cb.get(self.KEY, GetOptions(with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry)\n self.cb.touch(self.KEY, timedelta(seconds=0))\n expiry = self.cb.get(self.KEY, GetOptions(with_expiry=True)).expiryTime\n self.assertIsNone(expiry)\n\n def _authenticator(self):\n if self.is_mock:\n return ClassicAuthenticator(self.cluster_info.admin_username, self.cluster_info.admin_password)\n return PasswordAuthenticator(self.cluster_info.admin_username, self.cluster_info.admin_password)\n\n def _create_cluster_opts(self, **kwargs):\n return ClusterOptions(self._authenticator(), **kwargs)\n\n def _mock_hack(self):\n if self.is_mock:\n return {'bucket': self.bucket_name}\n return {}\n\n def test_get_and_touch(self):\n self.cb.get_and_touch(self.KEY, timedelta(seconds=3))\n self.cb.get(self.KEY)\n self.try_n_times_till_exception(\n 10, 3, self.cb.get, self.KEY, DocumentNotFoundException)\n\n def test_get_and_touch_no_expire(self):\n if self.is_mock:\n self.cb.get_and_touch(self.KEY, timedelta(seconds=0))\n time.sleep(1)\n res = self.cb.get(self.KEY)\n self.assertIsNotNone(res.content_as[dict])\n else:\n self.cb.get_and_touch(self.KEY, timedelta(seconds=15))\n expiry = self.cb.get(self.KEY, GetOptions(with_expiry=True)).expiryTime\n self.assertIsNotNone(expiry)\n self.cb.get_and_touch(self.KEY, timedelta(seconds=0))\n expiry = self.cb.get(self.KEY, GetOptions(with_expiry=True)).expiryTime\n self.assertIsNone(expiry)\n\n def test_get_and_lock(self):\n self.cb.get_and_lock(self.KEY, timedelta(seconds=3))\n # upsert should definitely fail\n self.assertRaises(DocumentLockedException,\n self.cb.upsert, self.KEY, self.CONTENT)\n # but succeed eventually\n self.try_n_times(10, 1, self.cb.upsert, self.KEY, self.CONTENT)\n\n def test_get_after_lock(self):\n orig = self.cb.get_and_lock(self.KEY, timedelta(seconds=3))\n # GET operation is allowed on locked document; however, returned CAS should be invalid\n res = self.cb.get(self.KEY)\n self.assertEqual(orig.content_as[dict], res.content_as[dict])\n self.assertNotEqual(orig.cas, res.cas)\n\n def test_get_and_lock_upsert_with_cas(self):\n result = self.cb.get_and_lock(self.KEY, timedelta(seconds=15))\n cas = result.cas\n self.assertRaises(DocumentLockedException,\n self.cb.upsert, self.KEY, self.CONTENT)\n self.cb.replace(self.KEY, self.CONTENT, ReplaceOptions(cas=cas))\n\n def test_unlock(self):\n cas = self.cb.get_and_lock(self.KEY, timedelta(seconds=15)).cas\n self.cb.unlock(self.KEY, cas)\n self.cb.upsert(self.KEY, self.CONTENT)\n\n @flaky(5, 1)\n def test_unlock_wrong_cas(self):\n cas = self.cb.get_and_lock(self.KEY, timedelta(seconds=15)).cas\n expectedException = TemporaryFailException if self.is_mock else DocumentLockedException\n self.assertRaises(expectedException, self.cb.unlock, self.KEY, 100)\n self.cb.unlock(self.KEY, cas)\n\n def test_client_durable_upsert(self):\n num_replicas = self.bucket._bucket.configured_replica_count\n durability = ClientDurability(\n persist_to=PersistTo.ONE, replicate_to=ReplicateTo(num_replicas))\n self.cb.upsert(self.NOKEY, self.CONTENT,\n UpsertOptions(durability=durability))\n result = self.cb.get(self.NOKEY)\n self.assertEqual(self.CONTENT, result.content_as[dict])\n\n def test_server_durable_upsert(self):\n if not self.supports_sync_durability():\n raise SkipTest(\"ServerDurability not supported\")\n durability = ServerDurability(level=Durability.PERSIST_TO_MAJORITY)\n self.cb.upsert(self.NOKEY, self.CONTENT,\n UpsertOptions(durability=durability))\n result = self.cb.get(self.NOKEY)\n self.assertEqual(self.CONTENT, result.content_as[dict])\n\n def test_client_durable_insert(self):\n num_replicas = self.bucket._bucket.configured_replica_count\n durability = ClientDurability(\n persist_to=PersistTo.ONE, replicate_to=ReplicateTo(num_replicas))\n self.cb.insert(self.NOKEY, self.CONTENT,\n InsertOptions(durability=durability))\n result = self.cb.get(self.NOKEY)\n self.assertEqual(self.CONTENT, result.content_as[dict])\n\n def test_server_durable_insert(self):\n if not self.supports_sync_durability():\n raise SkipTest(\"ServerDurability not supported\")\n durability = ServerDurability(level=Durability.PERSIST_TO_MAJORITY)\n self.cb.insert(self.NOKEY, self.CONTENT,\n InsertOptions(durability=durability))\n result = self.cb.get(self.NOKEY)\n self.assertEqual(self.CONTENT, result.content_as[dict])\n\n def test_client_durable_replace(self):\n num_replicas = self.bucket._bucket.configured_replica_count\n content = {\"new\": \"content\"}\n durability = ClientDurability(\n persist_to=PersistTo.ONE, replicate_to=ReplicateTo(num_replicas))\n self.cb.replace(self.KEY, content,\n ReplaceOptions(durability=durability))\n result = self.cb.get(self.KEY)\n self.assertEqual(content, result.content_as[dict])\n\n def test_server_durable_replace(self):\n content = {\"new\": \"content\"}\n if not self.supports_sync_durability():\n raise SkipTest(\"ServerDurability not supported\")\n durability = ServerDurability(level=Durability.PERSIST_TO_MAJORITY)\n self.cb.replace(self.KEY, content,\n ReplaceOptions(durability=durability))\n result = self.cb.get(self.KEY)\n self.assertEqual(content, result.content_as[dict])\n\n @unittest.skip(\"Client Durable remove not yet supported (CCBC-1199)\")\n def test_client_durable_remove(self):\n num_replicas = self.bucket._bucket.configured_replica_count\n durability = ClientDurability(\n persist_to=PersistTo.ONE, replicate_to=ReplicateTo(num_replicas))\n self.cb.remove(self.KEY, RemoveOptions(durability=durability))\n self.assertRaises(DocumentNotFoundException, self.cb.get, self.KEY)\n\n def test_server_durable_remove(self):\n if not self.supports_sync_durability():\n raise SkipTest(\"ServerDurability not supported\")\n durability = ServerDurability(level=Durability.PERSIST_TO_MAJORITY)\n self.cb.remove(self.KEY, RemoveOptions(durability=durability))\n self.assertRaises(DocumentNotFoundException, self.cb.get, self.KEY)\n\n def test_collection_access(self, # type: CollectionTests\n ):\n if not self.supports_collections():\n raise SkipTest()\n\n value = uuid.uuid4().int\n value_1 = str(value)\n value_2 = str(value + 1)\n value_3 = str(value + 2)\n value_4 = str(value + 3)\n test_dict = {\n \"scope_1\": {\n \"collection_1\": {\"key_1\": value_1},\n \"collection_2\": {\"key_1\": value_2},\n },\n \"scope_2\": {\n \"collection_1\": {\"key_1\": value_3},\n \"collection_2\": {\"key_1\": value_4},\n }\n }\n\n bucket = self.cluster.bucket(self.cluster_info.bucket_name)\n cm = bucket.collections()\n\n def upsert_values(coll, scope_name, coll_name, result_key_dict, key, value):\n return coll.upsert(key, value)\n from collections import defaultdict\n\n def recurse():\n return defaultdict(recurse)\n resultdict = recurse()\n\n def check_values(coll, scope_name, coll_name, result_key_dict, key, value):\n result_key_dict[key] = coll.get(key).content\n return True\n for action in [upsert_values, check_values]:\n self._traverse_scope_tree(\n bucket, cm, resultdict, test_dict, action)\n\n self.assertSanitizedEqual(test_dict, resultdict)\n\n def _traverse_scope_tree(self, bucket, cm, result_dict, test_dict, coll_verb):\n for scope_name, coll_dict in test_dict.items():\n result_coll_dict = result_dict[scope_name]\n logging.error(\"Creating scope {}\".format(scope_name))\n try:\n cm.create_scope(scope_name)\n except:\n pass\n scope = bucket.scope(scope_name)\n for coll_name, key_dict in coll_dict.items():\n result_key_dict = result_coll_dict[coll_name]\n logging.error(\n \"Creating collection {} in scope {}\".format(\n coll_name, scope_name)\n )\n try:\n cm.create_collection(\n CollectionSpec(scope_name=scope_name,\n collection_name=coll_name)\n )\n except:\n pass\n coll = scope.collection(coll_name)\n for key, value in key_dict.items():\n result = coll_verb(\n coll, scope_name, coll_name, result_key_dict, key, value)\n logging.error(\n \"Called {} on {} to {} in {} and got {}\".format(\n coll_verb,\n key,\n value,\n dict(scope_name=scope_name, coll_name=coll_name),\n result,\n )\n )\n\n def test_document_expiry_values(self):\n # per PYCBC-968\n\n # WORKAROUND_EXPIRY_CUTOFF_SECONDS:\n fifty_years = 50 * 365 * 24 * 60 * 60\n # RELATIVE_EXPIRY_CUTOFF_SECONDS:\n thirty_days = 30 * 24 * 60 * 60\n\n now = int(time.time() - 1.0)\n ttls = [\n fifty_years + 1,\n fifty_years,\n thirty_days - 1,\n thirty_days,\n\n now + 60,\n 60,\n ]\n bad_ttls = [\n -1,\n ]\n verify_expiry = True\n if self.is_mock:\n # other tests are skipped because \"mock will not return the\n # expiry in the xaddrs\", but we can at least test errors and\n # the warning added for PYCBC-968.\n ttls = [fifty_years + 1, fifty_years]\n verify_expiry = False\n\n options = GetOptions(with_expiry=True)\n\n for cases in (ttls, bad_ttls):\n warns = []\n for ttl in cases:\n expiry = timedelta(seconds=ttl)\n warnings.resetwarnings()\n with warnings.catch_warnings(record=True) as ws:\n try:\n result = self.cb.upsert(self.NOKEY, {\"x\": \"y\"},\n expiry=expiry)\n self.assertTrue(result.success)\n warns = ws\n except InvalidArgumentException:\n if ttl not in bad_ttls:\n raise\n continue\n try:\n result = self.cb.get(self.NOKEY, options)\n except DocumentNotFoundException:\n result = DocumentNotFoundException\n\n then = int(time.time() + 1.0)\n if ttl > fifty_years:\n self.assertEqual(len(warns), 1)\n # ttl taken as expiry time\n if verify_expiry and ttl > now:\n self.assertTrue(\n int(result.expiryTime.timestamp()) == ttl)\n else:\n # doc expired immediately\n self.assertTrue(result is DocumentNotFoundException)\n else:\n self.assertEqual(len(warns), 0)\n if verify_expiry:\n # ttl >= 30 days (and <= 50 yrs) changed to a timestamp\n # on the client; server interprets ttl < 30 as a true\n # duration. Either way expiryTime is a timestamp.\n self.assertTrue(\n now+ttl <= int(result.expiryTime.timestamp()) <= then+ttl)\n","sub_path":"couchbase/tests_v3/cases/collection_t.py","file_name":"collection_t.py","file_ext":"py","file_size_in_byte":28372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"382424331","text":"from django.shortcuts import render\n\nfrom django.shortcuts import render\nimport json\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom question.main import main\n\n\n# Create your views here.\n\ndef answer_test(request):\n return render(request, 'question/question_test.html')\n\n\ndef answer_options(request):\n\n question = request.POST['question_text']\n answeroption1 = request.POST['answeroptions1']\n answeroption2 = request.POST['answeroptions2']\n answeroption3 = request.POST['answeroptions3']\n\n # str_options = \",\".join(answeroptions)\n searchresult = main('{question}\\n\\n{op1}\\n\\n{op2}\\n\\n{op3}'.format(\n question=question,\n op1=answeroption1,\n op2=answeroption2,\n op3=answeroption3\n ))\n print(searchresult)\n # resp = {'errorCode': 100, 'detail': 'Get success', 'question': question, 'answeroptions': answeroptions}\n resp = {}\n return HttpResponse(json.dumps(searchresult), content_type='application/json')\n #return HttpResponseRedirect('/question/answertest/')\n\n\n","sub_path":"question/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"404590350","text":"import cv2\nimport numpy as np\nfrom sklearn import svm\nimg2=cv2.imread(\"c1.png\")\nimg3=cv2.imread(\"c2.png\")\nimg4=cv2.imread(\"x1.png\")\nimg5=cv2.imread(\"x2.png\")\nimg6=cv2.imread(\"c3.png\")\n\ndef process(img1):\n img1=cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)\n #cv2.imshow(\"c1.png\",img1)\n img1=img1/255\n #print(img1)\n img=np.identity(3)\n a=img1.shape\n l=[]\n global l1\n l1=[]\n m=0\n\n for i in range(0,18,3):\n for j in range(0,18,3):\n a=np.dot(img,img1[i:i+3,j:j+3])\n b=a.mean()\n l.append(b)\n #print(l)\n #print(a,l)\n c1=(np.asarray(l))\n c1=c1.reshape(6,6)\n #print(c1,c1.shape)\n\n for i in range(0,3,1):\n for j in range(0,3,1):\n a1=np.dot(img,c1[i:i+3,j:j+3])\n b1=a.mean()\n l1.append(b1)\n #print(l1)\n return l1\nprocess(img2)\na1=l1\nprocess(img3)\na2=l1\nprocess(img4)\na3=l1\nprocess(img5)\na4=l1\nprocess(img6)\na5=l1\n\n\nprint(a1,\"--------------\",a2,\"--------------\",a3,\"--------------\",a4)\n\nclf=svm.SVC(kernel=\"linear\",C=3)\nf=[a1,a2,a3,a4]\nl=[\"O\",\"O\",\"X\",\"X\"]\nt=clf.fit(f,l)\nr=t.predict([a5])\nprint(r)\n\n \n \n \n \n","sub_path":"imgrec1.py","file_name":"imgrec1.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"377853528","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport operator as op\n\nimport numpy as np\n\nfrom . import PixelRegion, SkyRegion, RegionMask\nfrom ..core.attributes import (CompoundRegionPix, CompoundRegionSky,\n RegionMeta, RegionVisual)\n\n__all__ = ['CompoundPixelRegion', 'CompoundSkyRegion']\n\n\nclass CompoundPixelRegion(PixelRegion):\n \"\"\"\n Represents the logical combination of two regions in pixel coordinates.\n\n Parameters\n ----------\n region1 : `~regions.PixelRegion` object\n The inner Pixel region.\n region2 : `~regions.PixelRegion` object\n The outer Pixel region.\n operator : `function`\n A callable binary operator.\n meta : `~regions.RegionMeta` object, optional\n A dictionary which stores the meta attributes of this region.\n visual : `~regions.RegionVisual` object, optional\n A dictionary which stores the visual meta attributes of this region.\n \"\"\"\n _params = ('region1', 'region2', 'operator')\n region1 = CompoundRegionPix('region1')\n region2 = CompoundRegionPix('region2')\n\n def __init__(self, region1, region2, operator, meta=None, visual=None):\n\n if not callable(operator):\n raise TypeError(\"operator must be callable\")\n\n self.region1 = region1\n self.region2 = region2\n if meta is None:\n self.meta = region1.meta\n else:\n self.meta = RegionMeta()\n if visual is None:\n self.visual = region1.visual\n else:\n self.visual = RegionVisual()\n self._operator = operator\n\n @property\n def operator(self):\n return self._operator\n\n def contains(self, pixcoord):\n in_reg = self.operator(self.region1.contains(pixcoord),\n self.region2.contains(pixcoord))\n if self.meta.get('include', True):\n return in_reg\n else:\n return np.logical_not(in_reg)\n\n def to_mask(self, mode='center', subpixels=1):\n if mode != 'center':\n raise NotImplementedError\n\n mask1 = self.region1.to_mask(mode=mode, subpixels=subpixels)\n mask2 = self.region2.to_mask(mode=mode, subpixels=subpixels)\n\n # Common bounding box\n bbox = self.bounding_box\n\n # Pad mask1.data and mask2.data to get the same shape\n padded_data = list()\n for mask in (mask1, mask2):\n pleft = abs(mask.bbox.ixmin - bbox.ixmin)\n pright = abs(bbox.ixmax - mask.bbox.ixmax)\n ptop = abs(bbox.iymax - mask.bbox.iymax)\n pbottom = abs(mask.bbox.iymin - bbox.iymin)\n padded_data.append(np.pad(mask.data,\n ((ptop, pbottom), (pleft, pright)),\n 'constant'))\n\n data = self.operator(*np.array(padded_data, dtype=np.int))\n return RegionMask(data=data, bbox=bbox)\n\n def to_sky(self, wcs):\n skyreg1 = self.region1.to_sky(wcs=wcs)\n skyreg2 = self.region2.to_sky(wcs=wcs)\n return CompoundSkyRegion(region1=skyreg1,\n operator=self.operator,\n region2=skyreg2, meta=self.meta, visual=self.visual)\n\n @staticmethod\n def _make_annulus_path(patch_inner, patch_outer):\n \"\"\"\n Defines a matplotlib annulus path from two patches.\n\n This preserves the cubic Bezier curves (CURVE4) of the aperture\n paths.\n\n # This is borrowed from photutils aperture.\n \"\"\"\n import matplotlib.path as mpath\n\n path_inner = patch_inner.get_path()\n transform_inner = patch_inner.get_transform()\n path_inner = transform_inner.transform_path(path_inner)\n\n path_outer = patch_outer.get_path()\n transform_outer = patch_outer.get_transform()\n path_outer = transform_outer.transform_path(path_outer)\n\n verts_inner = path_inner.vertices[:-1][::-1]\n verts_inner = np.concatenate((verts_inner, [verts_inner[-1]]))\n\n verts = np.vstack((path_outer.vertices, verts_inner))\n codes = np.hstack((path_outer.codes, path_inner.codes))\n\n return mpath.Path(verts, codes)\n\n def as_artist(self, origin=(0, 0), **kwargs):\n \"\"\"\n Matplotlib patch object for annulus region (`matplotlib.patches.PathPatch`).\n\n Parameters\n ----------\n origin : array_like, optional\n The ``(x, y)`` pixel position of the origin of the displayed image.\n Default is (0, 0).\n kwargs : `dict`\n All keywords that a `~matplotlib.patches.PathPatch` object accepts\n\n Returns\n -------\n patch : `~matplotlib.patches.PathPatch`\n Matplotlib patch object\n \"\"\"\n if self.region1.center == self.region2.center and self.operator == op.xor:\n import matplotlib.patches as mpatches\n\n patch_inner = self.region1.as_artist(origin=origin)\n patch_outer = self.region2.as_artist(origin=origin)\n path = self._make_annulus_path(patch_inner, patch_outer)\n patch = mpatches.PathPatch(path, **kwargs)\n return patch\n else:\n raise NotImplementedError\n\n @property\n def bounding_box(self):\n return self.region1.bounding_box | self.region2.bounding_box\n\n @property\n def area(self):\n raise NotImplementedError\n\n def rotate(self, center, angle):\n \"\"\"Make a rotated region.\n\n Rotates counter-clockwise for positive ``angle``.\n\n Parameters\n ----------\n center : `PixCoord`\n Rotation center point\n angle : `~astropy.coordinates.Angle`\n Rotation angle\n\n Returns\n -------\n region : `CompoundPixelRegion`\n Rotated region (an independent copy)\n \"\"\"\n region1 = self.region1.rotate(center, angle)\n region2 = self.region2.rotate(center, angle)\n return self.copy(region1=region1, region2=region2)\n\n\nclass CompoundSkyRegion(SkyRegion):\n \"\"\"\n Represents the logical combination of two regions in sky coordinates.\n\n Parameters\n ----------\n region1 : `~regions.SkyRegion` object\n The inner sky region.\n region2 : `~regions.SkyRegion` object\n The outer sky region.\n operator : `function`\n A callable binary operator.\n meta : `~regions.RegionMeta` object, optional\n A dictionary which stores the meta attributes of this region.\n visual : `~regions.RegionVisual` object, optional\n A dictionary which stores the visual meta attributes of this region.\n \"\"\"\n _params = ('region1', 'region2', 'operator')\n region1 = CompoundRegionSky('region1')\n region2 = CompoundRegionSky('region2')\n\n def __init__(self, region1, region2, operator, meta=None, visual=None):\n if not callable(operator):\n raise TypeError(\"operator must be callable\")\n\n self.region1 = region1\n self.region2 = region2\n if meta is None:\n self.meta = region1.meta\n else:\n self.meta = RegionMeta()\n if visual is None:\n self.visual = region1.visual\n else:\n self.visual = RegionVisual()\n self._operator = operator\n\n @property\n def operator(self):\n return self._operator\n\n def contains(self, skycoord, wcs):\n in_reg = self.operator(self.region1.contains(skycoord, wcs),\n self.region2.contains(skycoord, wcs))\n if self.meta.get('include', True):\n return in_reg\n else:\n return np.logical_not(in_reg)\n\n def to_pixel(self, wcs):\n pixreg1 = self.region1.to_pixel(wcs=wcs)\n pixreg2 = self.region2.to_pixel(wcs=wcs)\n return CompoundPixelRegion(region1=pixreg1,\n operator=self.operator,\n region2=pixreg2, meta=self.meta, visual=self.visual)\n\n def as_artist(self, ax, **kwargs):\n raise NotImplementedError\n","sub_path":"regions/core/compound.py","file_name":"compound.py","file_ext":"py","file_size_in_byte":8033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110141259","text":"import time\n# setup this in the end in controller when all modules are ready\nimport time\nclass DLogTime:\n def __init__(self):\n self.min = float('inf')\n self.max = 0\n self.avg = 0\n self.total = 0\n self.iters = 0\n # helper\n self.last_time = None\n\n def __str__(self):\n return \"min={0:.5f} max={1:.5f} avg={2:.5f} total={3:.5f} iters={4}\".format(self.min, self.max, \n self.avg, self.total, self.iters)\n\nclass DModLogger:\n def __init__(self, controller):\n self.controller = controller\n self.logging_modules = {}\n\n for k, m in controller.persistent_modules.items():\n self.logging_modules[k] = DLogTime()\n\n for k, m in controller.modules.items():\n self.logging_modules[k] = DLogTime()\n\n for c in controller.instant_command_classes:\n self.logging_modules[c.__name__] = DLogTime()\n\n for c in controller.buffered_command_classes:\n self.logging_modules[c.__name__] = DLogTime()\n\n def start(self, name):\n self.logging_modules[name].last_time = time.time()\n \n def stop(self, name):\n mod = self.logging_modules[name]\n t_diff = time.time() - mod.last_time\n if t_diff < mod.min:\n mod.min = t_diff\n elif t_diff > mod.max:\n mod.max = t_diff\n\n mod.iters += 1\n mod.avg = (mod.avg * (mod.iters - 1) + t_diff) / mod.iters \n\n mod.last_time = None\n mod.total += t_diff\n\n def __str__(self):\n out = \"\"\n for k, value in self.logging_modules.items():\n out += k + \" \" + str(value) + \"\\n\"\n return out\n","sub_path":"PythonClient/Framework/DLogTime.py","file_name":"DLogTime.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"322510410","text":"import os,sys\nimport numpy as np\nimport pandas as pd\n\n# User defined: -> play around with n_bins and x_range\n#################################################################################\ndatadir_input = \"DATA/raw_data/\" # Directory to raw data, change this!\ndatadir_output = \"DATA/generated_histograms/\" # Directory to generated histograms, change/create this!\nx_range=(110, 160) # m_mumu energy interval (110.,160.) for Higgs\nn_bins=50 # number of bins for histograms \n#################################################################################\n\nds_bkg=\"mc_bkg_new\" # filename for Background simulations (.h5)\nds_sig=\"mc_sig\" # filename for Signal simulations (.h5)\nds_data=\"data\" # filename for Measured data (.h5)\n\ndatasets=[ds_bkg,ds_sig,ds_data]\nlabels=[\"Background\",\"Signal\",\"Data\"]\n\n# Function for loading .h5 Atlas datasets\ndef load_data(dataset, datadir):\n infile = os.path.join(datadir, dataset+'.h5')\n print('Loading {}...'.format(infile))\n store = pd.HDFStore(infile,'r')\n dataset=store['ntuple']\n \n return dataset, store\n\nfor label, dataset in zip(labels, datasets):\n # Load dataset\n ds,file=load_data(dataset, datadir_input)\n \n # Get simulated (Background, Signal) or measured (Data) data\n all_events=ds[\"Muons_Minv_MuMu_Paper\"]\n \n # Get correct weights\n wts=ds[\"CombWeight\"]\n wts2=wts*wts\n \n # Firstly, get correct number of bin_values\n bin_values, _ = np.histogram(all_events,bins=n_bins,range=x_range,weights=wts) # wts!\n \n # Secondly, calculate bin_errors\n y, bin_edges = np.histogram(all_events,bins=n_bins,range=x_range,weights=wts2) # wts2!\n bin_centers = 0.5*(bin_edges[1:] + bin_edges[:-1])\n bin_errors = np.sqrt(y)\n\n # Finally, save several arrays into a single file in uncompressed .npz format\n save_name = datadir_output + 'hist_range_'+str(x_range[0]) + '-' + str(x_range[1]) + '_nbin-' + str(n_bins)+'_'+label+'.npz'\n with open(save_name, 'wb') as f:\n np.savez(f, bin_edges=bin_edges,bin_centers=bin_centers,bin_values=bin_values, bin_errors=bin_errors)\n f.close()\n\n\n\n","sub_path":"create_histograms.py","file_name":"create_histograms.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"338543635","text":"from ecmwfapi import ECMWFDataServer\n\nserver = ECMWFDataServer()\n\nserver.retrieve({\n 'use' : \"infrequent\",\n 'stream' : \"oper\",\n 'dataset' : \"interim\",\n 'step' : \"0/3/6/9/12\",\n 'levtype' : \"sfc\",\n 'date' : \"2008-01-03/to/2008-01-03\",\n 'time' : \"00/06/12/18\",\n 'type' : \"an/fc\",\n 'param' : \"165.128\",\n 'area' : \"90/00/-90/360\",\n 'grid' : \"0.125/0.125\",\n 'target' : \"/home/j_timmermans/Simulations/Matlab/SEBS/SEBS4SIGMA/Data/TMP/ECMWF/Wind_U.grib\"\n })","sub_path":"Download_ECMWF/DownloadBatchFile_Wind_U_20080103.py","file_name":"DownloadBatchFile_Wind_U_20080103.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483769404","text":"from ewolver.core import *\nfrom ewolver.reproduction import *\n\n\nclass BitVectorGenotype(Genotype):\n def __init__(self, birth_generation, data):\n super(BitVectorGenotype, self).__init__(birth_generation)\n self.data = data\n self.length = len(data)\n\n @staticmethod\n def factory_for_length(length):\n def create_random(birth_generation, rng):\n data = [rng.randint(0, 1) for _ in range(length)]\n return BitVectorGenotype(birth_generation, data)\n return create_random\n\n def child_copy(self, birth_generation):\n return BitVectorGenotype(birth_generation=birth_generation,\n data=self.data[:])\n\n def __str__(self):\n return ''.join('1' if x else '0' for x in self.data)\n\n\nclass BitVectorPhenotype(Phenotype):\n def __init__(self, genotype):\n super(BitVectorPhenotype, self).__init__(genotype)\n self.data = genotype.data\n\n def __str__(self):\n return ''.join('1' if x else '0' for x in self.data)\n\n\nclass IdentityBitVectorDevelopmentMethod(DevelopmentMethod):\n def develop_phenotype_from(self, genotype):\n return BitVectorPhenotype(genotype)\n\n\nclass BitVectorCrossoverOperator(CrossoverOperator):\n def __call__(self, first, second, child_gen, crossover_rate, rng):\n left_data = []\n right_data = []\n\n if rng.random() < crossover_rate:\n a = rng.randint(0, len(first.data))\n b = None\n while b is None or b == a:\n b = rng.randint(0, len(first.data))\n a, b = min(a, b), max(a, b)\n\n left_data = first.data[:a] + second.data[a:b] + first.data[b:]\n assert len(left_data) == len(first.data)\n right_data = second.data[:a] + first.data[a:b] + second.data[b:]\n else:\n left_data = first.data[:]\n right_data = second.data[:]\n return [\n BitVectorGenotype(child_gen, left_data),\n BitVectorGenotype(child_gen, right_data)\n ]\n\n\nclass BitVectorMutationOperator(MutationOperator):\n def __call__(self, genotype, child_gen, mutation_rate, rng):\n mutated_data = genotype.data[:]\n for k in range(len(mutated_data)):\n if rng.random() < mutation_rate:\n mutated_data[k] = not mutated_data[k]\n return BitVectorGenotype(child_gen, mutated_data)\n","sub_path":"ewolver/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"497117513","text":"# -*- coding: utf-8 -*-\n\ndef bytearray2str(bytearray, sep=' '):\n lst = []\n for byte in bytearray:\n lst.append('%.2x' % ord(byte))\n return sep.join(lst)\n\ndef bytearray2intlist(bytearray):\n lst = []\n for byte in bytearray:\n lst.append(ord(byte))\n return lst\n\ndef intlist2str(ilist, sep=' '):\n lst = []\n for val in ilist:\n lst.append('%.2x' % val)\n return sep.join(lst)\n\ndef get_short(seq, index = 0, net_order=True):\n hi_index = index + 1\n low_index = index\n if net_order:\n hi_index, low_index = low_index, hi_index\n hi = seq[hi_index] << 8\n low = seq[low_index]\n val = hi | low\n return val\n\ndef append_short(seq, val, net_order=True):\n if not isinstance(seq, list):\n return -1\n val &= 0xffff\n low_byte = val & 0xff\n hi_byte = val >> 8\n if net_order:\n seq.append(hi_byte)\n seq.append(low_byte)\n else:\n seq.append(low_byte)\n seq.append(hi_byte)\n return len(seq)\n\n\n\n\n\n","sub_path":"skpmeth.py","file_name":"skpmeth.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"55465535","text":"import numpy as np\nimport gym\n\nfrom PIL import Image\n\nclass Gymmer():\n def __init__(self, env_id):\n self.env = gym.make(env_id)\n self.is_done = True\n self.max_steps = 1024\n self.max_delta = 256\n self.bag_step = 0\n self.frame_bag = np.zeros((self.max_steps,) +self.env.observation_space.shape)\n self.get_pair_count = 0\n\n def refill_bag(self):\n self.get_pair_count = 0\n self.frame_bag = np.zeros((self.max_steps,) +self.env.observation_space.shape)\n self.env.reset()\n self.bag_step = 0\n last_action = self.env.action_space.sample()\n for s in range(self.max_steps):\n if(np.random.rand(1)[0] > 0.8):\n action = self.env.action_space.sample()\n else:\n action = last_action\n observation, reward, done, info = self.env.step(action)\n last_action = action\n self.frame_bag[s] = observation\n self.bag_step += 1\n if(done):\n break\n\n def get_pair(self):\n self.get_pair_count += 1\n if(self.bag_step == 0 or self.get_pair_count > self.bag_step/4):\n self.refill_bag()\n left_idx = int(np.random.rand(1)[0]*self.bag_step)\n right_idx = int(np.random.rand(1)[0]*self.max_delta)%self.bag_step\n time_delta = abs(left_idx - right_idx)\n return time_delta, self.frame_bag[left_idx], self.frame_bag[right_idx]\n\n \n\n def get_batch(self, size):\n batch = np.zeros((size*2,) +self.env.observation_space.shape)\n times = np.zeros(size)\n for i in range(size):\n td, left, right = self.get_pair()\n batch[2*i] = left\n batch[2*i+1] = right\n times[i] = td\n\n\n # Normalize\n times = times/self.max_steps\n\n\n return batch, times \n\n#gm = Gymmer('SpaceInvaders-v0')\n#gm.refill_bag()\n#batch, times = gm.get_batch(256)\n#print(times)\n#print(times.mean())\n","sub_path":"baselines/tsm_playground/data_gen.py","file_name":"data_gen.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"582498877","text":"import os\nimport sys\nimport torch\nimport torch.utils.data as data\nimport numpy as np\n\nclass Dataset(data.Dataset):\n def __init__(self, root, npoints = 2048, classification = False, class_choice = None, train = True):\n self.npoints = npoints\n self.root = root\n self.classification = classification\n self.catfile = os.path.join(root, 'synsetoffset2category.txt')\n self.cat = {}\n\n with open(self.catfile, 'r') as f:\n for line in f:\n ls = line.strip().split()\n self.cat[ls[0]] = ls[1]\n if not class_choice is None:\n self.cat = {k:v for k,v in self.cat.items() if k in class_choice}\n\n self.meta = {}\n for item in self.cat:\n self.meta[item] = []\n dir_point = os.path.join(self.root, self.cat[item],'points')\n dir_label = os.path.join(self.root, self.cat[item],'points_label')\n\n fns_point = sorted(os.listdir(dir_point))\n if train:\n fns_point = fns_point[:int(len(fns_point)*0.9)]\n else:\n fns_point = fns_point[int(len(fns_point)*0.9):]\n \n for fn in fns_point:\n file_name = (os.path.splitext(os.path.basename(fn))[0])\n self.meta[item].append((os.path.join(dir_point,file_name+'.pts'),os.path.join(dir_label,file_name+'.seg')))\n \n self.datapath = []\n for item in self.cat:\n for fn in self.meta[item]:\n self.datapath.append((item, fn[0], fn[1]))\n \n self.classes = dict(zip(sorted(self.cat), range(len(self.cat))))\n self.num_seg_class = 0\n if not self.classification:\n for i in range(len(self.datapath)//20):\n l = int(np.max(np.unique(np.loadtxt(self.datapath[i][2]).astype(np.uint8))))\n if l > self.num_seg_class:\n self.num_seg_class = l\n\n def __getitem__(self, index):\n fn = self.datapath[index]\n cls = self.classes[self.datapath[index][0]]\n point_set = np.loadtxt(fn[1]).astype(np.float32)\n seg = np.loadtxt(fn[2]).astype(np.int64)\n\n sample = np.random.choice(len(seg),self.npoints, replace = True)\n point_set = point_set[sample,:]\n seg = seg[sample]\n seg = seg-1\n point_set = torch.from_numpy(point_set)\n seg = torch.from_numpy(seg)\n cls = torch.from_numpy(np.array([cls]).astype(np.int64))\n if self.classification:\n return point_set, cls\n else:\n return point_set, seg\n\n def __len__(self):\n return len(self.datapath)\n \nif __name__ == '__main__':\n seg_data = Dataset(root = 'data/shapenetcore_partanno_segmentation_benchmark_v0', class_choice = ['Chair'])\n x = seg_data[0][0]\n print(x.size())\n print(seg_data.num_seg_class)\n print(len(seg_data))\n\n\n\n \n\n\n","sub_path":"data/shapenet.py","file_name":"shapenet.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"447513416","text":"import copy\r\nfrom os import path\r\nimport pytest\r\nfrom autocti import plot as aplt\r\n\r\ndirectory = path.dirname(path.realpath(__file__))\r\n\r\n\r\n@pytest.fixture(name=\"plot_path\")\r\ndef make_fit_plotter_setup():\r\n return path.join(\r\n \"{}\".format(path.dirname(path.realpath(__file__))), \"files\", \"plots\", \"fit\"\r\n )\r\n\r\n\r\ndef test__text_manual_dict(fit_ci_7x7):\r\n fit_ci_7x7 = copy.deepcopy(fit_ci_7x7)\r\n fit_ci_7x7.dataset.settings_dict = {\"hello\": 2.0, \"hi\": 3.0}\r\n\r\n fit_plotter = aplt.FitImagingCIPlotter(fit=fit_ci_7x7)\r\n\r\n assert fit_plotter.text_manual_dict_from(region=\"eper\") == {\r\n \"FPR (e-)\": 1.0,\r\n \"hello\": 2.0,\r\n \"hi\": 3.0,\r\n }\r\n assert fit_plotter.text_manual_dict_from(region=\"fpr\") == {\r\n \"hello\": 2.0,\r\n \"hi\": 3.0,\r\n }\r\n","sub_path":"test_autocti/plot/test_abstract_plotters.py","file_name":"test_abstract_plotters.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"58142076","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n#Grafico para coeficientes másicos de atenuacion con la base da datos de XCOM \n#Material: Argon (Z=18)\n\n#-----------------------------------\n#DATA FROM XCOM DATABASE (NIST)\n\n#ALUMINIUM \n#Densidad 2.70 g/cm^3\n'''\nAl= np.genfromtxt('xcomAl.txt')\nE = Al[:,0]\n\nAlCom = Al[:,1]\nAlPh = Al[:,2]\nAlT = Al[:,3]\n'''\n#Soft Tissue 4 Components\n#Densidad 1.00 g/cm^3\n'''\nSt = np.genfromtxt('xcomST.txt')\nE = St[:,0]\n\n\nStCom = St[:,1]\nStPh = St[:,2]\nStT = St[:,3]\n'''\n\n#Argon \n##Densidad \n\nBo = np.genfromtxt('ArgonXCOM.txt')\n\nE = Bo[:,0]\n\nBoCom = Bo[:,2]\nBoPh = Bo[:,3]\nBoPP=Bo[:,4]\nBoT = Bo[:,7]\n\n\n\n\n\n\n\n#----------------------------------\n\n\nplt.loglog(E,BoCom,'r',label= r'Compton')\nplt.loglog(E,BoPh,'b',label=r'Fotoeléctrico')\nplt.loglog(E,BoPP, label='Producción de Pares')\nplt.loglog(E,BoT,'g', label='Total')\n\nplt.legend()\n\nplt.xlabel(r'Energía (MeV)')\nplt.ylabel(r'$\\mu/\\rho$ ($cm^{2}/g$)')\n#plt.axis([0.001,2.1,0.000008,10000])\n#plt.grid(True)\n\nplt.text(0.4,1,'Argón',color='black', fontsize=14)\n\nplt.savefig('Argon.pdf')\nplt.show()\n\n","sub_path":"CrossSection.py","file_name":"CrossSection.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"24672157","text":"import math\n\n\nclass Complex(object):\n def __init__(self, real, imaginary):\n self.real = real\n self.imaginary = imaginary\n\n def __add__(self, other):\n real_add = self.real + other.real\n imag_add = self.imaginary + other.imaginary\n return Complex(real_add, imag_add)\n\n def __sub__(self, other):\n real_sub = self.real - other.real\n imag_sub = self.imaginary - other.imaginary\n return Complex(real_sub, imag_sub)\n\n def __mul__(self, other):\n # (a + bi)(c + di)\n # ac + (ad + bc)i + bd(-1)\n # real part = ac - bd\n # imag part = ad + bc\n a = self.real\n b = self.imaginary\n c = other.real\n d = other.imaginary\n real_mult = (a * c) - (b * d)\n imag_mult = (a * d) + (b * c)\n return Complex(real_mult, imag_mult)\n\n def __truediv__(self, other):\n # ((a + bi)(c - di))/(c + di)(c - di)\n # (ac + bd)/(cc + dd) + (bc - ad)i/(cc + dd)\n a = self.real\n b = self.imaginary\n c = other.real\n d = other.imaginary\n real_numerator = a * c + b * d\n imag_numerator = b * c - a * d\n denom = c * c + d * d\n real_div = real_numerator / denom\n imag_div = imag_numerator / denom\n return Complex(real_div, imag_div)\n\n def mod(self):\n a = self.real\n b = self.imaginary\n mod_ri = math.sqrt(a * a + b * b)\n return Complex(mod_ri, 0)\n\n def __str__(self):\n if self.imaginary == 0:\n result = \"%.2f+0.00i\" % (self.real)\n elif self.real == 0:\n if self.imaginary >= 0:\n result = \"0.00+%.2fi\" % (self.imaginary)\n else:\n result = \"0.00-%.2fi\" % (abs(self.imaginary))\n elif self.imaginary > 0:\n result = \"%.2f+%.2fi\" % (self.real, self.imaginary)\n else:\n result = \"%.2f-%.2fi\" % (self.real, abs(self.imaginary))\n return result\n\n\nif __name__ == '__main__':\n c = map(float, input().split())\n d = map(float, input().split())\n x = Complex(*c)\n y = Complex(*d)\n print(*map(str, [x + y, x - y, x * y, x / y, x.mod(), y.mod()]), sep='\\n')\n","sub_path":"Classes/complex_numbers.py","file_name":"complex_numbers.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"370455035","text":"import sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, inspect\nimport numpy as np\n\n# creating classes and engine\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\nbase = automap_base()\nbase.prepare(engine, reflect=True)\n\nStation = base.classes.station\nMeasure = base.classes.measurement\n\n\nfrom flask import Flask, render_template, jsonify\n\n# creating flask app\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n print(\"homepage accessed\")\n return render_template('home.html')\n\n@app.route(\"/api/v1.0/precipitation\")\ndef prcp():\n # initiates session and finds last twelve months of precipitation data, then returns json object\n session = Session(engine)\n last_twelve = session.query(Measure.date, Measure.prcp).filter(Measure.date > '2016-08-22').all()\n session.close()\n last_twelve = dict(last_twelve)\n return jsonify(last_twelve)\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n # initiates session and finds all unique stations in the dataset, then returns json object\n session = Session(engine)\n sts = session.query(Station.station, Station.name).all()\n session.close()\n sts = dict(sts)\n return jsonify(sts)\n \n@app.route(\"/api/v1.0/tobs\")\ndef tobs_j():\n # initiates session and finds last twelve months of temperature observation data for the \n # most active station, then returns json object\n session = Session(engine)\n _stations = session.query(Measure.station, func.count(Measure.station)).group_by(\n Measure.station).order_by(func.count(Measure.station).desc()).all()\n most_act = _stations[0][0]\n t_obs = session.query(Measure.tobs).filter(\n Measure.station == most_act).filter(\n Measure.date > '2016-08-22').all() \n session.close()\n d = {most_act : list(t_obs)}\n return jsonify(d)\n \n@app.route(\"/api/v1.0/\")\ndef start(start):\n # initiates session and finds min, max, and average temperature observation (across all stations)\n # since the given start date, and returns json object\n session = Session(engine)\n results = session.query(func.min(Measure.tobs), func.max(Measure.tobs), func.avg(Measure.tobs)).filter(\n Measure.date >= start).all()\n session.close()\n d = {\n f\"data after {start}\" : {\n 'min' : results[0][0],\n 'max' : results[0][1],\n 'mean' : results[0][2]\n }\n }\n return jsonify(d)\n \n@app.route(\"/api/v1.0//\")\ndef start_end(start, end):\n # initiates session and finds min, max, and average temperature observation (across all stations)\n # between the given start and end dates, and returns json object\n session = Session(engine)\n results = session.query(func.min(Measure.tobs), func.max(Measure.tobs), func.avg(Measure.tobs)).filter(\n Measure.date >= start).filter(Measure.date <= end).all()\n session.close()\n d = {\n f\"data between {start} and {end}\" : {\n 'min' : results[0][0],\n 'max' : results[0][1],\n 'mean' : results[0][2]\n }\n }\n return jsonify(d)\n\n\nif __name__ == '__main__':\n app.run()\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"119526807","text":"import time\nimport argparse\nimport re\nimport datetime\n\n\nclass TimeFormat():\n\t@staticmethod\n\tdef parse(f):\n\t\tform = '((?P[0-9]+)d)?((?P[0-9]+)h)?((?P[0-9]+)m)?((?P[0-9]+)s)?'\n\t\tg = re.match(form, f)\n\t\tparts = [(int(part or '0')) for part in g.group('days', 'hours', 'minutes', 'seconds')]\n\n\t\treturn dict(zip(['days', 'hours', 'minutes', 'seconds'], parts))\n\n\t@staticmethod\n\tdef to_seconds(f):\n\t\tif f is None:\n\t\t\treturn None\n\n\t\tif isinstance(f, str):\n\t\t\tparsed = TimeFormat.parse(f)\n\t\telif isinstance(f, dict):\n\t\t\tparsed = f\n\t\telse:\n\t\t\traise Exception('Unknown type: ' + str(type(f)))\n\n\t\tfactors = { \n\t\t\t'days': 24*60*60,\n\t\t\t'hours': 60*60,\n\t\t\t'minutes': 60,\n\t\t\t'seconds': 1\n\t\t}\n\n\t\ts = 0\n\n\t\tfor k in parsed:\n\t\t\ts += factors[k] * parsed[k]\n\n\t\treturn s\n\n\t@staticmethod\n\tdef calc_datetime(seconds):\n\t\treturn datetime.datetime.today() + datetime.timedelta(seconds=seconds)\n\ndef sleep(seconds, verbose):\n\tprint('Will sleep {} seconds (end at {})'.format(seconds, TimeFormat.calc_datetime(seconds)))\n\n\tif verbose is None:\n\t\ttime.sleep(seconds)\n\telse:\n\t\ttime.sleep(verbose)\n\n\t\tfor t in range(verbose, seconds, verbose):\n\t\t\tprint('Left: {} seconds'.format(seconds - t))\n\t\t\ttime.sleep(verbose)\t\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Simple anc configurable sleep script. Sleep and verbose param has format: 1d2h3d4m5s, where each part is optional. Script will sleep time passed in sleep param. Optionally script could print seconds left if you pass verbose param.')\n\n\tparser.add_argument('-s', '--sleep', help='Time to sleep, eg. 1d5h3m10s')\n\tparser.add_argument('-v', '--verbose', help='Interval in which script will print how much time is left, eg. 1m')\n\n\targs = parser.parse_args()\n\n\tif args.sleep:\n\t\tseconds = TimeFormat.to_seconds(args.sleep)\n\t\tverbose = TimeFormat.to_seconds(args.verbose)\n\n\t\tsleep(seconds, verbose)\n\telse:\n\t\tparser.print_help()\n\n\t","sub_path":"pythontools/sleep.py","file_name":"sleep.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"584263346","text":"from bottle import route, template, request\nfrom control.classes.permissao import permissao, usuario_logado\nfrom control.observador_controller import Observador\nfrom control.relatorios.relatorio_turma_controller import RelatorioTurma\nfrom control.dicionarios import SERIE\npath_template = 'gestao_aprendizagem/relatorios/turma/'\n\n\n@route('/relatorios/turma')\n@permissao('professor')\ndef relatorio_turma_view(no_repeat=False):\n observador = Observador(observador_logado=usuario_logado())\n\n return template(path_template + 'relatorio_turma', tipo=observador.get_observador_tipo(),\n turma=observador.get_turma(), teste_serie = SERIE)\n\n\n@route('/relatorios/visualizar_relatorio_turma')\n@permissao('professor')\ndef relatorio_aluno(no_repeat=False):\n observador = Observador(observador_logado=usuario_logado())\n relatorio = RelatorioTurma()\n turma = observador.get_turma(id_turma=request.params['turma'])\n descritores = relatorio.get_descritores(serie=turma['serie'])\n medias = relatorio.get_media_alunos(turma=turma['id'])\n porcentagem = relatorio.get_pontuacao_turma(medias=medias)\n alunos = []\n notas = []\n\n for index,i in enumerate(descritores):\n nota = []\n for z in medias:\n if z['nome'] not in alunos:\n alunos.append(z['nome'])\n try:\n nota.append(str(z['media'][index]))\n except IndexError:\n nota.append(0)\n notas.append(nota)\n\n por = []\n for i in porcentagem:\n if i != -1:\n por.append(i)\n porcentagem = por\n\n print(alunos)\n\n return template(path_template + 'relatorio_turma_detalhe', media_geral=relatorio.media_geral(porcentagem),\n media_portugues = relatorio.media_portugues(pontuacao=porcentagem),\n media_matematica=relatorio.media_matematica(porcentagem), tipo=observador.get_observador_tipo(),\n alunos=alunos, notas=notas, turma=turma,oa=descritores, porcentagem=porcentagem, teste_serie = SERIE)\n\n\n","sub_path":"src/route/relatorio_turma_route.py","file_name":"relatorio_turma_route.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375259825","text":"\"\"\"Run a battle among agents.\n\nCall this with a config, a game, and a list of agents. The script will start separate threads to operate the agents\nand then report back the result.\n\nAn example with all four test agents running ffa:\npython run_battle.py --agents=test::agents.SimpleAgent,test::agents.SimpleAgent,test::agents.SimpleAgent,test::agents.SimpleAgent --config=PommeFFACompetition-v0\n\nAn example with one player, two random agents, and one test agent:\npython run_battle.py --agents=player::arrows,test::agents.SimpleAgent,random::null,random::null --config=PommeFFACompetition-v0\n\nAn example with a docker agent:\npython run_battle.py --agents=player::arrows,docker::pommerman/test-agent,random::null,random::null --config=PommeFFACompetition-v0\n\"\"\"\nfrom datetime import datetime\n\nfrom pommerman.cli.Tournament import run_tournament\nfrom pommerman.cli.Tournament import run_single_match\n\nfrom pommerman.agents import SimpleAgent\nfrom pommerman.agents import SimpleCarefulAgent\nfrom pommerman.agents import UcbMCTSAgent\nfrom pommerman.agents import UcbLimitMCTSAgent\nfrom pommerman.agents import UcbMRMCTSAgent\nfrom pommerman.agents import UcbMRLimitMCTSAgent\nfrom pommerman.agents import NN_Agent\n\nfrom pommerman.NN.pommerman_neural_net import PommermanNNet\nfrom pommerman import constants\n\ndef run_ucb_vs_ucb():\n agent_pool1 = []\n agent_pool2 = []\n\n # create agents\n for i in [30, 20, 10, 5]:\n agent_ucb1 = UcbMCTSAgent\n kwargs = {'maxIterations': 100, 'maxTime': 0.2, 'depthLimit': 0}\n agent_pool1.append((f'UcbMCTSAgent_noDL', agent_ucb1, kwargs))\n\n agent_ucb2 = UcbMCTSAgent\n kwargs = {'maxIterations': 100, 'maxTime': 0.2, 'depthLimit': i}\n agent_pool2.append((f'UcbMCTSAgent_DL{i}', agent_ucb2, kwargs))\n\n # Tournament Settings\n tournament_name = 'UCB_DepthLimit_Test' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 20\n\n run_tournament(tournament_name, agent_pool1, agent_pool2, match_count, AllVsAll=False)\n\ndef run_simple_vs_ucb():\n agent_pool1 = []\n agent_pool2 = []\n\n # create agents\n agent_simple = SimpleAgent\n agent_pool1.append(('SimpleAgent', agent_simple, {}))\n\n iters = [1] + [(i+1) * 20 for i in range(5)]\n for i in iters:\n agent_ucb = UcbLimitMCTSAgent\n kwargs = {'expandTreeRollout': False,\n 'maxIterations': i,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': None,\n 'C': 0.5}\n agent_pool2.append((\n f'AgentUCBLimit_iter{kwargs[\"maxIterations\"]}_df{kwargs[\"discountFactor\"]}_dl{kwargs[\"depthLimit\"]}_ex{kwargs[\"expandTreeRollout\"]}_c{kwargs[\"C\"]}',\n agent_ucb, kwargs))\n\n # Tournament Settings\n tournament_name = 'Simple_Against_UCBLimit_' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 50\n\n run_tournament(tournament_name, agent_pool1, agent_pool2, match_count)\n\n\ndef run_ucb_rnd_vs_limit():\n agent_pool1 = []\n agent_pool2 = []\n\n # create agents\n iters = [1] + [(i + 1) * 20 for i in range(5)]\n for i in iters:\n agent_ucb = UcbMCTSAgent\n kwargs = {'expandTreeRollout': False,\n 'maxIterations': i,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': None,\n 'C': 0.5}\n agent_pool1.append((\n f'AgentUCB_iter{kwargs[\"maxIterations\"]}_df{kwargs[\"discountFactor\"]}_dl{kwargs[\"depthLimit\"]}_ex{kwargs[\"expandTreeRollout\"]}_c{kwargs[\"C\"]}',\n agent_ucb, kwargs))\n\n for i in iters:\n agent_ucb = UcbLimitMCTSAgent\n kwargs = {'expandTreeRollout': False,\n 'maxIterations': i,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': None,\n 'C': 0.5}\n agent_pool2.append((\n f'AgentUCBLimit_iter{kwargs[\"maxIterations\"]}_df{kwargs[\"discountFactor\"]}_dl{kwargs[\"depthLimit\"]}_ex{kwargs[\"expandTreeRollout\"]}_c{kwargs[\"C\"]}',\n agent_ucb, kwargs))\n\n # Tournament Settings\n tournament_name = 'UCB_Depth_Limit_Test' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 10\n\n run_tournament(tournament_name, agent_pool1, agent_pool2, match_count, False)\n\n\ndef run_ucb_rnd_vs_mcts():\n agent_pool1 = []\n agent_pool2 = []\n\n # create agents\n iters = [1] + [(i + 1) * 20 for i in range(5)]\n for i in iters:\n agent_ucb = UcbMCTSAgent\n kwargs = {'expandTreeRollout': False,\n 'maxIterations': i,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': None,\n 'C': 0.5}\n agent_pool1.append((\n f'AgentUCB_iter{kwargs[\"maxIterations\"]}_df{kwargs[\"discountFactor\"]}_dl{kwargs[\"depthLimit\"]}_ex{kwargs[\"expandTreeRollout\"]}_c{kwargs[\"C\"]}',\n agent_ucb, kwargs))\n\n for i in iters:\n agent_ucb = UcbMRMCTSAgent\n kwargs = {'expandTreeRollout': False,\n 'maxIterations': 6,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': 26,\n 'C': 0.5,\n 'MRDepthLimit': 2}\n agent_pool2.append((\n f'AgentUCBMRMCTS_iter{kwargs[\"maxIterations\"]}_df{kwargs[\"discountFactor\"]}_dl{kwargs[\"depthLimit\"]}_ex{kwargs[\"expandTreeRollout\"]}_c{kwargs[\"C\"]}',\n agent_ucb, kwargs))\n\n # Tournament Settings\n tournament_name = 'UCB_MR_VS_RND_Test' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 10\n\n run_tournament(tournament_name, agent_pool1, agent_pool2, match_count, False)\n\ndef compare_nnet_agents():\n nn_args = {\n 'input_channels': 8,\n 'board_x': constants.BOARD_SIZE_ONE_VS_ONE,\n 'board_y': constants.BOARD_SIZE_ONE_VS_ONE,\n\n 'lr': 0.001,\n 'dropout': 0.3,\n 'epochs': 10, # 10,\n 'batch_size': 64,\n 'cuda': False,\n 'num_channels': 512\n }\n agent_args = {\n 'expandTreeRollout': False,\n 'maxIterations': 25,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': 26,\n 'C': 1.0,\n 'tempThreshold': 0\n }\n nnet1 = PommermanNNet(**nn_args)\n nnet1.load_checkpoint('C:/tmp/Model/analyse_1', 'nnet_6.pth.tar')\n\n nnet2 = PommermanNNet(**nn_args)\n\n agent_pool1 = [(f'Trained_NN_Agent', NN_Agent, {'nnet': nnet1, **agent_args})]\n agent_pool2 = [(f'Rnd_NN_Agent', NN_Agent, {'nnet': nnet2, **agent_args})]\n match_count = 40\n wins, ties, loss = run_tournament('tournament_name', agent_pool1, agent_pool2, int(match_count / 2), False, False, False)\n print('Ended: ', wins, ties, loss)\n\ndef run_and_render_match():\n nn_args = {\n 'input_channels': 8,\n 'board_x': constants.BOARD_SIZE_ONE_VS_ONE,\n 'board_y': constants.BOARD_SIZE_ONE_VS_ONE,\n\n 'lr': 0.001,\n 'dropout': 0.3,\n 'epochs': 10, # 10,\n 'batch_size': 64,\n 'cuda': False,\n 'num_channels': 512\n }\n agent_args = {\n 'expandTreeRollout': False,\n 'maxIterations': 30,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': 30,\n 'C': 0,\n 'tempThreshold': 0,\n 'useDomainKnowledge': False\n }\n nnet1 = PommermanNNet(**nn_args)\n nnet1.load_checkpoint('C:/tmp/Model/analyse_2', 'nnet_3.pth.tar')\n\n #nnet2 = PommermanNNet(**nn_args)\n #nnet2.load_checkpoint('C:/tmp/Model/analyse_1', 'nnet_6.pth.tar')\n\n #agent1 = NN_Agent(SimpleAgent(), **agent_args)\n #agent2 = NN_Agent(SimpleAgent(), **agent_args)\n agent1 = SimpleCarefulAgent()\n agent2 = NN_Agent(nnet1, **agent_args)\n run_single_match(agent1, agent2, True)\n\ndef run_simple_vs_simple2():\n agent_pool1 = []\n agent_pool2 = []\n\n # create agents\n agent_simple = SimpleAgent2\n agent_pool1.append(('SimpleAgent', agent_simple, {}))\n\n agent_simple2 = SimpleAgent2\n agent_pool2.append(('SimpleAgent2', agent_simple2, {}))\n\n # Tournament Settings\n tournament_name = 'Simple_Against_SimpleAgent2_' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 1000\n\n run_tournament(tournament_name, agent_pool1, agent_pool2, match_count, only_one_side=True)\n\nfrom pommerman import my_utility\nfrom pommerman import forward_model\nfrom gym import spaces\ndef testSimpleAgent():\n game_type = constants.GameType(4)\n\n board = [[0, 0, 2, 1, 1, 1],\n [0, 0, 0, 0, 0, 0],\n [2, 8, 0, 1, 0, 1],\n [1, 0, 1, 0, 10, 1],\n [1, 0, 3, 0, 0, 1],\n [1, 11, 1, 1, 1, 0]]\n bomb_info = [(0, 1, 2, None)]\n\n game_state = my_utility.get_gamestate(board, bomb_info)\n game_data = my_utility.get_gamedata(game_state, game_type)\n\n fm = forward_model.ForwardModel()\n\n obs = fm.get_observations(game_data.board, game_data.agents, game_data.bombs, game_data.flames,\n False, None, game_data.game_type, None)\n\n simpel_agent = SimpleAgent()\n\n print(simpel_agent.act(obs[1], spaces.Discrete(6)))\n\ndef run_ucb_vs_simplecareful():\n agent_pool1 = []\n agent_pool2 = []\n\n nn_args = {\n 'input_channels': 8,\n 'board_x': constants.BOARD_SIZE_ONE_VS_ONE,\n 'board_y': constants.BOARD_SIZE_ONE_VS_ONE,\n\n 'lr': 0.001,\n 'dropout': 0.3,\n 'epochs': 10, # 10,\n 'batch_size': 64,\n 'cuda': False,\n 'num_channels': 512\n }\n agent_args = {\n 'expandTreeRollout': False,\n 'maxIterations': 80,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'depthLimit': 0,\n 'C': 0.1,\n 'tempThreshold': 0,\n 'useDomainKnowledge': False\n }\n nnet1 = PommermanNNet(**nn_args)\n nnet1.load_checkpoint('C:/tmp/Model/analyse_2', 'nnet_3.pth.tar')\n\n # create agents\n for i in [100, 120, 140]:\n agent_ucb1 = NN_Agent\n kwargs = agent_args.copy()\n kwargs['nnet'] = nnet1\n kwargs['maxIterations'] = i\n agent_pool1.append((f'AlphaZeroAgent_noDL_iter{i}', agent_ucb1, kwargs))\n\n agent_simple2 = SimpleAgent\n agent_pool2.append(('SimpleAgent', agent_simple2, {}))\n agent_pool1 = [('SimpleAgent', agent_simple2, {})]\n\n # Tournament Settings\n tournament_name = 'SimpleAgent_SimpleAgent_' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 100\n\n run_tournament(tournament_name, agent_pool2, agent_pool1, match_count, only_one_side=False)\n\ndef big_tournament():\n agent_pool = []\n agent_pool1 = []\n agent_pool2 = []\n\n nn_args = {\n 'input_channels': 8,\n 'board_x': constants.BOARD_SIZE_ONE_VS_ONE,\n 'board_y': constants.BOARD_SIZE_ONE_VS_ONE,\n\n 'lr': 0.001,\n 'dropout': 0.3,\n 'epochs': 10, # 10,\n 'batch_size': 64,\n 'cuda': False,\n 'num_channels': 512\n }\n agent_args = {\n 'expandTreeRollout': False,\n 'maxIterations': 80,\n 'maxTime': 0.0,\n 'discountFactor': 0.9999,\n 'C': 0.1,\n 'tempThreshold': 0,\n 'useDomainKnowledge': False\n }\n nnet_NORS = PommermanNNet(**nn_args)\n nnet_NORS.load_checkpoint('C:/tmp/Model/analyse_2', 'nnet_3.pth.tar')\n\n nnet_RS = PommermanNNet(**nn_args)\n nnet_RS.load_checkpoint('C:/tmp/Model/analyse_Reward', 'nnet_2.pth.tar')\n\n kwargs = agent_args.copy()\n kwargs['maxIterations'] = 60\n kwargs['depthLimit'] = 26\n agent_pool.append(('UCT-Agent', UcbMCTSAgent, kwargs))\n\n kwargs = agent_args.copy()\n kwargs['maxIterations'] = 40\n kwargs['depthLimit'] = 26\n agent_pool.append(('UCT-ActionPruning-Agent', UcbLimitMCTSAgent, kwargs))\n\n kwargs = agent_args.copy()\n kwargs['maxIterations'] = 5\n kwargs['depthLimit'] = 26\n agent_pool.append(('UCT-MiniMax-Agent', UcbMRLimitMCTSAgent, kwargs))\n\n kwargs = agent_args.copy()\n kwargs['nnet'] = nnet_NORS\n kwargs['maxIterations'] = 40\n agent_pool.append(('AlphaZero-Agent', NN_Agent, kwargs))\n\n kwargs = agent_args.copy()\n kwargs['nnet'] = nnet_RS\n kwargs['maxIterations'] = 40\n agent_pool.append(('AlphaZero-RewardShaping-Agent', NN_Agent, kwargs))\n\n start_i = 0\n game_num = 0\n for i, a in enumerate(agent_pool):\n for j in range(len(agent_pool)-i):\n game_num += 1\n if start_i <= game_num:\n print(i, j)\n agent_pool1.append(agent_pool[i])\n agent_pool2.append(agent_pool[i+j])\n\n print(agent_pool1[-1][0], 'vs', agent_pool2[-1][0])\n\n # Tournament Settings\n tournament_name = 'BigTournament' + datetime.now().strftime(\"%m-%d-%Y_%H-%M-%S\")\n match_count = 25\n\n run_tournament(tournament_name, agent_pool2, agent_pool1, match_count, only_one_side=False, AllVsAll=False)\n\nif __name__ == \"__main__\":\n #run_and_render_match()\n #run_simple_vs_simple2()\n #testSimpleAgent()\n run_ucb_vs_simplecareful()\n #big_tournament()","sub_path":"pommerman/cli/run_tournament.py","file_name":"run_tournament.py","file_ext":"py","file_size_in_byte":13042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"310992408","text":"import click\nimport sys\nimport traceback\nimport logging\nfrom cogscale.config import Configuration, Environment\nfrom cogscale.exceptions import ConfigurationException, CommandError\nfrom cogscale.command.config import ConfigCmd\nfrom cogscale.command.spark import SparkSubmitCmd\n\n\n__version__ = '4.0.0'\n\nlog = logging.getLogger()\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s/%(module)s @ %(threadName)s: %(message)s')\nhandler = logging.StreamHandler()\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\nlog.setLevel(logging.INFO)\n\n\nclass Context(object):\n\n def __init__(self):\n self.verbose = False\n self.api_key = None\n self.api_secret = None\n self.server = None\n self.spark_home = None\n self.agent_id = None\n\n def log(self, msg, fg='green', bg=None, bold=None, dim=None, underline=None,\n blink=None, reverse=None, reset=True):\n click.echo(click.style(msg, fg, bg, bold, dim, underline, blink, reverse, reset))\n\n def verbose(self, msg, fg='green', bg=None, bold=None, dim=None, underline=None,\n blink=None, reverse=None, reset=True):\n if self.verbose:\n self.log(msg, fg, bg, bold, dim, underline, blink, reverse, reset)\n\n def __repr__(self):\n return \"Context[server=%s, api_key=%s, api_secret=xxxxxxxx, agent_id=%s, spark_home=%s, verbose=%s]\" % (self.server, self.api_key, self.agent_id, self.spark_home, self.verbose)\n\n\nclass Server(object):\n\n def __init__(self, host, port, use_ssl):\n self.host = host\n self.port = port\n self.use_ssl = use_ssl\n\n def __repr__(self):\n return \"Server[host=%s, port=%s, use_ssl=%s]\" % (self.host, self.port, self.use_ssl)\n\n\ndef configure(ctx):\n s = ctx.server\n try:\n # Load saved configuration if it exists\n Configuration.load()\n\n # Configure the cogscale client environment\n Configuration.configure(Environment(\n s.host or Configuration.environment.server,\n s.port or Configuration.environment.port,\n s.use_ssl or Configuration.environment.use_ssl),\n ctx.api_key or Configuration.api_key,\n ctx.api_secret or Configuration.api_secret,\n ctx.agent_id or Configuration.agent_id,\n ctx.spark_home or Configuration.spark_home\n )\n\n except ConfigurationException as e:\n click.echo(click.style(\"Configuration error: %s\" % e.message, fg=\"red\"))\n sys.exit(2)\n\n\ndef execute(ctx, cmd, **kwargs):\n try:\n cmd.execute(ctx, **kwargs)\n except CommandError as e:\n ctx.log(e.message, fg=\"red\")\n if ctx.verbose:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback)\n except Exception as e:\n ctx.log(\"Unexpected error: \" + e.message, fg=\"red\")\n if ctx.verbose:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback)\n\n\n@click.group()\n@click.option('--host', '-h', envvar='CS_SERVER', default=None, metavar='HOST',\n help='CognitiveScale server host or IP address')\n@click.option('--port', '-p', envvar='CS_PORT', default=None, metavar='PORT',\n help='CognitiveScale server port')\n@click.option('--use-ssl', is_flag=True, help='Enable secure mode using SSL')\n@click.option('--api-key', envvar='CS_API_KEY', metavar='API_KEY', help='A valid CognitiveScale API key')\n@click.option('--api-secret', envvar='CS_API_SECRET', metavar='API_SECRET', help='A valid CognitiveScale API key secret')\n@click.option('--agent', envvar='CS_AGENT_ID', metavar='AGENT_ID', help='The identifier for the Cognitive Learning Agent')\n@click.option('--spark-home', envvar='SPARK_HOME', metavar='SPARK_HOME', help='Path to local Apache Spark install')\n@click.option('--verbose', '-v', is_flag=True, help='Enables verbose mode.')\n@click.version_option(__version__)\n@click.help_option()\n@click.pass_context\ndef cli(full_context, host, port, use_ssl, api_key, api_secret, agent, spark_home, verbose):\n # cli is the entry point and creates the project Context Object (instead of using @pass_context decorator)\n # this is to allow access to the full click.Context object\n ctx = Context()\n full_context.obj = ctx\n\n # Create a context object and remember it for all other commands. From\n # this point onwards other commands can refer to it by using the\n # @pass_context decorator.\n ctx.server = Server(host, port, use_ssl)\n ctx.verbose = verbose\n ctx.api_key = api_key\n ctx.api_secret = api_secret\n ctx.spark_home = spark_home\n ctx.agent_id = agent\n\n # config command doesn't need a configured environment - all other commands do\n if full_context.invoked_subcommand != \"config\":\n configure(ctx)\n\n if verbose:\n ctx.log(\"Server: %s\" % Configuration.environment.server)\n ctx.log(\"Port: %d\" % Configuration.environment.port)\n ctx.log(\"API Key: %s\" % Configuration.api_key)\n ctx.log(\"Agent: %s\" % Configuration.agent_id)\n print\n\n\n@cli.command()\n@click.argument('app_path')\n@click.pass_obj\ndef spark(ctx, app_path):\n execute(ctx, SparkSubmitCmd(), app_path=app_path, spark_home=ctx.spark_home)\n\n\n@cli.command()\n@click.option('--host', prompt=\"Host\", envvar='CS_SERVER', required=True)\n@click.option('--port', prompt=\"Port\", envvar='CS_PORT', required=True)\n@click.option('--api-key', prompt=\"API Key\", envvar='CS_API_KEY', required=True)\n@click.option('--api-secret', prompt=\"API Secret\", envvar='CS_API_SECRET', required=True)\n@click.option('--agent', prompt=\"Agent ID\", envvar='CS_AGENT_ID', required=True)\n@click.option('--spark-home', prompt=\"Spark Home\", envvar='SPARK_HOME', required=True)\n@click.pass_obj\ndef config(ctx, host, port, api_key, api_secret, agent, spark_home):\n ctx.server = Server(host, port, False)\n ctx.api_key = api_key\n ctx.api_secret = api_secret\n ctx.spark_home = spark_home\n ctx.agent_id = agent\n configure(ctx)\n execute(ctx, ConfigCmd())\n\n\n@cli.group()\ndef create():\n pass\n\n\n@create.command()\n@click.argument('name')\n@click.option('--display-name', metavar='NAME', help='A human friendly name', required=False)\n@click.pass_obj\ndef agent(ctx, name, display_name):\n click.echo('cogscale create agent ' + name)\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"cogscale/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"106595066","text":"import numpy as np\nfrom abc import ABC, abstractmethod\nfrom rec.utils import VerboseMode\nimport inspect\n\n\nclass FromNdArray(np.ndarray, VerboseMode):\n \"\"\"Subclass for Numpy's ndarrays.\n \"\"\"\n\n def __new__(cls, input_array, num_items=None, verbose=False):\n obj = np.asarray(input_array).view(cls)\n obj.verbose = verbose\n return obj\n\n def __init__(self, *args, **kwargs):\n pass\n\n def __array_finalize__(self, obj):\n if obj is None:\n return\n self.verbose = getattr(obj, \"verbose\", False)\n\n\nclass BaseObserver(ABC):\n \"\"\"Observer mixin for the observer design pattern.\n \"\"\"\n\n def register_observables(self, **kwargs):\n observables = kwargs.pop(\"observables\", None)\n\n observer = kwargs.pop(\"observer\", None)\n if observer is None:\n raise ValueError(\"Argument `observer` cannot be None\")\n elif not isinstance(observer, list):\n raise TypeError(\"Argument `observer` must be a list\")\n\n observable_type = kwargs.pop(\"observable_type\", None)\n if not inspect.isclass(observable_type):\n raise TypeError(\"Argument `observable_type` must be a class\")\n\n self._add_observables(\n observer=observer, observables=observables, observable_type=observable_type\n )\n\n def unregister_observables(self, **kwargs):\n observables = kwargs.pop(\"observables\", None)\n\n observer = kwargs.pop(\"observer\", None)\n if observer is None:\n raise ValueError(\"Argument `observer` cannot be None\")\n elif not isinstance(observer, list):\n raise TypeError(\"Argument `observer` must be a list\")\n\n self._remove_observables(observer=observer, observables=observables)\n\n def _add_observables(self, observer, observables, observable_type):\n if len(observables) < 1:\n raise ValueError(\"Can't add fewer than one observable!\")\n new_observables = list()\n for observable in observables:\n if isinstance(observable, observable_type):\n new_observables.append(observable)\n else:\n raise ValueError(\"Observables must be of type %s\" % observable_type)\n observer.extend(new_observables)\n\n def _remove_observables(self, observer, observables_to_remove):\n if len(observables) < 1:\n raise ValueError(\"Can't remove fewer than one observable!\")\n observables_copy = observer.copy()\n for observable in observables_to_remove:\n if observable in observables_copy:\n observables_copy.remove(observable)\n else:\n raise ValueError(\"Cannot find %s!\" % observable)\n observer = observables_copy\n\n\nclass BaseObservable(ABC):\n \"\"\"Observable mixin for the observer design pattern.\n \"\"\"\n\n def get_observable(self, **kwargs):\n data = kwargs.pop(\"data\", None)\n if data is None:\n raise ValueError(\"Argument `data` cannot be None\")\n elif not isinstance(data, list):\n raise TypeError(\"Argument `data` must be a list\")\n if len(data) > 0:\n name = getattr(self, \"name\", \"Unnamed\")\n return {name: data}\n else:\n return None\n\n @abstractmethod\n def observe(self, *args, **kwargs):\n pass\n\n\nclass BaseComponent(BaseObservable, VerboseMode, ABC):\n \"\"\"Observable that stores a history of its state.\n \"\"\"\n\n def __init__(self, verbose=False, init_value=None):\n VerboseMode.__init__(self, __name__.upper(), verbose)\n self.state_history = list()\n if isinstance(init_value, np.ndarray):\n init_value = np.copy(init_value)\n self.state_history.append(init_value)\n\n def get_component_state(self):\n return self.get_observable(data=self.state_history)\n\n def observe(self, state, copy=True):\n if copy:\n to_append = np.copy(state)\n else:\n to_append = state\n self.state_history.append(to_append)\n\n def get_timesteps(self):\n return len(self.state_history)\n\n\nclass Component(FromNdArray, BaseComponent):\n \"\"\"Class for components that make up the system state.\n \"\"\"\n\n def __init__(self, current_state=None, size=None, verbose=False, seed=None):\n # general input checks\n if current_state is not None:\n if not isinstance(current_state, (list, np.ndarray)):\n raise TypeError(\"current_state must be a list or numpy.ndarray\")\n if current_state is None and size is None:\n raise ValueError(\"current_state and size can't both be None\")\n if current_state is None and not isinstance(size, tuple):\n raise TypeError(\"size must be a tuple, is %s\" % type(size))\n if current_state is None and size is not None:\n current_state = Generator(seed).binomial(n=0.3, p=1, size=size)\n self.current_state = current_state\n # Initialize component state\n BaseComponent.__init__(self, verbose=verbose, init_value=self.current_state)\n\n def store_state(self):\n self.observe(self, copy=True)\n\n\nif __name__ == \"__main__\":\n from rec.models.recommender import SystemStateModule\n from rec.components import PredictedUserProfiles\n import numpy as np\n\n class Test(SystemStateModule):\n def __init__(self, user_profiles):\n self.user_profiles = PredictedUserProfiles(user_profiles)\n SystemStateModule.__init__(self)\n self.add_state_variable(self.user_profiles)\n\n def run(self, to_add=1):\n self.user_profiles += to_add\n print(\n \"Adding %d to user profiles. Result:\\n%s\\n\\n\"\n % (to_add, self.user_profiles)\n )\n self.measure_content()\n\n def measure_content(self):\n for component in self._system_state:\n component.store_state(np.asarray(component))\n\n profiles = np.zeros((5, 5))\n test = Test(profiles)\n test.run()\n test.run()\n print(\"State history:\")\n print(test.user_profiles.state_history)\n print(\"Final user profiles\")\n print(test.user_profiles)\n print(test.user_profiles.name)\n","sub_path":"rec/components/base_components.py","file_name":"base_components.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"342894802","text":"#!/usr/bin/env python3\n\nimport datetime\nimport logging\nimport pathlib\nimport os\nimport re\nfrom time import sleep\n\n\ndef make_log():\n today = datetime.date.today()\n logName = '/var/log/python-{}/xxxx.log'.format(today)\n log_BaseDir = re.match('(.*)xxxx(.log)', logName).group(1)\n\n if pathlib.Path(log_BaseDir).exists():\n if os.path.exists(logName):\n if not os.access(logName, os.W_OK):\n os.system(\"chmod u+w {}\".format(logName))\n\n else:\n logfile = open(logName, 'w+')\n logfile.close()\n\n else:\n os.makedirs(log_BaseDir)\n logfile = open(logName, 'w+')\n logfile.close()\n\n logging.basicConfig(filename=logName,level=logging.DEBUG,datefmt=\"%Y-%m-%d %H:%M:%S\",\n format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')\n logging.info(\"test logging\")\n\nif __name__ == '__main__':\n while True:\n make_log()\n sleep(1)\n","sub_path":"week01/week01_homework.py","file_name":"week01_homework.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"160927876","text":"#!/usr/bin/env python\n# -*-coding:utf-8 -*-\n\nimport os,json\nimport datetime,time\nfrom HttpRequest import HttpRequest\n\ndef parse_config(config):\n f = open(config,'r')\n try:\n content = json.load(f)\n except:\n content = {}\n return content\n\n\ndef post_alarm(host,err_log,timestamp):\n from module.Constant import alarm_url\n if not alarm_url:\n return -1\n query_args = {'host':host,'action':'agent','msg':err_log,'timestamp':timestamp,'status':0,'level':1,'method':1}\n request = HttpRequest(alarm_url,query_args,'POST')\n response = request.execute()\n if response.read() == 'OK':\n return 1\n else:\n return 0\n\n","sub_path":"utils_updates/fail_monitor/utils/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"202908377","text":"from collections import defaultdict\nfrom tabulate import tabulate\nimport operator, re, sys, socket\n\nID_PTR, table, mapping = 1, [], {'=':'eq','<':'lt','>':'gt','<=':'le','>=':'ge','!=':'ne'}\n\ndef custom_tabl(table): return tabulate(table, headers={'id':'id','key':'key','value':'value'}, tablefmt='psql')\n\ndef filter_col(table, cols): return [{col: row[col] for col in cols} for row in table] if cols != ['*'] else table\n\ndef sel(cols, condition=None): # SELECT STATEMENT\n if not condition: return custom_tabl(filter_col(table, cols.split(','))) if table else \"0 rows selected.\"\n col, op, val = re.split(r'(\\W+)', condition)\n subtable, reqd_cols = [], cols.split(',')\n for row in table:\n if getattr(operator, mapping[op])(str(row[col]), str(val)):\n subtable.append(row)\n if subtable: return custom_tabl(filter_col(subtable, reqd_cols))\n return \"0 rows selected.\"\n\ndef ins(data): # INSERT STATEMENT\n try:\n global ID_PTR\n table.append(defaultdict(lambda:'', {'id': ID_PTR, 'key': data.split(',')[0], 'value': data.split(',')[1]}))\n ID_PTR += 1\n return \"Inserted 1 row.\"\n except: return \"Insert failed, please check syntax/conflicting entries\"\n\ndef upd(col, condition): # UPDATE STATEMENT\n key_to_set, value_to_set = col.split('=')\n col, op, val = re.split(r'(\\W+)', condition)\n upd_count = 0\n for row in table:\n if getattr(operator, mapping[op])(str(row[col]), str(val)):\n row[key_to_set], upd_count = value_to_set, upd_count+1\n return f\"Updated {upd_count} row(s).\"\n\ndef delt(condition): # DELETE STATEMENT\n col, op, val = re.split(r'(\\W+)', condition)\n for row in table:\n if getattr(operator, mapping[op])(str(row[col]), str(val)):\n table.remove(row)\n return \"Deleted 1 row.\"\n else:\n return \"No rows matched condition\"\n\ndef exec_cmd(cmd): # SQL COMMAND PARSER\n accepted = ['select', 'insert', 'update', 'delete']\n cmdc = cmd.split()\n if not cmdc: return ''\n if cmdc[0] not in accepted:\n return f'Unknown command: {cmdc[0]}'\n if cmdc[0] == 'select': \n if len(cmdc) == 4: return sel(cmdc[1])\n return sel(cmdc[1], cmdc[5])\n if cmdc[0] == 'insert': return ins(cmdc[4])\n if cmdc[0] == 'update': return upd(cmdc[3], cmdc[5])\n else: return delt(cmdc[4])\n\nif __name__ == '__main__': # MAIN EVENT LOOP\n if len(sys.argv) == 1:\n while True:\n try: result = exec_cmd(input('db0 > '))\n except KeyboardInterrupt: sys.exit()\n except: print(\"There was an error with the SQL syntax.\")\n else: devnull = print(result) if result else None\n else:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.bind(('127.0.0.1', int(sys.argv[1])))\n sock.listen()\n connection, address = sock.accept()\n with connection:\n while True:\n connection.send('db0 > '.encode())\n connection.send(f\"{exec_cmd(connection.recv(1024).decode('utf-8'))}\\n\".encode())\n ","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"77659800","text":"from spellchecker import SpellChecker\n\ndef spell_check_me(sentence):\n\tspell = SpellChecker()\n\tspell.word_frequency.load_words(['microsoft', 'mp3', 'broadband','apple', 'google','hadoop','json','samsung', 'backend', 'ocr', 'keyphrase', 'MRI', 'turn-up','nauseam', 'vast', 'turn', 'NuVox'])\n\ttemp = \"\"\n\n\tfor word in sentence.split(\" \"):\n\t\ttemp += \" \" + spell.correction(word)\n\n\tprint(\"SpellChecker: \", temp)\n\treturn temp\n\n","sub_path":"Scheduler_FYP/Dictionary_FYP/dict_using_spellchecker.py","file_name":"dict_using_spellchecker.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"539882165","text":"import pygame\nimport src.utils\nimport operator\nimport math\n\n# CONSTANTS FOR STARSHIP BEHAVIOR\nDRAG = 0.1 # How fast does the starship lose its speed\nACCEL = 0.2 # How fast does the sharship accelerate\n\nclass starship(pygame.sprite.Sprite):\n\n def __init__(self):\n pygame.sprite.Sprite.__init__(self) #call Sprite initializer\n self.image, self.rect = src.utils.load_image('enterprise.png',(0,0,0))\n self.image = pygame.transform.scale(self.image, (50,50))\n self.rect = self.image.get_rect()\n self.speedx = 0\n self.speedy = 0\n self.WIDTH, self.HEIGHT = pygame.display.get_surface().get_size()\n\n\n def update(self):\n self.flight_control()\n # move the ship to new position\n self.rect.x += self.speedx\n self.rect.y += self.speedy\n\n self.wrap_around()\n\n def flight_control(self):\n # handles everything related to simple starship flight\n # check if direction buttons are pressed\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_UP]:\n # up\n self.speedy += -ACCEL\n elif keystate[pygame.K_LEFT]:\n # left\n self.speedx += -ACCEL\n elif keystate[pygame.K_DOWN]:\n # down\n self.speedy += ACCEL\n elif keystate[pygame.K_RIGHT]:\n # right\n self.speedx += ACCEL\n else:\n # if no button is pressed slowly reduce speed\n if self.speedy > DRAG:\n self.speedy += -DRAG\n elif self.speedy < -DRAG:\n self.speedy += DRAG\n if self.speedx > DRAG:\n self.speedx += -DRAG\n elif self.speedx < -DRAG:\n self.speedx += DRAG\n\n def wrap_around(self):\n # if starship leaves the screen make it reappear at opposite side\n\n if self.rect.left > self.WIDTH+20:\n self.rect.right = 0\n if self.rect.right < -20:\n self.rect.left = self.WIDTH\n if self.rect.top > self.HEIGHT+20:\n self.rect.bottom = 0\n if self.rect.bottom < -20:\n self.rect.top = self.HEIGHT\n","sub_path":"src/starship.py","file_name":"starship.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"553120072","text":"#!/usr/bin/env python\nimport os, vtk\nimport numpy as np\nfrom matplotlib import pyplot as plt, cm\nfrom math import pi\n\nfrom pymicro.crystal.lattice import *\nfrom pymicro.crystal.microstructure import *\nfrom pymicro.xray.xray_utils import *\nfrom pymicro.view.vtk_utils import *\nfrom pymicro.view.scene3d import Scene3D\nfrom pymicro.xray.detectors import RegArrayDetector2d\nfrom pymicro.xray.laue import compute_Laue_pattern, diffracted_vector, compute_ellipsis, select_lambda, diffracted_vector\nfrom vtk.util.colors import gold\nfrom pymicro.external.tifffile import TiffFile\n\nsod = 120. # mm, source-object distance\nsample_size_mm = 5.0 # mm\n# create the 3D scene\nbase_name = '3d_finite_sample'\ns3d = Scene3D(display=True, ren_size=(1000, 800), name=base_name)\ndetector = RegArrayDetector2d(size=(960, 768), u_dir=[0, -1, 0], v_dir=[0, 0, -1])\ndetector.pixel_size = 1 * 0.127 # mm, factor 2 binning XX check this !!\ndetector.ref_pos = np.array([125., 1.5, 0.])\ndetector_size_mm = detector.get_size_mm()\n\n# orientation of our single crystal\nsilicon = Lattice.face_centered_cubic(0.539)\neuler_angles = (0., 47.5, 0.)\n#euler_angles = (0.312, 46.864, 359.922)\norientation = Orientation.from_euler(euler_angles)\ngt = orientation.orientation_matrix().transpose()\n\n\nhkl_planes = [HklPlane(-1, 3, 3, silicon), HklPlane(-2, 1, 8, silicon)]\nhkl_planes = HklPlane.get_family('128', lattice=silicon)\n#hkl_planes = HklPlane.get_family('133', lattice=silicon)\n#hkl_planes = [HklPlane(2, 6, 6, silicon), HklPlane(-2, 6, 6, silicon), HklPlane(2, -6, 6, silicon), HklPlane(2, 6, -6, silicon)]\n#hkl_planes = [HklPlane(3, 9, 9, silicon), HklPlane(-3, 9, 9, silicon), HklPlane(3, -9, 9, silicon), HklPlane(3, 9, -9, silicon)]\nhkl_planes = HklPlane.get_family('137', lattice=silicon)\n#hkl_planes = HklPlane.get_family('369', lattice=silicon)\n#hkl_planes = HklPlane.get_family('246', lattice=silicon)\nhkl_planes = HklPlane.get_family('113', lattice=silicon)\n#hkl_planes = HklPlane.get_family('339', lattice=silicon)\n#hkl_planes = HklPlane.get_family([4, 8, 12], lattice=silicon)\n#hkl_planes = HklPlane.get_family('115', lattice=silicon)\nhkl_planes = HklPlane.get_family('117', lattice=silicon)\n'''\nhkl_planes = HklPlane.get_family('113', lattice=silicon)\nhkl_planes.extend(HklPlane.get_family('115', lattice=silicon))\nhkl_planes.extend(HklPlane.get_family('117', lattice=silicon))\n'''\n'''\nhkl_planes = HklPlane.get_family('117', lattice=silicon)\nhkl_planes.extend(HklPlane.get_family('115', lattice=silicon))\nhkl_planes.extend(HklPlane.get_family('133', lattice=silicon))\nhkl_planes.extend(HklPlane.get_family('135', lattice=silicon))\nhkl_planes.extend(HklPlane.get_family('137', lattice=silicon))\nhkl_planes.extend(HklPlane.get_family('246', lattice=silicon))\n'''\n# use our new external function to compute the detector image\npattern = compute_Laue_pattern(orientation, detector, hkl_planes, r_spot=3, inverted=True, show_direct_beam=True, verbose=True)\nplt.imsave('pattern.png', pattern.T, cmap=cm.gray)\n\n# load experimental image\npath = os.path.join(os.environ['RAWDATA'], '2018_10_15_DiffLaue_Navier', '2018_10_15_Mines_diffraction_Si/', )\nname = '01.tiff' \nref_name = 'ref_01.tiff'\nimage = tifffile.imread(path + name).astype(np.float32).transpose()\nprint('Image exp :', np.shape(image)[0], image.dtype, image.min(), image.max())\nref_image = tifffile.imread(path + ref_name).astype(np.float32).transpose()\nprint('Reference :', np.shape(ref_image), ref_image.dtype, ref_image.min(), ref_image.max())\nim_cor = image - ref_image\nfrom scipy import ndimage\nimcor_2 = ndimage.median_filter(im_cor, size=3)\nimcor_3 = ndimage.grey_erosion(imcor_2, size=(2, 2))\n\n# standalone figure\nplt.figure(1)\nplt.imshow(im_cor.T, cmap='gray_r')\nfor hkl in hkl_planes:\n (the_energy, theta) = select_lambda(hkl, orientation, verbose=False)\n K = diffracted_vector(hkl, orientation)\n R = detector.project_along_direction(K, origin=[0., 0., 0.])\n (u, v) = detector.lab_to_pixel(R)[0]\n plt.plot(u, v, 'ko')\n (h, k, l) = hkl.miller_indices()\n plt.annotate('$%d%d%d$' % (h, k, l), xycoords='data', xy=(u, v), horizontalalignment='center', verticalalignment='bottom', fontsize=16)\nplt.clim(100, 1000)\nplt.axis([0, 959, 0, 767])\nplt.title(r'Silicon')\nplt.show()\n\n# detector tilted actor positioned at det_distance mm from the center\ndet = vtk.vtkPlaneSource()\ndet.SetOrigin(0., detector_size_mm[0] / 2, -detector_size_mm[1] / 2)\ndet.SetPoint1(0., -detector_size_mm[0] / 2, -detector_size_mm[1] / 2)\ndet.SetPoint2(0., detector_size_mm[0] / 2, detector_size_mm[1] / 2)\nplaneMapper = vtk.vtkPolyDataMapper()\nplaneMapper.SetInputConnection(det.GetOutputPort())\nplaneActor = vtk.vtkActor()\nplaneActor.SetMapper(planeMapper)\n# create texture object (reuse the image we have just created)\nreader = vtk.vtkPNGReader()\nreader.SetFileName('pattern.png')\ntexture = vtk.vtkTexture()\ntexture.SetInputConnection(reader.GetOutputPort())\nplaneActor.SetTexture(texture)\napply_translation_to_actor(planeActor, detector.ref_pos)\ns3d.add(planeActor)\n\n# add the crystal lattice with hkl planes, move it so the centre of the cell is at (0, 0, 0)\nlattice_with_planes = lattice_3d_with_planes(silicon, hkl_planes, crystal_orientation=orientation, origin='mid',\n show_atoms=True, show_normal=True, plane_opacity=1.0, sphereRadius=0.1,\n sphereColor=gold)\ns3d.add(lattice_with_planes)\n\n# add axes actor\naxes = axes_actor(30, axisLabels=('X', 'Y', 'Z'), fontSize=50)\n#s3d.add(axes)\n\n# X-ray source\nsource = vtk.vtkSphereSource()\nsource.SetCenter(-sod, 0, 0)\nsource.SetRadius(1)\nsource_mapper = vtk.vtkPolyDataMapper()\nsource_mapper.SetInputConnection(source.GetOutputPort())\nsource_actor = vtk.vtkActor()\nsource_actor.SetMapper(source_mapper)\ns3d.add(source_actor)\n\n# slit limited incident beam\npyramidPoints = vtk.vtkPoints()\npyramidPoints.SetNumberOfPoints(5)\npyramidPoints.InsertPoint(0, 0, -0.5 * sample_size_mm, -0.5 * sample_size_mm)\npyramidPoints.InsertPoint(1, 0, 0.5 * sample_size_mm, -0.5 * sample_size_mm)\npyramidPoints.InsertPoint(2, 0, 0.5 * sample_size_mm, 0.5 * sample_size_mm)\npyramidPoints.InsertPoint(3, 0, -0.5 * sample_size_mm, 0.5 * sample_size_mm)\npyramidPoints.InsertPoint(4, -sod, 0, 0)\naPyramid = vtk.vtkPyramid()\naPyramid.GetPointIds().SetId(0, 0)\naPyramid.GetPointIds().SetId(1, 1)\naPyramid.GetPointIds().SetId(2, 2)\naPyramid.GetPointIds().SetId(3, 3)\naPyramid.GetPointIds().SetId(4, 4)\naPyramidGrid = vtk.vtkUnstructuredGrid()\naPyramidGrid.Allocate(1, 1)\naPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds())\naPyramidGrid.SetPoints(pyramidPoints)\naPyramidMapper = vtk.vtkDataSetMapper()\naPyramidMapper.SetInputData(aPyramidGrid)\naPyramidActor = vtk.vtkActor()\naPyramidActor.SetMapper(aPyramidMapper)\naPyramidActor.GetProperty().SetEdgeColor(0., 0., 0.)\naPyramidActor.GetProperty().SetLineWidth(1)\naPyramidActor.GetProperty().SetRepresentationToWireframe()\ns3d.add(aPyramidActor)\n\n# set up camera and render\ncam = setup_camera(size=(1, 1, 1))\n#cam.SetFocalPoint(detector.ref_pos)\ncam.SetPosition(-250, 250, 125)\ns3d.set_camera(cam)\ncam.SetClippingRange(1, 1000)\ncam.Dolly(0.95)\n#s3d.render(key_pressed_callback=True)\n","sub_path":"Experiments/05_Octobre18_Navier/Silicium/3d_finite_sample.py","file_name":"3d_finite_sample.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"216190099","text":"from django.conf.urls import url\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom .views import home, new_invitation, accept_invitation, SignUpView\n\n# r matches any string that ends with home\nurlpatterns = [\n url(r'home$', home, name=\"player_home\"),\n url(r'login$',\n LoginView.as_view(template_name=\"player/login_form.html\"),\n name=\"player_login\"),\n url(r'logout$',\n LogoutView.as_view(),\n name=\"player_logout\"),\n url(r'new_invitations', new_invitation, name='player_new_invitation'),\n # this is a regex to find anything in the group(?P) called id\n # that is any number of digits long\n # when we go to invitation/some digits/ we pass some digits as 'id'\n # to the view\n url(r'accept_invitation/(?P\\d+)/$',\n accept_invitation,\n name=\"player_accept_invitation\"),\n url(r'signup$',\n SignUpView.as_view(),\n name='player_signup')\n]\n","sub_path":"player/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"328428195","text":"\nimport glob\nfrom PIL import Image\nimport os\n\n\ndef resize_photos():\n for idx, name in enumerate(glob.glob('big_photos/*')):\n new_name = f\"small/{idx}_\" + str(name[11:])\n image = Image.open(name)\n half_height, half_weight = int((image.size[0])/2), int((image.size[1])/2)\n tup = tuple((half_height,half_weight))\n new_image = image.resize(tup)\n image.save(new_name)\n\ndef check_percent_size():\n for file in glob.glob('big_photos/*'):\n big_size =+ int(os.stat(file).st_size)\n for file in glob.glob('small/*'):\n small = + int(os.stat(file).st_size)\n print(f\"The size of your files has been reduced by: {int(small/big_size *100)} percent\")\n\ncheck_percent_size()\n\n\nresize_photos()\n","sub_path":"day_6_resizer/resizer_app.py","file_name":"resizer_app.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"515630760","text":"#!/usr/bin/python\n\nimport vot\nimport sys\nimport time\n\n# *****************************************\n# VOT: Create VOT handle at the beginning\n# Then get the initializaton region\n# and the first image\n# *****************************************\nhandle = vot.VOT(\"mask\")\nselection = handle.region()\n\n# Process the first frame\nimage = handle.frame()\nif not image:\n sys.exit(0)\n\nwhile True:\n # *****************************************\n # VOT: Call frame method to get path of the\n # current image frame. If the result is\n # null, the sequence is over.\n # *****************************************\n image = handle.frame()\n if not image:\n break\n\n # *****************************************\n # VOT: Report the position of the object\n # every frame using report method.\n # *****************************************\n handle.report(selection)\n\n time.sleep(0.01)\n\n","sub_path":"python/python_static_mask.py","file_name":"python_static_mask.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"429277214","text":"import argparse\nimport json\nimport os\nimport subprocess\nimport sys\nfrom proxy import Migration\nfrom uploader import Upload\n\ndef set_args():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\n\t\t'-m','--mode',\n\t\tchoices=['proxy','upload'],\n\t\tdefault='proxy',\n\t\thelp=(\n\t\t\t\"Choose from:\\n\"\n\t\t\t\"proxy (look for mp4 files and make proxies)\\n\"\n\t\t\t\"upload (just upload existing files in the target directory\"\n\t\t\t\t\" declaring the mime type you want)\\n\"\n\t\t\t),\n\t\trequired=True\n\t\t)\n\tparser.add_argument(\n\t\t'-t','--mimeType',\n\t\tdefault='video/mp4',\n\t\thelp=(\"Set the mimeType you want to declare for all the files on upload.\\n\"\n\t\t\t\"Default is 'mp4.' You can add more options in `mimeTypes.json` in \"\n\t\t\t\"this directory.\"\n\t\t\t),\n\t\trequired=True\n\t\t)\n\tparser.add_argument(\n\t\t'-p','--batchPath',\n\t\thelp=(\"Enter the full file path for the directory containing \"\n\t\t\t\"the batch you want to process.\"\n\t\t\t),\n\t\trequired=True\n\t\t)\n\tparser.add_argument(\n\t\t'-f','--folderAlt',\n\t\thelp=(\"Enter an alternative Drive folder ID \"\n\t\t\t\"to override the one set in `secrets/other.py`.\"\n\t\t\t)\n\t\t)\n\tparser.add_argument(\n\t\t'-o','--outPath',\n\t\thelp=(\"Enter a filepath where you want the proxy \"\n\t\t\t\"files to be stored temporarily.\"\n\t\t\t)\n\t\t)\n\n\treturn parser.parse_args()\n\ndef main():\n\targs = set_args()\n\tmode = args.mode\n\tmimeType = args.mimeType\n\tbatchPath = args.batchPath\n\tfolderAlt = args.folderAlt\n\toutPath = args.outPath\n\n\tif not mimeType == 'video/mp4':\n\t\twith open('mimetypes.json','r') as f:\n\t\t\tmtypes = json.load(f)\n\t\tmimeType = mtypes[mimeType]\n\n\tif mode == 'proxy':\n\t\tfor root, dirs, _ in os.walk(batchPath):\n\t\t\tfor _dir in dirs:\n\t\t\t\tfor _file in os.listdir(os.path.join(root,_dir)):\n\t\t\t\t\tif _file.endswith('.mp4'):\n\t\t\t\t\t\tmigrate = Migration(\n\t\t\t\t\t\t\t_file,\n\t\t\t\t\t\t\tos.path.join(root,_dir,_file),\n\t\t\t\t\t\t\toutPath\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tmigrate.transcode()\n\t\t\t\t\t\tmigrate.upload()\n\t\t\t\t\t\tmigrate.delete_me()\n\telse:\n\t\tfor _file in os.listdir(batchPath):\n\t\t\tfilepath = os.path.join(batchPath,_file)\n\t\t\tmimeType = mimeType\n\t\t\tbaseName = _file\n\t\t\tfolderAlt = folderAlt\n\t\t\tloader = Upload(filepath,baseName,mimeType,folderAlt)\n\t\t\t\n\t\t\tloader.login()\n\t\t\tloader.upload_it() \n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"555470372","text":"r\"\"\"\nGuava error-correcting code constructions\n\nThis module only contains Guava wrappers (Guava is an optional GAP package).\n\nAUTHORS:\n\n- David Joyner (2005-11-22, 2006-12-03): initial version\n\n- Nick Alexander (2006-12-10): factor GUAVA code to guava.py\n\n- David Joyner (2007-05): removed Golay codes, toric and trivial codes and\n placed them in code_constructions; renamed RandomLinearCode to\n RandomLinearCodeGuava\n\n- David Joyner (2008-03): removed QR, XQR, cyclic and ReedSolomon codes\n\n- David Joyner (2009-05): added \"optional package\" comments, fixed some\n docstrings to to be sphinx compatible\n\nFunctions\n---------\n\"\"\"\n#*****************************************************************************\n# Copyright (C) 2007 David Joyner \n# 2006 Nick Alexander \n#\n# Distributed under the terms of the GNU General Public License (GPL)\n#\n# http://www.gnu.org/licenses/\n#*****************************************************************************\nfrom __future__ import absolute_import\n\nfrom sage.interfaces.all import gap\nfrom sage.misc.randstate import current_randstate\nfrom sage.matrix.matrix_space import MatrixSpace\nfrom sage.rings.finite_rings.finite_field_constructor import FiniteField as GF\nfrom sage.interfaces.gap import gfq_gap_to_sage\nfrom .linear_code import LinearCode\n\n\ndef QuasiQuadraticResidueCode(p):\n r\"\"\"\n A (binary) quasi-quadratic residue code (or QQR code), as defined by\n Proposition 2.2 in [BM]_, has a generator matrix in the block form `G=(Q,N)`.\n Here `Q` is a `p \\times p` circulant matrix whose top row\n is `(0,x_1,...,x_{p-1})`, where `x_i=1` if and only if `i`\n is a quadratic residue `\\mod p`, and `N` is a `p \\times p` circulant\n matrix whose top row is `(0,y_1,...,y_{p-1})`, where `x_i+y_i=1` for all `i`.\n\n INPUT:\n\n - ``p`` -- a prime `>2`.\n\n OUTPUT:\n\n Returns a QQR code of length `2p`.\n\n EXAMPLES::\n\n sage: C = codes.QuasiQuadraticResidueCode(11); C # optional - gap_packages (Guava package)\n Linear code of length 22, dimension 11 over Finite Field of size 2\n\n REFERENCES:\n\n .. [BM] Bazzi and Mitter, {\\it Some constructions of codes from group actions}, (preprint\n March 2003, available on Mitter's MIT website).\n\n .. [Jresidue] \\D. Joyner, {\\it On quadratic residue codes and hyperelliptic curves},\n (preprint 2006)\n\n These are self-orthogonal in general and self-dual when $p \\\\equiv 3 \\\\pmod 4$.\n\n AUTHOR: David Joyner (11-2005)\n \"\"\"\n F = GF(2)\n gap.load_package(\"guava\")\n gap.eval(\"C:=QQRCode(\" + str(p) + \")\")\n gap.eval(\"G:=GeneratorMat(C)\")\n k = int(gap.eval(\"Length(G)\"))\n n = int(gap.eval(\"Length(G[1])\"))\n G = [[gfq_gap_to_sage(gap.eval(\"G[%s][%s]\" % (i, j)), F)\n for j in range(1, n + 1)] for i in range(1, k + 1)]\n MS = MatrixSpace(F, k, n)\n return LinearCode(MS(G))\n\n\ndef RandomLinearCodeGuava(n, k, F):\n r\"\"\"\n The method used is to first construct a `k \\times n` matrix of the block\n form `(I,A)`, where `I` is a `k \\times k` identity matrix and `A` is a\n `k \\times (n-k)` matrix constructed using random elements of `F`. Then\n the columns are permuted using a randomly selected element of the symmetric\n group `S_n`.\n\n INPUT:\n\n - ``n,k`` -- integers with `n>k>1`.\n\n OUTPUT:\n\n Returns a \"random\" linear code with length `n`, dimension `k` over field `F`.\n\n EXAMPLES::\n\n sage: C = codes.RandomLinearCodeGuava(30,15,GF(2)); C # optional - gap_packages (Guava package)\n Linear code of length 30, dimension 15 over Finite Field of size 2\n sage: C = codes.RandomLinearCodeGuava(10,5,GF(4,'a')); C # optional - gap_packages (Guava package)\n Linear code of length 10, dimension 5 over Finite Field in a of size 2^2\n\n AUTHOR: David Joyner (11-2005)\n \"\"\"\n current_randstate().set_seed_gap()\n\n q = F.order()\n gap.load_package(\"guava\")\n gap.eval(\"C:=RandomLinearCode(\"+str(n)+\",\"+str(k)+\", GF(\"+str(q)+\"))\")\n gap.eval(\"G:=GeneratorMat(C)\")\n k = int(gap.eval(\"Length(G)\"))\n n = int(gap.eval(\"Length(G[1])\"))\n G = [[gfq_gap_to_sage(gap.eval(\"G[%s][%s]\" % (i, j)), F)\n for j in range(1, n + 1)] for i in range(1, k + 1)]\n MS = MatrixSpace(F, k, n)\n return LinearCode(MS(G))\n","sub_path":"sage/src/sage/coding/guava.py","file_name":"guava.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273274775","text":"def pan(array):\n\n\tlength = len(array)\n\tdp =0 \n\tcount = 0\n\t\n\tif array[0] == '-':\n\n\t\ty = 1\n\t\tif length == 1:\n\t\t\treturn 1\n\n\t\twhile array[y] == '-':\n\t\t\ty += 1\n\t\t\tif y == length:\n\t\t\t\treturn 1\n\n\t\twhile array[y] == '+':\n\t\t\ty += 1\n\t\t\tif y == length:\n\t\t\t\treturn 1\n\n\t\tcount = 1\n\t\tdp = y\t\t\n\t\n\telse:\n\t\t\n\t\tif length == 1:\n\t\t\treturn 0\n\n\t\tu = 0\n\t\twhile array[u] == '+':\n\t\t\tu += 1\n\t\t\tif u == length:\n\t\t\t\treturn 0\n\n\t\tdp = u\t\t\n\n\twhile dp != length:\n\t\t\n\t\tj = dp\n\t\tk = 0\n\t\tl = 0\n\n\t\twhile array[j] == '+':\n\t\t\tl += 1\n\t\t\tj += 1\n\t\t\tif j == length:\n\t\t\t\tbreak\n\t\t\n\t\tdp += l\n\t\tif dp == length:\n\t\t\tbreak\n\n\t\twhile array[j] == '-':\n\t\t\tk += 1\n\t\t\tj += 1\n\t\t\tif j == length:\n\t\t\t\tbreak\n\n\t\tdp += k\n\t\tcount += 2\t\t\t\n\n\treturn count\n\na = int(raw_input())\nque = []\n\nfor i in range (0, a):\n\tv = raw_input()\n\tque.append(v)\n\nsol = []\n\nfor h in range(0, a):\n\t\n\tsol.append(pan(que[h]))\t\n\nfo = open('foo3.txt', 'w')\n\nfor g in range(0, a):\t\n\tfo.write(\"Case #%d: %d \\n\" % (g+1, sol[g]))\n\n\n\n\n\n\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_swapnil96_3.py","file_name":"16_0_2_swapnil96_3.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304690961","text":"# coding:utf-8\n# UV info, using Maya Python API 2.0, _TwoPolygonMesh.ma\n\nfrom maya.api import OpenMaya as om\n\ninfo = ''\n\nselList = om.MGlobal.getActiveSelectionList()\n# dagPath = selList.getDagPath(0)\ndagPath, component = selList.getComponent(0)\ninfo += 'Object: %s\\n'%(dagPath.fullPathName())\n\nmeshFn = om.MFnMesh(dagPath)\n# dir(meshFn)\nuvSets = meshFn.getUVSetNames()\nfor name in uvSets:\n info += ' UV Set: %s'%name\n info += ' # UVs: %s\\n'%(meshFn.numUVs(name))\n\n# currentUVSet = meshFn.getCurrentUVSetName() \n# Error: AttributeError: file line 1: 'OpenMaya.MFnMesh' object has no attribute 'getCurrentUVSetName' # \nfrom maya import cmds\ncurrentUVSet = cmds.polyUVSet(currentUVSet=True, q=True)[0]\ninfo += ' Current UV Set: %s\\n'%currentUVSet\n\n# vIter = om.MItMeshVertex(dagPath)\nvIter = om.MItMeshVertex(dagPath, component)\nwhile not vIter.isDone():\n index = vIter.index()\n info += ' Vertex: %s\\n'%index\n \n hasUV = False\n \n # uv = vIter.getUV()\n try:\n uv = vIter.getUV(currentUVSet)\n if uv:\n # hasUV = True\n info += ' Vertex UV:%s\\n'%uv\n except:\n info += ' No assigned uv\\n'\n # break\n \n # fvUs, fvVs, fIDs = vIter.getUVs()\n try:\n fvUs, fvVs, fIDs = vIter.getUVs(currentUVSet)\n # Result: [maya.api.OpenMaya.MFloatArray([0.5, 0.5]), maya.api.OpenMaya.MFloatArray([0.0, 0.0]), maya.api.OpenMaya.MIntArray([0, 1])] # \n if fvUs:\n hasUV = True\n for i in range(len(fIDs)):\n fIndex = fIDs[i]\n fvIDs = meshFn.getPolygonVertices(fIndex)\n for fvIndex in range(len(fvIDs)):\n if fvIDs[fvIndex] == index:\n break\n info += ' Face-vertex UV: face,vertexFace:(%s, %s), UV:(%s, %s)\\n'%(fIndex, fvIndex, fvUs[i], fvVs[i])\n \n if not hasUV:\n info += ' No assigned uv\\n'\n except:\n pass\n \n vIter.next()\n\nprint(info)\n\n'''\n\nObject: |square\n UV Set: map1 # UVs: 6\n UV Set: map2 # UVs: 0\n Current UV Set: map1\n Vertex: 0\n Vertex UV:[0.0, 0.0]\n Face-vertex UV: face,vertexFace:(0, 0), UV:(0.0, 0.0)\n Vertex: 1\n Vertex UV:[0.5, 0.0]\n Face-vertex UV: face,vertexFace:(0, 1), UV:(0.5, 0.0)\n Face-vertex UV: face,vertexFace:(1, 0), UV:(0.5, 0.0)\n Vertex: 2\n Vertex UV:[1.0, 0.0]\n Face-vertex UV: face,vertexFace:(1, 1), UV:(1.0, 0.0)\n Vertex: 3\n Vertex UV:[0.0, 1.0]\n Face-vertex UV: face,vertexFace:(0, 3), UV:(0.0, 1.0)\n Vertex: 4\n Vertex UV:[0.5, 1.0]\n Face-vertex UV: face,vertexFace:(1, 3), UV:(0.5, 1.0)\n Face-vertex UV: face,vertexFace:(0, 2), UV:(0.5, 1.0)\n Vertex: 5\n Vertex UV:[1.0, 1.0]\n Face-vertex UV: face,vertexFace:(1, 2), UV:(1.0, 1.0)\n\n'''\n\ncmds.polyUVSet(uvSet=\"map2\", currentUVSet=True)\n\n","sub_path":"ch8_polygonalMeshes/uvInfo_pyAPI20.py","file_name":"uvInfo_pyAPI20.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"276471131","text":"# Geo fence detection algorithm based on \"crossing number algorithm(cn)\"\n# The code is written and maintained by Probhakar Sarkar , March18, 2020\n\nfrom utils import Point, Edge\n\nclass GeoFenceDetectorPolygon:\n # pointList is a list of vertices of a polygon of type Point\n # observer is the location of type Point for whom geo-fence crossing should be detected\n # pointList = [Point(), Point(), Point()...]\n def __init__(self, pointList, observer = Point(0,0)):\n self.pointList = pointList\n self.observer = observer\n\n\n def isInsideGeoFenceWithObserver(self, observer): # user can check geo-fence breach for specific observer\n crossingNumber = 0\n fromPoint = self.pointList[0]\n for point in self.pointList[1:]:\n if(self.isEdgeHorizontal(fromPoint, point)):\n # do nothing because edhe is horizontal to x axis\n # update the from point and go to next\n fromPoint = point\n else:\n if(self.hasRightSideRayIntersection(Edge(fromPoint, point), observer)):\n crossingNumber += 1\n fromPoint = point\n else:\n fromPoint = point\n\n if(crossingNumber % 2 == 0):\n return False\n else:\n return True\n\n\n def isInsideGeoFence(self): # here observer is static, once class is initialized can not be changed\n crossingNumber = 0\n fromPoint = self.pointList[0]\n for point in self.pointList[1:]:\n if(self.isEdgeHorizontal(fromPoint, point)):\n # do nothing because edhe is horizontal to x axis\n # update the from point and go to next\n fromPoint = point\n else:\n if(self.hasRightSideRayIntersection(Edge(fromPoint, point), self.observer)):\n crossingNumber += 1\n fromPoint = point\n else:\n fromPoint = point\n\n if(crossingNumber % 2 == 0):\n return False\n else:\n return True\n\n\n @ staticmethod\n def isEdgeHorizontal(fromPoint, toPoint):\n if(fromPoint.y == toPoint.y):\n return True\n else:\n return False\n\n @ staticmethod\n def hasRightSideRayIntersection(edge, point):\n if (point.y > edge.fromPoint.y and point.y < edge.toPoint.y) or (point.y < edge.fromPoint.y and point.y > edge.toPoint.y):\n a1 = edge.fromPoint.x\n a2 = edge.toPoint.x\n b1 = edge.fromPoint.y\n b2 = edge.toPoint.y\n interSectedX = (((a1-a2)/(b1-b2))*(point.y - b1)) + a1 \n if(point.x < interSectedX):\n return True\n else:\n return False\n else:\n return False","sub_path":"geo_fence_detector.py","file_name":"geo_fence_detector.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"86558364","text":"\"\"\"\nNVD_CVE_LIST\n\"\"\"\nfrom flask import Flask\nimport datetime\nfrom gva.data.validator import Schema\nfrom gva.flows.operators import EndOperator, SaveToBucketOperator\nfrom operators import AcquireAnnualCveDataOperator, SplitCveDataOperator\nfrom gva.utils.common import build_context\nfrom flask_sslify import SSLify\nfrom flask_cors import CORS\nimport sqlalchemy\nimport os\n\n\n\nfrom gva.logging import get_logger\nlogger = get_logger()\nlogger.setLevel(5)\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\nsslify = SSLify(app)\n\ndef init_connection_engine():\n db_config = {\n # [START cloud_sql_postgres_sqlalchemy_limit]\n # Pool size is the maximum number of permanent connections to keep.\n \"pool_size\": 5,\n # Temporarily exceeds the set pool_size if no connections are available.\n \"max_overflow\": 2,\n # The total number of concurrent connections for your application will be\n # a total of pool_size and max_overflow.\n # [END cloud_sql_postgres_sqlalchemy_limit]\n\n # [START cloud_sql_postgres_sqlalchemy_backoff]\n # SQLAlchemy automatically uses delays between failed connection attempts,\n # but provides no arguments for configuration.\n # [END cloud_sql_postgres_sqlalchemy_backoff]\n\n # [START cloud_sql_postgres_sqlalchemy_timeout]\n # 'pool_timeout' is the maximum number of seconds to wait when retrieving a\n # new connection from the pool. After the specified amount of time, an\n # exception will be thrown.\n \"pool_timeout\": 30, # 30 seconds\n # [END cloud_sql_postgres_sqlalchemy_timeout]\n\n # [START cloud_sql_postgres_sqlalchemy_lifetime]\n # 'pool_recycle' is the maximum number of seconds a connection can persist.\n # Connections that live longer than the specified amount of time will be\n # reestablished\n \"pool_recycle\": 1800, # 30 minutes\n # [END cloud_sql_postgres_sqlalchemy_lifetime]\n }\n\n if os.environ.get(\"DB_HOST\"):\n return init_tcp_connection_engine(db_config)\n else:\n return init_unix_connection_engine(db_config)\n\n\ndef init_tcp_connection_engine(db_config):\n # [START cloud_sql_postgres_sqlalchemy_create_tcp]\n # Remember - storing secrets in plaintext is potentially unsafe. Consider using\n # something like https://cloud.google.com/secret-manager/docs/overview to help keep\n # secrets secret.\n db_user = os.environ[\"DB_USER\"]\n db_pass = os.environ[\"DB_PASS\"]\n db_name = os.environ[\"DB_NAME\"]\n db_host = os.environ[\"DB_HOST\"]\n\n # Extract host and port from db_host\n host_args = db_host.split(\":\")\n db_hostname, db_port = host_args[0], int(host_args[1])\n\n pool = sqlalchemy.create_engine(\n # Equivalent URL:\n # postgres+pg8000://:@:/\n sqlalchemy.engine.url.URL(\n drivername=\"postgresql+pg8000\",\n username=db_user, # e.g. \"my-database-user\"\n password=db_pass, # e.g. \"my-database-password\"\n host=db_hostname, # e.g. \"127.0.0.1\"\n port=db_port, # e.g. 5432\n database=db_name # e.g. \"my-database-name\"\n ),\n **db_config\n )\n # [END cloud_sql_postgres_sqlalchemy_create_tcp]\n pool.dialect.description_encoding = None\n return pool\n\n\ndef init_unix_connection_engine(db_config):\n # [START cloud_sql_postgres_sqlalchemy_create_socket]\n # Remember - storing secrets in plaintext is potentially unsafe. Consider using\n # something like https://cloud.google.com/secret-manager/docs/overview to help keep\n # secrets secret.\n db_user = os.environ[\"DB_USER\"]\n db_pass = os.environ[\"DB_PASS\"]\n db_name = os.environ[\"DB_NAME\"]\n db_socket_dir = os.environ.get(\"DB_SOCKET_DIR\", \"/cloudsql\")\n cloud_sql_connection_name = os.environ[\"CLOUD_SQL_CONNECTION_NAME\"]\n\n pool = sqlalchemy.create_engine(\n\n # Equivalent URL:\n # postgres+pg8000://:@/\n # ?unix_sock=//.s.PGSQL.5432\n sqlalchemy.engine.url.URL(\n drivername=\"postgresql+pg8000\",\n username=db_user, # e.g. \"my-database-user\"\n password=db_pass, # e.g. \"my-database-password\"\n database=db_name, # e.g. \"my-database-name\"\n query={\n \"unix_sock\": \"{}/{}/.s.PGSQL.5432\".format(\n db_socket_dir, # e.g. \"/cloudsql\"\n cloud_sql_connection_name) # i.e \"::\"\n }\n ),\n **db_config\n )\n # [END cloud_sql_postgres_sqlalchemy_create_socket]\n pool.dialect.description_encoding = None\n return pool\n\n\n# This global variable is declared with a value of `None`, instead of calling\n# `init_connection_engine()` immediately, to simplify testing. In general, it\n# is safe to initialize your database connection pool when your script starts\n# -- there is no need to wait for the first request.\ndb = None\n\ndef build_flow(context: dict):\n\n # define the operations in the flow\n acquire = AcquireAnnualCveDataOperator()\n split = SplitCveDataOperator()\n\n save_to_bucket = SaveToBucketOperator(\n project=context['config'].get('target_project'),\n to_path=context['config'].get('target_path'),\n schema=Schema(context),\n date=context.get('date'),\n compress=context['config'].get('compress'))\n\n end = EndOperator()\n\n # chain the operations to create the flow\n flow = acquire > split > save_to_bucket > end\n\n # attach the writers\n flow.attach_writers(context['config'].get('writers', []))\n\n return flow\n\n@app.before_first_request\ndef create_tables():\n global db\n db = init_connection_engine()\n # Create tables (if they don't already exist)\n with db.connect() as conn:\n conn.execute(\n \"CREATE TABLE IF NOT EXISTS state \"\n \"( data_feed SERIAL NOT NULL, date timestamp NOT NULL, \"\n \"last_state VARCHAR(6) NOT NULL );\"\n )\n\n@app.route('/ingest')\ndef main(context: dict = {}):\n context['config_file'] = 'NVD_CVE_LIST.metadata'\n # create the run context from the config and context passed to main\n # this would allow dates etc to be passed from something external\n context = build_context(**context)\n\n # create the flow\n flow = build_flow(context)\n\n # NVD files are separate files per year\n currentYear = datetime.datetime.now().year\n for year in range(2018, currentYear + 1):\n my_context = context.copy()\n my_context['year'] = year\n flow.run(\n data={},\n context=my_context,\n trace_sample_rate=context['config'].get('sample_rate'))\n\n # finalize the operators\n summary = flow.finalize()\n logger.trace(summary)\n return 'Finished Ingest'\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)","sub_path":"transformations/NVD_CVE_LIST/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"279012479","text":"from .config_json_parser import ClpipeConfigParser\nfrom .utils import get_logger\nimport os\nfrom pathlib import Path\n\nfrom .batch_manager import BatchManager, Job\n\nFLYWHEEL_TEMP_DIR_NAME = \"'0)\np2 = p2*1*(p2>0)\np4 = p4*1*(p4>0)\n\n\n#Phaser p\nPreal = -(p2+p4-2*p0)/6\nPimag = -(1/(2*math.sqrt(3)))*(p2-p4)\nPhaser = Preal + 1j*Pimag\nPhase = np.angle(Phaser)\nAmp = np.absolute(Phaser)\nPhase_data = Phase\nxsize = np.shape(Phase)[0]\nysize = np.shape(Phase)[1]\n\n#replace referenced patch with average\n#pathup0 = np.unwrap(np.append(xaxis_unwrap[xsize/2-1],Phase[xsize/2-1,ysize/2+1:ysize]))\n#pathup1 = np.unwrap(np.append(xaxis_unwrap[xsize/2+2],Phase[xsize/2-1,ysize/2+1:ysize]))\n#pathup2 = np.unwrap(np.append(xaxis_unwrap[xsize/2],Phase[xsize/2-1,ysize/2+1:ysize]))\n#pathup1 = np.unwrap(Phase[xsize/2+2,ysize/2+1:ysize])\n#pathup2 = np.unwrap(Phase[xsize/2,ysize/2+1:ysize])\n#Phase[xsize/2+1,ysize/2-1]=(Phase[xsize/2+1,ysize/2-2]+Phase[xsize/2+1,ysize/2-1])/2\nPhase[xsize/2+1,ysize/2]=(Phase[xsize/2+1,ysize/2-1]+Phase[xsize/2+1,ysize/2+2])/2\nPhase[xsize/2+1,ysize/2+1]=(Phase[xsize/2+1,ysize/2-1]+Phase[xsize/2+1,ysize/2+2])/2\nPhase[xsize/2,ysize/2+2]=(Phase[xsize/2+1,ysize/2+2]+Phase[xsize/2-1,ysize/2+2])/2\nPhase[xsize/2,ysize/2+3]=(Phase[xsize/2+1,ysize/2+3]+Phase[xsize/2-1,ysize/2+3])/2\n#Phase[6,0]=0.8#(Phase[0,5]+Phase[0,7])/2\n#Phase[10,4]=0.8\n#Phase[1,2]=0.8\n#Phase[xsize/2,ysize/2]=(Phase[xsize/2-1,ysize/2+1]+Phase[xsize/2+1,ysize/2-1])/2\n#Phase[xsize/2,ysize/2]=(Phase[xsize/2-1,ysize/2+2]+Phase[xsize/2+2,ysize/2+2])/2\n\n\n\n\n#Unwrap\nUnwrappedx = np.unwrap(Phase,math.pi,1)\nUnwrappedy = np.unwrap(Phase,math.pi,0)\nUnwrappedxy = np.unwrap(Unwrappedx,math.pi,0)\nUnwrappedyx = np.unwrap(Unwrappedy,math.pi,1)\nUnwrappedxyx = np.unwrap(Unwrappedxy,math.pi,1)\nUnwrappedyxy = np.unwrap(Unwrappedyx,math.pi,0)\n\n\n#unwrap from center, like this\n# ^ ^ ^ ^ ^\n# ^ ^ ^ ^ ^\n# < < o > >\n# v v v v v\n# v v v v v\n\n#extract paths\n\n#pathsUpper = np.zeros(np.shape(Phase)[0]/2+1,\n# for y in xrange(0,np.shape(Phase)[0]):\n\n\n#unwrap y=0 axis from center\n#[::-1] is to take inverse \nxaxis_unwrap_up = np.unwrap(Phase[xsize/2:xsize,ysize/2]) \nxaxis_unwrap_down = np.unwrap(Phase[0:xsize/2+1,ysize/2][::-1])[::-1] \nxaxis_unwrap = np.append(xaxis_unwrap_down,np.delete(xaxis_unwrap_up,0,0))\n\n\n#prepare unwrapped phase array\nUnwrap_center = np.zeros(np.shape(Phase))\n\nfor x in xrange(0,xsize):\n\n pathdown = Phase[x,0:ysize/2][::-1]\n pathup = Phase[x,ysize/2+1:ysize]\n #append wrapped x axis value and unwrap\n pathdown = np.unwrap(np.append(xaxis_unwrap[x],pathdown))[::-1]\n pathup = np.unwrap(np.append(xaxis_unwrap[x],pathup))\n #add to Unwrapped phase array\n Unwrap_center[x,:] = np.append(pathdown,np.delete(pathup,0,0))\nUnwrapcx = np.unwrap(Unwrap_center,math.pi,0)\n\n#unwrap x=0 axis from center\n#[::-1] is to take inverse \nyaxis_unwrap_up = np.unwrap(Phase[xsize/2,ysize/2:ysize]) \nyaxis_unwrap_down = np.unwrap(Phase[xsize/2,0:ysize/2+1][::-1])[::-1] \nyaxis_unwrap = np.append(yaxis_unwrap_down,np.delete(yaxis_unwrap_up,0,0))\n\n#prepare unwrapped phase array\nUnwrap_center2 = np.zeros(np.shape(Phase))\n\nfor y in xrange(0,ysize):\n\n pathdown = Phase[0:xsize/2,y][::-1]\n pathup = Phase[xsize/2+1:xsize,y]\n #append wrapped y axis value and unwrap\n pathdown = np.unwrap(np.append(yaxis_unwrap[x],pathdown))[::-1]\n pathup = np.unwrap(np.append(yaxis_unwrap[x],pathup))\n #add to Unwrapped phase array\n Unwrap_center2[:,y] = np.append(pathdown,np.delete(pathup,0,0))\n\n\n##interpolate\n#Unwrap_center[xsize/2+1,ysize/2]=(Unwrap_center[xsize/2,ysize/2]+Unwrap_center[xsize/2+2,ysize/2])/2\n#Unwrap_center[xsize/2+1,ysize/2+1]=(Unwrap_center[xsize/2+1,ysize/2]+Unwrap_center[xsize/2+2,ysize/2+1])/2\n\n\n#gaus fit\n#p0 = [1., 0., 1.]\n#coeff, var_matrix = curve_fit(gauss, bin_centres, Unwrap_center, p0=p0)\n# Get the fitted curve\n#hist_fit = gauss(bin_centres, *coeff)\n#plt.plot(bin_centres, hist, label='Test data')\n#plt.plot(bin_centres, hist_fit, label='Fitted data')\n\nfourier = np.fft.fftshift(np.fft.fft2(Unwrappedxy))\nfourier[:,8] = 0\nfourier[8,:] = 0\nUnwrappedxy_low = np.real(np.fft.ifft2(np.fft.fftshift(fourier)))\n\n\n\nnp.savetxt(path + \"Phasec1.csv\", Unwrap_center, delimiter=\",\")\nnp.savetxt(path + \"Phasec2.csv\", Unwrap_center2, delimiter=\",\")\nnp.savetxt(path + \"Phasexy.csv\", Unwrappedxy, delimiter=\",\")\nnp.savetxt(path + \"Phaseyx.csv\", Unwrappedyx, delimiter=\",\")\n#np.savetxt(\"Phase_amp.csv\", Unwrap_center, delimiter=\",\")\n#np.savetxt(\"Phase2_amp.csv\", Unwrap_center2, delimiter=\",\")\n\n\nfig1=plt.figure(1,(20,10))\n#plt.imshow(Phase,interpolation='nearest')\nplt.subplot(2,4,1)\nplt.imshow(Phase)\n#plt.title('wrap')\nplt.title('phase')\nplt.colorbar()\n\nplt.subplot(2,4,2)\nplt.imshow(Unwrap_center)\nplt.title('unwrap center x')\nplt.colorbar()\n\nplt.subplot(2,4,3)\nplt.imshow(Unwrap_center2)\nplt.title('unwrap center y')\nplt.colorbar()\n\nplt.subplot(2,4,4)\nplt.imshow(Unwrappedxy)\nplt.title('unwrap xy')\nplt.colorbar()\n\nplt.subplot(2,4,5)\nplt.imshow(Unwrappedyx)\nplt.title('unwrap yx')\nplt.colorbar()\n\nplt.subplot(2,4,6)\nplt.imshow(Unwrapcx)\nplt.title('phase center + x')\nplt.colorbar()\n\nplt.subplot(2,4,7)\nplt.imshow(Unwrappedxy_low)\nplt.title('low pass xy')\nplt.colorbar()\n\nplt.subplot(2,4,8)\nplt.imshow(Phase_data)\nplt.title('phase original')\nplt.colorbar()\n#plot x=0\n#plt.subplot(3,3,4)\n#plt.plot(Phase[0,:])\n#plt.plot(Phase[1,:])\n#plt.plot(Phase[2,:])\n#plt.plot(Phase[3,:])\n#plt.plot(Phase[4,:])\n#plt.plot(Phase[5,:])\n#plt.plot(Phase[6,:])\n#plt.plot(Phase[7,:])\n#plt.plot(Phase[8,:])\n#plt.title('wrap, x=0')\n\n#plt.subplot(3,3,5)\n#plt.plot(Unwrap_center2[0,:])\n#plt.plot(Unwrap_center2[1,:])\n#plt.plot(Unwrap_center2[2,:])\n#plt.plot(Unwrap_center2[3,:])\n#plt.plot(Unwrap_center2[4,:])\n#plt.plot(Unwrap_center2[5,:])\n#plt.plot(Unwrap_center2[6,:])\n#plt.plot(Unwrap_center2[7,:])\n#plt.plot(Unwrap_center2[8,:])\n#plt.title('unwrap from center x x=0')\n\n#plt.subplot(3,3,6)\n#plt.plot(Unwrap_center[0,:])\n#plt.plot(Unwrap_center[1,:])\n#plt.plot(Unwrap_center[2,:])\n#plt.plot(Unwrap_center[3,:])\n#plt.plot(Unwrap_center[4,:])\n#plt.plot(Unwrap_center[5,:])\n#plt.plot(Unwrap_center[6,:])\n#plt.plot(Unwrap_center[7,:])\n#plt.plot(Unwrap_center[8,:])\n#plt.title('unwrap from center y x=0')\n\n#plot y=0\n#plt.subplot(3,3,7)\n#plt.plot(Phase[:,3])\n#plt.title('wrap, y=0')\n\n#plt.subplot(3,3,8)\n#plt.plot(Unwrap_center2[:,3])\n#plt.title('unwrap from center x y=0')\n\n#plt.subplot(3,3,9)\n#plt.plot(Unwrap_center[:,3])\n#plt.title('unwrap from center y y=0')\nplt.show()\n\nfig = plt.figure(2)\nax = Axes3D(fig)\nx = np.arange(-(xsize/2)*50, (xsize/2+1)*50,50)\ny = np.arange(-(ysize/2)*50, (ysize/2+1)*50,50)\nX, Y = np.meshgrid(x, y)\nax.plot_surface(X, Y, Unwrap_center, rstride=1, cstride=1)\nplt.show()\n","sub_path":"Scripts/PhaseMeasurement/Unwrap.py","file_name":"Unwrap.py","file_ext":"py","file_size_in_byte":6972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"107772082","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom classes import FlowLayout, Canvas, ViewPort\n\nclass MainWindow(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n dialog = NewFileDialog(self)\n\n def setupUi(self, MainWindow):\n self.setWindowTitle('PyCasso')\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(800, 600)\n MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)\n MainWindow.setDockNestingEnabled(True)\n\n self.current_color = QtGui.QColor(0, 0, 0)\n self.thickness = 1\n self.fill_color = QtGui.QColor(255, 255, 255)\n\n self.scene = Canvas(self)\n self.viewport = ViewPort(self.scene)\n self.viewport.setMinimumSize(300, 300)\n\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.central_layout = QtWidgets.QHBoxLayout(self.centralwidget)\n self.central_layout.addWidget(self.viewport)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.initMenuBar()\n self.initToolbox()\n self.initToolProperties()\n self.initColorManager()\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def initMenuBar(self):\n self.menubar = QtWidgets.QMenuBar(self)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))\n self.menubar.setObjectName(\"menubar\")\n\n self.menuFile = QtWidgets.QMenu(self.menubar)\n self.menuFile.setObjectName(\"menuFile\")\n MainWindow.setMenuBar(self, self.menubar)\n\n self.statusbar = QtWidgets.QStatusBar(self)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self, self.statusbar)\n\n self.actionNew = QtWidgets.QAction(self)\n self.actionNew.setObjectName(\"actionNew\")\n self.actionNew.triggered.connect(self.ask_for_file)\n\n self.actionSave = QtWidgets.QAction(self)\n self.actionSave.setObjectName(\"actionSave\")\n self.actionSave.triggered.connect(self.save)\n\n self.actionQuit = QtWidgets.QAction(self)\n self.actionQuit.setObjectName(\"actionQuit\")\n self.actionQuit.triggered.connect(self.close)\n\n self.menuFile.addAction(self.actionNew)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionSave)\n self.menuFile.addSeparator()\n self.menuFile.addAction(self.actionQuit)\n self.menubar.addAction(self.menuFile.menuAction())\n\n def initToolbox(self):\n self.toolBox = QtWidgets.QDockWidget(self)\n self.toolBox.setObjectName(\"toolBox\")\n self.tools = QtWidgets.QWidget()\n self.tools.setObjectName(\"tools\")\n self.tools_grid = FlowLayout(self.tools)\n self.toolBox.setWidget(self.tools)\n names = ['Pencil', 'Line', 'Rectangle', 'Ellipse']\n self.tool_buttons = []\n for i in range(4):\n btn = QtWidgets.QPushButton(names[i], self)\n btn.clicked.connect(self.set_tool)\n self.tools_grid.addWidget(btn)\n btn.setCheckable(True)\n self.tool_buttons.append(btn)\n self.tool_buttons[0].setChecked(True)\n MainWindow.addDockWidget(self, QtCore.Qt.DockWidgetArea(1), self.toolBox)\n\n def initToolProperties(self):\n self.toolProperties = QtWidgets.QDockWidget(self)\n self.toolProperties.setObjectName(\"toolProperties\")\n\n self.properties = QtWidgets.QWidget()\n self.properties.setObjectName(\"properties\")\n\n self.properties_form = QtWidgets.QFormLayout(self.properties)\n\n self.thickness_slider = QtWidgets.QSlider(self)\n self.thickness_slider.setOrientation(QtCore.Qt.Horizontal)\n self.thickness_slider.setMinimum(1)\n self.thickness_slider.setMaximum(50)\n self.thickness_slider.valueChanged.connect(self.set_thickness)\n self.properties_form.addRow('Thickness', self.thickness_slider)\n\n self.fill_btn = QtWidgets.QPushButton(self.properties)\n self.fill_btn.setMaximumSize(20, 20)\n self.fill_btn.setMinimumSize(20, 20)\n self.fill_btn.clicked.connect(self.set_fill)\n self.fill_btn.setStyleSheet('background-color: #FFFFFF')\n self.properties_form.addRow('Fill color', self.fill_btn)\n\n self.fill_alpha_slider = QtWidgets.QSlider(self.properties)\n self.fill_alpha_slider.setOrientation(QtCore.Qt.Horizontal)\n self.fill_alpha_slider.setMaximum(255)\n self.fill_alpha_slider.setMinimum(0)\n self.fill_alpha_slider.setValue(255)\n self.fill_alpha_slider.valueChanged.connect(self.set_fill_alpha)\n self.properties_form.addRow('Fill alpha', self.fill_alpha_slider)\n\n self.toolProperties.setWidget(self.properties)\n MainWindow.addDockWidget(self, QtCore.Qt.DockWidgetArea(1), self.toolProperties)\n\n def initColorManager(self):\n self.colorManagement = QtWidgets.QDockWidget(self)\n self.colorManagement.setObjectName(\"colorManagement\")\n self.dockWidgetContents = QtWidgets.QWidget()\n self.dockWidgetContents.setObjectName(\"dockWidgetContents\")\n\n # Сетка, содержащая элементы управления цветом\n self.gridLayout_2 = QtWidgets.QGridLayout(self.dockWidgetContents)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n spacerItem = QtWidgets.QSpacerItem(20, 40,\n QtWidgets.QSizePolicy.Minimum,\n QtWidgets.QSizePolicy.Expanding)\n self.gridLayout_2.addItem(spacerItem, 10, 0, 1, 1)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)\n self.horizontalLayout.setContentsMargins(-1, -1, 6, -1)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n # Создание виджета со вкладками\n self.tabWidget = QtWidgets.QTabWidget(self.dockWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,\n QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())\n self.tabWidget.setSizePolicy(sizePolicy)\n self.tabWidget.setObjectName(\"tabWidget\")\n\n # Лейаут для RGB-палитры\n self.rgb_color_sliders = QtWidgets.QWidget()\n self.rgb_color_sliders.setObjectName(\"rgb_color_sliders\")\n self.formLayout = QtWidgets.QFormLayout(self.rgb_color_sliders)\n self.formLayout.setObjectName(\"formLayout\")\n\n # Red-канал для RGB-палитры\n self.red_lbl = QtWidgets.QLabel(self.rgb_color_sliders)\n self.red_lbl.setObjectName(\"red_lbl\")\n self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.red_lbl)\n self.red_slider = QtWidgets.QSlider(self.rgb_color_sliders)\n self.red_slider.setOrientation(QtCore.Qt.Horizontal)\n self.red_slider.setObjectName(\"red_slider\")\n self.red_slider.setMaximum(255)\n self.red_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.red_slider)\n\n # Green-канал для RGB-палитры\n self.green_lbl = QtWidgets.QLabel(self.rgb_color_sliders)\n self.green_lbl.setObjectName(\"green_lbl\")\n self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.green_lbl)\n self.green_slider = QtWidgets.QSlider(self.rgb_color_sliders)\n self.green_slider.setOrientation(QtCore.Qt.Horizontal)\n self.green_slider.setObjectName(\"green_slider\")\n self.green_slider.setMaximum(255)\n self.green_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.green_slider)\n\n # Blue-канал для RGB-палитры\n self.blue_lbl = QtWidgets.QLabel(self.rgb_color_sliders)\n self.blue_lbl.setObjectName(\"blue_lbl\")\n self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.blue_lbl)\n self.blue_slider = QtWidgets.QSlider(self.rgb_color_sliders)\n self.blue_slider.setOrientation(QtCore.Qt.Horizontal)\n self.blue_slider.setObjectName(\"blue_slider\")\n self.blue_slider.setMaximum(255)\n self.blue_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.blue_slider)\n\n # Альфа-канал для RGB-палитры\n self.alpha_lbl_rgb = QtWidgets.QLabel(self.rgb_color_sliders)\n self.alpha_lbl_rgb.setObjectName(\"alpha_lbl_rgb\")\n self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.alpha_lbl_rgb)\n self.alpha_rgb_slider = QtWidgets.QSlider(self.rgb_color_sliders)\n self.alpha_rgb_slider.setOrientation(QtCore.Qt.Horizontal)\n self.alpha_rgb_slider.setObjectName(\"alpha_rgb_slider\")\n self.alpha_rgb_slider.setMaximum(255)\n self.alpha_rgb_slider.setValue(255)\n self.alpha_rgb_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.alpha_rgb_slider)\n self.tabWidget.addTab(self.rgb_color_sliders, \"\")\n\n # Лейаут для слайдеров HSV-палитры\n self.hsv_color_sliders = QtWidgets.QWidget()\n self.hsv_color_sliders.setObjectName(\"hsv_color_sliders\")\n self.formLayout_2 = QtWidgets.QFormLayout(self.hsv_color_sliders)\n self.formLayout_2.setObjectName(\"formLayout_2\")\n\n # Hue-канал для HSV-палитры\n self.hue_lbl = QtWidgets.QLabel(self.hsv_color_sliders)\n self.hue_lbl.setObjectName(\"hue_lbl\")\n self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.hue_lbl)\n self.hue_slider = QtWidgets.QSlider(self.hsv_color_sliders)\n self.hue_slider.setOrientation(QtCore.Qt.Horizontal)\n self.hue_slider.setObjectName(\"hue_slider\")\n self.hue_slider.setMaximum(359)\n self.hue_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.hue_slider)\n\n # Saturation-канал для HSV-палитры\n self.saturation_lbl = QtWidgets.QLabel(self.hsv_color_sliders)\n self.saturation_lbl.setObjectName(\"saturation_lbl\")\n self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.saturation_lbl)\n self.saturation_slider = QtWidgets.QSlider(self.hsv_color_sliders)\n self.saturation_slider.setOrientation(QtCore.Qt.Horizontal)\n self.saturation_slider.setObjectName(\"saturation_slider\")\n self.saturation_slider.setMaximum(255)\n self.saturation_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.saturation_slider)\n\n # Value-канал для HSV-палитры\n self.value_lbl = QtWidgets.QLabel(self.hsv_color_sliders)\n self.value_lbl.setObjectName(\"value_lbl\")\n self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.value_lbl)\n self.value_slider = QtWidgets.QSlider(self.hsv_color_sliders)\n self.value_slider.setOrientation(QtCore.Qt.Horizontal)\n self.value_slider.setObjectName(\"value_slider\")\n self.value_slider.setMaximum(255)\n self.value_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.value_slider)\n\n # Альфа-канал для HSV-палитры\n self.alpha_lbl_hsv = QtWidgets.QLabel(self.hsv_color_sliders)\n self.alpha_lbl_hsv.setObjectName(\"alpha_lbl_hsv\")\n self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.alpha_lbl_hsv)\n self.alpha_hsv_slider = QtWidgets.QSlider(self.hsv_color_sliders)\n self.alpha_hsv_slider.setOrientation(QtCore.Qt.Horizontal)\n self.alpha_hsv_slider.setObjectName(\"alpha_hsv_slider\")\n self.alpha_hsv_slider.setMaximum(255)\n self.alpha_hsv_slider.setValue(255)\n self.alpha_hsv_slider.sliderMoved.connect(self.adjustColorSliders)\n self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole,\n self.alpha_hsv_slider)\n self.tabWidget.addTab(self.hsv_color_sliders, \"\")\n\n self.horizontalLayout.addWidget(self.tabWidget)\n self.gridLayout = QtWidgets.QGridLayout()\n self.gridLayout.setObjectName(\"gridLayout\")\n spacerItem1 = QtWidgets.QSpacerItem(20, 40,\n QtWidgets.QSizePolicy.Minimum,\n QtWidgets.QSizePolicy.Expanding)\n self.gridLayout.addItem(spacerItem1, 3, 1, 1, 1)\n spacerItem2 = QtWidgets.QSpacerItem(20, 40,\n QtWidgets.QSizePolicy.Minimum,\n QtWidgets.QSizePolicy.Expanding)\n self.gridLayout.addItem(spacerItem2, 0, 0, 1, 3)\n\n # Кнопка с текущим цветом\n self.current_color_btn = QtWidgets.QPushButton(self.dockWidgetContents)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.current_color_btn.sizePolicy().hasHeightForWidth())\n self.current_color_btn.setSizePolicy(sizePolicy)\n self.current_color_btn.setMinimumSize(QtCore.QSize(20, 20))\n self.current_color_btn.setMaximumSize(QtCore.QSize(20, 20))\n self.current_color_btn.setText(\"\")\n self.current_color_btn.setObjectName(\"color_preview_btn\")\n self.current_color_btn.setStyleSheet('background-color: #000000')\n self.gridLayout.addWidget(self.current_color_btn, 2, 1, 1, 1)\n self.color_pick_btn = QtWidgets.QPushButton(self.dockWidgetContents)\n self.color_pick_btn.setObjectName(\"color_pick_btn\")\n self.color_pick_btn.clicked.connect(self.getColorWithDialog)\n self.gridLayout.addWidget(self.color_pick_btn, 1, 0, 1, 3)\n self.horizontalLayout.addLayout(self.gridLayout)\n spacerItem3 = QtWidgets.QSpacerItem(0, 0,\n QtWidgets.QSizePolicy.MinimumExpanding,\n QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem3)\n self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)\n\n # Палитра готовых цветов\n self.colorPalette = FlowLayout()\n\n # Набор цветов для кнопок\n sampleColors = [QtGui.QColor(255, 255, 255),\n QtGui.QColor(0, 0, 0),\n QtGui.QColor(127, 127, 127),\n QtGui.QColor(195, 195, 195),\n QtGui.QColor(136, 0, 21),\n QtGui.QColor(185, 122, 87),\n QtGui.QColor(237, 28, 36),\n QtGui.QColor(255, 174, 201),\n QtGui.QColor(255, 127, 39),\n QtGui.QColor(255, 201, 14),\n QtGui.QColor(255, 242, 0),\n QtGui.QColor(239, 228, 176),\n QtGui.QColor(34, 177, 76),\n QtGui.QColor(181, 230, 29),\n QtGui.QColor(0, 162, 232),\n QtGui.QColor(153, 217, 234),\n QtGui.QColor(63, 72, 204),\n QtGui.QColor(112, 146, 190),\n QtGui.QColor(163, 73, 164),\n QtGui.QColor(200, 191, 231)]\n\n # Создание кнопок\n for i in range(20):\n btn = QtWidgets.QPushButton(\"\", self)\n btn.setMaximumSize(20, 20)\n # Смена цвета кнопки\n btn.setStyleSheet('background-color: ' + sampleColors[i].name())\n btn.clicked.connect(self.setCurrentColor)\n btn.show()\n self.colorPalette.addWidget(btn)\n # Занесение палитры в общий блок управления цветом\n self.gridLayout_2.addLayout(self.colorPalette, 1, 0, 1, 3)\n self.colorManagement.setWidget(self.dockWidgetContents)\n MainWindow.addDockWidget(self, QtCore.Qt.DockWidgetArea(2), self.colorManagement)\n\n def adjustColorSliders(self):\n rgb = {self.red_slider, self.green_slider, self.blue_slider, self.alpha_rgb_slider}\n hsv = {self.hue_slider, self.saturation_slider, self.value_slider, self.alpha_hsv_slider}\n if self.sender() in rgb:\n red = self.red_slider.value()\n green = self.green_slider.value()\n blue = self.blue_slider.value()\n alpha = self.alpha_rgb_slider.value()\n color = QtGui.QColor(red, green, blue, alpha)\n if color.isValid():\n self.current_color_btn.setStyleSheet('background-color: ' + color.name())\n self.current_color = color\n hsv_color = color.toHsv()\n self.hue_slider.setValue(hsv_color.hue())\n self.saturation_slider.setValue(hsv_color.saturation())\n self.value_slider.setValue(hsv_color.value())\n self.alpha_hsv_slider.setValue(hsv_color.alpha())\n elif self.sender() in hsv:\n hue = self.hue_slider.value()\n saturation = self.saturation_slider.value()\n value = self.value_slider.value()\n alpha = self.alpha_hsv_slider.value()\n color = QtGui.QColor.fromHsv(hue, saturation, value, alpha)\n if color.isValid():\n self.current_color_btn.setStyleSheet('background-color: ' + color.name())\n self.current_color = color\n rgb_color = color.toRgb()\n self.red_slider.setValue(rgb_color.red())\n self.green_slider.setValue(rgb_color.green())\n self.blue_slider.setValue(rgb_color.blue())\n self.alpha_rgb_slider.setValue(rgb_color.alpha())\n else:\n rgb_color = self.current_color.toRgb()\n self.red_slider.setValue(rgb_color.red())\n self.green_slider.setValue(rgb_color.green())\n self.blue_slider.setValue(rgb_color.blue())\n self.alpha_rgb_slider.setValue(rgb_color.alpha())\n\n hsv_color = self.current_color.toHsv()\n self.hue_slider.setValue(hsv_color.hue())\n self.saturation_slider.setValue(hsv_color.saturation())\n self.value_slider.setValue(hsv_color.value())\n self.alpha_hsv_slider.setValue(hsv_color.alpha())\n\n def setCurrentColor(self):\n color = QtGui.QColor(self.sender().styleSheet().split()[-1])\n if color.isValid():\n self.current_color = color\n self.current_color_btn.setStyleSheet('background-color: ' + color.name())\n self.adjustColorSliders()\n\n def getColorWithDialog(self):\n color = QtWidgets.QColorDialog.getColor(self.current_color)\n if color.isValid():\n self.current_color = color\n self.current_color_btn.setStyleSheet('background-color: ' + color.name())\n self.adjustColorSliders()\n\n def load_image(self, image):\n if image is None:\n image = QtGui.QPixmap(500, 500)\n image.fill(QtGui.QColor(255, 255, 255, 0))\n image = image.toImage()\n self.scene.load_image(image)\n self.viewport.setMaximumSize(image.size())\n else:\n try:\n with open(image):\n pass\n except FileNotFoundError:\n error = QtWidgets.QErrorMessage(self)\n error.showMessage('Specified file does not exist!')\n else:\n image = QtGui.QImage(image)\n self.scene.load_image(image)\n self.viewport.setMaximumSize(image.size())\n\n def save(self):\n title = 'Pick a place to save your file'\n files = 'Image Files (*.png *.jpg *.jpeg *.bmp *.ppm *.xbm *.xpm)'\n path, ok = QtWidgets.QFileDialog.getSaveFileName(self.parent(), caption=title,\n filter=files)\n if ok:\n self.scene.image.save(path)\n\n def set_tool(self):\n for btn in self.tool_buttons:\n btn.setChecked(False)\n self.sender().setChecked(True)\n self.scene.tool = self.sender().text().lower()\n\n def set_thickness(self):\n self.thickness = self.sender().value()\n\n def set_fill(self):\n color = QtWidgets.QColorDialog.getColor()\n if color.isValid():\n self.sender().setStyleSheet('background-color: ' + color.name())\n self.fill_color = color\n self.fill_color.setAlpha(self.fill_alpha_slider.value())\n\n def set_fill_alpha(self):\n self.fill_color.setAlpha(self.sender().value())\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.menuFile.setTitle(_translate(\"MainWindow\", \"File\"))\n self.toolBox.setWindowTitle(_translate(\"MainWindow\", \"Tools\"))\n self.toolProperties.setWindowTitle(_translate(\"MainWindow\", \"Tool properties\"))\n self.colorManagement.setWindowTitle(_translate(\"MainWindow\", \"Color Management\"))\n self.red_lbl.setText(_translate(\"MainWindow\", \"R\"))\n self.green_lbl.setText(_translate(\"MainWindow\", \"G\"))\n self.blue_lbl.setText(_translate(\"MainWindow\", \"B\"))\n self.alpha_lbl_rgb.setText(_translate(\"MainWindow\", \"A\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.rgb_color_sliders), _translate(\"MainWindow\", \"RGB\"))\n self.hue_lbl.setText(_translate(\"MainWindow\", \"H\"))\n self.saturation_lbl.setText(_translate(\"MainWindow\", \"S\"))\n self.value_lbl.setText(_translate(\"MainWindow\", \"V\"))\n self.alpha_lbl_hsv.setText(_translate(\"MainWindow\", \"A\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.hsv_color_sliders), _translate(\"MainWindow\", \"HSV\"))\n self.color_pick_btn.setText(_translate(\"MainWindow\", \"Pick with dialog\"))\n self.actionNew.setText(_translate(\"MainWindow\", \"New\"))\n self.actionNew.setToolTip(_translate(\"MainWindow\", \"Create a new file and open it immediately\"))\n self.actionSave.setText(_translate(\"MainWindow\", \"Save\"))\n self.actionSave.setToolTip(_translate(\"MainWindow\", \"Save current file\"))\n self.actionQuit.setText(_translate(\"MainWindow\", \"Quit\"))\n self.actionQuit.setToolTip(_translate(\"MainWindow\", \"Shutdown program\"))\n\n def ask_for_file(self):\n dialog = NewFileDialog(self)\n\n self.viewport.close()\n self.scene = Canvas(self)\n self.viewport = ViewPort(self.scene, self)\n self.central_layout.addWidget(self.viewport)\n for button in self.tool_buttons:\n button.setChecked(False)\n self.tool_buttons[0].setChecked(True)\n self.viewport.show()\n self.viewport.setMinimumSize(300, 300)\n\n\nclass NewFileDialog(QtWidgets.QDialog):\n def __init__(self, parent):\n super().__init__(parent=parent)\n self.setupUi(self)\n self.show()\n\n def setupUi(self, NewFileDialog):\n self.setWindowTitle('New file')\n NewFileDialog.setObjectName(\"NewFileDialog\")\n NewFileDialog.resize(280, 100)\n self.gridLayout = QtWidgets.QGridLayout(NewFileDialog)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.browse_btn = QtWidgets.QPushButton(NewFileDialog)\n self.browse_btn.setObjectName(\"browse\")\n self.browse_btn.clicked.connect(self.setSourceFile)\n self.browse_btn.hide()\n self.gridLayout.addWidget(self.browse_btn, 7, 2, 1, 1)\n self.buttonBox = QtWidgets.QDialogButtonBox(NewFileDialog)\n self.buttonBox.setOrientation(QtCore.Qt.Vertical)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setObjectName(\"buttonBox\")\n self.gridLayout.addWidget(self.buttonBox, 0, 2, 3, 1)\n self.source_input = QtWidgets.QLineEdit('', NewFileDialog)\n self.source_input.setObjectName(\"source_input\")\n self.source_input.hide()\n self.gridLayout.addWidget(self.source_input, 7, 0, 1, 2)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)\n self.open_radio = QtWidgets.QRadioButton(NewFileDialog)\n self.open_radio.setObjectName(\"open_radio\")\n self.open_radio.toggled.connect(self.showInput)\n self.gridLayout.addWidget(self.open_radio, 1, 0, 1, 1)\n self.create_radio = QtWidgets.QRadioButton(NewFileDialog)\n self.create_radio.setChecked(True)\n self.create_radio.setObjectName(\"radioButton\")\n self.create_radio.toggled.connect(self.hideInput)\n self.gridLayout.addWidget(self.create_radio, 0, 0, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.gridLayout.addItem(spacerItem1, 8, 0, 1, 3)\n\n self.retranslateUi(NewFileDialog)\n self.buttonBox.accepted.connect(NewFileDialog.accept)\n self.buttonBox.rejected.connect(NewFileDialog.reject)\n QtCore.QMetaObject.connectSlotsByName(NewFileDialog)\n\n def retranslateUi(self, NewFileDialog):\n _translate = QtCore.QCoreApplication.translate\n NewFileDialog.setWindowTitle(_translate(\"NewFileDialog\", \"New file\"))\n self.browse_btn.setText(_translate(\"NewFileDialog\", \"Browse\"))\n self.open_radio.setText(_translate(\"NewFileDialog\", \"Open\"))\n self.create_radio.setText(_translate(\"NewFileDialog\", \"Create\"))\n\n def setSourceFile(self):\n title = 'Pick an image'\n files = 'Image Files (*.png *.jpg *.jpeg *.bmp *.ppm *.xbm *.xpm *.gif *.pbm *.pgm)'\n path, ok = QtWidgets.QFileDialog.getOpenFileName(self.parent(), caption=title, filter=files)\n if ok:\n self.source_input.setText(path)\n\n def hideInput(self):\n self.source_input.hide()\n self.browse_btn.hide()\n\n def showInput(self):\n self.source_input.show()\n self.browse_btn.show()\n\n def accept(self):\n super().accept()\n self.parent().load_image(self.source_input.text() if self.open_radio.isChecked() else None)\n","sub_path":"windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":26969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"494904063","text":"import pandas as pd\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport os\n\ndp = []\ndp_c36 = []\n\nresnames = ['ADE', 'THY', 'GUA', 'CYT']\n\nfor res in resnames:\n print(res)\n df = pd.read_csv('%s.txt' % (res), sep=' ')\n df.dropna(inplace=True)\n df = df[(df != 0).all(1)]\n d = df.to_numpy()\n m = np.mean(d[:,3])\n s = np.std(d[:,3])\n df2 = pd.read_csv('c36.%s.txt' % (res), sep=' ')\n df2.dropna(inplace=True)\n df2 = df2[(df2 != 0).all(1)]\n d2 = df2.to_numpy()\n m2 = np.mean(d2[:,3])\n s2 = np.std(d2[:,3])\n dp.append((res,m,s))\n dp_c36.append((res,m2,s2))\n plt.figure(figsize=(1.2,2.0))\n plt.title(\"%s\\n$\\mu$ = %5.3f\\n$\\sigma$ = %5.3f\" % (res,m,s), family=\"Arial\", size='8', weight='bold')\n plt.ylim((1,13))\n plt.hist(d[:,3], bins=50, range=(max(0,m-5*s),m+5*s), density=True, orientation='horizontal', color='xkcd:blue')\n plt.hist(d2[:,3], bins=50, range=(max(0,m2-5*s2),m2+5*s2), density=True, orientation='horizontal', color='xkcd:black', alpha=0.25)\n #plt.hist(d[:,3], bins=50, range=(0,15), density=True)\n plt.ylabel('Dipole Moment (Debyes)', family=\"Arial\", size='8', weight='bold')\n plt.xticks(family=\"Arial\", size='8', weight='bold')\n plt.yticks([1,4,7,10,13], family=\"Arial\", size='8', weight='bold')\n plt.tight_layout(rect=(0,0,1.075,1.075))\n #plt.tight_layout()\n plt.savefig('%s.nb_dna_dp.png' % (res), dpi=300)\n plt.close()\n \ndp = np.array(dp)\nnp.savetxt('dipole.txt', dp, fmt=\"%s\")\n\ndp_c36 = np.array(dp_c36)\nnp.savetxt('dipole_c36.txt', dp_c36, fmt=\"%s\")\n","sub_path":"trajectory_analysis/cas9-sgrna-dna/data/nb_dna_dipole_moments/plot_nb_dna_dp.py","file_name":"plot_nb_dna_dp.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226923261","text":"\"\"\"The scripts will produce a pandas `DataFrame` which contains information\nabout which combinations of environments have which data types.\n\"\"\"\nimport itertools\nimport logging\nimport os\nfrom collections import defaultdict\n\nimport pandas\nfrom evaluator.properties import (\n Density,\n EnthalpyOfMixing,\n EnthalpyOfVaporization,\n ExcessMolarVolume,\n)\n\nfrom nistdataselection.curation.filtering import filter_by_checkmol\nfrom nistdataselection.utils import SubstanceType\nfrom nistdataselection.utils.utils import (\n chemical_environment_codes,\n substance_type_to_int,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n\n # Set up logging\n logging.basicConfig(level=logging.INFO)\n\n data_set_path = os.path.join(\"test_sets\", \"full_set.csv\")\n data_set = pandas.read_csv(data_set_path)\n\n # Define the environments we are interested in.\n environments = {\n \"alcohol\": [\n chemical_environment_codes[\"hydroxy\"],\n chemical_environment_codes[\"alcohol\"],\n ],\n \"ester\": [\n chemical_environment_codes[\"caboxylic_acid\"],\n chemical_environment_codes[\"ester\"],\n ],\n \"ether\": [chemical_environment_codes[\"ether\"]],\n \"ketone\": [chemical_environment_codes[\"ketone\"]],\n \"alkane\": [\"\"],\n }\n\n # Define the properties and environments we are interested in.\n properties_of_interest = [\n (Density, SubstanceType.Pure),\n (EnthalpyOfVaporization, SubstanceType.Pure),\n (EnthalpyOfMixing, SubstanceType.Binary),\n (Density, SubstanceType.Binary),\n (ExcessMolarVolume, SubstanceType.Binary),\n ]\n\n friendly_names = {\n (Density, SubstanceType.Pure): \"rho\",\n (EnthalpyOfVaporization, SubstanceType.Pure): \"Hvap\",\n (EnthalpyOfMixing, SubstanceType.Binary): \"Hmix(x)\",\n (Density, SubstanceType.Binary): \"rho(x)\",\n (ExcessMolarVolume, SubstanceType.Binary): \"Vexcess(x)\",\n }\n\n # Extend the combination of properties.\n property_combinations = [(x,) for x in properties_of_interest]\n\n binary_properties = [\n x for x in properties_of_interest if x[1] == SubstanceType.Binary\n ]\n property_combinations.extend(itertools.combinations(binary_properties, 2))\n\n # Define the combinations of environments\n environment_combinations = {\n SubstanceType.Pure: [(x,) for x in environments],\n SubstanceType.Binary: [\n *[(x, x) for x in environments],\n *itertools.combinations(environments, 2),\n ],\n }\n\n data_counts = defaultdict(dict)\n\n for property_types in property_combinations:\n\n all_substances = defaultdict(list)\n\n for property_type, substance_type in property_types:\n\n header = (\n f\"{property_type.__name__} Value ({property_type.default_unit():~})\"\n )\n\n n_components = substance_type_to_int[substance_type]\n\n property_data = data_set[data_set[header].notnull()]\n property_data = property_data[property_data[\"N Components\"] == n_components]\n\n for environment_types in environment_combinations[substance_type]:\n\n environment_types = tuple(sorted(environment_types))\n chemical_environments = [environments[x] for x in environment_types]\n\n environment_data = filter_by_checkmol(\n property_data, *chemical_environments\n )\n\n components = []\n\n for index in range(n_components):\n components.append([*environment_data[f\"Component {index + 1}\"]])\n\n all_substances[environment_types].append(\n set(tuple(sorted(x)) for x in zip(*components))\n )\n\n common_substances = {x: set.intersection(*y) for x, y in all_substances.items()}\n\n for environment_type in common_substances:\n\n data_counts[environment_type][property_types] = len(\n common_substances[environment_type]\n )\n\n data_rows = []\n\n for environment_types in data_counts:\n\n data_row = {}\n\n for index, environment_type in enumerate(environment_types):\n data_row[f\"Environment {index + 1}\"] = environment_type\n\n for property_types in data_counts[environment_types]:\n\n header = \" + \".join(friendly_names[x] for x in property_types)\n data_row[header] = int(data_counts[environment_types][property_types])\n\n data_rows.append(data_row)\n\n n_environments = max(len(x) for x in data_counts)\n\n count_frame = pandas.DataFrame(data_rows)\n reordered_frame = pandas.DataFrame()\n\n # Re-order the headers.\n for index in range(n_environments):\n\n reordered_frame[f\"Environment {index + 1}\"] = count_frame[\n f\"Environment {index + 1}\"\n ]\n\n for column_name in count_frame:\n\n if \"Environment\" in column_name:\n continue\n\n reordered_frame[column_name] = count_frame[column_name]\n\n reordered_frame.fillna(\"-\", inplace=True)\n reordered_frame.to_csv(\"summary.csv\", index=False)\n\n with open(\"summary.md\", \"w\") as file:\n reordered_frame.to_markdown(file, showindex=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"studies/mixture_feasibility/benchmarking/data_set_generation/expanded_set/summarise_data.py","file_name":"summarise_data.py","file_ext":"py","file_size_in_byte":5251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343957727","text":"from os import error\nimport logging\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom rcon.utils import MapsHistory\nfrom rcon.recorded_commands import RecordedRcon\nfrom rcon.commands import CommandFailedError\nfrom rcon.steam_utils import get_steam_profile\nfrom rcon.settings import SERVER_INFO\nfrom rcon import game_logs\nfrom rcon.models import LogLine, PlayerSteamID, PlayerName, enter_session\nfrom rcon.discord import send_to_discord_audit\nfrom rcon.scoreboard import LiveStats\n\nfrom .views import ctl\nfrom .auth import api_response, login_required\n\nlogger = logging.getLogger('rconweb')\n\ndef make_table(scoreboard):\n return \"\\n\".join(\n [\"Rank Name Ratio Kills Death\"]\n + [\n f\"{('#'+ str(idx+1)).ljust(6)}{obj['player'].ljust(27)}{obj['ratio'].ljust(6)}{str(obj['(real) kills']).ljust(6)}{str(obj['(real) death']).ljust(5)}\"\n for idx, obj in enumerate(scoreboard)\n ]\n )\n\n\ndef make_tk_table(scoreboard):\n justification = [6, 27, 10, 10, 14, 14]\n headers = [\"Rank\", \"Name\", \"Time(min)\", \"Teamkills\", \"Death-by-TK\", \"TK/Minutes\"]\n keys = [\n \"idx\",\n \"player\",\n \"Estimated play time (minutes)\",\n \"Teamkills\",\n \"Death by TK\",\n \"TK Minutes\",\n ]\n\n return \"\\n\".join(\n [\"\".join(h.ljust(justification[idx]) for idx, h in enumerate(headers))]\n + [\n \"\".join(\n [\n str({\"idx\": f\"#{idx}\", **obj}[key]).ljust(justification[i])\n for i, key in enumerate(keys)\n ]\n )\n for idx, obj in enumerate(scoreboard)\n ]\n )\n\n\n@csrf_exempt\ndef text_scoreboard(request):\n try:\n minutes = abs(int(request.GET.get(\"minutes\")))\n except (ValueError, KeyError, TypeError):\n minutes = 180\n\n name = ctl.get_name()\n try:\n scoreboard = ctl.get_scoreboard(minutes, \"ratio\")\n text = make_table(scoreboard)\n scoreboard = ctl.get_scoreboard(minutes, \"(real) kills\")\n text2 = make_table(scoreboard)\n except CommandFailedError:\n text, text2 = \"No logs\"\n\n return HttpResponse(\n f\"\"\"
    \n

    {name}

    \n

    Scoreboard (last {minutes} min. 2min delay)

    \n
    Real death only (redeploy / suicides not included). Kills counted only if player is not revived
    \n

    \n See for last:\n 120 min\n 90 min\n 60 min\n 30 min\n

    \n

    By Ratio

    {text}
    \n

    By Kills

    {text2}
    \n
    \n \"\"\"\n )\n\n\n@csrf_exempt\ndef text_tk_scoreboard(request):\n name = ctl.get_name()\n try:\n scoreboard = ctl.get_teamkills_boards()\n text = make_tk_table(scoreboard)\n scoreboard = ctl.get_teamkills_boards(\"Teamkills\")\n text2 = make_tk_table(scoreboard)\n except CommandFailedError:\n text, text2 = \"No logs\"\n\n return HttpResponse(\n f\"\"\"
    \n

    {name}

    \n

    By TK / Minute

    {text}
    \n

    By Total TK

    {text2}
    \n
    \n \"\"\"\n )\n\n@csrf_exempt\ndef live_info(request):\n status = ctl.get_status()\n\n\n@csrf_exempt\ndef live_scoreboard(request):\n stats = LiveStats()\n\n try:\n result = stats.get_cached_stats()\n result = {\n \"snapshot_timestamp\": result[\"snapshot_timestamp\"],\n \"stats\": list(result[\"stats\"].values())\n }\n error = None,\n failed = False\n except Exception as e:\n logger.exception(\"Unable to produce live stats\")\n result = {}\n error = \"\"\n failed=True\n\n return api_response(\n result=result,\n error=error,\n failed=failed,\n command=\"live_scoreboard\"\n )\n","sub_path":"rconweb/api/scoreboards.py","file_name":"scoreboards.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312979035","text":"from simep.core.baseobserver import BaseObserver\nfrom simep.sched import Order\nfrom simep.funcs.data.pyData import pyData\nimport math\nimport numpy as np\n\n\nclass MarketHistogram(BaseObserver):\n \n @staticmethod\n def public_parameters():\n \n setup = {'name' : {'label' : 'Name' , 'value' : 'MarketHistogram001'}}\n parameters = {'cycle' : {'label' : 'Cycle Time' , 'value' : 15}, \n 'side' : {'label' : 'Side' , 'value' : Order.Buy}, \n }\n return {'setup': setup, 'parameters': parameters}\n \n @staticmethod\n def indicators_list():\n #return ['avg_trade_size_t_60', 'avg_spread_bp_t_60']\n return [] \n \n def __init__(self, setup, context, parameters, trace): \n super(MarketHistogram, self).__init__(setup, context, parameters, trace) \n \n self.trades = []\n self.histogram = {}\n self.next_deal = 0\n self.opposite = 0\n self.best = 0\n \n def process(self, evt):\n c = self.update(evt)\n if self.next_deal <= self._bus['business_time_t']:\n for tr in self.trades:\n if self.histogram.has_key(tr[0]):\n self.histogram[tr[0]] += tr[1]\n else:\n self.histogram[tr[0]] = tr[1]\n \n self.histogram['opposite'] = self.opposite\n self.histogram['best'] = self.best\n self.histogram['current_opposite'] = evt.getLob().getBid(0).price if self['side'] == Order.Sell else evt.getLob().getAsk(0).price\n self.histogram['current_best'] = evt.getLob().getAsk(0).price if self['side'] == Order.Sell else evt.getLob().getBid(0).price\n self.appendIndicator(self.histogram)\n \n self.next_deal = self._bus['business_time_t'] + self['cycle']\n self.opposite = evt.getLob().getBid(0).price if self['side'] == Order.Sell else evt.getLob().getAsk(0).price\n self.best = evt.getLob().getAsk(0).price if self['side'] == Order.Sell else evt.getLob().getBid(0).price\n self.trades = []\n self.histogram = {}\n \n \n for t in evt.getTrades():\n self.trades.append((t.price, t.size))\n \n \n def processReport(self, evt):\n pass\n \n \n ","sub_path":"usr/sivla/agents/MarketHistogram.py","file_name":"MarketHistogram.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"214393301","text":"\"\"\"\nAn example demonstrating Logistic Regression \nand Multinomial Logistic Regression.\n\"\"\"\n\nfrom pyspark.ml.classification import LogisticRegression\nfrom pyspark.sql import SparkSession\n\n\nif __name__ == \"__main__\":\n spark = SparkSession \\\n .builder \\\n .appName(\"LogisticRegression\") \\\n .getOrCreate()\n\n # Load training data\n training = spark.read.format(\"libsvm\").load(\"data/sample_libsvm_data.txt\")\n\n training.show()\n\n # Applying Logistic Regression algorithm with regularizaton parameter = 0.3\n # and elastic net regularization parameter = 0.8\n lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)\n\n # If you need an explanation of a parameter, you can use the explainParam\n # method which gives you name, doc, default and current value.\n print(lr.explainParam(\"elasticNetParam\"))\n\n # Fit the model\n lrModel = lr.fit(training)\n\n # Print the coefficients and intercept for logistic regression\n print(\"Coefficients: \" + str(lrModel.coefficients))\n print(\"Intercept: \" + str(lrModel.intercept))\n\n # Extract the summary of training results from the returned\n # LogisticRegressionModel instance\n trainingSummary = lrModel.summary\n\n # Obtain the objective (= scaled loss + regularization) per iteration\n objectiveHistory = trainingSummary.objectiveHistory\n print(\"\\nobjectiveHistory:\")\n for objective in objectiveHistory:\n print(objective)\n\n # Obtain the receiver-operating characteristic as a dataframe and\n # areaUnderROC.\n trainingSummary.roc.show()\n print(\"areaUnderROC: \" + str(trainingSummary.areaUnderROC))\n\n # Set the model threshold to maximize F-Measure\n fMeasure = trainingSummary.fMeasureByThreshold\n\n maxFMeasure = fMeasure.groupBy()\\\n .max('F-Measure') \\\n .select('max(F-Measure)') \\\n .head()\n\n bestThreshold = fMeasure \\\n .where(fMeasure['F-Measure'] == maxFMeasure['max(F-Measure)']) \\\n .select('threshold').head()['threshold']\n\n print(\"Best threshold: \", bestThreshold)\n print()\n lr.setThreshold(bestThreshold)\n\n # We can also use the multinomial family for binary classification\n mlr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8,\n family=\"multinomial\")\n\n # Fit the model\n mlrModel = mlr.fit(training)\n\n # Print the coefficients and intercepts for logistic regression with multinomial family\n print(\"Multinomial coefficients: \" + str(mlrModel.coefficientMatrix))\n print(\"Multinomial intercepts: \" + str(mlrModel.interceptVector))\n\n spark.stop()\n","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203269085","text":"import numpy as np\nimport pandas as pd\nimport json\nfrom Bio import SeqIO\nfrom os import getcwd, listdir, system\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.fft import fft, ifft\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom sklearn.metrics import confusion_matrix, accuracy_score, matthews_corrcoef, classification_report\n\n#Going to Test folders\nfolder_path = getcwd() + \"/data\"\n\nfolders = sorted(listdir(folder_path))[2:10]\nfolders\n\nfolder_dict = {}\n\n# Going to Specific Virus Folders inside the Test folders\nfor folder in folders:\n subfolder_dict = {}\n for sub_folder in listdir(f\"{folder_path}/{folder}\"):\n subfolder_dict[sub_folder] = listdir(f\"{folder_path}/{folder}/{sub_folder}\")\n folder_dict[folder] = subfolder_dict\n\nfolder_dict.keys()\n\n#Adding data to a JSON file\noutput_path = getcwd() + \"/data/JSON_Files\"\n\n\nwith open(f\"{output_path}/fasta_files.json\", \"w\") as my_file:\n json.dump(folder_dict, my_file)\n\nf = open(f\"{output_path}/{listdir(output_path)[0]}\", )\n\nmy_dict = json.load(f)\nfor test in my_dict:\n test = sorted(test)\n\n# Calculating Entropy\ndef entropy(sequence):\n counts = Counter(sequence)\n props = {key: counts[key] / sum(counts.values()) for key in counts}\n products = {key: props[key]*np.log(props[key]) for key in props}\n return -1 * sum(products.values())\n\ndef magnitude_avg(sequence, representation = \"PP\"):\n if representation == \"Int1\":\n dict_of_bases = {\"T\":0,\"t\":0,\"C\":1,\"c\":1, \"A\":2,\"a\":2 ,\"G\":3, \"g\":3}\n elif representation == \"Int2\":\n dict_of_bases = {\"T\":1,\"t\":1,\"C\":2,\"c\":2, \"A\":3,\"a\":3 ,\"G\":4, \"g\":4}\n elif representation == \"Real\":\n dict_of_bases = {\"T\":-1.5,\"t\":-1.5,\"C\":0.5,\"c\":0.5, \"A\":1.5,\"a\":1.5 ,\"G\":-1.5, \"g\":-1.5}\n elif representation == \"Atomic\":\n dict_of_bases = {\"T\":6,\"t\":6,\"C\":58,\"c\":58, \"A\":70,\"a\":70 ,\"G\":78, \"g\":78}\n elif representation == \"EIIP\":\n dict_of_bases = {\"T\":0.1335,\"t\":0.1335,\"C\":0.1340,\"c\":0.1340, \"A\":0.1260,\"a\":0.1260 ,\"G\":0.0806, \"g\":0.0806}\n elif representation == \"PP\":\n dict_of_bases = {\"T\":1,\"t\":1,\"C\":1,\"c\":1, \"A\":-1,\"a\":-1 ,\"G\":-1, \"g\":-1}\n elif representation == \"Paired Numeric\":\n dict_of_bases = {\"T\":1,\"t\":1,\"C\":-1,\"c\":-1, \"A\":1,\"a\":1 ,\"G\":-1, \"g\":-1}\n elif representation == \"Just A\":\n dict_of_bases = {\"T\":0,\"t\":0,\"C\":0,\"c\":0, \"A\":1,\"a\":1 ,\"G\":0, \"g\":0}\n elif representation == \"Just C\":\n dict_of_bases = {\"T\":0,\"t\":0,\"C\":1,\"c\":1, \"A\":0,\"a\":0 ,\"G\":0, \"g\":0}\n elif representation == \"Just G\":\n dict_of_bases = {\"T\":0,\"t\":0,\"C\":0,\"c\":0, \"A\":0,\"a\":0 ,\"G\":1, \"g\":1}\n elif representation == \"Just T\":\n dict_of_bases = {\"T\":1,\"t\":1,\"C\":0,\"c\":0, \"A\":0,\"a\":0 ,\"G\":0, \"g\":0}\n numeric = []\n for base in sequence:\n numeric.append(dict_of_bases[base])\n dft = fft(np.array(numeric))\n mag = abs(dft)\n mag_avg = np.average(mag)\n return mag_avg\n\n\ndef magtropy(sequence):\n return magnitude_avg(sequence, representation = \"Just A\")/entropy(sequence)\n\n\n# Saving Entropy values to dictionary\n#removed temp_entropy_dict\nfile_path_1 = getcwd()\nmagtropy_dict = {}\nfor test in my_dict.keys():\n temp_dict = {}\n for family in my_dict[test].keys():\n magtropy_values = []\n for file in my_dict[test][family]:\n start_seq = list(SeqIO.parse((f\"{file_path_1}/data/{test}/{family}/{file}\"), \"fasta\"))\n count = len(start_seq[0].seq)\n final_seq = \"\".join([char for char in start_seq[0].seq])\n magtropy_values.append((magtropy(final_seq)))\n temp_dict[family] = magtropy_values\n magtropy_dict[test] = temp_dict\n\nmagtropy_dict[\"Test1\"]\n\n\n\ncolors = [\"red\", \"royalblue\", \"gold\", \"darkorchid\", \"paleturquoise\", \"crimson\", \"m\", \"darkgreen\", \"olive\", \"aqua\", \"coral\", \"gray\", \"firebrick\", \"violet\", \"chartreuse\"]\ndef plot_magtropy(test):\n loc = 0\n for family in magtropy_dict[test]:\n #sns.set(rc={\"figure.figsize\": (10, 7)})\n plt.figure(figsize = (8,6))\n print(sns.distplot(magtropy_dict[test][family], color=colors[loc], label=family, bins = 20))\n print(plt.title(family))\n loc = loc + 1\nplot_magtropy(\"Test8\")\n\n\n\n\n\n \n","sub_path":"ml without pearsons/hist_plots_for_pearsons.py","file_name":"hist_plots_for_pearsons.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"272037178","text":"from collections import Counter\nfrom itertools import combinations\n\nimport numpy as np\n\n\ndef solution(S, k):\n\t\"\"\"\n\tTakes a Set (S) and number of subsets (k)\n\tand returns sum( U(S, no_of_subsets)) where the function\n\tU is described here:\n\t\thttps://projecteuler.net/problem=201\n\t\"\"\"\n\ta = np.array(tuple(sum(c) for c in combinations(S, k)))\n\n\tcnt = Counter()\n\tfor x in a:\n\t\tcnt[x] += 1\n\n\tresult = [x for x in cnt if cnt[x] == 1]\n\tprint(sum(result))\n\n\n# # 0.3 sec\n# solution((1,3,6,8,10,11), 3)\n\n# # 0.2 sec\n# S = (x**2 for x in range(10))\n# k = 5\n# solution(S, k)\n\n\n# # 0.5 sec\n# S = (x**2 for x in range(20))\n# k = 10\n# solution(S, k)\n\n# # 12.2 sec\n# S = (x**2 for x in range(30))\n# k = 8\n# solution(S, k)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"projecteuler/201/subset_with_a_unique_sum.py","file_name":"subset_with_a_unique_sum.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"629317407","text":"# 對話紀錄改寫練習3\n\n# 讀取檔案\ndef read_file(filename):\n\trecord = []\n\twith open(filename, 'r', encoding = 'utf-8-sig') as f: # 用utf-8-sig去掉 \"\\ufeff\"\n\t\tfor line in f:\n\t\t\trecord.append(line.strip())\n\treturn record\n\n\n# 格式轉換\ndef transfer(record):\n\tcount_allen = 0\n\tsticker_allen = 0\n\tpicture_allen = 0\n\tcount_viki = 0\n\tsticker_viki = 0\n\tpicture_viki = 0\n\tfor line in record:\n\t\tline = line.split(' ')\n\t\ttime = line[0][:5]\n\t\tname = line[0][5:]\n\t\tif name == 'Allen':\n\t\t\t# for i in range(2, len(line)):\n\t\t\t# \tcount_allen += len(line[i])\n\t\t\tif line[1] == '貼圖':\n\t\t\t\tsticker_allen +=1\n\t\t\telif line[1] == '圖片':\n\t\t\t\tpicture_allen += 1\n\t\t\telse:\n\t\t\t\tfor i in line[1:]:\n\t\t\t\t\tcount_allen += len(i)\n\t\telif name == 'Viki':\n\t\t\t# for i in range(2, len(line)):\n\t\t\t# \tcount_viki += len(line[i])\n\t\t\tif line[1] == '貼圖':\n\t\t\t\tsticker_viki +=1\n\t\t\telif line[1] == '圖片':\n\t\t\t\tpicture_viki += 1\n\t\t\telse:\n\t\t\t\tfor i in line[1:]:\n\t\t\t\t\tcount_viki += len(i)\n\tprint('Allen說了:', count_allen)\n\tprint('Viki說了:', count_viki)\n\tprint('Allen貼圖:', sticker_allen)\n\tprint('Viki貼圖:', sticker_viki)\n\tprint('Allen圖片:', picture_allen)\n\tprint('Viki圖片:', picture_viki)\n\n\n# 寫入檔案\ndef write_file(filename, out_record):\n\twith open(filename, 'w', encoding = 'utf-8') as f:\n\t\tfor out in out_record:\n\t\t\tf.write(out + '\\n')\n\n\n# 主要程式\ndef main():\n\trecord = read_file('3.txt')\n\tout_record = transfer(record)\n\t#write_file('output.txt', out_record)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"chat3.py","file_name":"chat3.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"439752007","text":"# Copyright (c) 2020 Graphcore Ltd. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport itertools\nimport math\n\nimport tensorflow as tf\nfrom tensorflow.python.ipu import outlined_function as ipu_function\nfrom tensorflow.python.ipu import utils\n\n\ndef next_power_of_two(x):\n return 2**int(math.ceil(math.log2(x)))\n\n\ndef ladder_numbering_iterator():\n \"\"\"Generate an IPU ladder-style numbering [0, 1, 3, 2, 4, 5, 7, 6...].\n returns -- generator(int)\n \"\"\"\n return (x ^ ((x & 0x02) >> 1) for x in itertools.count())\n\n\ndef get_ipu_config(fp_exceptions=True,\n stochastic_rounding=True,\n xla_recompute=False,\n available_memory_proportion=None,\n disable_graph_outlining=False,\n num_ipus_required=0,\n max_cross_replica_sum_buffer_size=0,\n scheduler_selection='',\n compile_only=False,\n partials_type=\"half\"):\n \"\"\"Builds ipu_options\"\"\"\n config = utils.create_ipu_config(\n max_report_size=3001819596000,\n merge_infeed_io_copies=True,\n always_rearrange_copies_on_the_host=False,\n selection_order=utils.SelectionOrder.AUTO,\n disable_graph_outlining=disable_graph_outlining,\n max_cross_replica_sum_buffer_size=max_cross_replica_sum_buffer_size,\n scheduler_selection=scheduler_selection\n )\n\n config = utils.auto_select_ipus(config, num_ipus_required)\n\n config = utils.set_matmul_options(config, clear_pass_type=True)\n\n if available_memory_proportion is not None:\n config = utils.set_convolution_options(config, {\n \"availableMemoryProportion\": str(available_memory_proportion),\n \"partialsType\": partials_type\n })\n config = utils.set_matmul_options(config, {\n \"availableMemoryProportion\": str(available_memory_proportion),\n \"partialsType\": partials_type\n })\n\n config = utils.set_norm_options(config, use_stable_statistics=True)\n\n config = utils.set_recomputation_options(config, allow_recompute=xla_recompute)\n\n if compile_only:\n config = utils.set_ipu_connection_type(config, utils.DeviceConnectionType.NEVER, ipu_version=2, enable_remote_buffers=True)\n\n config = utils.set_floating_point_behaviour_options(config, inv=fp_exceptions, div0=fp_exceptions,\n oflo=fp_exceptions, esr=stochastic_rounding,\n nanoo=fp_exceptions)\n return config\n\n\ndef function_decorator(use_ipu_function, func=None):\n \"\"\"Wrapper which uses @ipu.function when enabled, and not otherwise\"\"\"\n def decorated(inner_func):\n if use_ipu_function:\n return ipu_function(inner_func)\n return inner_func\n\n if func is not None:\n return decorated(func)\n return decorated\n","sub_path":"applications/tensorflow/bert/ipu_utils.py","file_name":"ipu_utils.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"62582357","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport itertools\nimport matplotlib as mpl\n\nimport pandas_common as pc\n\ndef plot_mlmc(current, filename_base):\n all = ['mlmc.all', 'fem.apply', 'msfem.Elliptic_MsFEM_Solver.apply']\n all_labels = ['Overall', 'CgFem', 'MsFem', 'Ideal']\n simple = ['mlmc.all']\n for pref, tpl in {'all': (all, all_labels), 'simple': (simple, ['Overall', 'Ideal'])}.items():\n cat, labels = tpl\n ycols = ['{}_avg_wall_speedup'.format(v) for v in cat] + ['ideal_speedup']\n pc.plot_common(current, '{}_{}'.format(pref, filename_base), ycols, labels)\n\ncommon_string = pc.common_substring(sys.argv[1:])\nmerged = 'merged_{}.csv'.format(common_string)\nbaseline_name = 'mlmc.all'\n\nheader, current = pc.read_files(sys.argv[1:])\nheaderlist = header['profiler']\ncurrent = pc.sorted_f(current, True)\n# full = pc.speedup(headerlist, current.copy(), baseline_name)\n# full.transpose().to_csv(merged)\ncurrent = pc.speedup(headerlist, current, baseline_name)\n# pprint(t_sections)\nplot_mlmc(current, merged, baseline_name=baseline_name)\n\ncurrent.transpose().to_csv('filtered_' + merged)\n","sub_path":"python/profiler_ana/mlmc.py","file_name":"mlmc.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"274131505","text":"#!/usr/bin/python3\n# -*- coding=utf-8 -*-\nimport re\nimport pprint\n\nport_list = ['eth 1/101/1/42','eth 1/101/1/26','eth 1/101/1/23','eth 1/101/1/7','eth 1/101/2/46','eth 1/101/1/34',\n 'eth 1/101/1/18','eth 1/101/1/13','eth 1/101/1/32','eth 1/101/1/25','eth 1/101/1/45','eth 1/101/2/8']\n\n\n# port_list.sort()\n# print(port_list)\n#lambda是一个匿名函数,是固定写法;x表示匿名函数的输入,即列表中的一个元素,在这里,表示一个元组,x只是临时起的一个名字,\n# 你可以使用任意的名字;x[0]表示匿名函数的输出,即元组里的第一个元素,即key = x[0];所以这句命令的意思就是按照列表中第一个元素进行排序。\n# a = [('b', 4), ('a', 12), ('d', 7), ('h', 6), ('j', 3)]\n# a.sort(key=lambda x: x[0])\n# print(a)
    >>>[('a', 12), ('b', 4), ('d', 7), ('h', 6), ('j', 3)]\n\n\n\n\nport_list.sort(key=lambda x:(int(re.findall('\\d+',x)[0]),\n int(re.findall('\\d+',x)[1]),\n int(re.findall('\\d+',x)[2]),\n int(re.findall('\\d+',x)[3])\n )\n )\n# # key = x,x是列表中的第一个元组中的整数\\d 中第一位[0]\n# print(port_list)\npprint.pprint(port_list) #pprint优化打印\n\n# print(sorted(port_list, key=lambda x: (int(re.findall(r'\\d+', x)[0]),\n# int(re.findall(r'\\d+', x)[1]),\n# int(re.findall(r'\\d+', x)[2]),\n# int(re.findall(r'\\d+', x)[3]))\n# )\n# )\n#\n\n\n","sub_path":"python基础/正则表达式/sort_lambda.py","file_name":"sort_lambda.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"324660262","text":"import FWCore.ParameterSet.Config as cms\n\nfrom Configuration.Generator.PythiaUEZ2starSettings_cfi import *\ngenerator = cms.EDFilter(\"Pythia6GeneratorFilter\",\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n maxEventsToPrint = cms.untracked.int32(1),\n pythiaPylistVerbosity = cms.untracked.int32(3),\n filterEfficiency = cms.untracked.double(1.0),\n# comEnergy = cms.double(8000.0),\n comEnergy = cms.double(13000.0),\n PythiaParameters = cms.PSet(\n pythiaUESettingsBlock,\n processParameters = cms.vstring(\n 'IMSS(1) = 11 ! Spectrum from external SLHA file',\n 'IMSS(21) = 33 ! LUN number for SLHA File (must be 33) ',\n 'IMSS(22) = 33 ! Read-in SLHA decay table ',\n 'MSEL = 0 ! General SUSY',\n 'MSUB(226) = 1 ! to double chargino',\n 'MSUB(229) = 1 ! to neutralino + chargino',\n 'MDCY(312,1) = 0 ! set the chargino stable.',\n ),\n parameterSets = cms.vstring('pythiaUESettings', 'processParameters', 'SLHAParameters'),\n SLHAParameters = cms.vstring('SLHAFILE = DisappTrks/SignalMC/data/AMSB_chargino_600GeV_Isajet780.slha'),\n ),\n slhaFile = cms.untracked.string('DisappTrks/SignalMC/data/AMSB_chargino_600GeV_Isajet780.slha'),\n# The following parameters are required by Exotica_HSCP_SIM_cfi:\n processFile = cms.untracked.string('SimG4Core/CustomPhysics/data/RhadronProcessList.txt'),\n useregge = cms.bool(False),\n hscpFlavor = cms.untracked.string('stau'),\n massPoint = cms.untracked.int32(600),\n particleFile = cms.untracked.string('DisappTrks/SignalMC/data/geant4/geant4_AMSB_chargino_600GeV_ctau10000cm.slha')\n)\n","sub_path":"SignalMC/python/pythia6/AMSB_chargino600GeV_ctau10000cm_NoFilter_13TeV.py","file_name":"AMSB_chargino600GeV_ctau10000cm_NoFilter_13TeV.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"420649093","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass BatchNormNet(nn.Module):\n def __init__(self, input_dim=5, layer_sizes=[20,80,1],\n layer_activations=[\"relu\", \"relu\", \"linear\"]):\n # number of hidden layers = num_layer - 1\n super(BatchNormNet, self).__init__()\n\n # Initialize layers\n self.layers = nn.ModuleList([nn.Linear(input_dim, layer_sizes[0])])\n self.layers.append(nn.BatchNorm1d(layer_sizes[0]))\n for i in range(1, len(layer_sizes) - 1):\n self.layers.append(nn.Linear(layer_sizes[i - 1], layer_sizes[i]))\n self.layers.append(nn.BatchNorm1d(layer_sizes[i]))\n self.layers.append(nn.Linear(layer_sizes[i], layer_sizes[i+1]))\n self.num_layers = len(self.layers)\n\n # Define nonlinearities\n self.layer_activations = []\n for activation in layer_activations:\n if activation == \"relu\":\n self.layer_activations.append(F.relu)\n elif activation == \"sigmoid\":\n self.layer_activations.append(F.sigmoid)\n elif activation == \"leakyrelu\":\n self.layer_activations.append(F.leaky_relu)\n elif activation == \"linear\":\n continue\n\n def forward(self, x):\n for i in range(0, self.num_layers - 1, 2):\n x = self.layer_activations[i // 2](self.layers[i](x))\n x = self.layers[i + 1](x)\n x = self.layers[-1](x)\n return x\n\n\n\n\n","sub_path":"torch_models/torch_model_batchnorm.py","file_name":"torch_model_batchnorm.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"343509417","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom contextlib import suppress\nfrom datetime import datetime\nimport logging\n\nimport helpers\nfrom .Position import *\n\nclass Invoice(object):\n\n\tdef __init__(self):\n\t\tself.__Created = datetime.now()\n\t\tself.__Positions = []\n\n\tcreated = property(lambda self: self.__Created)\n\n\t@property\n\tdef number(self):\n\t\treturn self.__Number\n\n\t@number.setter\n\t@helpers.info_value\n\t@helpers.value_not_none\n\tdef number(self, value):\n\t\tself.__Number = value\n\n\t@number.deleter\n\tdef number(self):\n\t\tlogging.info(\"Number {0} deleted\".format(self.number))\n\t\tdel self.__Number\n\n\taddress = property(lambda self: self.__Address)\n\n\t@address.setter\n\t@helpers.warn_value\n\t@helpers.value_not_none\n\tdef address(self, value):\n\t\tself.__Address = value\n\n\tpesponser = property(lambda self: self.__Pesponser)\n\n\t@pesponser.setter\n\t@helpers.trace_value(logging.ERROR - 1)\n\t@helpers.value_not_none\n\tdef pesponser(self, value):\n\t\tself.__Pesponser = value\n\n\tsubscribed = property(lambda self: False)\n\n\t@property\n\tdef itogo(self):\n\t\tif self.subscribed:\n\t\t\treturn self.__Itogo\n\t\telse:\n\t\t\treturn sum(p.total for p in self.__Positions)\n\n\tdef append(self, *args, **kwargs):\n\t\tif isinstance(args[0], Position):\n\t\t\tP = args[0]\n\t\telse:\n\t\t\tP = Position(*args, **kwargs)\n\t\tself.__Positions.append(P)\n\n\t__StrData = [\n\t\t(\"Number\", \"number\"),\n\t\t(\"Created date\", \"created\"),\n\t\t(\"Address\", \"address\"),\n\t\t(\"Responible person\", \"pesponser\"),\n\t\t(\"Is subscribed\", \"subscribed\"),\n\t\t(\"Result\", \"itogo\"),\n\t]\n\n\tdef __len__(self):\n\t\treturn len(self.__Positions)\n\n\tdef __str__(self):\n\t\tL = []\n\t\tfor text, propname in self.__StrData:\n\t\t\twith suppress(AttributeError):\n\t\t\t\tT = \"{0}: {1}\".format(text, getattr(self, propname))\n\t\t\t\tL.append(T)\n\t\tL.extend(map(str, self.__Positions))\n\t\treturn \"\\n\".join(L)\n\n\tdef __getitem__(self, key):\n\t\tif not isinstance(key, int):\n\t\t\traise ValueError(\"Slices or keys not supported\")\n\t\treturn self.__Positions[key]\n\n\tdef __setitem__(self, key, value):\n\t\tif not isinstance(key, int):\n\t\t\traise ValueError(\"Slices or keys not supported\")\n\t\tself.__Positions[key] = value\n\n\tdef __delitem__(self, key):\n\t\tif not isinstance(key, int):\n\t\t\traise ValueError(\"Slices or keys not supported\")\n\t\tdel self.__Positions[key]\n\n\tdef __iter__(self):\n\t\tyield from self.__Positions","sub_path":"two/second/doc/Invoice.py","file_name":"Invoice.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"82881594","text":"\"\"\"\n\nFollowing tutorial in https://stackabuse.com/python-for-nlp-movie-sentiment-analysis-using-deep-learning-in-keras/ as nlp transfer learning\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\n\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers.core import Activation, Dropout, Dense\nfrom keras.layers import Flatten\nfrom keras.layers import GlobalMaxPooling1D\nfrom keras.layers.embeddings import Embedding\nfrom keras.regularizers import l2\nfrom keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.text import Tokenizer\n\n\n# Load data\nmovie_reviews = pd.read_csv('../data/IMDB_Dataset.csv')\nmovie_reviews.isnull().values.any()\nmovie_reviews.shape\nprint(movie_reviews.head())\nmovie_reviews[\"review\"][3]\nprint(movie_reviews.groupby('sentiment').count())\n\n\ndef remove_tags(text):\n \"\"\"\n\n This function removes HTML tags\n\n \"\"\"\n # pattern anything between <> characters\n TAG_RE = re.compile(r'<[^>]+>')\n return TAG_RE.sub('', text)\n\n\ndef preprocess_text(sen):\n \"\"\"\n\n Helper function to preprocess text\n\n \"\"\"\n # Remove HTML tags\n sentence = remove_tags(sen)\n # remove punctuation\n sentence = re.sub('[^A-zA-Z]', ' ', sentence)\n # single character removal\n sentence = re.sub(r\"\\s+[a-zA-Z]\\s+\", ' ', sentence)\n # remove multiple spaces\n sentence = re.sub(r'\\s+', ' ', sentence)\n return(sentence)\n\n\n# Preprocess data\nX = [preprocess_text(sen) for sen in list(movie_reviews['review'])]\ny = movie_reviews.sentiment.apply(lambda x: 1 if x == 'positive' else 0).tolist()\nprint('Preprocessed example:')\nprint(X[3])\n\n# Train-test\nX_train, X_test, y_train, y_test = train_test_split(X,\n y,\n test_size=0.20,\n random_state=42)\n\n# Transform data to one-hot\ntokenizer = Tokenizer(num_words=5000)\ntokenizer.fit_on_texts(X_train)\nX_train = tokenizer.texts_to_sequences(X_train)\nX_test = tokenizer.texts_to_sequences(X_test)\n\n# Padd data to get input with same size\nvocab_size = len(tokenizer.word_index)+1\nmaxlen = 100\nX_train = pad_sequences(X_train, padding='post', maxlen=maxlen)\nX_test = pad_sequences(X_test, padding='post', maxlen=maxlen)\n\n# this loads the pretrained embedding (GloVe)\nembedding_dictionary = dict()\nglove_file = open('../data/glove.6B.100d.txt', encoding='utf8')\nfor line in glove_file:\n records = line.split()\n word = records[0]\n vector_dimensions = np.asarray(records[1:], dtype='float32')\n embedding_dictionary[word] = vector_dimensions\nglove_file.close()\n\n# create the mapping from one-hot to glove features\nembedding_matrix = np.zeros((vocab_size, 100))\nfor word, index in tokenizer.word_index.items():\n embedding_vector = embedding_dictionary.get(word)\n if embedding_vector is not None:\n embedding_matrix[index] = embedding_vector\n\n# create neural network\nmodel = Sequential()\nembedding_layer = Embedding(vocab_size,\n 100,\n weights=[embedding_matrix],\n input_length=maxlen,\n trainable=False)\nmodel.add(embedding_layer)\nmodel.add(Flatten())\nmodel.add(Dense(1, kernel_regularizer=l2(0.01), activation='sigmoid'))\nmodel.compile(optimizer=Adam(learning_rate=1e-4),\n loss='binary_crossentropy',\n metrics=['acc'])\nprint(model.summary())\n\nhistory = model.fit(X_train,\n y_train,\n batch_size=128,\n epochs=10,\n verbose=1,\n validation_split=0.2)\n\nacc = model.evaluate(X_test, y_test, verbose=1)\nprint(\"Test Score:\", acc[0])\nprint(\"Test Accuracy:\", acc[1])\n\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train','val'], loc='upper left')\nplt.show()\n","sub_path":"word_embeddings/transfer_learning_keras.py","file_name":"transfer_learning_keras.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205089458","text":"import csv\nimport sys\n\nif __name__ == '__main__':\n actual_csv = sys.argv[1]\n predicted_csv = sys.argv[2]\n\n with open(actual_csv, newline='') as f:\n read = csv.reader(f)\n # [1:] to skip header, remove if no header\n actual_data = list(read)[1:]\n actual_data = [int(data[0]) for data in actual_data]\n\n with open(predicted_csv, newline='') as f:\n read = csv.reader(f)\n # [1:] to skip header, remove if no header\n predicted_data = list(read)[1:]\n predicted_data = [int(data[0]) for data in predicted_data]\n\n if (len(predicted_data) != len(actual_data)):\n print('Error: Lengths of two csvs are not the same')\n exit()\n\n tp = 0\n fp = 0\n fn = 0\n for val1, val2 in zip(actual_data, predicted_data):\n if (val1 == 1 and val2 == 1):\n tp += 1\n if (val1 == 0 and val2 == 1):\n fp += 1\n if (val1 == 1 and val2 == 0):\n fn += 1\n recall = tp / (tp + fp)\n precision = tp / (tp + fn)\n f1 = 2 * ((precision * recall) / (precision + recall))\n print(\"F1 Score is: \" + str(f1))","sub_path":"code/f1_score.py","file_name":"f1_score.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"142249425","text":"def I(x, y, s, codes):\n for i in range(y):\n codes.insert(x, s[i])\n\n return codes\n\n\ndef D(x, y, codes):\n codes = codes[:x] + codes[x + y:]\n return codes\n\n\nfor tc in range(1, 11):\n N = int(input())\n\n original_codes = list(map(int, input().split()))\n\n order_count = int(input())\n\n commands = input().split()\n\n for i, cmd in enumerate(commands):\n if cmd == 'I':\n s = []\n x = int(commands[i + 1])\n y = int(commands[i + 2])\n\n for j in range(y - 1, -1, -1):\n s.append(commands[i + 3 + j])\n\n I(x, y, s, original_codes)\n\n if cmd == 'D':\n x = int(commands[i + 1])\n y = int(commands[i + 2])\n\n D(x, y, original_codes)\n\n if cmd == 'A':\n y = int(commands[i + 1])\n for j in range(y):\n original_codes.append(commands[i + 2 + j])\n\n print(f\"#{tc} {' '.join(original_codes[:10])}\")\n","sub_path":"PYTHON/SWEXPERT/익스퍼트미분류/D3/1230_암호문3.py","file_name":"1230_암호문3.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375523048","text":"from Piece import *\nfrom Board import *\nimport random\nfrom ProbabalisticPossibleWorld import *\n\n# class for the simplest probabalistic AI\n# doesn't maintain different possible states\n# only tries to fit pieces where there are unknowns (doesn't try to place ships through known hits)\nclass ProbabalisticBattleshipAI:\n\t# constants for the two firing modes\n\tSINKING_SHIP = 0\n\tSEARCHING_FOR_SHIP = 1\n\n\t# constants for internal view of the opponent's board\n\tHITVAL = 2\n\tUNKNOWN = -1\n\tMISS = 0\n\n\t# initialize an AI for the computer with given the opponent's board dimensions\n\tdef __init__(self, boardWidth, boardHeight):\n\t\t# initialize a board representation with all cells as unknown\n\t\tself.boardRepresentation = []\n\t\tfor i in range(boardHeight):\n\t\t\tboardColumn = [ProbabalisticBattleshipAI.UNKNOWN]*boardWidth\n\t\t\tself.boardRepresentation.append(boardColumn)\n\t\t# start in searching mode\n\t\tself.targetMode = ProbabalisticBattleshipAI.SEARCHING_FOR_SHIP\n\t\tself.boardHeight = boardHeight\n\t\tself.boardWidth = boardWidth\n\t\t# start with no pieces being hit\n\t\tself.hitSequence = [] \n\t\t\n\t# have the computer take a turn\n\t# returns a tuple with the x and y coordinate of the computer's guess\n\tdef takeTurn(self): \n\t\t# if the computer has hit something recently, try to hit around the same area (use the sequence of hits since the last sink of a ship)\n\t\tif (self.targetMode == ProbabalisticBattleshipAI.SINKING_SHIP):\n\t\t\treturn self.getGuessFromHitSequence()\n\t\telse:\n\t\t\t# get the possible ship placements through only unknown cells for each spot on the board\n\t\t\tlikelihoods = self.possibleProbabilityCalculator()\n\t\t\tmaxX = 0\n\t\t\tmaxY = 0\n\t\t\tmaxVal = -1\n\n\t\t\t# choose the cell with the highest number of possible ship placements\n\t\t\tfor i in range(self.boardWidth):\n\t\t\t\tfor j in range(self.boardHeight):\n\t\t\t\t\t# if the likelihood is better, replace the guess\n\t\t\t\t\t# if the likelihood is the same as the max, flip a coin to see if we replace the guess\n\t\t\t\t\tif ((likelihoods[j][i] > maxVal) or ((likelihoods[j][i] == maxVal) and (random.randint(0, 1) == 0))):\n\t\t\t\t\t\tmaxX = i\n\t\t\t\t\t\tmaxY = j\n\t\t\t\t\t\tmaxVal = likelihoods[j][i]\n\t\t\treturn maxX, maxY\n\n\t# update the internal board state after hearing the result of the guess\n\tdef getMoveFeedback(self, guess, hit):\n\t\t# if the guess resulted in a hit or a sink\n\t\tif ((hit == Board.HIT) or (hit == Board.SUNK)):\n\n\t\t\t# change the board's state at the guessed cell to be a hit\n\t\t\tself.changeBoardAtPiece(guess[0], guess[1], ProbabalisticBattleshipAI.HITVAL)\n\t\t\t# update the firing mode to guess near hits\n\t\t\tself.targetMode = ProbabalisticBattleshipAI.SINKING_SHIP\n\t\t\t# add the hit cell to the sequence of hits since the last sink\n\t\t\tself.hitSequence.append([guess[0], guess[1]])\n\n\t\t\t# if the guess caused a sink\n\t\t\tif (hit == Board.SUNK):\n\t\t\t\t# go back to firing based on possible ship placements and clear the sequence of hits\n\t\t\t\tself.targetMode = ProbabalisticBattleshipAI.SEARCHING_FOR_SHIP\n\t\t\t\tself.hitSequence = []\n\t\t# if the guess was a miss\n\t\telse:\n\t\t\t# update that cell on the AI's view of the board\n\t\t\tself.changeBoardAtPiece(guess[0], guess[1], ProbabalisticBattleshipAI.MISS)\n\n\t# update the AI's board state at a given cell to be the given value\n\t# xPos - x coordinate of the cell to update\n\t# yPos - y coordinate of the cell to update\n\t# newVal - new value of the given cell\n\tdef changeBoardAtPiece(self, xPos, yPos, newVal):\n\t\tself.boardRepresentation[yPos][xPos] = newVal\n\n\t# return the value at the given coordinate for the AI's view of the opponent's board\n\tdef getValOnBoard(self, xPos, yPos):\n\t\treturn self.boardRepresentation[yPos][xPos]\n\n\t# make a guess based on recent hits\n\t# returns tuple with x and y coordinate of guess\n\tdef getGuessFromHitSequence(self):\n\t\t# initialize lists for keeping track of the number of hits that occur in each row and column of the board\n\t\t# we'll want to guess in the row/column with the most consecutive hits because there is likely a ship placed where there are consecutive hits\n\t\txPosCounts = [0]*self.boardWidth\n\t\tyPosCounts = [0]*self.boardHeight\n\n\t\t# initialize the minimum and maximum x and y positions of hits in the sequence\n\t\txHitMin = self.boardWidth\n\t\txHitMax = -1\n\t\tyHitMin = self.boardHeight\n\t\tyHitMax = -1\n\n\t\t# for each hit coordinate\n\t\tfor coord in self.hitSequence:\n\t\t\t# add one to the arrays for hits in each row and column of the board for the row and column of the current hit\n\t\t\txPosCounts[coord[0]] += 1\n\t\t\tyPosCounts[coord[1]] += 1\n\n\t\t\t# update the mins and maxs\n\t\t\tif (coord[0] < xHitMin):\n\t\t\t\txHitMin = coord[0]\n\t\t\tif (coord[0] > xHitMax):\n\t\t\t\txHitMax = coord[0]\n\t\t\tif (coord[1] < yHitMin):\n\t\t\t\tyHitMin = coord[1]\n\t\t\tif (coord[1] > yHitMax):\n\t\t\t\tyHitMax = coord[1]\n\n\t\t# determine the maximum number of hits in each direction\n\t\tmaxXCounts = max(xPosCounts)\n\t\tmaxYCounts = max(yPosCounts)\n\n\t\t# determine the row and column corresponding to the maximum number of hits in each direction\n\t\txMax = xPosCounts.index(maxXCounts)\n\t\tyMax = yPosCounts.index(maxYCounts)\n\n\t\t# if there are the same max number of hits in the x and y direction (we don't have an idea which direction the piece is)\n\t\tif (maxXCounts == maxYCounts):\n\n\t\t\t# check for unguessed cells as close as possible to the cell corresponding to the row with the highest hits and the column with the highest hits\n\t\t\tdistFromMax = 1\n\t\t\twhile (True):\n\t\t\t\t# 2 if we should check cells in the same row as the cell to guess near, 0 if we should look in the same column\n\t\t\t\tcheckVertical = 2*random.randint(0, 1) \n\t\t\t\t# 1 if we should check a cell closer to the bottom right corner, 0 if we should check a cell closer to the top left corner\n\t\t\t\tcheckGreater = random.randint(0, 1)\n\n\t\t\t\t# iterate through the different neighboring cells until we find one that is on the board and is unknown (we can guess it)\n\t\t\t\tcheckVal = checkVertical + checkGreater\n\t\t\t\tfor i in range(4):\n\t\t\t\t\tif (checkVal == 0):\n\t\t\t\t\t\t# horizontal\n\t\t\t\t\t\t# check less than\n\t\t\t\t\t\tguessX = xMax - distFromMax\n\t\t\t\t\t\tguessY = yMax\n\t\t\t\t\t\t# if the piece is on the board and it's value is unknown, guess this cell\n\t\t\t\t\t\tif (xMax - distFromMax >= 0):\n\t\t\t\t\t\t\tif (self.getValOnBoard(guessX, guessY) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn guessX, guessY\n\t\t\t\t\telif (checkVal == 1):\n\t\t\t\t\t\t# horizontal\n\t\t\t\t\t\t# check greater than\n\t\t\t\t\t\tguessX = xMax + distFromMax\n\t\t\t\t\t\tguessY = yMax\n\n\t\t\t\t\t\t# if the piece is on the board and it's value is unknown, guess this cell\n\t\t\t\t\t\tif (xMax + distFromMax < self.boardWidth):\n\t\t\t\t\t\t\tif (self.getValOnBoard(guessX, guessY) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn guessX, guessY\n\t\t\t\t\telif (checkVal == 2):\n\t\t\t\t\t\t# vertical\n\t\t\t\t\t\t# check less than\n\t\t\t\t\t\tguessX = xMax \n\t\t\t\t\t\tguessY = yMax - distFromMax\n\n\t\t\t\t\t\t# if the piece is on the board and it's value is unknown, guess this cell\n\t\t\t\t\t\tif (yMax - distFromMax >= 0):\n\t\t\t\t\t\t\tif (self.getValOnBoard(guessX, guessY) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn guessX, guessY\n\t\t\t\t\telse:\n\t\t\t\t\t\t# vertical\n\t\t\t\t\t\t# check greater than\n\t\t\t\t\t\tguessX = xMax \n\t\t\t\t\t\tguessY = yMax + distFromMax\n\n\t\t\t\t\t\t# if the piece is on the board and it's value is unknown, guess this cell\n\t\t\t\t\t\tif (yMax + distFromMax < self.boardHeight):\n\t\t\t\t\t\t\tif (self.getValOnBoard(guessX, guessY) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn guessX, guessY\n\t\t\t\t\t\t\n\t\t\t\t\tcheckVal += 1\n\t\t\t\t\tcheckVal = checkVal % 4\n\t\t\t\t# if none of the immediately neighboring cells are valid guesses, go to cells that are a little further away\n\t\t\t\tdistFromMax += 1\n\n\t\telse:\n\t\t\tif (maxXCounts > maxYCounts):\n\t\t\t\t# we suspect the piece to be vertical because the hits in a single row are higher than the hits in a single column\n\t\t\t\t# start guessing vertically\n\t\t\t\tstartWithVertical = 1\n\t\t\telse:\n\t\t\t\t# we suspect the piece to be horizontal\n\t\t\t\t# start guessing horizontally\n\t\t\t\tstartWithVertical = 0\n\n\t\t\t# try to guess in the direction that we suspect the piece to be, but if there aren't any valid guesses, switch to guessing the other orientation\n\t\t\tfor i in range(2):\t\n\t\t\t\t# we're guessing as if the ship is placed vertically\n\t\t\t\tif (startWithVertical == 1):\n\t\t\t\t\t# check if our hit sequence has an unknown cell in the middle, if so, guess that\n\t\t\t\t\tfor j in range(yHitMin + 1, yHitMax):\n\t\t\t\t\t\tif (self.getValOnBoard(xMax, j) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\treturn xMax, j\n\n\t\t\t\t\t# while we still have options for guessing with this orientation\n\t\t\t\t\tpointCanBeFound = True\n\t\t\t\t\tdistFromMax = 1\n\t\t\t\t\twhile (pointCanBeFound):\n\t\t\t\t\t\t# check to see if we can guess pieces with higher and/or lower values than the cells we've hit so far \n\t\t\t\t\t\t# (i.e. our hit isn't on the edge of the board)\n\t\t\t\t\t\tlessThanInRange = ((yHitMin - distFromMax) >= 0)\n\t\t\t\t\t\tgreaterThanInRange = ((yHitMax + distFromMax) < self.boardHeight)\n\t\t\t\t\t\t\n\t\t\t\t\t\t# if we can guess lower, check if the cell distFromMax away from the minimum hit cell is unknown and if so, guess it\n\t\t\t\t\t\tif (lessThanInRange):\n\t\t\t\t\t\t\tif (self.getValOnBoard(xMax, yHitMin - distFromMax) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn xMax, yHitMin - distFromMax\n\t\t\t\t\t\t# if we can guess higher, check if the cell distFromMax away from the maximum hit cell is unknown, and if so, guess it\n\t\t\t\t\t\tif (greaterThanInRange):\n\t\t\t\t\t\t\tif (self.getValOnBoard(xMax, yHitMax + distFromMax) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn xMax, yHitMax + distFromMax\n\t\t\t\t\t\t# if we can't guess on either end of the sequence of pieces, give up looking in this direction (switch to horizontal)\n\t\t\t\t\t\tif (not lessThanInRange) and (not greaterThanInRange):\n\t\t\t\t\t\t\tpointCanBeFound = False\n\t\t\t\t\t\tdistFromMax += 1\n\t\t\t\telse:\n\n\t\t\t\t\t# check if our hit sequence has an unknown cell in the middle, if so, guess that cell\n\t\t\t\t\tfor j in range(xHitMin + 1, xHitMax):\n\t\t\t\t\t\tif (self.getValOnBoard(j, yMax) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\treturn j, yMax\n\n\t\t\t\t\t# while we still have options for guessing with this orientation\n\t\t\t\t\tpointCanBeFound = True\n\t\t\t\t\tdistFromMax = 1\n\t\t\t\t\twhile (pointCanBeFound):\n\t\t\t\t\t\t# check to see if we can guess pieces with higher and/or lower values than the cells we've hit so far \n\t\t\t\t\t\t# (i.e. our hit isn't on the edge of the board)\n\t\t\t\t\t\tlessThanInRange = (xHitMin - distFromMax >= 0)\n\t\t\t\t\t\tgreaterThanInRange = (xHitMax + distFromMax < self.boardWidth)\n\n\t\t\t\t\t\t# if we can guess lower, check if the cell distFromMax away from the minimum hit cell is unknown and if so, guess it\n\t\t\t\t\t\tif (lessThanInRange):\n\t\t\t\t\t\t\tif (self.getValOnBoard(xHitMin - distFromMax, yMax) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn xHitMin - distFromMax, yMax\n\t\t\t\t\t\t# if we can guess higher, check if the cell distFromMax away from the maximum hit cell is unknown, and if so, guess it\n\t\t\t\t\t\tif (greaterThanInRange):\n\t\t\t\t\t\t\tif (self.getValOnBoard(xHitMax + distFromMax, yMax) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\t\t\treturn xHitMax + distFromMax, yMax\n\t\t\t\t\t\t\n\t\t\t\t\t\t# if we can't guess on either end of the sequence of pieces, give up looking in this direction (switch to horizontal)\n\t\t\t\t\t\tif (not lessThanInRange) and (not greaterThanInRange):\n\t\t\t\t\t\t\tpointCanBeFound = False\n\t\t\t\t\t\t# if the nearest cells werent' unknown, guess at cells slightly further away\n\t\t\t\t\t\tdistFromMax += 1\n\t\t\t\tstartWithVertical += 1\n\t\t\t\tstartWithVertical = startWithVertical%2\n\n\t# check if a piece of the given length orientation will fit on the board if it starts at the given coordinate\n\t# pieces are only considered to fit if they can be placed completely in unknown cells\n\t# xPos - x coordinate of the beginning of the piece\n\t# yPos - y coordinate of the beginning of the piece\n\t# pieceLen - length of the piece\n\t# pieceOrientation - orientation of the piece\n\t# assumes we've already checked that the piece would fit on the board (it doesn't go off the side of the board)\n\t# return true if the described piece would fit at the given location, false otherwise\n\tdef willPieceCompletelyFit(self, xPos, yPos, pieceLen, pieceOrientation):\n\t\tif (pieceOrientation == Piece.HORIZONTAL):\n\t\t\tfor i in range(pieceLen):\n\t\t\t\tif not (self.getValOnBoard(xPos + i, yPos) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\treturn False\n\t\telse:\n\t\t\tfor i in range(pieceLen):\n\t\t\t\tif not (self.getValOnBoard(xPos, yPos + i) == ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\treturn False\n\t\treturn True\n\n\t# determines number of times a piece placement could go through each cell on the board given the results of guesses so far in this game\n\tdef possibleProbabilityCalculator(self):\n\t\t# try to place pieces of all lengths (we don't eliminate pieces as we sink them)\n\t\tpieceLengths = [2, 3, 4, 5] # will be repeating results of 3\n\t\t# initialize a 2D array for possible piece placements\n\t\tsingleRow = [0]*self.boardWidth\n\t\tlikelihoodArray = []\n\t\tfor i in range(self.boardHeight):\n\t\t\tlikelihoodArray.append(singleRow[:])\t\n\t\t# initialize total possible piece placements (so we can normalize piece placements 2d array)\n\t\tpossiblePlacements = 0\n\n\t\t# for each piece, check where it could fit\n\t\tfor pieceLen in pieceLengths:\n\t\t\t# 2 possible pieces could fit in spot if piece is 3 b/c 2 pieces length 3\n\t\t\tif (pieceLen == 3):\n\t\t\t\tmultplier = 2\n\t\t\telse:\n\t\t\t\tmultplier = 1\n\t\t\t\n\t\t\t# check if the piece would fit if it starts at each cell on the board for each orientation\n\t\t\tfor i in range(self.boardWidth):\n\t\t\t\tfor j in range(self.boardHeight):\n\t\t\t\t\tpieceOrientation = Piece.HORIZONTAL\n\t\t\t\t\tif ((i + pieceLen) <= self.boardWidth):\n\t\t\t\t\t\t# if the piece would fit at the current cell\n\t\t\t\t\t\tif (self.willPieceCompletelyFit(i, j, pieceLen, pieceOrientation)):\n\t\t\t\t\t\t\t# increase the possilbe placements at cells covered by this ship if it starts at this orientation and this point\n\t\t\t\t\t\t\tfor k in range(pieceLen):\n\t\t\t\t\t\t\t\tlikelihoodArray[j][i + k] = likelihoodArray[j][i + k] + multplier\n\t\t\t\t\t\t\tpossiblePlacements += multplier\n\t\t\t\t\tpieceOrientation = Piece.VERTICAL\n\t\t\t\t\tif ((j + pieceLen) <= self.boardHeight):\n\t\t\t\t\t\t# if the piece would fit at the current cell\n\t\t\t\t\t\tif (self.willPieceCompletelyFit(i, j, pieceLen, pieceOrientation)):\n\t\t\t\t\t\t\t# increase the possilbe placements at cells covered by this ship if it starts at this orientation and this point\n\t\t\t\t\t\t\tfor k in range(pieceLen):\n\t\t\t\t\t\t\t\tlikelihoodArray[j + k][i] = likelihoodArray[j + k][i] + multplier\n\t\t\t\t\t\t\tpossiblePlacements += multplier\n\t\t\t\t\t# if the cell has already been guessed, give it a negative probability so it will never guess an already guessed cell\n\t\t\t\t\tif (self.getValOnBoard(i, j) != ProbabalisticBattleshipAI.UNKNOWN):\n\t\t\t\t\t\tlikelihoodArray[j][i] = -1\n\n\t\t# normalize likelihood of each cell\n\t\tif (possiblePlacements > 0):\n\t\t\tfor i in range(self.boardWidth):\n\t\t\t\tfor j in range(self.boardHeight):\n\t\t\t\t\tlikelihoodArray[j][i] = float(likelihoodArray[j][i])/possiblePlacements\n\t\treturn likelihoodArray\n\n","sub_path":"finalProject/ProbabalisticBattleshipAI.py","file_name":"ProbabalisticBattleshipAI.py","file_ext":"py","file_size_in_byte":14663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"649191546","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: wangzq \n\nfrom itdblib.common.hr_intf import fetch_info_by_id\n\n\n# 根据rtx_id获取leader\ndef get_employee_owner(rtx_id):\n res_dict = fetch_info_by_id('userId=', rtx_id)\n if judge_value_is_none(res_dict):\n return u'员工不存在'\n data = res_dict['data']\n if data['hire_type'] == u'正式':\n return rtx_id\n return data['manager_email'].split('@')[0]\n\n\ndef get_rtx_id_by_sn(sn):\n res_dict = fetch_info_by_id('sn=', sn)\n if judge_value_is_none(res_dict):\n return sn\n data = res_dict['data']\n return data['user_name']\n\n\ndef judge_value_is_none(res_dict):\n if len(res_dict) == 0:\n return True\n data = res_dict['data']\n if len(data) == 0:\n return True\n return False\n\n\n# 将输入的员工编号转为rtx_id\ndef get_actual_rtx_id(id):\n if id == '' or id is None:\n return ''\n if id[0:2] == 'Q0':\n return get_rtx_id_by_sn(id)\n return id","sub_path":"itdblib/common/corehr_api_utils.py","file_name":"corehr_api_utils.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"336416069","text":"import os\nimport pprint\nimport shutil\nfrom collections import defaultdict\n\nfrom sklearn.externals import joblib\n\nfrom steppy.adapter import AdapterError\nfrom steppy.utils import view_graph, save_graph, get_logger, initialize_logger\n\ninitialize_logger()\nlogger = get_logger()\n\n\nclass Step:\n \"\"\"Building block of steps pipelines.\n\n Step is an execution wrapper over the transformer (see BaseTransformer class documentation) that enables building complex machine learning pipelines.\n It handles multiple input/output data flows, has build-in persistence/caching of both models (transformers) and\n intermediate step outputs.\n Step executes fit_transform on every step recursively starting from the very last step and making its way forward\n through the input_steps. If step transformer was fitted already then said transformer is loaded in and the transform method\n is executed.\n One can easily debug the data flow by plotting the pipeline graph with either step.save_graph(filepath) method\n or simply returning it in a jupyter notebook cell.\n Every part of the pipeline can be easily accessed via step.get_step(name) method which makes it easy to reuse parts of the pipeline\n across multiple solutions.\n \"\"\"\n def __init__(self,\n name,\n transformer,\n input_steps=None,\n input_data=None,\n adapter=None,\n cache_dirpath=None,\n cache_output=False,\n save_output=False,\n load_saved_output=False,\n save_graph=False,\n force_fitting=False):\n \"\"\"\n Args:\n name (str): Step name. Each step in a pipeline needs to have a unique name.\n Transformers, and Step outputs will be persisted/cached/saved under this exact name.\n transformer (obj): Step instance or object that inherits from BaseTransformer.\n When Step instance is passed transformer from that Step will be copied and used to perform transformations.\n It is useful when both train and valid data are passed in one pipeline (common situation in deep learning).\n input_steps (list): list of Step instances default []. Current step will combine outputs from input_steps and input_data\n and pass to the transformer methods fit_transform and transform.\n input_data (list): list of str default []. Elements of this list are keys in the data dictionary that is passed\n to the pipeline/step fit_transform and/or transform methods.Current step will combine input_data and outputs from input_steps\n and pass to the transformer methods fit_transform and transform.\n Example:\n data = {'input_1':{'X':X,\n 'y':y}\n },\n 'input_2': {'X':X,\n 'y':y}\n }\n }\n step_1 = Step(...,\n input_data = ['input_1']\n ...\n )\n adapter (dict): dictionary of mappings used to adapt input_steps outputs and input_data to match transform and fit_transform\n arguments for the transformer specified in this step. For each argument one needs to specify the\n argument: ([(step_name, output_key)...(input_name, output_key)], aggregation_function).\n If no aggregation_function is specified adapters.take_first_inputs function is used.\n Number of aggregation functions are available in the steps.adapters module.\n Example:\n from steps.adapters import hstack_inputs\n data = {'input_1':{'X':X,\n 'y':y\n },\n 'input_2': {'X':X,\n 'y':y\n }\n }\n step_1 = Step(name='step_1',\n ...\n )\n step_2 = Step(name='step_2',\n ...\n )\n step_3 = Step(name='step_3',\n input_steps=[step_1, step_2],\n input_data=['input_2'],\n adapter = {'X':([('step_1','X_transformed'),\n ('step_2','X_transformed'),\n ('step_2','categorical_features'),\n ('input_2','auxilary_features'),\n ], hstack_inputs)\n 'y':(['input_1', 'y'])\n }\n ...\n )\n cache_dirpath (str): path to the directory where all transformers, step outputs and temporary files\n should be stored.\n The following subfolders will be created if they were not created by other steps:\n transformers: transformer objects are persisted in this folder\n outputs: step output dictionaries are persisted in this folder (if save_output=True)\n tmp: step output dictionaries are persisted in this folder (if cache_output=True).\n This folder is temporary and should be cleaned before/after every run\n cache_output (bool): default False. If true then step output dictionary will be cached to cache_dirpath/tmp/name after transform method\n of the step transformer is completed. If the same step is used multiple times in the pipeline only the first time\n the transform method is executed and later the output dictionary is loaded from the cache_dirpath/tmp/name directory.\n Warning:\n One should always run pipeline.clean_cache() before executing pipeline.fit_transform(data) or pipeline.transform(data)\n Caution when working with large datasets is advised.\n save_output (bool): default False. If True then step output dictionary will be saved to cache_dirpath/outputs/name after transform method\n of the step transformer is completed. It will save the output after every run of the step.transformer.transform method.\n It will not be loaded unless specified with load_saved_output. It is especially useful when debugging and working with\n ensemble models or time consuming feature extraction. One can easily persist already computed pieces of the pipeline\n and not waste time recalculating them in the future.\n Warning:\n Caution when working with large datasets is advised.\n load_saved_output (bool): default False. If True then step output dictionary saved to the cache_dirpath/tmp/name will be loaded when\n step is called.\n Warning:\n Reruning the same pipeline on new data with load_saved_output may lead to errors when outputs from\n old data are loaded while user would expect the pipeline to use new data instead.\n force_fitting (bool): default False. If True then step transformer will be fitted (via fit_transform) even if\n cache_dirpath/transformers/name exists. This is helpful when one wants to use save_output=True and load save_output=True\n on a previous step and fit current step multiple times. That is a typical usecase when tuning hyperparameters\n for an ensemble model trained on the outputs from first level models or a model build on features that are\n time consuming to compute.\n save_graph (bool): default False. If true then the pipeline graph will be saved to the cache_dirpath/name_graph.json file\n \"\"\"\n\n self.name = name\n self.transformer = transformer\n\n self.input_steps = input_steps or []\n self.input_data = input_data or []\n self.adapter = adapter\n\n self.force_fitting = force_fitting\n self.cache_output = cache_output\n self.save_output = save_output\n self.load_saved_output = load_saved_output\n\n self.cache_dirpath = cache_dirpath\n self._prep_cache(cache_dirpath)\n\n if save_graph:\n graph_filepath = os.path.join(self.cache_dirpath, '{}_graph.json'.format(self.name))\n logger.info('Saving graph to {}'.format(graph_filepath))\n joblib.dump(self.graph_info, graph_filepath)\n\n @property\n def graph_info(self):\n \"\"\"(dict): dictionary describing the pipeline execution graph.\n \"\"\"\n graph_info = {'edges': set(),\n 'nodes': set()}\n\n graph_info = self._get_graph_info(graph_info)\n\n return graph_info\n\n @property\n def all_steps(self):\n \"\"\"(dict): dictionary of steps in the pipeline.\n \"\"\"\n all_steps = {}\n all_steps = self._get_steps(all_steps)\n return all_steps\n\n @property\n def transformer_is_cached(self):\n \"\"\"(bool): True if transformer exists under the cache_dirpath/transformers/name\n \"\"\"\n if isinstance(self.transformer, Step):\n self._copy_transformer(self.transformer, self.name, self.cache_dirpath)\n return os.path.exists(self.cache_filepath_step_transformer)\n\n @property\n def output_is_cached(self):\n \"\"\"(bool): True if step outputs exists under the cache_dirpath/tmp/name.\n See cache_output.\n \"\"\"\n return os.path.exists(self.save_filepath_step_tmp)\n\n @property\n def output_is_saved(self):\n \"\"\"(bool): True if step outputs exists under the cache_dirpath/outputs/name.\n See save_output.\n \"\"\"\n return os.path.exists(self.save_filepath_step_output)\n\n def fit_transform(self, data):\n \"\"\"fits the model and transforms data or loads already processed data\n\n Loads cached/saved outputs or adapts data for the current transformer and executes transformer.fit_transform\n\n Args:\n data (dict): data dictionary with keys as input names and values as dictionaries of key:value pairs that can\n be passed to the step.transformer.fit_transform method\n Example:\n data = {'input_1':{'X':X,\n 'y':y\n },\n 'input_2': {'X':X,\n 'y':y\n }\n }\n Returns:\n dict: step outputs from the transformer.fit_transform method\n \"\"\"\n if self.output_is_cached and not self.force_fitting:\n logger.info('step {} loading output...'.format(self.name))\n step_output_data = self._load_output(self.save_filepath_step_tmp)\n elif self.output_is_saved and self.load_saved_output and not self.force_fitting:\n logger.info('step {} loading output...'.format(self.name))\n step_output_data = self._load_output(self.save_filepath_step_output)\n else:\n step_inputs = {}\n if self.input_data is not None:\n for input_data_part in self.input_data:\n step_inputs[input_data_part] = data[input_data_part]\n\n for input_step in self.input_steps:\n step_inputs[input_step.name] = input_step.fit_transform(data)\n\n if self.adapter:\n step_inputs = self._adapt(step_inputs)\n else:\n step_inputs = self._unpack(step_inputs)\n step_output_data = self._cached_fit_transform(step_inputs)\n return step_output_data\n\n def transform(self, data):\n \"\"\"transforms data or loads already processed data\n\n Loads cached/saved outputs or adapts data for the current transformer and executes transformer.transform\n\n Args:\n data (dict): data dictionary with keys as input names and values as dictionaries of key:value pairs that can\n be passed to the step.transformer.fit_transform method\n Example:\n data = {'input_1':{'X':X,\n 'y':y\n },\n 'input_2': {'X':X,\n 'y':y\n }\n }\n Returns:\n dict: step outputs from the transformer.transform method\n \"\"\"\n if self.output_is_cached:\n logger.info('step {} loading output...'.format(self.name))\n step_output_data = self._load_output(self.save_filepath_step_tmp)\n elif self.output_is_saved and self.load_saved_output:\n logger.info('step {} loading output...'.format(self.name))\n step_output_data = self._load_output(self.save_filepath_step_output)\n else:\n step_inputs = {}\n if self.input_data is not None:\n for input_data_part in self.input_data:\n step_inputs[input_data_part] = data[input_data_part]\n\n for input_step in self.input_steps:\n step_inputs[input_step.name] = input_step.transform(data)\n\n if self.adapter:\n step_inputs = self._adapt(step_inputs)\n else:\n step_inputs = self._unpack(step_inputs)\n step_output_data = self._cached_transform(step_inputs)\n return step_output_data\n\n def clean_cache(self):\n \"\"\"Removes cached step outputs.\n\n It removes all cached step output from the cache_dirpath/tmp\n \"\"\"\n for name, step in self.all_steps.items():\n step._clean_cache()\n\n def get_step(self, name):\n \"\"\"Extracts step by name from the pipeline.\n\n Extracted step is a fully functional pipeline as well.\n This method can be used to port parts of the pipeline between problems.\n\n Args:\n name (str): name of the step to be fetched\n Returns:\n Step: extracted step\n \"\"\"\n return self.all_steps[name]\n\n def save_graph(self, filepath):\n \"\"\"Creates pipeline graph and saves it to a file\n\n Pydot graph is created and saved to filepath. This feature is usefull for debugging purposes especially\n when working with complex pipelines.\n\n Args:\n filepath (str): filepath where the graph should be saved\n \"\"\"\n save_graph(self.graph_info, filepath)\n\n def _copy_transformer(self, step, name, dirpath):\n self.transformer = self.transformer.transformer\n\n original_filepath = os.path.join(step.cache_dirpath, 'transformers', step.name)\n copy_filepath = os.path.join(dirpath, 'transformers', name)\n logger.info('copying transformer from {} to {}'.format(original_filepath, copy_filepath))\n shutil.copyfile(original_filepath, copy_filepath)\n\n def _prep_cache(self, cache_dirpath):\n for dirname in ['transformers', 'outputs', 'tmp']:\n os.makedirs(os.path.join(cache_dirpath, dirname), exist_ok=True)\n\n self.cache_dirpath_transformers = os.path.join(cache_dirpath, 'transformers')\n self.save_dirpath_outputs = os.path.join(cache_dirpath, 'outputs')\n self.save_dirpath_tmp = os.path.join(cache_dirpath, 'tmp')\n\n self.cache_filepath_step_transformer = os.path.join(self.cache_dirpath_transformers, self.name)\n self.save_filepath_step_output = os.path.join(self.save_dirpath_outputs, '{}'.format(self.name))\n self.save_filepath_step_tmp = os.path.join(self.save_dirpath_tmp, '{}'.format(self.name))\n\n def _clean_cache(self):\n if os.path.exists(self.save_filepath_step_tmp):\n os.remove(self.save_filepath_step_tmp)\n\n def _cached_fit_transform(self, step_inputs):\n if self.transformer_is_cached and not self.force_fitting:\n logger.info('step {} loading transformer...'.format(self.name))\n self.transformer.load(self.cache_filepath_step_transformer)\n logger.info('step {} transforming...'.format(self.name))\n step_output_data = self.transformer.transform(**step_inputs)\n else:\n logger.info('step {} fitting and transforming...'.format(self.name))\n step_output_data = self.transformer.fit_transform(**step_inputs)\n logger.info('step {} saving transformer...'.format(self.name))\n self.transformer.save(self.cache_filepath_step_transformer)\n\n if self.cache_output:\n logger.info('step {} caching outputs...'.format(self.name))\n self._save_output(step_output_data, self.save_filepath_step_tmp)\n if self.save_output:\n logger.info('step {} saving outputs...'.format(self.name))\n self._save_output(step_output_data, self.save_filepath_step_output)\n return step_output_data\n\n def _load_output(self, filepath):\n return joblib.load(filepath)\n\n def _save_output(self, output_data, filepath):\n joblib.dump(output_data, filepath)\n\n def _cached_transform(self, step_inputs):\n if self.transformer_is_cached:\n logger.info('step {} loading transformer...'.format(self.name))\n self.transformer.load(self.cache_filepath_step_transformer)\n logger.info('step {} transforming...'.format(self.name))\n step_output_data = self.transformer.transform(**step_inputs)\n else:\n raise ValueError('No transformer cached {}'.format(self.name))\n if self.cache_output:\n logger.info('step {} caching outputs...'.format(self.name))\n self._save_output(step_output_data, self.save_filepath_step_tmp)\n if self.save_output:\n logger.info('step {} saving outputs...'.format(self.name))\n self._save_output(step_output_data, self.save_filepath_step_output)\n return step_output_data\n\n def _adapt(self, step_inputs):\n logger.info('step {} adapting inputs'.format(self.name))\n try:\n return self.adapter.adapt(step_inputs)\n except AdapterError as e:\n msg = \"Error while adapting step '{}'\".format(self.name)\n raise StepsError(msg) from e\n\n def _unpack(self, step_inputs):\n logger.info('step {} unpacking inputs'.format(self.name))\n unpacked_steps = {}\n key_to_step_names = defaultdict(list)\n for step_name, step_dict in step_inputs.items():\n unpacked_steps.update(step_dict)\n for key in step_dict.keys():\n key_to_step_names[key].append(step_name)\n\n repeated_keys = [(key, step_names) for key, step_names in key_to_step_names.items()\n if len(step_names) > 1]\n if len(repeated_keys) == 0:\n return unpacked_steps\n else:\n msg = \"Could not unpack inputs. Following keys are present in multiple input steps:\\n\"\\\n \"\\n\".join([\" '{}' present in steps {}\".format(key, step_names)\n for key, step_names in repeated_keys])\n raise StepsError(msg)\n\n def _get_steps(self, all_steps):\n for input_step in self.input_steps:\n all_steps = input_step._get_steps(all_steps)\n all_steps[self.name] = self\n return all_steps\n\n def _get_graph_info(self, graph_info):\n for input_step in self.input_steps:\n graph_info = input_step._get_graph_info(graph_info)\n graph_info['edges'].add((input_step.name, self.name))\n graph_info['nodes'].add(self.name)\n for input_data in self.input_data:\n graph_info['nodes'].add(input_data)\n graph_info['edges'].add((input_data, self.name))\n return graph_info\n\n def __str__(self):\n return pprint.pformat(self.graph_info)\n\n def _repr_html_(self):\n return view_graph(self.graph_info)\n\n\nclass BaseTransformer:\n \"\"\"Abstraction on two level fit and transform execution.\n\n Base transformer is an abstraction strongly inspired by the sklearn.Transformer sklearn.Estimator.\n Two main concepts are:\n 1. Every action that can be performed on data (transformation, model training) can be performed in two steps\n fitting (where trainable parameters are estimated) and transforming (where previously estimated parameters are used\n to transform the data into desired state)\n 2. Every transformer knows how it should be saved and loaded (especially useful when working with Keras/Pytorch and Sklearn)\n in one pipeline\n \"\"\"\n\n def __init__(self):\n self.estimator = None\n\n def fit(self, *args, **kwargs):\n \"\"\"Performs estimation of trainable parameters\n\n All model estimations with sklearn, keras, pytorch models as well as some preprocessing techniques (normalization)\n estimate parameters based on data (training data). Those parameters are trained during fit execution and\n are persisted for the future.\n Only the estimation logic, nothing else.\n\n Args:\n args: positional arguments (can be anything)\n kwargs: keyword arguments (can be anything)\n\n Returns:\n BaseTransformer: self object\n \"\"\"\n return self\n\n def transform(self, *args, **kwargs):\n \"\"\"Performs transformation of data\n\n All data transformation including prediction with deep learning/machine learning models can be performed here.\n No parameters should be estimated in this method nor stored as class attributes.\n Only the transformation logic, nothing else.\n\n Args:\n args: positional arguments (can be anything)\n kwargs: keyword arguments (can be anything)\n\n Returns:\n dict: outputs\n \"\"\"\n raise NotImplementedError\n\n def fit_transform(self, *args, **kwargs):\n \"\"\"Performs fit followed by transform\n\n This method simply combines fit and transform.\n\n Args:\n args: positional arguments (can be anything)\n kwargs: keyword arguments (can be anything)\n\n Returns:\n dict: outputs\n \"\"\"\n self.fit(*args, **kwargs)\n return self.transform(*args, **kwargs)\n\n def load(self, filepath):\n \"\"\"Loads the trainable parameters of the transformer\n\n Specific implementation of loading persisted model parameters should be implemented here.\n In case of transformers that do not learn any parameters one can leave this method as is.\n\n Args:\n filepath (str): filepath from which the transformer should be loaded\n Returns:\n BaseTransformer: self instance\n \"\"\"\n return self\n\n def save(self, filepath):\n \"\"\"Saves the trainable parameters of the transformer\n\n Specific implementation of model parameter persistance should be implemented here.\n In case of transformers that do not learn any parameters one can leave this method as is.\n\n Args:\n filepath (str): filepath where the transformer parameters should be saved\n \"\"\"\n joblib.dump({}, filepath)\n\n\nclass IdentityOperation(BaseTransformer):\n \"\"\"Transformer that performs identity operation, f(x)=x.\n\n It is sometimes useful to organize the outputs from previous steps, join them together or rename them before\n passing to the next step. Typical use-case would be to join features extracted with\n multiple transformers into one object called joined_features. In that case the adapter attribute is used to define\n the mapping/joining scheme.\n\n \"\"\"\n def transform(self, **kwargs):\n return kwargs\n\n\nclass StepsError(Exception):\n pass\n\n\ndef make_transformer(func):\n class StaticTransformer(BaseTransformer):\n def transform(self, *args, **kwargs):\n return func(*args, **kwargs)\n return StaticTransformer()\n","sub_path":"steppy/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":24595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"459300560","text":"__author__ = 'willrolleston'\n\nfrom numpy import arange\nfrom math import log10\n\n'''\na = []\n\nfor x in xrange(0,10):\n a.append(x)\n\nb = []\nfor x in xrange(0,5):\n b.append(0)\n\nprint a\n\na[:0] = b\n\nprint a\n'''\n#text = \"My hovercraft is full of eels.\"\n#first_chars = [word[0] for word in text.split() if word[0].lower() in \"aeiou\"]\n#print first_chars\n'''\nl = []\nl = [1,2,3,4,5,2,6,7,7,8,10]\n\nfor i in xrange(len(l)-1, -1, -1):\n print l[i]\n'''\n\n'''\ndef namestr(obj, namespace):\n return [name for name in namespace if namespace[name] is obj]\n\na = {'some var': 2}\n\nprint namestr(a, globals())\n'''\n\ng = globals()\n\n\n\nfor i in arange(1,52):\n varname = 'k{}'.format(i)\n g[varname] = log10(g[varname])\n\n\n","sub_path":"RawData/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"53468808","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nimport re\nimport sys\nimport warnings\nimport lxml.etree as et\nfrom PyQt5 import (QtCore, QtGui, uic, QtWidgets)\nfrom PyQt5.QtWidgets import (QMainWindow, QTextEdit, QAction, QFileDialog,\n QApplication, QProgressBar)\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import *\n\nwarnings.filterwarnings(\"ignore\")\nForm, Base = uic.loadUiType(\"converter.ui\")\n\nclass MyWindow(QtWidgets.QWidget, Form):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Form()\n self.ui.setupUi(self)\n self.timer = QBasicTimer()\n self.step = 0\n self.ui.btnQuit.clicked.connect(QCoreApplication.instance().quit)\n self.ui.showd.clicked.connect(self.getfiles)\n self.ui.btnConv.clicked.connect(self.convertfiles)\n self.setGeometry(300, 400, 656, 354)\n\n def getfiles(self):\n\n fname = QFileDialog.getOpenFileName(self, \"Open fb2\", \"/home/\", \"FictionBook Files (*.fb2)\")[0]\n\n with open(fname, 'r') as data:\n data = data.read()\n self.ui.textIn.setText(data)\n self.ui.mylabel.setText('Input file: ' + fname)\n\n global fout\n fout = re.sub(r'\\.fb2', '', fname)\n fout = fout + '.txt'\n\n with open(fname, 'rb') as f_in, open(fout, 'w') as f_out:\n check = f_in.read()\n\n #check = bytes(bytearray(f_in.read(), encoding='utf-8'))\n tree = et.fromstring(check)\n ns = {'ns': \"http://www.gribuser.ru/xml/fictionbook/2.0\"}\n for bin_eb in tree.xpath('//ns:binary', namespaces=ns):\n bin_eb.getparent().remove(bin_eb)\n for bin_ed in tree.xpath('//ns:description', namespaces=ns):\n bin_ed.getparent().remove(bin_ed)\n global cleart, cleart2\n cleart = et.tounicode(tree)\n cleart = re.sub(r'\\<[^>]*\\>', '', cleart)\n self.ui.textOut.setText(cleart)\n\n def convertfiles(self):\n cleart2 = self.ui.textOut.toPlainText()\n self.ui.mylabel.setText('')\n with open(fout, 'w') as f_out:\n f_out.write(cleart2)\n self.ui.mylabel.setText(f'Saved file: ' + fout)\n print(fout)\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n window = MyWindow()\n window.setWindowTitle(\"Ковертер Fb2 > Txt\")\n window.setWindowIcon(\n QtGui.QIcon('skull.png'))\n window.show()\n\n sys.exit(app.exec_())\n","sub_path":"convert-v27.py","file_name":"convert-v27.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"636490014","text":"from random import randint\r\nfrom fractions import Fraction\r\nfrom yunsuan import formula_result, formula_change\r\n\r\n\r\nclass configuration:\r\n def __init__(self, formula_num=10, num_length=10, symbols_num=3):\r\n self.formula_num = formula_num\r\n self.num_length = num_length\r\n self.symbols_num = symbols_num\r\n\r\n\r\nclass construction:\r\n def construct_symbol(self): # 随机生成运算符\r\n symbols = ['+', '-', '×', '÷']\r\n return symbols[randint(0, len(symbols) - 1)] # 通过随机的位置号来确认对应的运算符\r\n\r\n def construct_fraction(self, num_length):\r\n denominator = randint(2, num_length)\r\n numerator = randint(1, denominator - 1)\r\n first_num = randint(0, num_length - 1)\r\n fraction = str(Fraction(numerator, denominator))\r\n if first_num != 0:\r\n fraction = str(first_num) + \"'\" + fraction\r\n return fraction\r\n\r\n def construct_operand(self, fraction_need, num_length): # 生成运算数据\r\n if not fraction_need:\r\n return self.construct_fraction(num_length) # 随机生成运算范围内的真分数作为运算数据\r\n else:\r\n return str(randint(0, num_length - 1)) # 随机生成运算数范围内的整数作为运算数据\r\n\r\n def construct_formula_parentheses(self, formula, num_number):\r\n formulas = []\r\n num = num_number\r\n if formula:\r\n formula_length = len(formula)\r\n left_position = randint(0, int(num / 2))\r\n right_position = randint(left_position + 1, int(num / 2) + 1)\r\n position_mark = -1\r\n for i in range(formula_length):\r\n if formula[i] in ['+', '-', '×', '÷']:\r\n formulas.append(formula[i]) # 运算符直接入栈\r\n else:\r\n position_mark += 1\r\n if position_mark == left_position: # 当位置标记与随机生成的左括号位置一致时,左括号先入栈运算数据后入栈\r\n formulas.append('(')\r\n formulas.append(formula[i])\r\n elif position_mark == right_position: # 当位置标记与随机生成的右括号位置一致时,操作数先入栈运算数据后入栈\r\n formulas.append(formula[i])\r\n formulas.append(')')\r\n else:\r\n formulas.append(formula[i]) # 运算数据直接入栈\r\n if formulas[0] == '(' and formulas[-1] == ')': # 若生成的括号表达式形如(x+y+z)则重新生成括号表达式\r\n formulas = self.construct_formula_parentheses(formula, num_number)\r\n return formulas\r\n return formulas\r\n\r\n def construct(self, Configuration):\r\n formula_num = Configuration.formula_num\r\n formula_list = []\r\n i = 0\r\n while i < formula_num:\r\n ran_symbols_num = randint(1, Configuration.symbols_num)\r\n parentheses_need = randint(0, 1)\r\n num_number = ran_symbols_num + 1\r\n formula = []\r\n for j in range(ran_symbols_num + num_number):\r\n if j % 2 == 0:\r\n formula.append(self.construct_operand(randint(0, 3), Configuration.num_length))\r\n if j > 1 and formula[j - 1] == '÷' and formula[j] == '0':\r\n while True:\r\n formula[j - 1] = self.construct_symbol()\r\n if formula[j - 1] == '÷':\r\n continue\r\n else:\r\n break\r\n else:\r\n formula.append(self.construct_symbol())\r\n\r\n if parentheses_need and num_number != 2:\r\n formulas = \" \".join(self.construct_formula_parentheses(formula, num_number))\r\n else:\r\n formulas = \" \".join(formula)\r\n if formula_result(formula_change(formulas)) is False:\r\n continue\r\n else:\r\n formula_list.append(formulas)\r\n print('第%d道题' % int(i + 1))\r\n i = i + 1\r\n\r\n return formula_list\r\n\r\n def formula_output(self, formula_list):\r\n if not formula_list:\r\n return\r\n with open('Exercises.txt', \"r+\", encoding='utf-8') as file:\r\n file.truncate()\r\n file.close()\r\n for i, formula in enumerate(formula_list):\r\n formula_str = str(i + 1) + ': ' + formula + ' = ' + \"\\n\"\r\n with open('Exercises.txt', \"a+\", encoding='utf-8') as file:\r\n file.write(formula_str)\r\n file.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"3118005402/PythonDemo/creation.py","file_name":"creation.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"340556738","text":"import pygame,sys\n\npygame.init()\nsize = width,height = [600,400]\nspeed = [1,1]\nBLACK = 0,0,0\nscreen = pygame.display.set_mode(size)\n#game name\npygame.display.set_caption(\"pygame squash\")\n#Import the picture path of the ball, which can be customized\nball = pygame.image.load(\"ball.png\")\nballrect = ball.get_rect()\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n #Mobile Way\n ballrect = ballrect.move(speed[0],speed[1])\n if ballrect.left < 0 or ballrect.right > width:\n speed[0] = -speed[0]\n if ballrect.top < 0 or ballrect.bottom > height:\n speed[1] = -speed[1]\n\n #background color\n screen.fill(BLACK)\n screen.blit(ball,ballrect)\n #Refresh\n pygame.display.update()","sub_path":"rolling.py","file_name":"rolling.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"537919873","text":"import matplotlib.pyplot as plt\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 5\n\nplots = list()\nplot_z = list()\nplot_v = list()\n\nfile = open('list_row.txt', 'r')\nlines = file.readlines()\nfor line in lines:\n if line.split()[2] != 'NaN':\n z = float(line.split()[1]) / (0.008575/2)\n v = line.split()[2].split('+')[0]\n if line.split()[2][0] == '-':\n v = '-' + v.split('-')[1]\n else:\n v = v.split('-')[0]\n v = float(v)\n plots.append((z, v))\nfile.close()\n\nplots.sort()\nfor p in plots:\n plot_z.append(p[0])\n plot_v.append(p[1])\nplt.plot(plot_z, plot_v)\nplt.title('yz cut plane at x=7(cm), y=7(cm)')\nplt.xlabel('1 grid = λ/2 (λ=8.575mm)')\nplt.ylabel('pressure(Pa)')\nplt.show()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"583491372","text":"#借出书籍 查询功能\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport urllib\n\n\ndef getUrl():\n\turl = 'http://218.28.96.52:8899/museweb/wxjs/tmjs.asp?'\n\t\n\tprint('1.题名') \n\tprint('2.题名拼音头')\n\tchoice_types = input('请选择查询方法')\n\tif choice_types == '1':\n\t\tchoice_types = 'HZ'\n\telif choice_types == '2':\n\t\tchoice_types = 'PY'\n\n\tprint('\\n')\n\tprint('1.前方一致')\n\tprint('2.模糊查询')\n\tprint('3.精确查询')\n\tchoice_methmod = input('请选择查询方法')\n\t\n\tbookname = urllib.parse.quote(input('\\n查询书名:'))\n\t\n\tparms = { \n\t\"txtWxlx\":\"CN\",\n\t\"txtTm\":bookname,\n\t\"txtSearchType\":choice_methmod, \n\t'txtPY':choice_types,\n\t\"nSetPageSize\":\"100\"\n\t} \t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\turlParms = urllib.parse.urlencode(parms)\n\tglobal urls\n\turls = url + urlParms\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ndef get_html(url):\t\t\t\t\t\t\t\t\t\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1\",}\n\treq = requests.get(url,headers=headers) \n\tif req.encoding == 'ISO-8859-1':\n\t\n\t\tencodings = requests.utils.get_encodings_from_content(req.text)\n\t\tif encodings:\n\t\t\tencoding = encodings[0]\n\t\telse:\n\t\t\tencoding = req.apparent_encoding\n\n\t\t# encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')\n\t\tglobal html_content #定义全局变量 'content'\n\t\thtml_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符;\n\t\tglobal html\n\t\thtml = BeautifulSoup(html_content,'html.parser')\n\n\n\n#获取书名与链接 \ndef getBookLinke_name(html):\n content = html.find_all('a')\n global bookLink_Name\n bookLink_Name = list()\n for indexs in range(10,len(content)-1):\n li = list()\n bookinfo = content[indexs]\n bookName = bookinfo.string.strip()\n bookLink1 = bookinfo['href']\n bookLink2 = re.search('(\\d+)',bookLink1).group(0)\n bookLink3 = 'http://218.28.96.52:8899/museweb/showmarc/table.asp?nTmpKzh=%s'%bookLink2\n \n li.append(bookName)\n li.append(bookLink3)\n bookLink_Name.append(li)\n \n \n print('{n}书名:{bookName}{n}链接: {bookLink}'.format(n='\\n',bookName=bookName,bookLink=bookLink3))\n\n\nif __name__ == '__main__':\n getUrl()\n get_html(urls) \n getBookLinke_name(html)\n \n","sub_path":"getBookLink.py","file_name":"getBookLink.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"597757270","text":"from os import geteuid as os_geteuid\nfrom os import environ as os_environ\nfrom zshpower.utils.catch import current_user\nfrom .lib.utils import Color\n\n\nclass Username(Color):\n def __init__(self, config):\n super().__init__()\n self.username_enable = config[\"username\"][\"enable\"]\n self.username_color = config[\"username\"][\"color\"]\n if os_geteuid() == 0:\n self.username_color = \"red\"\n\n def __str__(self, space_elem=\" \"):\n if \"SSH_CONNECTION\" in os_environ or self.username_enable or os_geteuid() == 0:\n user = current_user()\n username_export = (\n f\"{Color(self.username_color)}{user}{space_elem}{Color().NONE}\"\n )\n return str(username_export)\n return \"\"\n","sub_path":"zshpower/prompt/sections/username.py","file_name":"username.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"319042677","text":"\"\"\"\ncluster.py\n\"\"\"\nfrom collections import Counter, OrderedDict\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport sys\nimport time, json\nfrom TwitterAPI import TwitterAPI\n#from config import *\n\nfollowers_filename = 'followersdata.json'\n\ndef get_common_followers(filename):\n \n followers_count = Counter()\n follow_list = []\n \n with open(filename, 'r',encoding='utf-8') as file:\n for line in file:\n data_fetched = json.loads(line)\n \n for key,value in data_fetched.items():\n if len(value)>0:\n followers_count.update(value)\n else:\n print('no value in followerdata file')\n \n for key_name, values_list in dict(followers_count).items():\n if values_list > 2:\n follow_list.append(key_name)\n \n return follow_list\n\ndef girvan_newman(G, depth=0):\n\t\n if G.order() == 1:\n return [G.nodes()]\n\n def find_best_edge(G0):\n eb = nx.edge_betweenness_centrality(G0)\n\t\t\n return sorted(eb.items(), key=lambda x: x[1], reverse=True)[0][0]\n\n\t# Each component is a separate community. We cluster each of these.\n components = [c for c in nx.connected_component_subgraphs(G)]\n while len(components) == 1:\n edge_to_remove = find_best_edge(G)\n G.remove_edge(*edge_to_remove)\n components = [c for c in nx.connected_component_subgraphs(G)]\n return components\n\n\n \ndef get_edges(follow_list):\n edges_dict = {}\n user_dict = {}\n with open('tweets.txt',encoding='utf-8') as fp:\n for line in fp:\n data_fetched = line.split(' || ')\n user_dict[data_fetched[2]] = data_fetched[0]\n \n \n print(\"creating edges file...\")\n top_list = set(follow_list)\n print(\"TOP_LIST::\",len(top_list))\n \n with open(followers_filename, 'r',encoding='utf-8') as fp:\n for line in fp:\n data = json.loads(line)\n for key, value in data.items():\n common_list = set(value).intersection(top_list)\n print(\"Common_List::\",len(common_list))\n if common_list:\n edges_dict[str(user_dict[key])] = list(common_list)[:20]\n else:\n edges_dict[str(user_dict[key])] = value[:20]\n \n with open('edges.txt', 'w',encoding='utf-8') as fp:\n for key, value in edges_dict.items():\n for ids in value:\n if ids>-1:\n fp.write(str(key)+ \"-->\"+ str(ids)+ \"\\n\")\n else:\n print('error')\n print(\"edges file created\")\n\n \ndef draw_network(graph, filename):\n \"\"\"\n Draw the network to a file. Only label the candidate nodes; the friend\n nodes should have no labels (to reduce clutter).\n \"\"\"\n pos=nx.spring_layout(graph)\n plt.figure(figsize=(14,14))\n nx.draw_networkx(graph,pos, node_color='r',edge_color='b', alpha=.8, width=.5, node_size=400)\n plt.axis(\"off\")\n plt.savefig(filename, format=\"PNG\")\n \n\ndef read_graph():\n\t\"\"\" Read 'edges.txt.gz' into a networkx **undirected** graph.\n\tDone for you.\n\tReturns:\n\tA networkx undirected graph.\n\t\"\"\"\n\treturn nx.read_edgelist('edges.txt', delimiter='-->')\n\ndef main():\n \n common_followers_list = get_common_followers(followers_filename) #find common followers for different users \n get_edges(common_followers_list)\n \n graph = read_graph()\n\n draw_network(graph, 'network.png')\n print('graph has %d nodes and %d edges' %(graph.order(), graph.number_of_edges()))\n \n i = 0\n while i < 3:\n clusters = girvan_newman(graph)\n if len(clusters)==1:\n break\n graph = clusters[0]\n i += 1\n #print(\"total clusters formed: %s\" %len(clusters))\n #for i in range(len(clusters)):\n #print(\"cluster[%s] has %s nodes\" %(i, clusters[i].order()))\n \nif __name__ == '__main__': \n main()\n\n","sub_path":"a4/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"375333917","text":"\"\"\"Primeira pergunta da prova, bola quicando e alterando a direção ao encontrar os limites da pagina.\"\"\"\n\n# importa biblioteca.\nimport pygame\n\n\nclass bola:\n \"\"\"Cria objeto bola.\"\"\"\n def __init__(self, centro, raio, cor):\n \"\"\"inicia objeto bola.\"\"\"\n self.bola = pygame.draw.circle(screen, cor, centro, raio, preenche)\n\n\n# Inicia a função que abre uma janela com o principio do jogo.\ndef inicio():\n \"\"\"Inicia função.\"\"\"\n pygame.init()\n# velocidade_x = 1\n# velocidade_y = 1\n\n pygame.display.set_caption(\"Bola\")\n screen = pygame.display.set_mode((400, 400))\n screen.blit(bola, (0, 0))\n pygame.display.flip()\n running = True\n\n while running:\n for event in pygame.event.get():\n key = pygame.key.get_pressed()\n # Fecha o programa quando apertado a tecla ESC\n if key[pygame.K_ESCAPE]:\n running = False\n if event.type == pygame.QUIT:\n running = False\n\n\nif __name__== \"__main__\" :\n inicio()\n","sub_path":"aula_9/pergunta_1/bola.py","file_name":"bola.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"}